From 4ae9e11c47fd1f1af41a4105f678fddf7e3c97d7 Mon Sep 17 00:00:00 2001 From: Eric Minish Date: Sun, 8 Nov 2026 21:08:00 -0500 Subject: [PATCH 1/7] fix(resolution): block method guesses through module namespaces --- CHANGELOG.md | 1 + __tests__/js-default-binding-members.test.ts | 86 ++++++++++++++++++++ src/resolution/name-matcher.ts | 63 +++++++++++--- 3 files changed, 138 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26c0ecbc62..2d25fca70e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixes +- JavaScript and TypeScript calls through CommonJS or default imports of modules without a value default no longer link missing members to unrelated class methods; re-index after upgrading. - TypeScript generic calls and typed tags using `typeof abstract` now retain their callers, while runtime `typeof` comparisons and optional chains keep their runtime meaning; re-index TypeScript projects after upgrading. - TypeScript classes with members named `abstract` or `accessor`, and auto-accessors with `static`, `override` or `abstract` modifiers, now index correctly; re-index TypeScript projects after upgrading. - A TSX file with a broken JSX attribute such as `c:d(e f)` no longer stalls indexing for about 90 seconds and then drops out of the index; it is indexed like any other file with a syntax error. diff --git a/__tests__/js-default-binding-members.test.ts b/__tests__/js-default-binding-members.test.ts index cc76ffcee9..e5267e71df 100644 --- a/__tests__/js-default-binding-members.test.ts +++ b/__tests__/js-default-binding-members.test.ts @@ -106,6 +106,92 @@ describe('a member read through a default binding', () => { expect(callsOf(cg, 'run')).toEqual([]); }); + it.each([ + ["const named = require('./m');", 'Decoy'], + ["import named from './m.js';", 'Decoy'], + ["const named = require('./m');", 'named'], + ])('does not borrow an unimported method after %s, even from class %s', async (binding, className) => { + const cg = await indexProject({ + 'm.js': 'exports.known = function known() {};\n', + 'decoy.js': `export class ${className} { static missing() {} }\n`, + 'use.js': CALLER(binding, ['missing']), + }); + expect(callsOf(cg, 'run')).toEqual([]); + }); + + it('keeps real exports beside an unimported method and through a forwarding module', async () => { + const cg = await indexProject({ + 'm.js': 'exports.second = function second() {};\n', + 'index.js': "module.exports = require('./m');\n", + 'decoy.js': 'export class Decoy { second() {} missing() {} }\n', + 'use.js': CALLER("const named = require('./index');", ['second', 'missing']), + }); + expect(callsOf(cg, 'run')).toEqual(['3 m.js:second']); + }); + + it('keeps CommonJS stated class, object, instance and callable exports', async () => { + const cg = await indexProject({ + 'class.js': 'class Widget { static make() {} }\nmodule.exports = Widget;\n', + 'object.js': 'const api = { read() {} };\nmodule.exports = api;\n', + 'instance.js': 'class Store { load() {} }\nmodule.exports = new Store();\n', + 'callable.js': 'function create() {}\nmodule.exports = create;\nmodule.exports.extra = function extra() {};\n', + 'decoy.js': 'export class Decoy { make() {} read() {} load() {} extra() {} }\n', + 'use.js': "const Widget = require('./class');\nconst object = require('./object');\nconst store = require('./instance');\nconst create = require('./callable');\nfunction run() {\n Widget.make();\n object.read();\n store.load();\n create();\n create.extra();\n}\nmodule.exports = run;\n", + }); + expect(callsOf(cg, 'run')).toEqual([ + '10 callable.js:extra', '6 class.js:Widget::make', '7 object.js:api::read', + '8 instance.js:Store::load', '9 callable.js:create', + ]); + }); + + it('keeps typed parameters and local objects that shadow a default binding', async () => { + const cg = await indexProject({ + 'm.ts': 'export function known() {}\n', + 'use.ts': "import named from './m';\nclass Local { missing() {} }\nexport function typed(named: Local) {\n named.missing();\n}\nexport function literal() {\n const named = { present() {} };\n named.present();\n}\n", + 'decoy.ts': 'export class Decoy { missing() {} present() {} }\n', + }); + expect(callsOf(cg, 'typed')).toEqual(['4 use.ts:Local::missing']); + expect(callsOf(cg, 'literal')).toEqual(['8 use.ts:literal::named::present']); + }); + + it.each([ + "import named from './m';", + "import * as named from './m';", + ])('keeps a lexical class shadow after %s', async (binding) => { + const cg = await indexProject({ + 'm.ts': 'export function known() {}\n', + 'use.ts': `${binding}\nexport function outer() {\n class named { static missing() {} }\n function run() { named.missing(); }\n return run;\n}\n`, + }); + expect(callsOf(cg, 'run')).toEqual(['4 use.ts:outer::named::missing']); + }); + + it.each([ + 'module.exports = new Store();', + 'export default new Store();', + ])('keeps the instance stated by %s', async (statement) => { + const cg = await indexProject({ + 'm.js': `class Store { load() {} }\n${statement}\n`, + 'decoy.js': 'export class Decoy { missing() {} }\n', + 'use.js': CALLER("const named = require('./m');", ['load']), + }); + expect(callsOf(cg, 'run')).toEqual(['3 m.js:Store::load']); + }); + + it('keeps a missing member unresolved when a decoy is added by sync', async () => { + const cg = await indexProject({ + 'm.js': 'exports.known = function known() {};\n', + 'use.js': CALLER("const named = require('./m');", ['missing']), + }); + expect(callsOf(cg, 'run')).toEqual([]); + const decoy = path.join(roots[roots.length - 1]!, 'decoy.js'); + fs.writeFileSync(decoy, 'export class Decoy { missing() {} }\n'); + await cg.sync(); + expect(callsOf(cg, 'run')).toEqual([]); + fs.unlinkSync(decoy); + await cg.sync(); + expect(callsOf(cg, 'run')).toEqual([]); + }); + it('takes what `module.exports =` states over a neighbour assigned to it', async () => { const cg = await indexProject({ 'm.js': 'function main() {}\nmodule.exports = main;\nmodule.exports.extra = function () {};\n', diff --git a/src/resolution/name-matcher.ts b/src/resolution/name-matcher.ts index 9bc65dcd01..9380dc8363 100644 --- a/src/resolution/name-matcher.ts +++ b/src/resolution/name-matcher.ts @@ -23207,6 +23207,7 @@ export function clearNameMatcherMemos(context: ResolutionContext): void { CSHARP_EXTENSION_METHODS.delete(context); CSHARP_PARAMETERS.delete(context); JS_ASSIGNED_MEMBERS.delete(context); + JS_MODULE_NAMESPACES.delete(context); CFML_CHAINS.delete(context); NO_RECEIVER_LINES.delete(context); OBJC_SUPERS.delete(context); @@ -26821,6 +26822,14 @@ function matchMethodCallOn( if (bounded !== undefined) return bounded; } + // Import, typed-receiver and object-member resolution have had their chance. + // A namespace binding, including a default/require of a module with no + // value default, must not borrow a member from an unrelated class. + // Stop before class-name matching too: the class may share the import alias. + if (ref.referenceKind === 'calls' && JS_FAMILY.has(ref.language) && isImportedModuleReceiver(objectOrClass!, ref, context)) { + return null; + } + // Strategy 1: Direct class name match (existing logic). When the receiver // names a class that exists in several files (`Logger.log()` / `Logger::log()` // with a `Logger` in both `a/` and `b/`), try the class in the call site's @@ -26931,16 +26940,6 @@ function matchMethodCallOn( objectOrClass !== 'this' && objectOrClass !== 'super' && JS_BUILTIN_METHODS.has(methodName!)) return null; - // A receiver the file imports is past guessing. A namespace import is the - // module object, whose members are its exports, never some class's method; - // a binding from a package outside the repository names nothing in it. The - // import resolver placed what it could, and a method picked by name alone is - // wrong: zod's `z.string()` (`import * as z from "zod/v4"`) bound 3,207 calls - // to a test helper's `string` getter, trpc's `z.record()` another class's. - if (ref.referenceKind === 'calls' && JS_FAMILY.has(ref.language) && isImportedModuleReceiver(objectOrClass!, ref, context)) { - return null; - } - // A receiver written as a type name the project doesn't declare // (`Exception.Create(…)` in Delphi, `Collections.sort(…)`) is a type from // outside it: a same-named method of some project type is a guess. horse's @@ -27337,13 +27336,53 @@ function matchMethodCallOn( /** * Is a member call's receiver (`z` in `z.string`, `ns` in `ns.util.fn`) an - * import binding that is a module namespace, or one from outside the repo? + * namespace import, a default binding to a namespace-only module, or one + * from outside the repo? A require of `exports.x = …` is a default binding, + * but its absent members are no unrelated class's methods. */ function isImportedModuleReceiver(receiver: string, ref: UnresolvedRef, context: ResolutionContext): boolean { const root = receiver.split('.')[0]!; const binding = context.getImportMappings?.(ref.filePath, ref.language)?.find((m) => m.localName === root); if (!binding) return false; - return binding.isNamespace || context.isOutOfRepoImport?.(binding.source, ref.filePath, ref.language) === true; + // A class declared in this lexical scope shadows a file-wide import. It + // still gets the direct class lookup below; an unrelated file's class does not. + const locals = context.getNodesInFileNamed?.(ref.filePath, root) ?? + context.getNodesInFile(ref.filePath).filter((n) => n.name === root); + if (locals.some((n) => n.kind === 'class' && isLexicallyReachable(n, ref, context))) return false; + return binding.isNamespace || + (binding.isDefault && isDefaultModuleNamespace(binding.source, ref.filePath, ref.language, context)) || + context.isOutOfRepoImport?.(binding.source, ref.filePath, ref.language) === true; +} + +const JS_MODULE_NAMESPACES = new WeakMap>(); + +/** Only a known namespace, never a module's stated or uncertain default value. + * Conservative raw checks also exclude comments/text mentioning a default: + * uncertainty must preserve existing value resolution, not invent its type. + */ +function isDefaultModuleNamespace(source: string, from: string, language: Language, context: ResolutionContext, seen = new Set()): boolean { + const file = context.resolveModuleFile?.(source, from, language); + if (!file || !/\.[cm]?[jt]sx?$/.test(file) || seen.has(file) || seen.size >= 8) return false; + seen.add(file); + let memo = JS_MODULE_NAMESPACES.get(context); + if (!memo) JS_MODULE_NAMESPACES.set(context, (memo = new Map())); + const key = `${file}\0${language}`; + const cached = memo.get(key); + if (cached !== undefined) return cached; + const code = context.readFile(file); + let namespace = false; + if (code !== null && !/\bdefault\b|\bexport\s*=/.test(code)) { + // Follow only a whole-file forwarder; extra assignments or other code + // make the effective default uncertain. Named module.exports.x writes + // still describe the namespace, whereas any other use of module may + // replace it (including computed writes or assignment through an alias). + const forwarded = /^\s*(?:['"]use strict['"];\s*)?(?:exports\s*=\s*)?module\.exports\s*=\s*(?:exports\s*=\s*)?require\(\s*['"]([^'"]+)['"]\s*\)\s*;?\s*$/.exec(code); + namespace = forwarded + ? isDefaultModuleNamespace(forwarded[1]!, file, language, context, seen) + : !/\bmodule\b(?!\s*\.\s*exports\s*[.\[])/.test(code); + } + memo.set(key, namespace); + return namespace; } const JS_ASSIGNED_MEMBERS = new WeakMap>>(); From a96ee995c498e857852459b4934cf4e630294dcf Mon Sep 17 00:00:00 2001 From: Eric Minish Date: Mon, 9 Nov 2026 07:04:42 -0500 Subject: [PATCH 2/7] fix(resolution): refresh module calls and preserve visible exports Track imported export files during sync, retain callable export aliases, and require block visibility for local class shadows. --- __tests__/js-default-binding-members.test.ts | 67 ++++++++++++++++++++ src/extraction/index.ts | 5 +- src/resolution/name-matcher.ts | 66 +++++++++++++++---- 3 files changed, 122 insertions(+), 16 deletions(-) diff --git a/__tests__/js-default-binding-members.test.ts b/__tests__/js-default-binding-members.test.ts index e5267e71df..f63895c524 100644 --- a/__tests__/js-default-binding-members.test.ts +++ b/__tests__/js-default-binding-members.test.ts @@ -200,6 +200,73 @@ describe('a member read through a default binding', () => { expect(callsOf(cg, 'run')).toEqual(['3 m.js:main', '4 m.js:extra']); }); + it.each([ + ['./m', 'named'], ['./index', 'named'], + ['./m', 'Store'], ['./index', 'Store'], + ])('rechecks calls through %s as %s when it changes between a value and a namespace', async (specifier, alias) => { + const value = 'class Store { load() {} }\nmodule.exports = new Store();\n'; + const namespace = 'class Store { load() {} }\nexports.known = function known() {};\n'; + const files = { + 'm.js': value, + 'index.js': "module.exports = require('./m');\n", + 'use.js': CALLER(`const named = require('${specifier}');`, ['load']).replace(/\bnamed\b/g, alias), + }; + const cg = await indexProject(files); + const moduleFile = path.join(roots[roots.length - 1]!, 'm.js'); + expect(callsOf(cg, 'run')).toEqual(['3 m.js:Store::load']); + for (const source of [namespace, value, namespace]) { + fs.writeFileSync(moduleFile, source); + await cg.sync(); + const fresh = await indexProject({ ...files, 'm.js': source }); + expect(callsOf(cg, 'run')).toEqual(callsOf(fresh, 'run')); + expect(callsOf(cg, 'run')).toEqual(source === value ? ['3 m.js:Store::load'] : []); + } + }); + + it.each(['exports.load', 'module.exports.load', "exports['load']", "module.exports['load']"])( + 'keeps the callable alias in %s without borrowing an absent member', async (assignment) => { + const cg = await indexProject({ + 'm.js': `class Store { load() {} }\n${assignment} = Store.prototype.load;\n`, + 'decoy.js': 'export class Decoy { missing() {} }\n', + 'use.js': CALLER("const named = require('./m');", ['load', 'missing']), + }); + expect(callsOf(cg, 'run')).toEqual(['3 m.js:Store::load']); + } + ); + + it('drops an exported callable alias when sync removes only the assignment', async () => { + const cg = await indexProject({ + 'm.js': 'class Store { load() {} }\nexports.load = Store.prototype.load;\n', + 'use.js': CALLER("const named = require('./m');", ['load']), + }); + const moduleFile = path.join(roots[roots.length - 1]!, 'm.js'); + expect(callsOf(cg, 'run')).toEqual(['3 m.js:Store::load']); + fs.writeFileSync(moduleFile, 'class Store { load() {} }\nexports.known = function known() {};\n'); + await cg.sync(); + expect(callsOf(cg, 'run')).toEqual([]); + }); + + it.each([ + "const named = require('./m');", + "import named from './m';", + "import * as named from './m';", + ])('sees a block-local class only inside its block after %s', async (binding) => { + const cg = await indexProject({ + 'm.ts': 'export function known() {}\n', + 'use.ts': `${binding}\nexport function run() {\n if (true) {\n class named { static missing() {} }\n function inside() { named.missing(); }\n }\n named.missing();\n}\n`, + }); + expect(callsOf(cg, 'run')).toEqual([]); + expect(callsOf(cg, 'inside')).toEqual(['5 use.ts:run::named::missing']); + }); + + it('does not mistake a class inside a TypeScript namespace for an import shadow', async () => { + const cg = await indexProject({ + 'm.ts': 'export function known() {}\n', + 'use.ts': "import named from './m';\nnamespace Parent {\n export class named { static missing() {} }\n}\nexport function run() { named.missing(); }\n", + }); + expect(callsOf(cg, 'run')).toEqual([]); + }); + it('links the member a sync brings, and drops the one it takes away', async () => { const cg = await indexProject({ 'm.js': 'exports.first = function () {};\n', diff --git a/src/extraction/index.ts b/src/extraction/index.ts index 05bf5e1ddc..d48b2b23f5 100644 --- a/src/extraction/index.ts +++ b/src/extraction/index.ts @@ -3730,8 +3730,9 @@ export class ExtractionOrchestrator { * touched, although neither end of the edge changed: a python attribute typed * through a factory or a base class in another file records those files as * `metadata.typeFrom`, as does a TS/JS receiver typed by the signature of a - * function in another file (a callback's parameter). The definition delta - * cannot see these — editing what a factory returns, what a base `__init__` + * function in another file (a callback's parameter), and a JS/TS default + * import's namespace ownership (the export assignment it was read from). The + * definition delta cannot see these — editing what a factory returns, what a base `__init__` * assigns or the type a callee gives its callback adds or removes no * definition — so without this a synced index keeps the old type forever. * The edges go back to pending refs; returns the files they come from, whose diff --git a/src/resolution/name-matcher.ts b/src/resolution/name-matcher.ts index 9380dc8363..767cf61899 100644 --- a/src/resolution/name-matcher.ts +++ b/src/resolution/name-matcher.ts @@ -26826,7 +26826,7 @@ function matchMethodCallOn( // A namespace binding, including a default/require of a module with no // value default, must not borrow a member from an unrelated class. // Stop before class-name matching too: the class may share the import alias. - if (ref.referenceKind === 'calls' && JS_FAMILY.has(ref.language) && isImportedModuleReceiver(objectOrClass!, ref, context)) { + if (ref.referenceKind === 'calls' && JS_FAMILY.has(ref.language) && isImportedModuleReceiver(objectOrClass!, methodName!, ref, context)) { return null; } @@ -27340,7 +27340,7 @@ function matchMethodCallOn( * from outside the repo? A require of `exports.x = …` is a default binding, * but its absent members are no unrelated class's methods. */ -function isImportedModuleReceiver(receiver: string, ref: UnresolvedRef, context: ResolutionContext): boolean { +function isImportedModuleReceiver(receiver: string, member: string, ref: UnresolvedRef, context: ResolutionContext): boolean { const root = receiver.split('.')[0]!; const binding = context.getImportMappings?.(ref.filePath, ref.language)?.find((m) => m.localName === root); if (!binding) return false; @@ -27348,21 +27348,34 @@ function isImportedModuleReceiver(receiver: string, ref: UnresolvedRef, context: // still gets the direct class lookup below; an unrelated file's class does not. const locals = context.getNodesInFileNamed?.(ref.filePath, root) ?? context.getNodesInFile(ref.filePath).filter((n) => n.name === root); - if (locals.some((n) => n.kind === 'class' && isLexicallyReachable(n, ref, context))) return false; + if (locals.some((n) => n.kind === 'class' && isLexicallyReachable(n, ref, context) && + holderScopeAt(n, ref, false, context) !== null)) return false; + const module = binding.isDefault ? defaultModuleNamespace(binding.source, ref.filePath, ref.language, context) : null; + const firstMember = receiver.includes('.') ? receiver.slice(root.length + 1).split('.')[0]! : member; return binding.isNamespace || - (binding.isDefault && isDefaultModuleNamespace(binding.source, ref.filePath, ref.language, context)) || + (module?.namespace === true && !module.members.has(firstMember)) || context.isOutOfRepoImport?.(binding.source, ref.filePath, ref.language) === true; } -const JS_MODULE_NAMESPACES = new WeakMap>(); +interface ModuleNamespaceInfo { + namespace: boolean; + members: ReadonlySet; + files: ReadonlySet; + truncated?: boolean; +} + +const JS_MODULE_NAMESPACES = new WeakMap>(); /** Only a known namespace, never a module's stated or uncertain default value. * Conservative raw checks also exclude comments/text mentioning a default: * uncertainty must preserve existing value resolution, not invent its type. */ -function isDefaultModuleNamespace(source: string, from: string, language: Language, context: ResolutionContext, seen = new Set()): boolean { +function defaultModuleNamespace(source: string, from: string, language: Language, context: ResolutionContext, seen = new Set()): ModuleNamespaceInfo { const file = context.resolveModuleFile?.(source, from, language); - if (!file || !/\.[cm]?[jt]sx?$/.test(file) || seen.has(file) || seen.size >= 8) return false; + const files = new Set(file ? [file] : []); + const members = new Set(); + if (!file || !/\.[cm]?[jt]sx?$/.test(file)) return { namespace: false, members, files }; + if (seen.has(file) || seen.size >= 8) return { namespace: false, members, files, truncated: true }; seen.add(file); let memo = JS_MODULE_NAMESPACES.get(context); if (!memo) JS_MODULE_NAMESPACES.set(context, (memo = new Map())); @@ -27370,19 +27383,31 @@ function isDefaultModuleNamespace(source: string, from: string, language: Langua const cached = memo.get(key); if (cached !== undefined) return cached; const code = context.readFile(file); - let namespace = false; + let info: ModuleNamespaceInfo = { namespace: false, members, files }; if (code !== null && !/\bdefault\b|\bexport\s*=/.test(code)) { // Follow only a whole-file forwarder; extra assignments or other code // make the effective default uncertain. Named module.exports.x writes // still describe the namespace, whereas any other use of module may // replace it (including computed writes or assignment through an alias). const forwarded = /^\s*(?:['"]use strict['"];\s*)?(?:exports\s*=\s*)?module\.exports\s*=\s*(?:exports\s*=\s*)?require\(\s*['"]([^'"]+)['"]\s*\)\s*;?\s*$/.exec(code); - namespace = forwarded - ? isDefaultModuleNamespace(forwarded[1]!, file, language, context, seen) - : !/\bmodule\b(?!\s*\.\s*exports\s*[.\[])/.test(code); + if (forwarded) { + const next = defaultModuleNamespace(forwarded[1]!, file, language, context, seen); + info = { ...next, files: new Set([...files, ...next.files]) }; + } else { + // An explicit member may be a callable alias the import resolver cannot + // follow yet. Its presence is not evidence that the member is absent. + for (const m of code.matchAll(/\b(?:module\s*\.\s*)?exports\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"]+)\2\s*\])\s*=(?![=>])/g)) { + members.add(m[1] ?? m[3]!); + } + const uncertain = /\bmodule\b(?!\s*\.\s*exports\s*[.\[])/.test(code) || + /\bexports\b(?!\s*[.\[])/.test(code) || + /\bexports\s*\[(?!\s*(['"])[^'"]+\1\s*\])/.test(code) || members.has('__proto__'); + info = { namespace: !uncertain, members, files }; + } } - memo.set(key, namespace); - return namespace; + // A depth/cycle cutoff says nothing about a shorter lookup of this file. + if (!info.truncated) memo.set(key, info); + return info; } const JS_ASSIGNED_MEMBERS = new WeakMap>>(); @@ -34258,7 +34283,20 @@ export function matchReference( if (overload === null) return null; if (overload) return overload.id === result.targetNodeId ? result : { ...result, targetNodeId: overload.id }; } - return result ? retargetSelfOverload(result, ref, context) : result; + const target = result ? retargetSelfOverload(result, ref, context) : result; + // Class-name matches also depend on imported namespace ownership, even + // though they do not carry the method-name strategy's byName marker. + if (target && ref.referenceKind === 'calls' && JS_FAMILY.has(ref.language)) { + const root = /^([A-Za-z_$][\w$]*)\./.exec(ref.referenceName)?.[1]; + const binding = root && context.getImportMappings?.(ref.filePath, ref.language)?.find((m) => m.isDefault && m.localName === root); + if (binding) { + const module = defaultModuleNamespace(binding.source, ref.filePath, ref.language, context); + const previous = Array.isArray(target.metadata?.typeFrom) ? target.metadata.typeFrom.filter((f): f is string => typeof f === 'string') : []; + const files = new Set([...previous, ...module.files]); + if (files.size) return { ...target, metadata: { ...target.metadata, typeFrom: [...files].sort() } }; + } + } + return target; } /** From aeaa53ee71445a5b78abcc9e2b1b9adec036f38c Mon Sep 17 00:00:00 2001 From: Eric Minish Date: Mon, 9 Nov 2026 09:22:28 -0500 Subject: [PATCH 3/7] refactor(resolution): isolate CommonJS export member discovery --- __tests__/commonjs-export-members.test.ts | 71 ++++++++++++++++++ __tests__/js-default-binding-members.test.ts | 31 ++++++++ package-lock.json | 7 ++ package.json | 1 + src/resolution/commonjs-export-members.ts | 78 ++++++++++++++++++++ src/resolution/name-matcher.ts | 12 +-- 6 files changed, 191 insertions(+), 9 deletions(-) create mode 100644 __tests__/commonjs-export-members.test.ts create mode 100644 src/resolution/commonjs-export-members.ts diff --git a/__tests__/commonjs-export-members.test.ts b/__tests__/commonjs-export-members.test.ts new file mode 100644 index 0000000000..9b423f0f07 --- /dev/null +++ b/__tests__/commonjs-export-members.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from 'vitest'; +import { readCommonJsExportMembers } from '../src/resolution/commonjs-export-members'; + +describe('CommonJS export member discovery', () => { + it.each([ + 'exports.load = Store.prototype.load;', + 'module.exports.load = Store.prototype.load;', + "exports['load'] = Store.prototype.load;", + 'module.exports["load"] = Store.prototype.load;', + 'module["exports"]["load"] = Store.prototype.load;', + 'exports /* target */ . /* key */ load = Store.prototype.load;', + 'const text = `${exports.load = Store.prototype.load}`;', + 'const text = `outer ${`inner ${exports.load = Store.prototype.load}`}`;', + 'function generic() { exports.load = Store.prototype.load; }', + ])('finds executable assignment: %s', (source) => { + const result = readCommonJsExportMembers(source); + expect([...result.members]).toEqual(['load']); + expect(result.uncertain).toBe(false); + }); + + it.each([ + '// exports.missing = fake;', + '/* exports.missing = fake; */', + 'const text = "exports.missing = fake;";', + 'const text = `exports.missing = fake;`;', + 'const pattern = /exports.missing = fake/;', + 'if (true) /exports.missing = fake/.test("x");', + 'function setup(holder) { holder.exports.missing = 42; }', + 'function setup(holder) { holder . exports . missing = 42; }', + 'function setup(holder) { holder.module.exports.missing = 42; }', + 'holder?.exports.missing;', + '$exports.missing = fake;', + 'αexports.missing = fake;', + 'exports.missing === fake;', + 'const text = "module exports";', + 'let value: typeof exports.missing = undefined;', + 'type Loader = typeof require.cache;', + 'class Evaluator { eval(code) {} }', + ])('ignores non-export text: %s', (source) => { + const result = readCommonJsExportMembers(source); + expect([...result.members]).toEqual([]); + expect(result.uncertain).toBe(false); + }); + + it.each([ + 'module.exports = new Store();', + 'take(exports);', + 'Object.setPrototypeOf(exports, Store.prototype);', + 'module.exports.__proto__ = Store.prototype;', + 'exports[key] = Store.prototype.load;', + 'exports["lo\\u0061d"] = Store.prototype.load;', + "eval('exports.load = Store.prototype.load;');", + 'eval(`exports.load = Store.prototype.load;`);', + 'eval(`exports.load = ${Store.prototype.load};`);', + "(eval)('exports.load = Store.prototype.load;');", + "((eval))(('exports.load = Store.prototype.load;'));", + 'require.cache[__filename].exports = new Store();', + "const Module = require('node:module');", + "import { Module } from 'node:module';", + "const Module = await import('node:module');", + ])('preserves uncertain object APIs: %s', (source) => { + expect(readCommonJsExportMembers(source).uncertain).toBe(true); + }); + + it('ignores JSX text but keeps assignments in JSX expressions', () => { + const source = '
exports.missing = fake{exports.load = Store.prototype.load}
'; + const result = readCommonJsExportMembers(source, true); + expect([...result.members]).toEqual(['load']); + expect(result.uncertain).toBe(false); + }); +}); diff --git a/__tests__/js-default-binding-members.test.ts b/__tests__/js-default-binding-members.test.ts index f63895c524..0628622365 100644 --- a/__tests__/js-default-binding-members.test.ts +++ b/__tests__/js-default-binding-members.test.ts @@ -267,6 +267,37 @@ describe('a member read through a default binding', () => { expect(callsOf(cg, 'run')).toEqual([]); }); + it.each([ + '// exports.missing = fake;', + '/* exports.missing = fake; */', + 'const text = "exports.missing = fake;";', + 'const text = `exports.missing = fake;`;', + 'const pattern = /exports.missing = fake/;', + 'function setup(holder) { holder.exports.missing = 42; }', + 'function setup(holder) { holder . exports . missing = 42; }', + 'function setup(holder) { holder.module.exports.missing = 42; }', + ])('does not treat non-export text as a member: %s', async (extra) => { + const cg = await indexProject({ + 'm.js': `exports.known = function known() {};\n${extra}\n`, + 'decoy.js': 'export class Decoy { missing() {} }\n', + 'use.js': CALLER("const named = require('./m');", ['missing']), + }); + expect(callsOf(cg, 'run')).toEqual([]); + }); + + it.each([ + "eval('exports.load = Store.prototype.load;');", + 'eval(`exports.load = Store.prototype.load;`);', + "(eval)('exports.load = Store.prototype.load;');", + 'require.cache[__filename].exports = new Store();', + ])('keeps uncertain runtime export APIs: %s', async (mutation) => { + const cg = await indexProject({ + 'm.js': `class Store { load() {} }\n${mutation}\n`, + 'use.js': CALLER("const named = require('./m');", ['load']), + }); + expect(callsOf(cg, 'run')).toEqual(['3 m.js:Store::load']); + }); + it('links the member a sync brings, and drops the one it takes away', async () => { const cg = await indexProject({ 'm.js': 'exports.first = function () {};\n', diff --git a/package-lock.json b/package-lock.json index 524310036b..7851f8eccd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "ignore": "^7.0.14", + "js-tokens": "9.0.1", "jsonc-parser": "^3.3.1", "picomatch": "^4.0.3", "sisteransi": "^1.0.5", @@ -2181,6 +2182,12 @@ "@types/estree": "^1.0.6" } }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "license": "MIT" + }, "node_modules/jsdom": { "version": "25.0.1", "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-25.0.1.tgz", diff --git a/package.json b/package.json index 9930f901a4..23c67dcf7f 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "ignore": "^7.0.14", + "js-tokens": "9.0.1", "jsonc-parser": "^3.3.1", "picomatch": "^4.0.3", "sisteransi": "^1.0.5", diff --git a/src/resolution/commonjs-export-members.ts b/src/resolution/commonjs-export-members.ts new file mode 100644 index 0000000000..5b1fdf8904 --- /dev/null +++ b/src/resolution/commonjs-export-members.ts @@ -0,0 +1,78 @@ +import jsTokens from 'js-tokens'; + +interface LexicalToken { type: string; value: string; closed?: boolean } +interface Property { name: string | null; next: number } + +const TRIVIA = new Set(['WhiteSpace', 'LineTerminatorSequence', 'SingleLineComment', 'MultiLineComment', 'HashbangComment']); + +/** Syntactic CommonJS writes, without interpreting their values or executing code. */ +export function readCommonJsExportMembers(source: string, jsx = false): { members: ReadonlySet; uncertain: boolean } { + const tokens: LexicalToken[] = [...jsTokens(source, { jsx })].filter((t) => !TRIVIA.has(t.type)); + const members = new Set(); + let uncertain = false; + const moduleApi = (token: LexicalToken | undefined): boolean => token?.type === 'StringLiteral' && + (token.value.slice(1, -1) === 'module' || token.value.slice(1, -1) === 'node:module'); + + const literalEvalCall = (at: number): boolean => { + let before = at - 1; + let after = at + 1; + // Parentheses around the bare callee preserve direct eval semantics. + while (tokens[before]?.value === '(' && tokens[after]?.value === ')') { + before--; + after++; + } + if (tokens[after]?.value !== '(') return false; + let argument = after + 1; + while (tokens[argument]?.value === '(') argument++; + const type = tokens[argument]?.type; + return type === 'StringLiteral' || type === 'NoSubstitutionTemplate' || type === 'TemplateHead'; + }; + + const property = (at: number): Property | null => { + const key = tokens[at + 1]; + if (tokens[at]?.value === '.' && key?.type === 'IdentifierName') { + return { name: key.value.includes('\\') ? null : key.value, next: at + 2 }; + } + if (tokens[at]?.value !== '[') return null; + if (key?.type === 'StringLiteral' && key.closed && tokens[at + 2]?.value === ']') { + const name = key.value.slice(1, -1); + return { name: name.includes('\\') ? null : name, next: at + 3 }; + } + return { name: null, next: at + 1 }; + }; + + for (let at = 0; at < tokens.length; at++) { + const root = tokens[at]; + if (root?.type !== 'IdentifierName') continue; + // obj.exports and obj.module.exports are not the CommonJS bindings. + if (tokens[at - 1]?.value === '.' || tokens[at - 1]?.value === '?.') continue; + if (tokens[at - 1]?.value === 'typeof') continue; + // Literal eval code and Node's module/cache APIs can supply exports + // without an assignment to the ordinary CommonJS bindings in this file. + if ((root.value === 'eval' && literalEvalCall(at)) || + (root.value === 'require' && (property(at + 1)?.name === 'cache' || + (tokens[at + 1]?.value === '(' && moduleApi(tokens[at + 2])))) || + (root.value === 'from' && moduleApi(tokens[at + 1])) || + (root.value === 'import' && (moduleApi(tokens[at + 1]) || + (tokens[at + 1]?.value === '(' && moduleApi(tokens[at + 2]))))) { + uncertain = true; + continue; + } + if (root.value !== 'exports' && root.value !== 'module') continue; + let next = at + 1; + if (root.value === 'module') { + const exported = property(next); + if (exported?.name !== 'exports') { uncertain = true; continue; } + next = exported.next; + } + const member = property(next); + // Escaping the object, replacing its default, or mutating its prototype + // supplies an API whose absent members cannot be established here. + if (!member || member.name === null || member.name === '__proto__') { + uncertain = true; + continue; + } + if (tokens[member.next]?.value === '=') members.add(member.name); + } + return { members, uncertain }; +} diff --git a/src/resolution/name-matcher.ts b/src/resolution/name-matcher.ts index 767cf61899..bfb5782f2b 100644 --- a/src/resolution/name-matcher.ts +++ b/src/resolution/name-matcher.ts @@ -11,6 +11,7 @@ import { Language, Node, IMPLICIT_RECORD_ACCESSOR_DOC } from '../types'; import { escapeRegExp, escapesRoot } from '../utils'; import { UnresolvedRef, ResolvedRef, ResolutionContext, ImportMapping, isSupertypeTarget, CPP_DEFINE_SIGNATURE, isInheritanceRef, isImportableKind } from './types'; import { blankStringContents, stripCommentsForRegex } from './strip-comments'; +import { readCommonJsExportMembers } from './commonjs-export-members'; import { isJsSuperCallSite } from './js-super-calls'; import { JS_ARRAY_METHODS, JS_BROWSER_HOST_GLOBALS, JS_BUILT_INS, JS_BUILTIN_METHODS, TS_PRIMITIVE_TYPES } from './js-builtins'; import { SWIFT_TYPE_PATH_CALL, resolveSwiftTypePathCall } from './swift-type-visibility'; @@ -27394,15 +27395,8 @@ function defaultModuleNamespace(source: string, from: string, language: Language const next = defaultModuleNamespace(forwarded[1]!, file, language, context, seen); info = { ...next, files: new Set([...files, ...next.files]) }; } else { - // An explicit member may be a callable alias the import resolver cannot - // follow yet. Its presence is not evidence that the member is absent. - for (const m of code.matchAll(/\b(?:module\s*\.\s*)?exports\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"]+)\2\s*\])\s*=(?![=>])/g)) { - members.add(m[1] ?? m[3]!); - } - const uncertain = /\bmodule\b(?!\s*\.\s*exports\s*[.\[])/.test(code) || - /\bexports\b(?!\s*[.\[])/.test(code) || - /\bexports\s*\[(?!\s*(['"])[^'"]+\1\s*\])/.test(code) || members.has('__proto__'); - info = { namespace: !uncertain, members, files }; + const exported = readCommonJsExportMembers(code, /\.(?:[cm]?js|[jt]sx)$/.test(file)); + info = { namespace: !exported.uncertain, members: exported.members, files }; } } // A depth/cycle cutoff says nothing about a shorter lookup of this file. From 4b50700431ce494604872228174e9813f5bb95b3 Mon Sep 17 00:00:00 2001 From: Eric Minish Date: Mon, 9 Nov 2026 09:29:43 -0500 Subject: [PATCH 4/7] fix(resolution): distinguish eval arguments from grouped callees --- __tests__/commonjs-export-members.test.ts | 8 ++++++++ __tests__/js-default-binding-members.test.ts | 12 ++++++++++++ src/resolution/commonjs-export-members.ts | 9 +++++++++ 3 files changed, 29 insertions(+) diff --git a/__tests__/commonjs-export-members.test.ts b/__tests__/commonjs-export-members.test.ts index 9b423f0f07..1e03dd9d09 100644 --- a/__tests__/commonjs-export-members.test.ts +++ b/__tests__/commonjs-export-members.test.ts @@ -36,6 +36,13 @@ describe('CommonJS export member discovery', () => { 'let value: typeof exports.missing = undefined;', 'type Loader = typeof require.cache;', 'class Evaluator { eval(code) {} }', + 'wrap(eval)("ignored");', + 'wrap((eval))(("ignored"));', + '(makeWrap())(eval)("ignored");', + 'wrap["call"](eval)("ignored");', + 'wrap?.(eval)("ignored");', + 'wrap`tag`(eval)("ignored");', + 'if (eval) ("ignored");', ])('ignores non-export text: %s', (source) => { const result = readCommonJsExportMembers(source); expect([...result.members]).toEqual([]); @@ -54,6 +61,7 @@ describe('CommonJS export member discovery', () => { 'eval(`exports.load = ${Store.prototype.load};`);', "(eval)('exports.load = Store.prototype.load;');", "((eval))(('exports.load = Store.prototype.load;'));", + "function setup() { return (eval)('exports.load = Store.prototype.load;'); }", 'require.cache[__filename].exports = new Store();', "const Module = require('node:module');", "import { Module } from 'node:module';", diff --git a/__tests__/js-default-binding-members.test.ts b/__tests__/js-default-binding-members.test.ts index 0628622365..1ea8141170 100644 --- a/__tests__/js-default-binding-members.test.ts +++ b/__tests__/js-default-binding-members.test.ts @@ -285,6 +285,18 @@ describe('a member read through a default binding', () => { expect(callsOf(cg, 'run')).toEqual([]); }); + it.each([ + 'wrap(eval)("ignored");', + 'wrap((eval))(("ignored"));', + ])('does not mistake a wrapped eval argument for a direct eval call: %s', async (call) => { + const cg = await indexProject({ + 'm.js': `exports.known = function known() {};\nfunction wrap(value) { return function ignore(code) {}; }\n${call}\n`, + 'decoy.js': 'export class Decoy { missing() {} }\n', + 'use.js': CALLER("const named = require('./m');", ['missing']), + }); + expect(callsOf(cg, 'run')).toEqual([]); + }); + it.each([ "eval('exports.load = Store.prototype.load;');", 'eval(`exports.load = Store.prototype.load;`);', diff --git a/src/resolution/commonjs-export-members.ts b/src/resolution/commonjs-export-members.ts index 5b1fdf8904..9a1795e206 100644 --- a/src/resolution/commonjs-export-members.ts +++ b/src/resolution/commonjs-export-members.ts @@ -4,6 +4,7 @@ interface LexicalToken { type: string; value: string; closed?: boolean } interface Property { name: string | null; next: number } const TRIVIA = new Set(['WhiteSpace', 'LineTerminatorSequence', 'SingleLineComment', 'MultiLineComment', 'HashbangComment']); +const EXPRESSION_PREFIX_WORDS = new Set(['return', 'throw', 'case', 'delete', 'void', 'typeof', 'new', 'in', 'instanceof', 'else', 'do', 'await', 'yield']); /** Syntactic CommonJS writes, without interpreting their values or executing code. */ export function readCommonJsExportMembers(source: string, jsx = false): { members: ReadonlySet; uncertain: boolean } { @@ -21,6 +22,14 @@ export function readCommonJsExportMembers(source: string, jsx = false): { member before--; after++; } + const prefix = tokens[before]; + // wrap(eval)(code) passes eval as an argument; its parentheses do not + // group the callee. The same applies after a member access or call. + if (after > at + 1 && prefix && ( + (prefix.type === 'IdentifierName' && !EXPRESSION_PREFIX_WORDS.has(prefix.value)) || + prefix.type.endsWith('Literal') || prefix.type === 'NoSubstitutionTemplate' || prefix.type === 'TemplateTail' || + [')', ']', '?.', '++', '--'].includes(prefix.value) + )) return false; if (tokens[after]?.value !== '(') return false; let argument = after + 1; while (tokens[argument]?.value === '(') argument++; From 1ac02803c680f4851846c3a6b8a239feb03316b3 Mon Sep 17 00:00:00 2001 From: Eric Minish Date: Thu, 12 Nov 2026 15:56:57 -0500 Subject: [PATCH 5/7] fix(resolution): follow a forwarding module past its comments A whole-file `module.exports = require('./m')` forwarder was matched on raw text, so a license header or a trailing comment line made it look like other code. The default binding then lost its namespace answer and an absent member fell back to an unrelated class's method by name. Match the forwarder on comment-blanked text instead. --- __tests__/js-default-binding-members.test.ts | 14 ++++++++++++++ src/resolution/name-matcher.ts | 4 +++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/__tests__/js-default-binding-members.test.ts b/__tests__/js-default-binding-members.test.ts index 1ea8141170..1985740726 100644 --- a/__tests__/js-default-binding-members.test.ts +++ b/__tests__/js-default-binding-members.test.ts @@ -129,6 +129,20 @@ describe('a member read through a default binding', () => { expect(callsOf(cg, 'run')).toEqual(['3 m.js:second']); }); + it.each([ + "/* license */\nmodule.exports = require('./m');\n", + "module.exports = require('./m');\n// trailing note\n", + "'use strict'; // forward\nmodule.exports = require('./m');\n/* end */\n", + ])('follows a forwarding module through its comments: %j', async (index) => { + const cg = await indexProject({ + 'm.js': 'exports.second = function second() {};\n', + 'index.js': index, + 'decoy.js': 'export class Decoy { second() {} missing() {} }\n', + 'use.js': CALLER("const named = require('./index');", ['second', 'missing']), + }); + expect(callsOf(cg, 'run')).toEqual(['3 m.js:second']); + }); + it('keeps CommonJS stated class, object, instance and callable exports', async () => { const cg = await indexProject({ 'class.js': 'class Widget { static make() {} }\nmodule.exports = Widget;\n', diff --git a/src/resolution/name-matcher.ts b/src/resolution/name-matcher.ts index bfb5782f2b..7e8b41d039 100644 --- a/src/resolution/name-matcher.ts +++ b/src/resolution/name-matcher.ts @@ -27390,7 +27390,9 @@ function defaultModuleNamespace(source: string, from: string, language: Language // make the effective default uncertain. Named module.exports.x writes // still describe the namespace, whereas any other use of module may // replace it (including computed writes or assignment through an alias). - const forwarded = /^\s*(?:['"]use strict['"];\s*)?(?:exports\s*=\s*)?module\.exports\s*=\s*(?:exports\s*=\s*)?require\(\s*['"]([^'"]+)['"]\s*\)\s*;?\s*$/.exec(code); + // Comments are blanked first: a license header or trailing note is not code. + const forwarded = /^\s*(?:['"]use strict['"];\s*)?(?:exports\s*=\s*)?module\.exports\s*=\s*(?:exports\s*=\s*)?require\(\s*['"]([^'"]+)['"]\s*\)\s*;?\s*$/ + .exec(stripCommentsForRegex(code, language === 'typescript' || language === 'tsx' ? 'typescript' : 'javascript')); if (forwarded) { const next = defaultModuleNamespace(forwarded[1]!, file, language, context, seen); info = { ...next, files: new Set([...files, ...next.files]) }; From a0899253e8dfe032a383b54153b3e2b363460add Mon Sep 17 00:00:00 2001 From: Eric Minish Date: Thu, 12 Nov 2026 17:03:03 -0500 Subject: [PATCH 6/7] fix(resolution): keep CommonJS namespace answers right after generics and syncs A .js module is read in JSX mode, where a Flow or TS generic such as `type Fn = (x: T) => T;` opens an element that never closes and turns the rest of the file into text. A later `module.exports = new Store()` went unseen, the module read as a namespace, and a correct member call was dropped. A read that ends with an element still open is now uncertain. A call the namespace guard leaves unresolved waits under the module key of the binding it goes through. Behind a `module.exports = require('./m')` forwarder that key names the forwarder, so an edit to m.js that made the call resolvable was never retried, and a sync disagreed with a fresh index. The sync's failed-reference retry now adds the keys of the forwarders that reach a changed file. --- __tests__/commonjs-export-members.test.ts | 9 +++++ __tests__/js-default-binding-members.test.ts | 35 ++++++++++++++++++++ src/engine.ts | 1 + src/index.ts | 7 ++++ src/resolution/commonjs-export-members.ts | 30 ++++++++++++++++- src/resolution/module-importers.ts | 35 ++++++++++++++++++++ src/resolution/name-matcher.ts | 10 +++--- 7 files changed, 120 insertions(+), 7 deletions(-) diff --git a/__tests__/commonjs-export-members.test.ts b/__tests__/commonjs-export-members.test.ts index 1e03dd9d09..6c595732d1 100644 --- a/__tests__/commonjs-export-members.test.ts +++ b/__tests__/commonjs-export-members.test.ts @@ -76,4 +76,13 @@ describe('CommonJS export member discovery', () => { expect([...result.members]).toEqual(['load']); expect(result.uncertain).toBe(false); }); + + it.each([ + 'type Fn = (x: T) => T;\nfunction a() {}\nmodule.exports = { a };\n', + 'const id = (x: T): T => x;\nmodule.exports = id;', + 'const id = (x: T) => x;\nexports.id = id;\nmodule.exports = { id }', + 'type Fn = (x: T) => T;\nmodule.exports = function () { return 1; }', + ])('is uncertain when a generic leaves JSX mode reading the rest as text: %j', (source) => { + expect(readCommonJsExportMembers(source, true).uncertain).toBe(true); + }); }); diff --git a/__tests__/js-default-binding-members.test.ts b/__tests__/js-default-binding-members.test.ts index 1985740726..7e19c27d26 100644 --- a/__tests__/js-default-binding-members.test.ts +++ b/__tests__/js-default-binding-members.test.ts @@ -206,6 +206,41 @@ describe('a member read through a default binding', () => { expect(callsOf(cg, 'run')).toEqual([]); }); + it.each([ + ['a Flow generic function type', 'type Fn = (x: T) => T;'], + ['a Flow generic arrow', 'const id = (x: T): T => x;'], + ])('keeps the stated value of a .js module containing %s', async (_shape, line) => { + const cg = await indexProject({ + 'decoy.js': 'class Decoy { second() {} }\nmodule.exports.Decoy = Decoy;\n', + 'm.js': `// @flow\nconst { Decoy } = require('./decoy');\n${line}\nmodule.exports = new Decoy();\n`, + 'use.js': CALLER("const named = require('./m');", ['second']), + }); + expect(callsOf(cg, 'run')).toEqual(['3 decoy.js:Decoy::second']); + }); + + it.each([ + ['directly', {}, './m'], + ['through a forwarding module', { 'index.js': "module.exports = require('./m');\n" }, './index'], + ['through two forwarding modules', { + 'index.js': "module.exports = require('./mid');\n", 'mid.js': "module.exports = require('./m');\n", + }, './index'], + ])('re-resolves a blocked call %s when the module stops being a namespace', async (_how, extra, spec) => { + const files = { + 'decoy.js': 'class Decoy { second() {} }\nmodule.exports.Decoy = Decoy;\n', + ...extra, + 'm.js': 'exports.known = function known() {};\n', + 'use.js': CALLER(`const named = require('${spec}');`, ['second']), + }; + const cg = await indexProject(files); + expect(callsOf(cg, 'run')).toEqual([]); + const value = "const { Decoy } = require('./decoy');\nmodule.exports = new Decoy();\n"; + fs.writeFileSync(path.join(roots[roots.length - 1]!, 'm.js'), value); + await cg.sync(); + const fresh = await indexProject({ ...files, 'm.js': value }); + expect(callsOf(fresh, 'run')).toEqual(['3 decoy.js:Decoy::second']); + expect(callsOf(cg, 'run')).toEqual(callsOf(fresh, 'run')); + }); + it('takes what `module.exports =` states over a neighbour assigned to it', async () => { const cg = await indexProject({ 'm.js': 'function main() {}\nmodule.exports = main;\nmodule.exports.extra = function () {};\n', diff --git a/src/engine.ts b/src/engine.ts index 8661815b93..ebd1a4a6c9 100644 --- a/src/engine.ts +++ b/src/engine.ts @@ -11,6 +11,7 @@ export { hasSynthesisPattern, isJsxChildCandidate } from './resolution/callback- export { aliasMayName } from './resolution/const-alias-synthesizer'; export { ESM_IMPORT_LANGUAGES } from './resolution/import-resolver'; export { + commonJsForwarderKeys, createImportReader, reopenNameMatchedImports, reopenReferencesThroughAddedFiles, diff --git a/src/index.ts b/src/index.ts index 0283988f87..1181d25d48 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1135,6 +1135,7 @@ export class CodeGraph { aliasMayName, changedModuleConfigs, changedRoutes, + commonJsForwarderKeys, createImportReader, hasSynthesisPattern, isJsxChildCandidate, @@ -1469,6 +1470,12 @@ export class CodeGraph { const retryable = this.queries.getRetryableFailedReferences([...new Set([ ...this.queries.getNodeNamesByFiles(result.changedFilePaths), ...result.changedFilePaths.flatMap(moduleReferenceKeys), + // And through a whole-file `module.exports = require(...)` + // forwarder of a changed file, which a member call through the + // forwarder waits under (`module:index` for `m.js`). + ...commonJsForwarderKeys(this.queries, (file) => { + try { return fs.readFileSync(path.join(this.projectRoot, file), 'utf8'); } catch { return null; } + }, result.changedFilePaths), ])]); // A failed import waits for a file, a folder or a namespace, not a // symbol: `package:app/b.dart` for a file named `b.dart`, `./ui` diff --git a/src/resolution/commonjs-export-members.ts b/src/resolution/commonjs-export-members.ts index 9a1795e206..7b1b529d0e 100644 --- a/src/resolution/commonjs-export-members.ts +++ b/src/resolution/commonjs-export-members.ts @@ -1,4 +1,17 @@ import jsTokens from 'js-tokens'; +import { stripCommentsForRegex } from './strip-comments'; + +/** + * The module a whole-file CommonJS forwarder (`module.exports = + * require('./m')`, optionally after `'use strict'`) hands on, or null when + * the file holds anything else. Comments are blanked first: a license header + * or trailing note is not code. + */ +export function readCommonJsForwarder(code: string, typescript: boolean): string | null { + const text = stripCommentsForRegex(code, typescript ? 'typescript' : 'javascript'); + return /^\s*(?:['"]use strict['"];\s*)?(?:exports\s*=\s*)?module\.exports\s*=\s*(?:exports\s*=\s*)?require\(\s*['"]([^'"]+)['"]\s*\)\s*;?\s*$/ + .exec(text)?.[1] ?? null; +} interface LexicalToken { type: string; value: string; closed?: boolean } interface Property { name: string | null; next: number } @@ -6,11 +19,26 @@ interface Property { name: string | null; next: number } const TRIVIA = new Set(['WhiteSpace', 'LineTerminatorSequence', 'SingleLineComment', 'MultiLineComment', 'HashbangComment']); const EXPRESSION_PREFIX_WORDS = new Set(['return', 'throw', 'case', 'delete', 'void', 'typeof', 'new', 'in', 'instanceof', 'else', 'do', 'await', 'yield']); +/** Does the token stream end with a JSX element or fragment still open? */ +function unclosedJsx(tokens: readonly LexicalToken[]): boolean { + let depth = 0; + const punct = (t: LexicalToken | undefined, value: string): boolean => t?.type === 'JSXPunctuator' && t.value === value; + for (let i = 0; i < tokens.length; i++) { + if (punct(tokens[i], '<')) depth += punct(tokens[i + 1], '/') ? -1 : 1; + // `/>` ends a self-closing element; the `/` of `') && !punct(tokens[i - 1], '<')) depth--; + } + return depth > 0; +} + /** Syntactic CommonJS writes, without interpreting their values or executing code. */ export function readCommonJsExportMembers(source: string, jsx = false): { members: ReadonlySet; uncertain: boolean } { const tokens: LexicalToken[] = [...jsTokens(source, { jsx })].filter((t) => !TRIVIA.has(t.type)); const members = new Set(); - let uncertain = false; + // JSX mode reads `(x) =>` (a Flow or TS generic) as an element that never + // closes, so the rest of the file, a `module.exports =` included, becomes + // its text. A file that ends with an element still open was not read as code. + let uncertain = jsx && unclosedJsx(tokens); const moduleApi = (token: LexicalToken | undefined): boolean => token?.type === 'StringLiteral' && (token.value.slice(1, -1) === 'module' || token.value.slice(1, -1) === 'node:module'); diff --git a/src/resolution/module-importers.ts b/src/resolution/module-importers.ts index 2f23150170..aff1688918 100644 --- a/src/resolution/module-importers.ts +++ b/src/resolution/module-importers.ts @@ -27,6 +27,7 @@ import { resurrectRefFromDroppedEdge } from './resurrect-ref'; import { defaultExportBinding, extractLocalExportAliases } from './alias-binding'; import { isDeclarationFile, scanAmbientModules } from './ambient-modules'; import { moduleReferenceKeys } from '../db/reference-tail'; +import { readCommonJsForwarder } from './commonjs-export-members'; /** * Languages whose import bindings name what their references are written as: @@ -834,3 +835,37 @@ function pythonImportNamesFor(modulePath: string): string[] { } return [...names]; } + +const COMMONJS_FORWARDER_LANGUAGES = new Set(['javascript', 'jsx', 'typescript', 'tsx']); + +/** + * The module keys of the whole-file CommonJS forwarders (`module.exports = + * require('./m')`) that hand one of `files` on, followed up as deep as the + * resolver follows them. A member call through `require('./index')` whose + * answer depends on what `m.js` is waits under `module:index`, which an edit + * to `m.js` alone never names; the sync's failed-reference retry adds these. + */ +export function commonJsForwarderKeys( + queries: QueryBuilder, + readFile: (file: string) => string | null, + files: readonly string[], +): string[] { + const keys = new Set(); + const seen = new Set(files); + let level = [...files]; + for (let depth = 0; depth < 8 && level.length > 0; depth++) { + const next: string[] = []; + for (const file of level) { + for (const i of queries.getImportsInto(`file:${file}`, file)) { + if (seen.has(i.filePath) || !COMMONJS_FORWARDER_LANGUAGES.has(i.language)) continue; + seen.add(i.filePath); + const code = readFile(i.filePath); + if (code === null || readCommonJsForwarder(code, i.language === 'typescript' || i.language === 'tsx') === null) continue; + for (const key of moduleReferenceKeys(i.filePath)) keys.add(key); + next.push(i.filePath); + } + } + level = next; + } + return [...keys]; +} diff --git a/src/resolution/name-matcher.ts b/src/resolution/name-matcher.ts index 7e8b41d039..1767cd0564 100644 --- a/src/resolution/name-matcher.ts +++ b/src/resolution/name-matcher.ts @@ -11,7 +11,7 @@ import { Language, Node, IMPLICIT_RECORD_ACCESSOR_DOC } from '../types'; import { escapeRegExp, escapesRoot } from '../utils'; import { UnresolvedRef, ResolvedRef, ResolutionContext, ImportMapping, isSupertypeTarget, CPP_DEFINE_SIGNATURE, isInheritanceRef, isImportableKind } from './types'; import { blankStringContents, stripCommentsForRegex } from './strip-comments'; -import { readCommonJsExportMembers } from './commonjs-export-members'; +import { readCommonJsExportMembers, readCommonJsForwarder } from './commonjs-export-members'; import { isJsSuperCallSite } from './js-super-calls'; import { JS_ARRAY_METHODS, JS_BROWSER_HOST_GLOBALS, JS_BUILT_INS, JS_BUILTIN_METHODS, TS_PRIMITIVE_TYPES } from './js-builtins'; import { SWIFT_TYPE_PATH_CALL, resolveSwiftTypePathCall } from './swift-type-visibility'; @@ -27390,11 +27390,9 @@ function defaultModuleNamespace(source: string, from: string, language: Language // make the effective default uncertain. Named module.exports.x writes // still describe the namespace, whereas any other use of module may // replace it (including computed writes or assignment through an alias). - // Comments are blanked first: a license header or trailing note is not code. - const forwarded = /^\s*(?:['"]use strict['"];\s*)?(?:exports\s*=\s*)?module\.exports\s*=\s*(?:exports\s*=\s*)?require\(\s*['"]([^'"]+)['"]\s*\)\s*;?\s*$/ - .exec(stripCommentsForRegex(code, language === 'typescript' || language === 'tsx' ? 'typescript' : 'javascript')); - if (forwarded) { - const next = defaultModuleNamespace(forwarded[1]!, file, language, context, seen); + const forwarded = readCommonJsForwarder(code, language === 'typescript' || language === 'tsx'); + if (forwarded !== null) { + const next = defaultModuleNamespace(forwarded, file, language, context, seen); info = { ...next, files: new Set([...files, ...next.files]) }; } else { const exported = readCommonJsExportMembers(code, /\.(?:[cm]?js|[jt]sx)$/.test(file)); From c6bb300be9d103d7ba14f2d10eb4a14e27397eb4 Mon Sep 17 00:00:00 2001 From: Eric Minish Date: Tue, 17 Nov 2026 06:40:37 -0500 Subject: [PATCH 7/7] fix(resolution): read a .js file with JSX in plain mode too, for CommonJS writes A Flow or TS generic such as `type Fn = (x: T) => T;` reads as a JSX element in JSX mode, and a `` later in a comment or string closes it, so the file looked fully read while `module.exports = new Decoy()` sat in the swallowed text. The module read as a namespace and a correct member call was dropped. A file with any JSX is now read in plain mode as well: either read being uncertain makes it uncertain, and a member either read sees is a member. Both only hand the file back to the resolution it had before. A whole-file forwarder needs both `require(` and `exports`, so files without them skip the comment strip (the sync's forwarder walk reads every importer). --- __tests__/commonjs-export-members.test.ts | 20 ++++++++++++-- __tests__/js-default-binding-members.test.ts | 24 +++++++++++++--- src/resolution/commonjs-export-members.ts | 29 ++++++++++++++++---- 3 files changed, 62 insertions(+), 11 deletions(-) diff --git a/__tests__/commonjs-export-members.test.ts b/__tests__/commonjs-export-members.test.ts index 6c595732d1..e9177d22ce 100644 --- a/__tests__/commonjs-export-members.test.ts +++ b/__tests__/commonjs-export-members.test.ts @@ -70,10 +70,12 @@ describe('CommonJS export member discovery', () => { expect(readCommonJsExportMembers(source).uncertain).toBe(true); }); - it('ignores JSX text but keeps assignments in JSX expressions', () => { + it('keeps assignments in JSX expressions, and counts a write in JSX text too', () => { + // The plain-mode read (see the generic cases below) sees JSX text as code. + // An extra member only hands that name back to ordinary resolution. const source = '
exports.missing = fake{exports.load = Store.prototype.load}
'; const result = readCommonJsExportMembers(source, true); - expect([...result.members]).toEqual(['load']); + expect([...result.members].sort()).toEqual(['load', 'missing']); expect(result.uncertain).toBe(false); }); @@ -85,4 +87,18 @@ describe('CommonJS export member discovery', () => { ])('is uncertain when a generic leaves JSX mode reading the rest as text: %j', (source) => { expect(readCommonJsExportMembers(source, true).uncertain).toBe(true); }); + + it.each([ + 'type Fn = (x: T) => T;\nmodule.exports = new Store();\n// renders here', + "type Fn = (x: T) => T;\nmodule.exports = new Store();\nconst tag = '

';", + 'type Fn = (x: T) => T;\nmodule.exports = new Store();\n/** @example */', + 'const id = (x: T): T => x;\nmodule[name] = id;\nconst el =
;', + ])('stays uncertain when a later closing tag balances a generic: %j', (source) => { + expect(readCommonJsExportMembers(source, true).uncertain).toBe(true); + }); + + it('counts a write a generic hides from the JSX read', () => { + const source = 'type Fn = (x: T) => T;\nexports.second = second;\n// '; + expect(readCommonJsExportMembers(source, true).members.has('second')).toBe(true); + }); }); diff --git a/__tests__/js-default-binding-members.test.ts b/__tests__/js-default-binding-members.test.ts index 7e19c27d26..fc0001810c 100644 --- a/__tests__/js-default-binding-members.test.ts +++ b/__tests__/js-default-binding-members.test.ts @@ -207,17 +207,33 @@ describe('a member read through a default binding', () => { }); it.each([ - ['a Flow generic function type', 'type Fn = (x: T) => T;'], - ['a Flow generic arrow', 'const id = (x: T): T => x;'], - ])('keeps the stated value of a .js module containing %s', async (_shape, line) => { + ['a Flow generic function type', 'type Fn = (x: T) => T;', ''], + ['a Flow generic arrow', 'const id = (x: T): T => x;', ''], + // A closing tag later in the file must not make the swallowed text read as closed. + ['a generic and a closing tag in a comment', 'type Fn = (x: T) => T;', '// renders here\n'], + ['a generic and a closing tag in a string', 'type Fn = (x: T) => T;', "const tag = '

';\n"], + ['a generic and a closing tag in a doc comment', 'type Fn = (x: T) => T;', '/** @example */\n'], + ])('keeps the stated value of a .js module containing %s', async (_shape, line, tail) => { const cg = await indexProject({ 'decoy.js': 'class Decoy { second() {} }\nmodule.exports.Decoy = Decoy;\n', - 'm.js': `// @flow\nconst { Decoy } = require('./decoy');\n${line}\nmodule.exports = new Decoy();\n`, + 'm.js': `// @flow\nconst { Decoy } = require('./decoy');\n${line}\nmodule.exports = new Decoy();\n${tail}`, 'use.js': CALLER("const named = require('./m');", ['second']), }); expect(callsOf(cg, 'run')).toEqual(['3 decoy.js:Decoy::second']); }); + it.each([ + ['its own function', 'function second() {}\nexports.second = second;', '3 m.js:second'], + ["a class's method", "const { Decoy } = require('./decoy');\nexports.second = Decoy.prototype.second;", '3 decoy.js:Decoy::second'], + ])('keeps an export of %s that a Flow generic hides from the JSX read, behind a later closing tag', async (_shape, body, edge) => { + const cg = await indexProject({ + 'decoy.js': 'class Decoy { second() {} }\nmodule.exports.Decoy = Decoy;\n', + 'm.js': `// @flow\ntype Fn = (x: T) => T;\n${body}\n// renders here\n`, + 'use.js': CALLER("const named = require('./m');", ['second']), + }); + expect(callsOf(cg, 'run')).toEqual([edge]); + }); + it.each([ ['directly', {}, './m'], ['through a forwarding module', { 'index.js': "module.exports = require('./m');\n" }, './index'], diff --git a/src/resolution/commonjs-export-members.ts b/src/resolution/commonjs-export-members.ts index 7b1b529d0e..cd9650d742 100644 --- a/src/resolution/commonjs-export-members.ts +++ b/src/resolution/commonjs-export-members.ts @@ -8,6 +8,8 @@ import { stripCommentsForRegex } from './strip-comments'; * or trailing note is not code. */ export function readCommonJsForwarder(code: string, typescript: boolean): string | null { + // Blanking comments never creates these, so a file without both is no forwarder. + if (!code.includes('require(') || !code.includes('exports')) return null; const text = stripCommentsForRegex(code, typescript ? 'typescript' : 'javascript'); return /^\s*(?:['"]use strict['"];\s*)?(?:exports\s*=\s*)?module\.exports\s*=\s*(?:exports\s*=\s*)?require\(\s*['"]([^'"]+)['"]\s*\)\s*;?\s*$/ .exec(text)?.[1] ?? null; @@ -31,14 +33,31 @@ function unclosedJsx(tokens: readonly LexicalToken[]): boolean { return depth > 0; } -/** Syntactic CommonJS writes, without interpreting their values or executing code. */ +/** + * Syntactic CommonJS writes, without interpreting their values or executing code. + * + * JSX mode reads `(x) =>` (a Flow or TS generic) as an element, so what + * follows, a `module.exports =` included, can become its text. A file that + * ends with an element still open was not read as code; neither was one where + * a `` in a later comment or string closes that element. So a file with + * any JSX is read in plain mode too: what either read finds uncertain is + * uncertain, and a member either read sees is a member. Both directions only + * hand the file back to the resolution it had without this reader. + */ export function readCommonJsExportMembers(source: string, jsx = false): { members: ReadonlySet; uncertain: boolean } { const tokens: LexicalToken[] = [...jsTokens(source, { jsx })].filter((t) => !TRIVIA.has(t.type)); + if (!jsx || !tokens.some((t) => t.type.startsWith('JSX'))) return readTokens(tokens); + const jsxRead = readTokens(tokens); + const plainRead = readCommonJsExportMembers(source, false); + return { + members: new Set([...jsxRead.members, ...plainRead.members]), + uncertain: jsxRead.uncertain || plainRead.uncertain || unclosedJsx(tokens), + }; +} + +function readTokens(tokens: readonly LexicalToken[]): { members: ReadonlySet; uncertain: boolean } { const members = new Set(); - // JSX mode reads `(x) =>` (a Flow or TS generic) as an element that never - // closes, so the rest of the file, a `module.exports =` included, becomes - // its text. A file that ends with an element still open was not read as code. - let uncertain = jsx && unclosedJsx(tokens); + let uncertain = false; const moduleApi = (token: LexicalToken | undefined): boolean => token?.type === 'StringLiteral' && (token.value.slice(1, -1) === 'module' || token.value.slice(1, -1) === 'node:module');