Skip to content

Commit 0d46f32

Browse files
committed
chore(gates): resolve Vitest import aliases when reading mock-family module sites
parseModuleMockSpecifiers matched only the global vi/vitest receivers, so import { vi as mocks } from 'vitest' or a vitest namespace import hid a provider mock from R85 and every other specifierSites walk. The shared extractor now resolves top-level value imports from vitest (named vi/vitest aliases and namespace members), honours lexical redeclaration of those local names, and still ignores type-only imports, other modules and other exports. Bindings made by a dynamic import of vitest are not followed.
1 parent 1d1e2bb commit 0d46f32

5 files changed

Lines changed: 441 additions & 12 deletions

File tree

‎scripts/layering/layering-ast.ts‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,18 @@
11
/** Shared AST helpers for permanent layering policies. */
22
export type ProductionSource = Readonly<{ path: string; source: string }>;
33

4+
export type AstNode = Record<string, unknown>;
5+
6+
export function asNode(value: unknown): AstNode | undefined {
7+
return value !== null && typeof value === 'object' && !Array.isArray(value)
8+
? (value as AstNode)
9+
: undefined;
10+
}
11+
12+
export function nodeList(value: unknown): unknown[] {
13+
return Array.isArray(value) ? value : [];
14+
}
15+
416
export function memberName(node: Record<string, unknown>): string | undefined {
517
const property = node.property as Record<string, unknown> | undefined;
618
if (!property) return undefined;
@@ -122,3 +134,116 @@ export function destructuredDynamicImportBindings(
122134
visit(program);
123135
return captures;
124136
}
137+
138+
function patternNames(pattern: unknown, into: string[]): void {
139+
const node = asNode(pattern);
140+
if (node === undefined) return;
141+
switch (node.type) {
142+
case 'Identifier':
143+
into.push(node.name as string);
144+
break;
145+
case 'ObjectPattern':
146+
for (const property of nodeList(node.properties)) {
147+
const entry = asNode(property);
148+
patternNames(entry?.type === 'Property' ? entry.value : entry, into);
149+
}
150+
break;
151+
case 'ArrayPattern':
152+
for (const element of nodeList(node.elements)) patternNames(element, into);
153+
break;
154+
case 'AssignmentPattern':
155+
patternNames(node.left, into);
156+
break;
157+
case 'RestElement':
158+
patternNames(node.argument, into);
159+
break;
160+
case 'TSParameterProperty':
161+
patternNames(node.parameter, into);
162+
break;
163+
}
164+
}
165+
166+
function lexicalNames(statements: unknown[], into: string[]): void {
167+
for (const statement of statements) {
168+
const node = asNode(statement);
169+
if (node?.type === 'VariableDeclaration' && node.kind !== 'var') {
170+
for (const declarator of nodeList(node.declarations)) {
171+
patternNames(asNode(declarator)?.id, into);
172+
}
173+
} else if (node?.type === 'FunctionDeclaration' || node?.type === 'ClassDeclaration') {
174+
patternNames(node.id, into);
175+
}
176+
}
177+
}
178+
179+
function isFunctionNode(node: AstNode): boolean {
180+
return (
181+
node.type === 'FunctionDeclaration' ||
182+
node.type === 'FunctionExpression' ||
183+
node.type === 'ArrowFunctionExpression'
184+
);
185+
}
186+
187+
function hoistedVarNames(node: unknown, into: string[]): void {
188+
for (const child of Array.isArray(node) ? node : [node]) {
189+
const record = asNode(child);
190+
if (record === undefined || isFunctionNode(record)) continue;
191+
if (record.type === 'VariableDeclaration' && record.kind === 'var') {
192+
for (const declarator of nodeList(record.declarations)) {
193+
patternNames(asNode(declarator)?.id, into);
194+
}
195+
}
196+
for (const value of Object.values(record)) hoistedVarNames(value, into);
197+
}
198+
}
199+
200+
/** Names `node` itself declares for its own subtree: parameters, `var`s, block-level lexical declarations. */
201+
function scopeBindings(node: AstNode): string[] {
202+
const names: string[] = [];
203+
if (isFunctionNode(node)) {
204+
for (const param of nodeList(node.params)) patternNames(param, names);
205+
if (node.type === 'FunctionExpression') patternNames(node.id, names);
206+
hoistedVarNames(node.body, names);
207+
} else if (
208+
node.type === 'BlockStatement' ||
209+
node.type === 'StaticBlock' ||
210+
node.type === 'TSModuleBlock'
211+
) {
212+
lexicalNames(nodeList(node.body), names);
213+
} else if (node.type === 'ClassExpression') {
214+
patternNames(node.id, names);
215+
} else if (node.type === 'SwitchStatement') {
216+
for (const switchCase of nodeList(node.cases)) {
217+
lexicalNames(nodeList(asNode(switchCase)?.consequent), names);
218+
}
219+
} else if (node.type === 'ForStatement') {
220+
lexicalNames([node.init], names);
221+
} else if (node.type === 'ForInStatement' || node.type === 'ForOfStatement') {
222+
lexicalNames([node.left], names);
223+
} else if (node.type === 'CatchClause') {
224+
patternNames(node.param, names);
225+
}
226+
return names;
227+
}
228+
229+
/**
230+
* `visitAst` that also hands the visitor the names declared by the enclosing scopes: function
231+
* parameters and `var`s, block-level `let`/`const`/`function`/`class`, loop heads and `catch`
232+
* parameters. A `with` statement or `eval` can rebind names invisibly and is not modelled.
233+
*/
234+
export function visitAstScoped(
235+
node: unknown,
236+
shadowed: ReadonlySet<string>,
237+
visitor: (node: AstNode, shadowed: ReadonlySet<string>) => void,
238+
): void {
239+
if (Array.isArray(node)) {
240+
for (const child of node) visitAstScoped(child, shadowed, visitor);
241+
return;
242+
}
243+
const record = asNode(node);
244+
if (record === undefined) return;
245+
const declared = scopeBindings(record);
246+
const scope = declared.length > 0 ? new Set([...shadowed, ...declared]) : shadowed;
247+
visitor(record, scope);
248+
for (const child of Object.values(record)) visitAstScoped(child, scope, visitor);
249+
}
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// How `parseModuleMockSpecifiers` resolves the receiver of a mock-family call: the global
2+
// `vi`/`vitest`, or a local name an `import ... from 'vitest'` declaration binds to them.
3+
4+
import assert from 'node:assert/strict';
5+
import { test } from 'node:test';
6+
import { parseModuleMockSpecifiers } from './model.ts';
7+
8+
function specs(...lines: string[]): string[] {
9+
return parseModuleMockSpecifiers(lines.join('\n')).map(({ spec }) => spec);
10+
}
11+
12+
test('a named import aliasing vi or vitest is a mock receiver', () => {
13+
assert.deepEqual(
14+
specs(
15+
"import { vi as mocks, vitest as runner } from 'vitest';",
16+
"mocks.mock('a');",
17+
"runner.doMock('b');",
18+
"mocks['unmock']('c');",
19+
"await mocks.importActual('d');",
20+
"mocks?.importMock('e');",
21+
"(mocks as typeof vi).mock('f');",
22+
"mocks!.doUnmock('g');",
23+
),
24+
['a', 'b', 'c', 'd', 'e', 'f', 'g'],
25+
);
26+
});
27+
28+
test('a string-named import and an unaliased import resolve like a named alias', () => {
29+
assert.deepEqual(
30+
specs("import { 'vi' as quoted, vi } from 'vitest';", "quoted.mock('a');", "vi.mock('b');"),
31+
['a', 'b'],
32+
);
33+
});
34+
35+
test('a vitest namespace import reaches the mock API through vi and vitest members', () => {
36+
assert.deepEqual(
37+
specs(
38+
"import * as testing from 'vitest';",
39+
"testing.vi.mock('a');",
40+
"testing.vitest.doMock('b');",
41+
"testing['vi'].unmock('c');",
42+
"testing.vi['importActual']('d');",
43+
"testing[`vitest`].importMock('e');",
44+
"testing?.vi?.mock('f');",
45+
"(testing.vi as typeof vi).mock('g');",
46+
),
47+
['a', 'b', 'c', 'd', 'e', 'f', 'g'],
48+
);
49+
});
50+
51+
test('only a value import from vitest binds a mock receiver', () => {
52+
assert.deepEqual(
53+
specs(
54+
"import { vi as fromOther } from 'not-vitest';",
55+
"import { vi as fromRelative } from './vitest.ts';",
56+
"import type { vi as typeDeclaration } from 'vitest';",
57+
"import { type vi as typeSpecifier } from 'vitest';",
58+
"import { expect as notMock, describe as alsoNotMock } from 'vitest';",
59+
"import * as otherNamespace from 'not-vitest';",
60+
"import type * as typeNamespace from 'vitest';",
61+
"fromOther.mock('a');",
62+
"fromRelative.mock('b');",
63+
"typeDeclaration.mock('c');",
64+
"typeSpecifier.mock('d');",
65+
"notMock.mock('e');",
66+
"alsoNotMock.mock('f');",
67+
"otherNamespace.vi.mock('g');",
68+
"typeNamespace.vi.mock('h');",
69+
),
70+
[],
71+
);
72+
});
73+
74+
test('a vitest namespace member other than vi or vitest is not the mock API', () => {
75+
assert.deepEqual(
76+
specs(
77+
"import * as testing from 'vitest';",
78+
"testing.expect.mock('a');",
79+
"testing[member].mock('b');",
80+
"testing['expect'].mock('c');",
81+
),
82+
[],
83+
);
84+
});
85+
86+
test('an alias is not a mock receiver where an enclosing scope redeclares its name', () => {
87+
assert.deepEqual(
88+
specs(
89+
"import { vi as mocks } from 'vitest';",
90+
"import * as testing from 'vitest';",
91+
"function parameter(mocks) { mocks.mock('a'); }",
92+
"const arrow = (testing) => testing.vi.mock('b');",
93+
"{ const mocks = other; mocks.mock('c'); }",
94+
"function hoisted() { if (flag) { var mocks = other; } mocks.mock('d'); }",
95+
"try {} catch (mocks) { mocks.mock('e'); }",
96+
"for (const { mocks } of list) mocks.mock('f');",
97+
"switch (kind) { case 1: class testing {} testing.vi.mock('g'); }",
98+
"const expression = function mocks() { mocks.mock('h'); };",
99+
"const named = class mocks { run() { mocks.mock('i'); } };",
100+
"namespace Fixture { const testing = other; testing.vi.mock('j'); }",
101+
),
102+
[],
103+
);
104+
assert.deepEqual(
105+
specs(
106+
"import { vi as mocks } from 'vitest';",
107+
'function unrelated(mocks) { return mocks; }',
108+
'{ const mocks = other; }',
109+
"mocks.mock('outside');",
110+
),
111+
['outside'],
112+
);
113+
});
114+
115+
test('the global vi and vitest names stay mock receivers beside import aliases', () => {
116+
assert.deepEqual(
117+
specs(
118+
"import { vi as mocks } from 'vitest';",
119+
"vi.mock('a');",
120+
"vitest.mock('b');",
121+
"async function setup() { const { vi } = await import('vitest'); vi.doMock('c'); }",
122+
),
123+
['a', 'b', 'c'],
124+
);
125+
});
126+
127+
test('an alias call still ignores comments, non-literal modules and non-module methods', () => {
128+
assert.deepEqual(
129+
specs(
130+
"import { vi as mocks } from 'vitest';",
131+
"import * as testing from 'vitest';",
132+
"// mocks.mock('commented');",
133+
"/* testing.vi.doMock('block') */",
134+
'const text = "mocks.mock(\'in-string\')";',
135+
'mocks.mock(variable);',
136+
'mocks.mock(`interpolated-${name}`);',
137+
'testing.vi.mock();',
138+
"mocks.fn('not-a-module-api');",
139+
"mocks.mocked('not-a-module-api');",
140+
"mocks[method]('computed-member');",
141+
"mocks.mock.mockReset('nested');",
142+
"mocks('call-not-member');",
143+
),
144+
[],
145+
);
146+
});
147+
148+
test('a Vitest binding made by a dynamic import is not followed', () => {
149+
assert.deepEqual(
150+
specs(
151+
"const { vi: mocks } = await import('vitest');",
152+
"const testing = await import('vitest');",
153+
"mocks.mock('a');",
154+
"testing.vi.mock('b');",
155+
),
156+
[],
157+
);
158+
});
159+
160+
test('a module named by an alias call keeps its source line', () => {
161+
assert.deepEqual(
162+
parseModuleMockSpecifiers(
163+
"import { vi as mocks } from 'vitest';\n\nmocks.mock(\n `multi`,\n);",
164+
),
165+
[{ spec: 'multi', line: 3 }],
166+
);
167+
});

0 commit comments

Comments
 (0)