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 @@ -72,6 +72,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- In JavaScript and TypeScript, a call on a local variable declared after another one in the same statement, like `let n = 0, ob = make()`, or beside a default in a destructuring, like `const { ob = make() } = o`, links again when a variable of the same name outside the function holds a library's type, as it did before 1.6.3. Thanks @inth3shadows for the report and @mohitdixit02. (#3293)
- In JavaScript, a call to a member a required module of your project doesn't have, like `utils.missing()` after `const utils = require('./utils')`, no longer links to an unrelated class's method of that name. Thanks @inth3shadows for the report and @johnhldiver-beep. (#3272)
- 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)

## [1.6.3] - 2026-11-17

Expand Down
116 changes: 116 additions & 0 deletions __tests__/js-unimported-global-calls.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* A call or `new` of a standard global that an ES module neither declares nor
* imports is the runtime's (#3238).
*
* `parseInt(s, 10)` and `new Response('ok')` in a module with no such import
* linked to a project export of that name in another file, exact-match: the
* short built-ins list missed them, and the name fell through to a
* project-wide match. A standard global (ECMAScript's, the web platform's) in
* an ES module is now the module's own declaration, a global one (a script's
* top level, `declare global`, a polyfill hung on `window`) or the runtime's,
* never another module's export, which only an import reaches. Any other
* name keeps the name match as a fallback, and a script (no import or export)
* still shares its top level with other scripts.
*/
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-unimported-globals-'));
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 -kind-> file:name` for every call and instantiation out of `file`. */
function linksFrom(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' && e.kind !== 'instantiates') continue;
const target = graph.getNode(e.target)!;
out.push(`${node.name} -${e.kind}-> ${target.filePath}:${target.name}`);
}
}
return out.sort();
}

const DECOYS =
'export function parseInt(s: string) { return s.length; }\nexport class Response { constructor(_body: string) {} }\n' +
'export function structuredClone(x: unknown) { return x; }\nexport class URL { constructor(_u: string) {} }\n';

describe('a standard global an ES module neither declares nor imports', () => {
it("links no other module's export of that name (#3238)", async () => {
const graph = await index({
// The issue's reproduction, and two more globals it lists.
'lib/other.ts': DECOYS,
'use.ts':
'export function parse(s: string) { return parseInt(s, 10); }\n' +
"export function reply() { return new Response('ok'); }\n" +
'export function stamp() { return Date.now(); }\n' +
'export function copy(x: object) { return structuredClone(x); }\n' +
"export function link() { return new URL('x'); }\n",
// The same from JavaScript, an ES module too.
'use.js': 'export function parse(s) { return parseInt(s, 10); }\n',
});
expect(linksFrom(graph, 'use.ts')).toEqual([]);
expect(linksFrom(graph, 'use.js')).toEqual([]);
}, 120_000);

it("still links the module's own, an imported, and a global declaration of the name", async () => {
const graph = await index({
'lib/other.ts': DECOYS,
// Polyfills: a script's top level is the global scope; so is `declare global`.
'polyfills/atob.js': 'function atob(s) { return s; }\n',
'types/global.d.ts': 'export {};\ndeclare global {\n function queueMicrotask(cb: () => void): void;\n}\n',
'polyfills/btoa.js': 'export const installed = true;\nwindow.btoa = function btoa(s) { return s; };\n',
'own.ts': "class Event { constructor(readonly type: string) {} }\nexport function fire() { return new Event('x'); }\n",
'imported.ts': "import { parseInt } from './lib/other';\nexport function parse(s: string) { return parseInt(s); }\n",
'globals.ts':
"export function decode(s: string) { return atob(s); }\n" +
'export function later(cb: () => void) { return queueMicrotask(cb); }\n' +
"export function load() { return btoa('x'); }\n",
// A script calling another script's top-level function.
'scripts/page.js': 'function boot() { return atob("x"); }\n',
// A name a parameter binds is no global: here a dynamic import's export.
'lazy.ts': "export function later() { return import('./lib/other').then(({ URL }) => new URL('x')); }\n",
});
expect(linksFrom(graph, 'own.ts')).toEqual(['fire -instantiates-> own.ts:Event']);
expect(linksFrom(graph, 'imported.ts')).toEqual(['parse -calls-> lib/other.ts:parseInt']);
expect(linksFrom(graph, 'globals.ts')).toEqual([
'decode -calls-> polyfills/atob.js:atob',
'later -calls-> types/global.d.ts:queueMicrotask',
'load -calls-> polyfills/btoa.js:btoa',
]);
expect(linksFrom(graph, 'scripts/page.js')).toEqual(['boot -calls-> polyfills/atob.js:atob']);
expect(linksFrom(graph, 'lazy.ts')).toEqual(['later -instantiates-> lib/other.ts:URL']);
}, 120_000);

it("keeps an app's auto-imported exports linked by name, and any other name's match", async () => {
const graph = await index({
'package.json': JSON.stringify({ name: 'app', dependencies: { nuxt: '^3.0.0' } }),
'composables/useRequest.ts': 'export class Request { constructor(readonly url: string) {} }\n',
'utils/format.ts': "export function make() { return new Request('x'); }\n",
});
expect(linksFrom(graph, 'utils/format.ts')).toEqual(['make -instantiates-> composables/useRequest.ts:Request']);
}, 120_000);
});
32 changes: 32 additions & 0 deletions src/resolution/js-builtins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,38 @@ export const JS_ARRAY_METHODS = new Set([
'propertyIsEnumerable',
]);

/**
* The standard globals a script reaches by name in every JavaScript runtime
* it commonly runs on: ECMAScript's own (`parseInt`, `Uint8Array`, `Proxy`),
* and the web platform's that browsers, Node, Deno and workers share
* (`Response`, `URL`, `TextEncoder`, `structuredClone`), plus the browser's
* common constructors and functions. A call or `new` of one in an ES module
* that neither declares nor imports the name is the global (#3238).
*/
export const JS_STANDARD_GLOBALS = new Set([
// ECMAScript.
'AggregateError', 'Array', 'ArrayBuffer', 'Atomics', 'BigInt', 'BigInt64Array', 'BigUint64Array',
'Boolean', 'DataView', 'Date', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent',
'Error', 'escape', 'eval', 'EvalError', 'FinalizationRegistry', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Intl', 'isFinite', 'isNaN', 'Iterator', 'JSON',
'Map', 'Math', 'Number', 'Object', 'parseFloat', 'parseInt', 'Promise', 'Proxy', 'RangeError',
'ReferenceError', 'Reflect', 'RegExp', 'Set', 'SharedArrayBuffer', 'String', 'Symbol', 'SyntaxError',
'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'unescape', 'URIError',
'WeakMap', 'WeakRef', 'WeakSet',
// The web platform, as browsers, Node, Deno and workers all have it.
'AbortController', 'AbortSignal', 'atob', 'Blob', 'BroadcastChannel', 'btoa',
'ByteLengthQueuingStrategy', 'clearInterval', 'clearTimeout', 'CompressionStream',
'CountQueuingStrategy', 'CustomEvent', 'DecompressionStream', 'DOMException', 'Event', 'EventTarget',
'fetch', 'File', 'FormData', 'Headers', 'MessageChannel', 'MessageEvent', 'MessagePort',
'queueMicrotask', 'ReadableStream', 'Request', 'Response', 'setInterval', 'setTimeout',
'structuredClone', 'TextDecoder', 'TextDecoderStream', 'TextEncoder', 'TextEncoderStream',
'TransformStream', 'URL', 'URLSearchParams', 'WebAssembly', 'WebSocket', 'WritableStream',
// The browser's.
'alert', 'cancelAnimationFrame', 'ClipboardItem', 'confirm', 'DOMParser', 'FileReader', 'getComputedStyle',
'Image', 'IntersectionObserver', 'matchMedia', 'MutationObserver', 'prompt', 'requestAnimationFrame',
'requestIdleCallback', 'ResizeObserver', 'Worker', 'XMLHttpRequest', 'XMLSerializer',
]);

/**
* TypeScript primitive type names. Distinct from JS_BUILT_INS on purpose: those
* are runtime globals a receiver can be constructed from, these only ever come
Expand Down
79 changes: 78 additions & 1 deletion src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ 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 { 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 { JS_ARRAY_METHODS, JS_BROWSER_HOST_GLOBALS, JS_BUILT_INS, JS_BUILTIN_METHODS, JS_STANDARD_GLOBALS, TS_PRIMITIVE_TYPES } from './js-builtins';
import { SWIFT_TYPE_PATH_CALL, resolveSwiftTypePathCall } from './swift-type-visibility';
import { dartImportPrefixes, dartLibrarySees, dartPrefixSees, dartPrivateVisible, inSameDartLibrary } from './dart-libraries';
import { isDartLocallyBound } from './dart-local-scope';
Expand Down Expand Up @@ -2189,6 +2189,77 @@ function isTsTypeInScope(n: Node, ref: UnresolvedRef, context: ResolutionContext
return scope.globalWords.has(`${n.startLine}:${n.startColumn}`);
}

/**
* The packages that make a project's own exports callable by a bare name with
* no import written: Nuxt's auto-imports of `composables/` and `utils/`, and
* unplugin-auto-import's.
*/
const JS_AUTO_IMPORT_PACKAGES = ['nuxt', 'nuxt3', '@nuxt/kit', 'unplugin-auto-import'];

/**
* Whether `ref` calls or constructs a standard global (JS_STANDARD_GLOBALS)
* that its ES module neither declares nor imports (#3238): `parseInt(s)`,
* `new Response(body)` are the runtime's, never another module's export,
* which is reached only through an import that the import resolver has
* followed already. Any other name keeps the name match as a fallback. Not
* in a script, a file with no import or export, whose top level other scripts
* share; nor in a project whose build auto-imports its own exports.
*/
function isJsBareGlobalName(ref: UnresolvedRef, context: ResolutionContext): boolean {
if ((ref.referenceKind !== 'calls' && ref.referenceKind !== 'instantiates') || !JS_FAMILY.has(ref.language) ||
!JS_STANDARD_GLOBALS.has(ref.referenceName) || !TS_JS_FILE.test(ref.filePath) ||
context.getImportMappings?.(ref.filePath, ref.language)?.some((m) => m.localName === ref.referenceName)) return false;
const scope = tsGlobalScope(ref.filePath, context);
return !!scope && !scope.script && !scope.importAliases.has(ref.referenceName) &&
!JS_AUTO_IMPORT_PACKAGES.some((p) => context.isDeclaredPackage?.(p, ref.filePath) === true) &&
isJsWrittenBare(ref, context) && !isJsBoundAtRef(ref, context);
}

/**
* Whether a binding of the name holds where `ref` is written: a declaration,
* a parameter, a destructured one (`.then(({ encode }) => encode(x))` after a
* dynamic import), as jsBindingAt reads them. Such a name is no global, and
* this leaves its call as it was.
*/
function isJsBoundAtRef(ref: UnresolvedRef, context: ResolutionContext): boolean {
const file = jsScopeFile(ref.filePath, context);
if (!file) return isLocallyBoundJsName(ref.referenceName, ref.filePath, context);
const at = (file.lineStarts[ref.line - 1] ?? file.code.length) + ref.column;
return jsBindingAt(ref.referenceName, file, at) !== null;
}

/**
* Whether a call or `new` recorded by a bare name was written so: `parseInt(…)`,
* `new Response(…)`. A member recorded by its last name, `this.set(…)` or
* `new ctx.Request(…)`, is some object's, which isJsBareGlobalName doesn't
* read; nor is a name its column doesn't find.
*/
function isJsWrittenBare(ref: UnresolvedRef, context: ResolutionContext): boolean {
const line = context.getFileLines?.(ref.filePath)?.[ref.line - 1] ?? context.readFile(ref.filePath)?.split(/\r?\n/)[ref.line - 1] ?? '';
if (ref.referenceKind === 'instantiates') {
const made = /^new\s+([\w$.]+)/.exec(line.slice(ref.column));
if (made) return made[1] === ref.referenceName;
}
return line.startsWith(ref.referenceName, ref.column) && !isWrittenQualified(ref, context);
}

/**
* Whether a value a bare global name (isJsBareGlobalName) may be `n`: one of
* the file's own, or a global declaration — at a script's top level, directly
* inside `declare global`, or one the code hangs on the global object
* (`window.helper = …`). A test's or fixture's globals are its tests' only.
*/
function isJsValueInScope(n: Node, ref: UnresolvedRef, context: ResolutionContext): boolean {
if (n.filePath === ref.filePath || !TS_JS_FILE.test(n.filePath)) return true;
const scope = tsGlobalScope(n.filePath, context);
if (!scope) return true;
if (isTestFile(n.filePath) && !isTestFile(ref.filePath)) return false;
if (scope.globalWords.has(`${n.startLine}:${n.startColumn}`)) return true;
// `window.helper = function helper() {…}`: a global wherever it is written.
const line = context.getFileLines?.(n.filePath)?.[n.startLine - 1] ?? context.readFile(n.filePath)?.split(/\r?\n/)[n.startLine - 1] ?? '';
return new RegExp(`(?:^|[^\\w$.])(?:window|globalThis|global|self)\\s*\\.\\s*${escapeRegExp(n.name)}\\s*=(?!=)`).test(line);
}

/**
* Whether a name in a JS/TS monorepo inside the repository would reach past it:
* it has an install of its own (WorkspacePackages.nestedRoots). The tests of
Expand Down Expand Up @@ -15842,6 +15913,8 @@ export function matchByExactName(
// Every candidate uses the same binding key. Keep this check lazy.
let locallyBoundJsName: boolean | undefined;
const tsBareTypeName = (): boolean => (bareTypeName ??= isTsBareTypeName(ref, context));
let bareGlobalName: boolean | undefined;
const jsBareGlobalName = (): boolean => (bareGlobalName ??= isJsBareGlobalName(ref, context));
const ambientDeclarations = ambientModuleDeclarations(context);
const sameName = outOfRepoCall
? innerScopeShadows(context.getNodesByName(ref.referenceName), ref, context)
Expand Down Expand Up @@ -15961,6 +16034,9 @@ export function matchByExactName(
// its own or a global, never another module's — ahead of the ranking, so
// a global `interface Window` in a `declare global` still wins.
!(n.filePath !== ref.filePath && tsBareTypeName() && !isTsTypeInScope(n, ref, context)) &&
// So is a call or `new` of a bare name the module doesn't import: a
// global's, `parseInt` or `Response`, never another module's export (#3238).
!(n.filePath !== ref.filePath && jsBareGlobalName() && !isJsValueInScope(n, ref, context)) &&
// Nor is a `declare module` block a file can't see any candidate, ahead of
// the ranking, where the gate on the winner would drop the reference: a
// sibling's test stub's `createRef` is no rival to `packages/react`'s own.
Expand Down Expand Up @@ -35944,6 +36020,7 @@ export function matchFuzzy(
(finalCandidates[0]!.filePath !== ref.filePath && isLocallyBoundJsName(ref.referenceName, ref.filePath, context)))) &&
!(JS_FAMILY.has(ref.language) && isOutOfRepoBinding(ref.referenceName, ref, context)) &&
!(finalCandidates[0]!.filePath !== ref.filePath && isTsBareTypeName(ref, context) && !isTsTypeInScope(finalCandidates[0]!, ref, context)) &&
!(finalCandidates[0]!.filePath !== ref.filePath && isJsBareGlobalName(ref, context) && !isJsValueInScope(finalCandidates[0]!, ref, context)) &&
!(finalCandidates[0]!.kind === 'method' && isBareGoCall(ref, context)) &&
// A bare PHP call is a function call (case-insensitive, so fuzzy may find
// one) — never the class `View` for `view(…)`, never a method.
Expand Down