Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- A `fetch` or HTTP-client call to another company's API, like `fetch('https://api.github.com/users/…')`, no longer links to your own server's route with the same path; a call to localhost, to a host your code fills in, or through a client's base URL still links. Thanks @inth3shadows for the report and @johnhldiver-beep. (#2974)
- In JavaScript and TypeScript, a call or `new` of a global, like `parseInt(…)`, `new Response(…)` or `new URL(…)`, in a module that doesn't import that name no longer links to a same-named export of another file in your project. Thanks @inth3shadows for the report. (#3238)
- In JavaScript, a `require()` of a folder by a relative path, like `require('..')` from a package's tests, now loads the file the folder's `package.json` names as `main`, as Node does, so calls through it link to the function that file exports. Before, a folder without an `index.js` wasn't followed, and the call linked to the variable holding the `require()` result; on fastify, every test's `Fastify()` linked to its own test file. Thanks @inth3shadows for the report. (#2964)
- In JavaScript, a variable that holds what a required module's function returns, like `const app = require('./app')()`, no longer counts as the module itself, so a call like `app.listen()` no longer links to the module's factory function, and links to the method of the class the factory returns when that is known. Thanks @inth3shadows for the report. (#2964)

## [1.6.3] - 2026-11-17

Expand Down
87 changes: 87 additions & 0 deletions __tests__/require-call-result.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/**
* A local that holds what a required module's function returns is not the
* module.
*
* `const fastify = require('..')()` was read as binding `fastify` to the
* module, for the whole file, so every `fastify.get(…)`, `fastify.listen(…)`
* in it linked to the `fastify()` factory itself: 101 such calls in fastify's
* examples, and with #2964's `require('..')` resolved, about 400 across its
* tests. The call's value is now typed by what the module's function returns,
* when that is known, and is no binding of the module otherwise. A package's
* call result (`require('debug')('app')`) stays bound to the package, which
* keeps a name match off it.
*/
import { describe, it, expect, afterEach } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { CodeGraph } from '../src';

let roots: string[] = [];
let graphs: CodeGraph[] = [];

afterEach(() => {
for (const graph of graphs) graph.close();
graphs = [];
for (const root of roots) fs.rmSync(root, { recursive: true, force: true });
roots = [];
});

async function index(files: Record<string, string>): Promise<CodeGraph> {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-require-call-'));
roots.push(root);
for (const [rel, content] of Object.entries(files)) {
const file = path.join(root, rel);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
}
const graph = await CodeGraph.init(root, { index: true });
graphs.push(graph);
return graph;
}

/** `caller -> file:qualifiedName` for every `calls` edge out of `file`. */
function callsFrom(graph: CodeGraph, file: string): string[] {
const out: string[] = [];
for (const node of graph.getNodesInFile(file)) {
for (const e of graph.getOutgoingEdges(node.id)) {
if (e.kind !== 'calls') continue;
const target = graph.getNode(e.target)!;
out.push(`${node.name} -> ${target.filePath}:${target.qualifiedName}`);
}
}
return out.sort();
}

describe("a local holding a required module's call result", () => {
it('is not the module, so its members are no calls of the factory', async () => {
const graph = await index({
'app.js': "'use strict'\nfunction app (opts) {\n const instance = { get () {}, listen () {} }\n return instance\n}\nmodule.exports = app\n",
// fastify's tests: one test gets its instance from the call, another from a binding of the factory.
'test/a.test.js':
"'use strict'\nconst App = require('../app')\n" +
"function one () { const server = require('../app')(); server.get('/'); server.listen() }\n" +
"function two () { const server = App(); server.get('/') }\n",
});
expect(callsFrom(graph, 'test/a.test.js')).toEqual(['two -> app.js:app']);
}, 120_000);

it("is typed by what the module's function returns, when that is known", async () => {
const graph = await index({
'factory.js':
"class Server {\n listen () { return 1 }\n}\nfunction create () { return new Server() }\nmodule.exports = create\n",
'use.js': "const srv = require('./factory')()\nfunction run () { return srv.listen() }\nmodule.exports = run\n",
'other.js': 'class Decoy {\n listen () { return 2 }\n}\nmodule.exports = Decoy\n',
});
expect(callsFrom(graph, 'use.js')).toEqual(['run -> factory.js:Server::listen']);
}, 120_000);

it("keeps a package's call result bound to the package", async () => {
const graph = await index({
'package.json': JSON.stringify({ name: 'app', dependencies: { debug: '^4.0.0' } }),
'log.js': "const debug = require('debug')('app')\nfunction log () { debug('x') }\nmodule.exports = log\n",
'mine.js': 'function debug (m) { return m }\nmodule.exports = debug\n',
});
expect(callsFrom(graph, 'log.js')).toEqual([]);
}, 120_000);
});
6 changes: 6 additions & 0 deletions src/resolution/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2226,6 +2226,12 @@ function extractJSImports(content: string): ImportMapping[] {
const requireRegex = /(?:\b(?:const|let|var)\s+|,\s*)(?:([A-Za-z_$][\w$]*)|{([^}]+)})\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)(?:\s*\.\s*([A-Za-z_$][\w$]*))?/g;
while ((match = requireRegex.exec(content)) !== null) {
const [, defaultName, destructured, source, member] = match;
// `const app = require('./app')(opts)` holds what the module's export
// returns, not the module: a member of it is no export of the module's
// (the call's type, when known, is read where the local is declared). A
// package's call result stays bound to the package, which keeps a name
// match off it, as before.
if (source!.startsWith('.') && /^\s*\(/.test(content.slice(requireRegex.lastIndex, requireRegex.lastIndex + 40))) continue;

if (defaultName) {
mappings.push({
Expand Down
45 changes: 42 additions & 3 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15342,7 +15342,12 @@ const LOCAL_BINDING_PATTERNS = new Map<string, LocalBindingPatterns>();
const LOCAL_BINDING_PATTERNS_CAP = 4096;
const JS_BINDING_NAME = /^[\w$]+$/;
const ARROW_HEAD_CHAR = /[\w$.]/;
const IMPORT_BINDING_VALUE = /^\s*(?:await\s+)?(?:require|import)\s*\(/;
/**
* A declaration's value that binds an import: `require('./m')`, `await
* import('./m')`. Not a required module's export called on the spot,
* `require('./app')(opts)`: that is a local holding the call's result.
*/
const IMPORT_BINDING_VALUE = /^\s*(?:await\s+)?(?:import\s*\(|require\s*\((?!\s*(['"])[^'"\n]*\1\s*\)\s*\())/;

// The balanced groups a parameter's type or default can hold, two levels deep.
const PARAM_PAREN = '\\((?:[^()]|\\([^()]*\\))*\\)';
Expand Down Expand Up @@ -26375,6 +26380,26 @@ const JS_CALL_DECLARATION = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:([A
/** Bare calls whose value no project function's signature gives. */
const JS_NOT_TYPED_CALLEE = new Set(['require', 'import', 'await', 'typeof', 'new', 'function', 'async', 'super']);

/** `require('./app')(` opening a value: a project module's export, called. Group 2 is the specifier. */
const JS_CALLED_REQUIRE = /^require\s*\(\s*(['"])(\.[^'"]*)\1\s*\)\s*\(/;

/**
* The function a project module exports as the whole module or its default
* (`module.exports = create`, `export default function create`), which
* `require('./m')(…)` calls; null unless the index holds one function of the
* name there.
*/
function requiredModuleFunction(specifier: string, where: UnresolvedRef, context: ResolutionContext): Node | null {
const file = context.resolveModuleFile?.(specifier, where.filePath, where.language);
if (!file) return null;
const source = context.readFile(file) ?? '';
const name = /(?:^|[^\w$.])module\.exports\s*=\s*(?:(?:async\s+)?function\s*\*?\s*)?([A-Za-z_$][\w$]*)\s*[;(\r\n]/m.exec(source)?.[1] ??
/^[ \t]*export\s+default\s+(?:(?:async\s+)?function\s*\*?\s*)?([A-Za-z_$][\w$]*)/m.exec(source)?.[1];
if (!name) return null;
const fns = (context.getNodesInFileNamed?.(file, name) ?? context.getNodesInFile(file)).filter((n) => n.kind === 'function' && n.name === name);
return fns.length === 1 && fns[0]!.signature && ESM_FAMILY.has(fns[0]!.language) ? fns[0]! : null;
}

/**
* The names a JS/TS file may type from another declaration's signature
* (jsReceiverReadElsewhere), read off the raw text at the file's arrows,
Expand Down Expand Up @@ -26409,7 +26434,10 @@ function jsReceiverCandidates(filePath: string, language: Language, context: Res
for (const at of sites.varDecls) {
JS_CALL_DECLARATION.lastIndex = at;
const m = JS_CALL_DECLARATION.exec(source);
if (m && !(m[2] && (JS_NOT_TYPED_CALLEE.has(m[2]) || !callees.has(m[2])))) calls.add(m[1]!);
// `require('./app')(opts)`: what the module's function returns (tsValueType).
const calledRequire = m?.[2] === 'require' &&
JS_CALLED_REQUIRE.test(source.slice(at + m[0].lastIndexOf('require'), at + m[0].length + 300));
if (m && (calledRequire || !(m[2] && (JS_NOT_TYPED_CALLEE.has(m[2]) || !callees.has(m[2]))))) calls.add(m[1]!);
}
// A function at `fnStart` with parameters in source[open..close], when a
// call by a bare name the file imports or declares takes it: its untyped
Expand Down Expand Up @@ -26715,7 +26743,18 @@ function tsValueType(file: JsScopeFile, at: number, where: UnresolvedRef, contex
if (!match || (top && made)) return null;
const open = at + lead + match[0].length - 1;
const close = jsCloseOf(code, open);
if (close < 0 || !JS_WHOLE_VALUE_END.test(code.slice(close + 1, close + 200))) return null;
if (close < 0) return null;
// `require('./app')(opts)`: what the function the module exports returns.
if (!made && called![1] === 'require' && !called![2]) {
const required = JS_CALLED_REQUIRE.exec((context.readFile(where.filePath) ?? '').slice(at + lead, at + lead + 300));
const callOpen = required ? at + lead + required[0].length - 1 : -1;
const callClose = callOpen < 0 ? -1 : jsCloseOf(code, callOpen);
if (callClose < 0 || !JS_WHOLE_VALUE_END.test(code.slice(callClose + 1, callClose + 200))) return null;
const fn = requiredModuleFunction(required![2]!, where, context);
const read = fn ? tsReturnedType(fn, context, walk) : null;
return read && { ...read, from: [...read.from, fn!.filePath] };
}
if (!JS_WHOLE_VALUE_END.test(code.slice(close + 1, close + 200))) return null;
if (made) {
const raw = made[1]!.replace(/\s+/g, '');
// `new Backend(root)` of a parameter or a local names no class (jsDeclarationReading).
Expand Down