@under18dev/veritas-test-inventory 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +12 -2
- package/dist/index.d.ts +94 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1268 -0
- package/dist/index.js.map +1 -0
- package/package.json +26 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1268 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { resolveInsideRoot, sha256, stableId, symbolId, TestCase, TestPropertyEdge, toPosixRelative, } from '@under18dev/veritas-core';
|
|
4
|
+
import ts from 'typescript';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
export const TestInventory = z.object({
|
|
7
|
+
tests: z.array(TestCase),
|
|
8
|
+
edges: z.array(TestPropertyEdge),
|
|
9
|
+
files: z.array(z.object({
|
|
10
|
+
path: z.string(),
|
|
11
|
+
hash: z.string(),
|
|
12
|
+
/** Files inside the root the test file imports, directly or through other local files (POSIX, sorted). */
|
|
13
|
+
dependencies: z.array(z.string()).default([]),
|
|
14
|
+
/**
|
|
15
|
+
* The file or a local file it imports runs code static analysis cannot follow (a child process, a
|
|
16
|
+
* dynamic import) or imports a relative module that does not resolve, anywhere, recognized test or not.
|
|
17
|
+
*/
|
|
18
|
+
unseenReach: z.boolean().default(false),
|
|
19
|
+
})),
|
|
20
|
+
diagnostics: z.array(z.object({ file: z.string(), message: z.string() })),
|
|
21
|
+
});
|
|
22
|
+
const modifiers = new Set(['skip', 'only', 'todo', 'concurrent', 'each']);
|
|
23
|
+
const testNames = new Set(['it', 'test']);
|
|
24
|
+
export function testId(file, suitePath, name) {
|
|
25
|
+
return stableId('T', { file: file.split('\\').join('/'), suitePath, name });
|
|
26
|
+
}
|
|
27
|
+
export function inventoryTests(options) {
|
|
28
|
+
const root = path.resolve(options.root);
|
|
29
|
+
const testFiles = options.files?.map((file) => resolveInsideRoot(root, path.isAbsolute(file) ? path.relative(root, file) : file)) ?? collectFiles(root, options.config.analysis.testInclude, options.config.analysis.exclude);
|
|
30
|
+
const uniqueFiles = [...new Set(testFiles.map((file) => path.resolve(file)))].filter(isSourceFile);
|
|
31
|
+
const projectFiles = collectFiles(root, options.config.analysis.include, options.config.analysis.exclude).filter((file) => !uniqueFiles.includes(path.resolve(file)) && !isTestSupportFile(root, file));
|
|
32
|
+
const compilerOptions = readCompilerOptions(root, options.config);
|
|
33
|
+
const program = ts.createProgram([...projectFiles, ...uniqueFiles], compilerOptions);
|
|
34
|
+
const checker = program.getTypeChecker();
|
|
35
|
+
const sourceFiles = new Map();
|
|
36
|
+
for (const sourceFile of program.getSourceFiles())
|
|
37
|
+
sourceFiles.set(path.resolve(sourceFile.fileName), sourceFile);
|
|
38
|
+
const projectSet = new Set(projectFiles.map((file) => path.resolve(file)));
|
|
39
|
+
const tests = [];
|
|
40
|
+
const diagnostics = [];
|
|
41
|
+
const callInfoCache = new Map();
|
|
42
|
+
const helperInfoCache = new Map();
|
|
43
|
+
for (const file of uniqueFiles) {
|
|
44
|
+
const source = sourceFiles.get(file);
|
|
45
|
+
if (!source)
|
|
46
|
+
continue;
|
|
47
|
+
for (const diagnostic of [
|
|
48
|
+
...program.getSyntacticDiagnostics(source),
|
|
49
|
+
...program.getSemanticDiagnostics(source),
|
|
50
|
+
]) {
|
|
51
|
+
diagnostics.push({
|
|
52
|
+
file: toPosixRelative(root, file),
|
|
53
|
+
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
const ctx = {
|
|
57
|
+
checker,
|
|
58
|
+
projectSet,
|
|
59
|
+
root,
|
|
60
|
+
program,
|
|
61
|
+
compilerOptions,
|
|
62
|
+
file,
|
|
63
|
+
callInfo: callInfoCache,
|
|
64
|
+
helperInfo: helperInfoCache,
|
|
65
|
+
};
|
|
66
|
+
const mocks = collectMocks(source, ctx);
|
|
67
|
+
visitTests(source, [], [], file, mocks, ctx, tests);
|
|
68
|
+
}
|
|
69
|
+
const edges = [];
|
|
70
|
+
for (const test of tests) {
|
|
71
|
+
for (const symbol of test.calledSymbols) {
|
|
72
|
+
const evidence = [
|
|
73
|
+
{
|
|
74
|
+
kind: 'static_call',
|
|
75
|
+
detail: 'Project symbol called from the test, directly, through a test helper or in shared setup',
|
|
76
|
+
artifactIds: [],
|
|
77
|
+
},
|
|
78
|
+
];
|
|
79
|
+
if (test.targetCalls.some((call) => call.symbol === symbol && call.asserted)) {
|
|
80
|
+
evidence.push({
|
|
81
|
+
kind: 'direct_assertion',
|
|
82
|
+
detail: 'Result of project symbol flows into an assertion',
|
|
83
|
+
artifactIds: [],
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
edges.push({
|
|
87
|
+
id: stableId('E', { testId: test.id, symbol, propertyId: null }),
|
|
88
|
+
testId: test.id,
|
|
89
|
+
symbol,
|
|
90
|
+
propertyId: null,
|
|
91
|
+
evidence,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const files = uniqueFiles.map((file) => {
|
|
96
|
+
const source = sourceFiles.get(file);
|
|
97
|
+
const dependencies = source ? localDependencies(source, checker, root) : [];
|
|
98
|
+
const reached = [
|
|
99
|
+
source,
|
|
100
|
+
...dependencies.map((dependency) => sourceFiles.get(path.resolve(root, dependency))),
|
|
101
|
+
];
|
|
102
|
+
return {
|
|
103
|
+
path: toPosixRelative(root, file),
|
|
104
|
+
hash: sha256(readFileSync(file)),
|
|
105
|
+
dependencies,
|
|
106
|
+
// An unparsed file is unknown too.
|
|
107
|
+
unseenReach: !source || reached.some((reachedFile) => reachedFile && hasUnseenReach(reachedFile, checker)),
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
return TestInventory.parse({ tests, edges, files, diagnostics });
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Calls, assertions and result flow in a test body or helper body. Values are followed through local and
|
|
114
|
+
* enclosing (describe-level or module-level) variables of the same file, including `let` set in a hook.
|
|
115
|
+
*/
|
|
116
|
+
function analyzeBody(body, ctx) {
|
|
117
|
+
const { checker } = ctx;
|
|
118
|
+
const source = body.getSourceFile();
|
|
119
|
+
const calls = [];
|
|
120
|
+
const recorded = new Set();
|
|
121
|
+
const assertions = [];
|
|
122
|
+
const unresolvedImports = new Set();
|
|
123
|
+
let helperAsserts = false;
|
|
124
|
+
let opaque = false;
|
|
125
|
+
const record = (node) => {
|
|
126
|
+
const info = callInfo(node, ctx);
|
|
127
|
+
if (!recorded.has(node)) {
|
|
128
|
+
recorded.add(node);
|
|
129
|
+
for (const target of info.targets)
|
|
130
|
+
calls.push({ node, target });
|
|
131
|
+
helperAsserts ||= info.helperAsserts;
|
|
132
|
+
opaque ||= info.opaque;
|
|
133
|
+
}
|
|
134
|
+
return info.targets.length > 0;
|
|
135
|
+
};
|
|
136
|
+
// Variables holding (something derived from) a project call's result, keyed by symbol so shadowing is respected.
|
|
137
|
+
const localCalls = new Map();
|
|
138
|
+
const outerDone = new Set();
|
|
139
|
+
const sourcesOf = (expressions) => {
|
|
140
|
+
const found = new Set();
|
|
141
|
+
for (const expression of expressions) {
|
|
142
|
+
// A function value is a helper; it is followed where it is called, not where it is defined.
|
|
143
|
+
if (isFunctionLike(skipParens(expression)))
|
|
144
|
+
continue;
|
|
145
|
+
const direct = [expression, ...descendants(expression)].filter((item) => ts.isCallExpression(item) && record(item));
|
|
146
|
+
for (const item of direct.length > 0 ? direct : trackedCalls(expression))
|
|
147
|
+
found.add(item);
|
|
148
|
+
}
|
|
149
|
+
return [...found];
|
|
150
|
+
};
|
|
151
|
+
const outerCalls = (symbol) => {
|
|
152
|
+
if (outerDone.has(symbol))
|
|
153
|
+
return;
|
|
154
|
+
outerDone.add(symbol);
|
|
155
|
+
const expressions = [];
|
|
156
|
+
for (const declaration of symbol.declarations ?? []) {
|
|
157
|
+
if (!ts.isVariableDeclaration(declaration) || declaration.getSourceFile() !== source)
|
|
158
|
+
continue;
|
|
159
|
+
if (contains(body, declaration))
|
|
160
|
+
continue;
|
|
161
|
+
if (declaration.initializer)
|
|
162
|
+
expressions.push(declaration.initializer);
|
|
163
|
+
else
|
|
164
|
+
expressions.push(...assignmentsTo(symbol, source, checker));
|
|
165
|
+
}
|
|
166
|
+
const sources = sourcesOf(expressions);
|
|
167
|
+
if (sources.length > 0)
|
|
168
|
+
localCalls.set(symbol, sources);
|
|
169
|
+
};
|
|
170
|
+
const trackedCalls = (expression) => {
|
|
171
|
+
const found = new Set();
|
|
172
|
+
for (const item of [expression, ...descendants(expression)]) {
|
|
173
|
+
if (!ts.isIdentifier(item))
|
|
174
|
+
continue;
|
|
175
|
+
const symbol = checker.getSymbolAtLocation(item);
|
|
176
|
+
if (!symbol)
|
|
177
|
+
continue;
|
|
178
|
+
if (!localCalls.has(symbol))
|
|
179
|
+
outerCalls(symbol);
|
|
180
|
+
for (const call of localCalls.get(symbol) ?? [])
|
|
181
|
+
found.add(call);
|
|
182
|
+
}
|
|
183
|
+
return [...found];
|
|
184
|
+
};
|
|
185
|
+
const bind = (identifiers, sources, merge = false) => {
|
|
186
|
+
if (sources.length === 0)
|
|
187
|
+
return;
|
|
188
|
+
for (const identifier of identifiers) {
|
|
189
|
+
const symbol = checker.getSymbolAtLocation(identifier);
|
|
190
|
+
if (!symbol)
|
|
191
|
+
continue;
|
|
192
|
+
const previous = merge ? (localCalls.get(symbol) ?? []) : [];
|
|
193
|
+
localCalls.set(symbol, [...new Set([...previous, ...sources])]);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
// Project code runs the callbacks it is given: what they write to is an output of that call. So is the
|
|
197
|
+
// state of a local object after a project method ran on it (`client.complete(); client.cachedResponses`).
|
|
198
|
+
const bindCallOutputs = (call) => {
|
|
199
|
+
const callee = skipParens(call.expression);
|
|
200
|
+
if (ts.isPropertyAccessExpression(callee)) {
|
|
201
|
+
let receiver = skipParens(callee.expression);
|
|
202
|
+
while (ts.isPropertyAccessExpression(receiver) || ts.isElementAccessExpression(receiver))
|
|
203
|
+
receiver = skipParens(receiver.expression);
|
|
204
|
+
const declaration = ts.isIdentifier(receiver)
|
|
205
|
+
? checker.getSymbolAtLocation(receiver)?.valueDeclaration
|
|
206
|
+
: undefined;
|
|
207
|
+
if (ts.isIdentifier(receiver) && declaration?.getSourceFile() === source)
|
|
208
|
+
bind([receiver], [call], true);
|
|
209
|
+
}
|
|
210
|
+
const callbacks = new Set();
|
|
211
|
+
for (const argument of call.arguments)
|
|
212
|
+
for (const item of [argument, ...descendants(argument)]) {
|
|
213
|
+
if (isFunctionLike(item))
|
|
214
|
+
callbacks.add(item);
|
|
215
|
+
if (!ts.isIdentifier(item))
|
|
216
|
+
continue;
|
|
217
|
+
const declaration = checker.getSymbolAtLocation(item)?.valueDeclaration;
|
|
218
|
+
if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer)
|
|
219
|
+
for (const inner of [declaration.initializer, ...descendants(declaration.initializer)])
|
|
220
|
+
if (isFunctionLike(inner))
|
|
221
|
+
callbacks.add(inner);
|
|
222
|
+
}
|
|
223
|
+
for (const callback of callbacks)
|
|
224
|
+
bind(writtenOuterIdentifiers(callback, checker), [call], true);
|
|
225
|
+
};
|
|
226
|
+
for (const node of descendants(body)) {
|
|
227
|
+
if (ts.isTryStatement(node) && node.catchClause?.variableDeclaration)
|
|
228
|
+
bind(bindingIdentifiers(node.catchClause.variableDeclaration.name), descendants(node.tryBlock).filter((item) => ts.isCallExpression(item) && record(item)));
|
|
229
|
+
if (ts.isVariableDeclaration(node) && node.initializer)
|
|
230
|
+
bind(bindingIdentifiers(node.name), sourcesOf([node.initializer]));
|
|
231
|
+
if (ts.isBinaryExpression(node) &&
|
|
232
|
+
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
|
233
|
+
ts.isIdentifier(node.left))
|
|
234
|
+
bind([node.left], sourcesOf([node.right]));
|
|
235
|
+
if (ts.isForOfStatement(node) && ts.isVariableDeclarationList(node.initializer))
|
|
236
|
+
bind(node.initializer.declarations.flatMap((declaration) => bindingIdentifiers(declaration.name)), sourcesOf([node.expression]));
|
|
237
|
+
if (!ts.isCallExpression(node))
|
|
238
|
+
continue;
|
|
239
|
+
if (record(node))
|
|
240
|
+
bindCallOutputs(node);
|
|
241
|
+
else {
|
|
242
|
+
const specifier = unresolvedImportOf(node.expression, ctx);
|
|
243
|
+
if (specifier !== undefined)
|
|
244
|
+
unresolvedImports.add(specifier);
|
|
245
|
+
}
|
|
246
|
+
if (isExpectCall(node) || isAssertCall(node))
|
|
247
|
+
assertions.push(node);
|
|
248
|
+
}
|
|
249
|
+
// What a helper returns may come from enclosing variables, e.g. `const of = (n) => candidates.filter(...)`.
|
|
250
|
+
const returned = new Set(sourcesOf(ts.isBlock(body) ? returnedExpressions(body) : ts.isExpression(body) ? [body] : []));
|
|
251
|
+
const asserted = new Set();
|
|
252
|
+
// Either side of a comparison counts: `expect(['a', 'b']).toContain(result.status)` checks the result.
|
|
253
|
+
for (const value of assertions.flatMap(comparedValues)) {
|
|
254
|
+
for (const call of trackedCalls(value))
|
|
255
|
+
asserted.add(call);
|
|
256
|
+
for (const { node } of calls)
|
|
257
|
+
if (contains(value, node))
|
|
258
|
+
asserted.add(node);
|
|
259
|
+
}
|
|
260
|
+
// A value passed to a helper of this file that asserts on that parameter is asserted too. The helper is
|
|
261
|
+
// resolved through the checker, so a shadowing local of the same name is not mistaken for it.
|
|
262
|
+
const helpers = assertingHelpers(source);
|
|
263
|
+
for (const node of descendants(body)) {
|
|
264
|
+
if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression))
|
|
265
|
+
continue;
|
|
266
|
+
const declarations = checker.getSymbolAtLocation(node.expression)?.declarations ?? [];
|
|
267
|
+
const positions = declarations.map((declaration) => helpers.get(declaration)).find(Boolean);
|
|
268
|
+
for (const index of positions ?? []) {
|
|
269
|
+
const argument = node.arguments[index];
|
|
270
|
+
if (!argument)
|
|
271
|
+
continue;
|
|
272
|
+
for (const call of trackedCalls(argument))
|
|
273
|
+
asserted.add(call);
|
|
274
|
+
for (const { node: call } of calls)
|
|
275
|
+
if (contains(argument, call))
|
|
276
|
+
asserted.add(call);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return { calls, assertions, asserted, unresolvedImports, helperAsserts, opaque, returned };
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* The project symbols a call reaches: directly, through a function defined in test code, or as a method of a
|
|
283
|
+
* project value (`Schema.parse(x)` exercises the project's `Schema`).
|
|
284
|
+
*/
|
|
285
|
+
function callInfo(node, ctx) {
|
|
286
|
+
const cached = ctx.callInfo.get(node);
|
|
287
|
+
if (cached)
|
|
288
|
+
return cached;
|
|
289
|
+
const none = { targets: [], helperAsserts: false, opaque: false };
|
|
290
|
+
const direct = resolveProjectCall(node, ctx.checker, ctx.projectSet, ctx.root);
|
|
291
|
+
let info;
|
|
292
|
+
if (direct)
|
|
293
|
+
info = {
|
|
294
|
+
...none,
|
|
295
|
+
targets: [{ symbol: direct, ownArgs: true, assertedInside: false, flowsToResult: true }],
|
|
296
|
+
};
|
|
297
|
+
else {
|
|
298
|
+
const helper = helperBody(node, ctx);
|
|
299
|
+
const receiver = helper ? undefined : projectReceiver(node, ctx);
|
|
300
|
+
if (helper)
|
|
301
|
+
info = helperInfo(helper, ctx);
|
|
302
|
+
else if (receiver)
|
|
303
|
+
info = {
|
|
304
|
+
...none,
|
|
305
|
+
targets: [{ symbol: receiver, ownArgs: false, assertedInside: false, flowsToResult: true }],
|
|
306
|
+
};
|
|
307
|
+
else
|
|
308
|
+
info = { ...none, opaque: isOpaqueCall(node, ctx.checker) };
|
|
309
|
+
}
|
|
310
|
+
ctx.callInfo.set(node, info);
|
|
311
|
+
return info;
|
|
312
|
+
}
|
|
313
|
+
/** `X.method(...)` or `X.a.b(...)` where `X` is a value declared in a project file. */
|
|
314
|
+
function projectReceiver(node, ctx) {
|
|
315
|
+
const callee = skipParens(node.expression);
|
|
316
|
+
if (!ts.isPropertyAccessExpression(callee) && !ts.isElementAccessExpression(callee))
|
|
317
|
+
return undefined;
|
|
318
|
+
let current = callee;
|
|
319
|
+
while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current))
|
|
320
|
+
current = skipParens(current.expression);
|
|
321
|
+
if (!ts.isIdentifier(current))
|
|
322
|
+
return undefined;
|
|
323
|
+
let symbol = ctx.checker.getSymbolAtLocation(current);
|
|
324
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias)
|
|
325
|
+
symbol = ctx.checker.getAliasedSymbol(symbol);
|
|
326
|
+
// A namespace import's members resolve directly; the module itself is not a value under test.
|
|
327
|
+
if (!symbol || symbol.flags & ts.SymbolFlags.ValueModule)
|
|
328
|
+
return undefined;
|
|
329
|
+
return projectSymbolId(symbol, ctx.checker, ctx.projectSet, ctx.root);
|
|
330
|
+
}
|
|
331
|
+
const CHILD_PROCESS_FUNCTIONS = new Set([
|
|
332
|
+
'spawn',
|
|
333
|
+
'spawnSync',
|
|
334
|
+
'exec',
|
|
335
|
+
'execSync',
|
|
336
|
+
'execFile',
|
|
337
|
+
'execFileSync',
|
|
338
|
+
'fork',
|
|
339
|
+
]);
|
|
340
|
+
/** A dynamic `import()` or a Node.js child_process call: what runs there is invisible to static analysis. */
|
|
341
|
+
function isOpaqueCall(node, checker) {
|
|
342
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword)
|
|
343
|
+
return true;
|
|
344
|
+
// `require(...)` and `createRequire(...)` load modules at run time, which static imports do not show.
|
|
345
|
+
if (ts.isIdentifier(node.expression) && ['require', 'createRequire'].includes(node.expression.text))
|
|
346
|
+
return true;
|
|
347
|
+
// A loader made by `createRequire` (`const load = createRequire(import.meta.url); load('./x')`).
|
|
348
|
+
if (ts.isIdentifier(node.expression)) {
|
|
349
|
+
const declaration = checker.getSymbolAtLocation(node.expression)?.valueDeclaration;
|
|
350
|
+
const initializer = declaration && ts.isVariableDeclaration(declaration) && declaration.initializer
|
|
351
|
+
? skipParens(declaration.initializer)
|
|
352
|
+
: undefined;
|
|
353
|
+
if (initializer &&
|
|
354
|
+
ts.isCallExpression(initializer) &&
|
|
355
|
+
ts.isIdentifier(initializer.expression) &&
|
|
356
|
+
initializer.expression.text === 'createRequire')
|
|
357
|
+
return true;
|
|
358
|
+
}
|
|
359
|
+
// By import source, which works without @types/node: `spawnSync(...)` or `cp.spawnSync(...)`.
|
|
360
|
+
const callee = skipParens(node.expression);
|
|
361
|
+
const local = ts.isPropertyAccessExpression(callee) ? skipParens(callee.expression) : callee;
|
|
362
|
+
const name = ts.isPropertyAccessExpression(callee) ? callee.name.text : undefined;
|
|
363
|
+
if (ts.isIdentifier(local))
|
|
364
|
+
for (const declaration of checker.getSymbolAtLocation(local)?.declarations ?? []) {
|
|
365
|
+
const imported = ts.isImportSpecifier(declaration)
|
|
366
|
+
? {
|
|
367
|
+
from: declaration.parent.parent.parent,
|
|
368
|
+
name: (declaration.propertyName ?? declaration.name).text,
|
|
369
|
+
}
|
|
370
|
+
: ts.isNamespaceImport(declaration)
|
|
371
|
+
? { from: declaration.parent.parent, name }
|
|
372
|
+
: ts.isImportClause(declaration)
|
|
373
|
+
? { from: declaration.parent, name }
|
|
374
|
+
: undefined;
|
|
375
|
+
const specifier = imported?.from.moduleSpecifier;
|
|
376
|
+
if (specifier &&
|
|
377
|
+
ts.isStringLiteral(specifier) &&
|
|
378
|
+
(specifier.text === 'child_process' || specifier.text === 'node:child_process') &&
|
|
379
|
+
imported?.name !== undefined &&
|
|
380
|
+
CHILD_PROCESS_FUNCTIONS.has(imported.name))
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
383
|
+
let symbol = checker.getSymbolAtLocation(node.expression);
|
|
384
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias)
|
|
385
|
+
symbol = checker.getAliasedSymbol(symbol);
|
|
386
|
+
if (!symbol || !CHILD_PROCESS_FUNCTIONS.has(symbol.getName()))
|
|
387
|
+
return false;
|
|
388
|
+
return (symbol.declarations ?? []).some((declaration) => /[\\/]child_process\.d\.ts$/.test(declaration.getSourceFile().fileName));
|
|
389
|
+
}
|
|
390
|
+
function helperInfo(body, ctx) {
|
|
391
|
+
const cached = ctx.helperInfo.get(body);
|
|
392
|
+
if (cached)
|
|
393
|
+
return cached;
|
|
394
|
+
// Recursive helpers see themselves as reaching nothing while they are being analysed.
|
|
395
|
+
ctx.helperInfo.set(body, { targets: [], helperAsserts: false, opaque: false });
|
|
396
|
+
const analysis = analyzeBody(body, ctx);
|
|
397
|
+
const bySymbol = new Map();
|
|
398
|
+
for (const { node, target } of analysis.calls) {
|
|
399
|
+
const assertedInside = target.assertedInside || (target.flowsToResult && analysis.asserted.has(node));
|
|
400
|
+
const flowsToResult = target.flowsToResult && analysis.returned.has(node);
|
|
401
|
+
const previous = bySymbol.get(target.symbol);
|
|
402
|
+
bySymbol.set(target.symbol, {
|
|
403
|
+
symbol: target.symbol,
|
|
404
|
+
ownArgs: false,
|
|
405
|
+
assertedInside: assertedInside || previous?.assertedInside === true,
|
|
406
|
+
flowsToResult: flowsToResult || previous?.flowsToResult === true,
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
const info = {
|
|
410
|
+
targets: [...bySymbol.values()],
|
|
411
|
+
helperAsserts: analysis.assertions.length > 0 || analysis.helperAsserts,
|
|
412
|
+
opaque: analysis.opaque,
|
|
413
|
+
};
|
|
414
|
+
ctx.helperInfo.set(body, info);
|
|
415
|
+
return info;
|
|
416
|
+
}
|
|
417
|
+
/** The body of the function a call invokes, when that function is test code inside the root. */
|
|
418
|
+
function helperBody(node, ctx) {
|
|
419
|
+
let symbol = ctx.checker.getSymbolAtLocation(node.expression);
|
|
420
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias)
|
|
421
|
+
symbol = ctx.checker.getAliasedSymbol(symbol);
|
|
422
|
+
for (const declaration of symbol?.declarations ?? []) {
|
|
423
|
+
const fn = ts.isVariableDeclaration(declaration) && declaration.initializer
|
|
424
|
+
? skipParens(declaration.initializer)
|
|
425
|
+
: declaration;
|
|
426
|
+
if (!isFunctionLike(fn) || !fn.body)
|
|
427
|
+
continue;
|
|
428
|
+
const sourceFile = fn.getSourceFile();
|
|
429
|
+
const file = path.resolve(sourceFile.fileName);
|
|
430
|
+
const relative = path.relative(ctx.root, file);
|
|
431
|
+
if (sourceFile.isDeclarationFile ||
|
|
432
|
+
ctx.projectSet.has(file) ||
|
|
433
|
+
relative.startsWith('..') ||
|
|
434
|
+
path.isAbsolute(relative) ||
|
|
435
|
+
relative.split(path.sep).includes('node_modules'))
|
|
436
|
+
continue;
|
|
437
|
+
return fn.body;
|
|
438
|
+
}
|
|
439
|
+
return undefined;
|
|
440
|
+
}
|
|
441
|
+
function isFunctionLike(node) {
|
|
442
|
+
return (ts.isFunctionDeclaration(node) ||
|
|
443
|
+
ts.isArrowFunction(node) ||
|
|
444
|
+
ts.isFunctionExpression(node) ||
|
|
445
|
+
ts.isMethodDeclaration(node));
|
|
446
|
+
}
|
|
447
|
+
/** Variables declared outside a callback that it assigns (`x = …`, `x.y = …`) or mutates (`x.push(…)`). */
|
|
448
|
+
function writtenOuterIdentifiers(callback, checker) {
|
|
449
|
+
const rootOf = (expression) => {
|
|
450
|
+
let current = skipParens(expression);
|
|
451
|
+
while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current))
|
|
452
|
+
current = skipParens(current.expression);
|
|
453
|
+
return ts.isIdentifier(current) ? current : undefined;
|
|
454
|
+
};
|
|
455
|
+
const written = [];
|
|
456
|
+
for (const node of descendants(callback)) {
|
|
457
|
+
let target;
|
|
458
|
+
if (ts.isBinaryExpression(node) &&
|
|
459
|
+
node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
|
460
|
+
node.operatorToken.kind <= ts.SyntaxKind.LastAssignment)
|
|
461
|
+
target = rootOf(node.left);
|
|
462
|
+
else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression))
|
|
463
|
+
target = rootOf(node.expression.expression);
|
|
464
|
+
const declaration = target && checker.getSymbolAtLocation(target)?.valueDeclaration;
|
|
465
|
+
if (target &&
|
|
466
|
+
declaration?.getSourceFile() === callback.getSourceFile() &&
|
|
467
|
+
!contains(callback, declaration))
|
|
468
|
+
written.push(target);
|
|
469
|
+
}
|
|
470
|
+
return written;
|
|
471
|
+
}
|
|
472
|
+
/** Expressions of the `return` statements of a function body, not of functions nested in it. */
|
|
473
|
+
function returnedExpressions(body) {
|
|
474
|
+
const found = [];
|
|
475
|
+
const visit = (node) => {
|
|
476
|
+
if (isFunctionLike(node))
|
|
477
|
+
return;
|
|
478
|
+
if (ts.isReturnStatement(node) && node.expression)
|
|
479
|
+
found.push(node.expression);
|
|
480
|
+
ts.forEachChild(node, visit);
|
|
481
|
+
};
|
|
482
|
+
ts.forEachChild(body, visit);
|
|
483
|
+
return found;
|
|
484
|
+
}
|
|
485
|
+
/** Right-hand sides of `name = value` anywhere in the file, for a `let` set in a hook. */
|
|
486
|
+
function assignmentsTo(symbol, source, checker) {
|
|
487
|
+
return descendants(source)
|
|
488
|
+
.filter((node) => ts.isBinaryExpression(node) &&
|
|
489
|
+
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
|
490
|
+
ts.isIdentifier(node.left) &&
|
|
491
|
+
checker.getSymbolAtLocation(node.left) === symbol)
|
|
492
|
+
.map((node) => node.right);
|
|
493
|
+
}
|
|
494
|
+
function visitTests(source, suitePath, inheritedModifiers, file, mocks, ctx, output) {
|
|
495
|
+
const walk = (node, currentSuite, currentModifiers) => {
|
|
496
|
+
if (ts.isCallExpression(node)) {
|
|
497
|
+
const describe = describeRegistration(node);
|
|
498
|
+
if (describe) {
|
|
499
|
+
const name = literalString(node.arguments[0]);
|
|
500
|
+
const callback = callbackArgument(node);
|
|
501
|
+
if (name !== undefined && callback && isFunction(callback)) {
|
|
502
|
+
const childModifiers = [...new Set([...currentModifiers, ...describe.modifiers])];
|
|
503
|
+
ts.forEachChild(callback, (child) => walk(child, [...currentSuite, name], childModifiers));
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
const info = testRegistration(node);
|
|
508
|
+
if (info) {
|
|
509
|
+
output.push(analyzeTest(node, { ...info, modifiers: [...new Set([...currentModifiers, ...info.modifiers])] }, currentSuite, file, mocks, ctx));
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
ts.forEachChild(node, (child) => walk(child, currentSuite, currentModifiers));
|
|
514
|
+
};
|
|
515
|
+
walk(source, suitePath, inheritedModifiers);
|
|
516
|
+
}
|
|
517
|
+
/** Vitest takes `(name, fn, timeout | options)` as well as `(name, options, fn)`: the callback is the last function. */
|
|
518
|
+
function callbackArgument(node) {
|
|
519
|
+
return node.arguments.slice(1).findLast(isFunction) ?? node.arguments.at(-1);
|
|
520
|
+
}
|
|
521
|
+
function testRegistration(node) {
|
|
522
|
+
const direct = registration(node, 'it') ?? registration(node, 'test');
|
|
523
|
+
if (direct && Array.isArray(direct))
|
|
524
|
+
return { name: literalString(node.arguments[0]), callback: callbackArgument(node), modifiers: direct };
|
|
525
|
+
if (ts.isCallExpression(node.expression)) {
|
|
526
|
+
const chain = propertyChain(node.expression.expression);
|
|
527
|
+
const root = rootIdentifier(node.expression.expression);
|
|
528
|
+
if (root && testNames.has(root) && chain.includes('each')) {
|
|
529
|
+
const eachModifiers = chain.filter((name) => modifiers.has(name));
|
|
530
|
+
if (!eachModifiers.includes('each'))
|
|
531
|
+
eachModifiers.push('each');
|
|
532
|
+
return {
|
|
533
|
+
name: literalString(node.arguments[0]),
|
|
534
|
+
callback: callbackArgument(node),
|
|
535
|
+
modifiers: eachModifiers,
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return undefined;
|
|
540
|
+
}
|
|
541
|
+
function describeRegistration(node) {
|
|
542
|
+
const direct = registration(node, 'describe');
|
|
543
|
+
if (direct && Array.isArray(direct)) {
|
|
544
|
+
return { name: literalString(node.arguments[0]), callback: callbackArgument(node), modifiers: direct };
|
|
545
|
+
}
|
|
546
|
+
if (!ts.isCallExpression(node.expression))
|
|
547
|
+
return undefined;
|
|
548
|
+
const chain = propertyChain(node.expression.expression);
|
|
549
|
+
const root = rootIdentifier(node.expression.expression);
|
|
550
|
+
if (!root || root !== 'describe' || !chain.includes('each'))
|
|
551
|
+
return undefined;
|
|
552
|
+
const eachModifiers = chain.filter((name) => modifiers.has(name));
|
|
553
|
+
if (!eachModifiers.includes('each'))
|
|
554
|
+
eachModifiers.push('each');
|
|
555
|
+
return {
|
|
556
|
+
name: literalString(node.arguments[0]),
|
|
557
|
+
callback: callbackArgument(node),
|
|
558
|
+
modifiers: eachModifiers,
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
function registration(node, kind) {
|
|
562
|
+
const chain = [];
|
|
563
|
+
let expression = node.expression;
|
|
564
|
+
while (ts.isPropertyAccessExpression(expression)) {
|
|
565
|
+
chain.push(expression.name.text);
|
|
566
|
+
expression = expression.expression;
|
|
567
|
+
}
|
|
568
|
+
if (!ts.isIdentifier(expression) || expression.text !== kind)
|
|
569
|
+
return undefined;
|
|
570
|
+
const found = chain.filter((name) => modifiers.has(name));
|
|
571
|
+
return found;
|
|
572
|
+
}
|
|
573
|
+
function analyzeTest(registrationCall, info, suitePath, file, mocks, ctx) {
|
|
574
|
+
const { checker, root } = ctx;
|
|
575
|
+
const source = registrationCall.getSourceFile();
|
|
576
|
+
const callback = info.callback;
|
|
577
|
+
const name = info.name ?? '<dynamic test>';
|
|
578
|
+
const body = callback && isFunction(callback) ? callback.body : undefined;
|
|
579
|
+
const nodes = body ? descendants(body) : [];
|
|
580
|
+
const analysis = body ? analyzeBody(body, ctx) : undefined;
|
|
581
|
+
const assertions = analysis?.assertions ?? [];
|
|
582
|
+
const unresolvedImports = analysis?.unresolvedImports ?? new Set();
|
|
583
|
+
const calledSymbols = [...new Set(analysis?.calls.map((call) => call.target.symbol))];
|
|
584
|
+
const relativeFile = toPosixRelative(root, file);
|
|
585
|
+
const targetCalls = (analysis?.calls ?? []).map(({ node, target }) => ({
|
|
586
|
+
symbol: target.symbol,
|
|
587
|
+
// A helper's or a method's arguments are not the project function's, so they say nothing about its inputs.
|
|
588
|
+
args: target.ownArgs ? node.arguments.map(literalArgument) : [],
|
|
589
|
+
asserted: target.assertedInside || (target.flowsToResult && analysis?.asserted.has(node) === true),
|
|
590
|
+
location: location(source, node, relativeFile),
|
|
591
|
+
}));
|
|
592
|
+
// Tautological only when every compared value (subject and expected) is a compile-time
|
|
593
|
+
// constant; runtime values such as process.env or non-project call results are not.
|
|
594
|
+
const comparisons = assertions.filter((assertion) => !isAssertionCountCall(assertion));
|
|
595
|
+
const tautological = comparisons.length > 0 &&
|
|
596
|
+
comparisons.every((assertion) => comparedValues(assertion).every((value) => isCompileTimeConstant(value, checker)));
|
|
597
|
+
const applicableMocks = mocks.filter((mock) => mockApplies(mock, registrationCall, callback));
|
|
598
|
+
const usesMocks = applicableMocks.length > 0;
|
|
599
|
+
const mockedTarget = applicableMocks.some((mock) => mock.targets.some((target) => calledSymbols.includes(target)));
|
|
600
|
+
const usesSnapshots = nodes.some((node) => ts.isCallExpression(node) &&
|
|
601
|
+
/\.(toMatchSnapshot|toMatchInlineSnapshot|toMatchFileSnapshot)\s*\(/.test(node.getText()));
|
|
602
|
+
const fakeTimers = nodes.some((node) => ts.isCallExpression(node) && node.getText().includes('useFakeTimers'));
|
|
603
|
+
const nondeterminism = [...new Set(nodes.flatMap((node) => nondeterminismFor(node, fakeTimers)))];
|
|
604
|
+
const suspicions = [];
|
|
605
|
+
if (assertions.length === 0 && !analysis?.helperAsserts && !callsHelperWithAssertion(body, source))
|
|
606
|
+
suspicions.push('no_assertion');
|
|
607
|
+
if (tautological)
|
|
608
|
+
suspicions.push('tautological_assertion');
|
|
609
|
+
// Code that runs when the file loads (outside any function), its own or that of the local modules it imports,
|
|
610
|
+
// runs before every test in it.
|
|
611
|
+
const loading = fileLoadReach(source, ctx);
|
|
612
|
+
const opaque = analysis?.opaque === true || loading.opaque;
|
|
613
|
+
const unresolved = unresolvedImports.size > 0 || loading.unresolved;
|
|
614
|
+
// An unresolved import, a child process or a dynamic import may well reach project code: absence is not proven.
|
|
615
|
+
if (calledSymbols.length === 0 && !unresolved && !opaque)
|
|
616
|
+
suspicions.push('target_not_called');
|
|
617
|
+
if (mockedTarget)
|
|
618
|
+
suspicions.push('unconditional_mock');
|
|
619
|
+
if (unresolved)
|
|
620
|
+
suspicions.push('unresolved_import');
|
|
621
|
+
if (opaque)
|
|
622
|
+
suspicions.push('opaque_call');
|
|
623
|
+
return {
|
|
624
|
+
id: testId(toPosixRelative(root, file), suitePath, name),
|
|
625
|
+
file: toPosixRelative(root, file),
|
|
626
|
+
name,
|
|
627
|
+
suitePath,
|
|
628
|
+
location: location(source, registrationCall, relativeFile),
|
|
629
|
+
modifiers: [...new Set(info.modifiers)],
|
|
630
|
+
assertionCount: assertions.length,
|
|
631
|
+
calledSymbols,
|
|
632
|
+
targetCalls,
|
|
633
|
+
usesMocks,
|
|
634
|
+
usesSnapshots,
|
|
635
|
+
nondeterminism,
|
|
636
|
+
suspicions,
|
|
637
|
+
granularity: info.name === undefined ? 'suite' : 'test',
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
function resolveProjectCall(node, checker, projectSet, root) {
|
|
641
|
+
return projectSymbolId(checker.getSymbolAtLocation(node.expression), checker, projectSet, root);
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Local files a source file reaches through static imports, re-exports and literal `import()`, transitively. Declaration files and dependencies under node_modules are not followed: a workspace package
|
|
645
|
+
* imported through its built `.d.ts` runs its build output, which changing the source does not affect.
|
|
646
|
+
*/
|
|
647
|
+
function localDependencies(start, checker, root) {
|
|
648
|
+
const seen = new Set([start]);
|
|
649
|
+
const queue = [start];
|
|
650
|
+
for (let source = queue.shift(); source; source = queue.shift()) {
|
|
651
|
+
for (const node of descendants(source)) {
|
|
652
|
+
let specifier;
|
|
653
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier)
|
|
654
|
+
specifier = node.moduleSpecifier;
|
|
655
|
+
else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword)
|
|
656
|
+
specifier = node.arguments[0];
|
|
657
|
+
if (!specifier || !ts.isStringLiteralLike(specifier))
|
|
658
|
+
continue;
|
|
659
|
+
const target = checker
|
|
660
|
+
.getSymbolAtLocation(specifier)
|
|
661
|
+
?.declarations?.find((declaration) => ts.isSourceFile(declaration));
|
|
662
|
+
if (!target || !ts.isSourceFile(target) || target.isDeclarationFile || seen.has(target))
|
|
663
|
+
continue;
|
|
664
|
+
const relative = path.relative(root, path.resolve(target.fileName));
|
|
665
|
+
if (relative.startsWith('..') ||
|
|
666
|
+
path.isAbsolute(relative) ||
|
|
667
|
+
relative.split(path.sep).includes('node_modules'))
|
|
668
|
+
continue;
|
|
669
|
+
seen.add(target);
|
|
670
|
+
queue.push(target);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return [...seen]
|
|
674
|
+
.filter((source) => source !== start)
|
|
675
|
+
.map((source) => toPosixRelative(root, source.fileName))
|
|
676
|
+
.sort();
|
|
677
|
+
}
|
|
678
|
+
const TEST_SUPPORT_DIRECTORIES = new Set(['test', 'tests', '__tests__', '__mocks__', 'e2e']);
|
|
679
|
+
/**
|
|
680
|
+
* Whether a file (POSIX, relative to the root) lives in a test directory. Helpers next to the tests are test
|
|
681
|
+
* code even when a broad include matches them: they are followed, not targets.
|
|
682
|
+
*/
|
|
683
|
+
export function isTestSupportPath(relative) {
|
|
684
|
+
return relative
|
|
685
|
+
.split('/')
|
|
686
|
+
.slice(0, -1)
|
|
687
|
+
.some((segment) => TEST_SUPPORT_DIRECTORIES.has(segment));
|
|
688
|
+
}
|
|
689
|
+
function isTestSupportFile(root, file) {
|
|
690
|
+
return isTestSupportPath(toPosixRelative(root, file));
|
|
691
|
+
}
|
|
692
|
+
function bindingIdentifiers(name) {
|
|
693
|
+
if (ts.isIdentifier(name))
|
|
694
|
+
return [name];
|
|
695
|
+
return name.elements.flatMap((element) => ts.isBindingElement(element) ? bindingIdentifiers(element.name) : []);
|
|
696
|
+
}
|
|
697
|
+
const moduleLoadCache = new WeakMap();
|
|
698
|
+
const fileLoadCache = new WeakMap();
|
|
699
|
+
/** `moduleLoadReach` of a test file and of every local file it imports, transitively. */
|
|
700
|
+
function fileLoadReach(source, ctx) {
|
|
701
|
+
const cached = fileLoadCache.get(source);
|
|
702
|
+
if (cached)
|
|
703
|
+
return cached;
|
|
704
|
+
const files = [
|
|
705
|
+
source,
|
|
706
|
+
...localDependencies(source, ctx.checker, ctx.root).map((file) => ctx.program.getSourceFile(path.resolve(ctx.root, file))),
|
|
707
|
+
].filter((file) => file !== undefined);
|
|
708
|
+
const reach = files.map((file) => moduleLoadReach(file, ctx.checker));
|
|
709
|
+
const result = { opaque: reach.some((r) => r.opaque), unresolved: reach.some((r) => r.unresolved) };
|
|
710
|
+
fileLoadCache.set(source, result);
|
|
711
|
+
return result;
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* What a file runs when it loads: opaque calls outside any function, and relative imports or re-exports that do
|
|
715
|
+
* not resolve (their module, if it exists at run time, is loaded and executed before the tests).
|
|
716
|
+
*/
|
|
717
|
+
function moduleLoadReach(source, checker) {
|
|
718
|
+
const cached = moduleLoadCache.get(source);
|
|
719
|
+
if (cached)
|
|
720
|
+
return cached;
|
|
721
|
+
let opaque = false;
|
|
722
|
+
let unresolved = false;
|
|
723
|
+
const visit = (node) => {
|
|
724
|
+
// A function body runs later, unless the function is invoked right away (an IIFE).
|
|
725
|
+
if (isFunctionLike(node)) {
|
|
726
|
+
let outer = node.parent;
|
|
727
|
+
while (ts.isParenthesizedExpression(outer))
|
|
728
|
+
outer = outer.parent;
|
|
729
|
+
const invoked = ts.isCallExpression(outer) && skipParens(outer.expression) === node;
|
|
730
|
+
if (!invoked)
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (ts.isCallExpression(node) && isOpaqueCall(node, checker))
|
|
734
|
+
opaque = true;
|
|
735
|
+
const specifier = ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : undefined;
|
|
736
|
+
if (specifier &&
|
|
737
|
+
ts.isStringLiteral(specifier) &&
|
|
738
|
+
specifier.text.startsWith('.') &&
|
|
739
|
+
!checker.getSymbolAtLocation(specifier))
|
|
740
|
+
unresolved = true;
|
|
741
|
+
ts.forEachChild(node, visit);
|
|
742
|
+
};
|
|
743
|
+
ts.forEachChild(source, visit);
|
|
744
|
+
const result = { opaque, unresolved };
|
|
745
|
+
moduleLoadCache.set(source, result);
|
|
746
|
+
return result;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Whether a file runs code out of process, loads modules at run time (dynamic import, `require`, `createRequire`),
|
|
750
|
+
* or imports a relative module that does not resolve.
|
|
751
|
+
*/
|
|
752
|
+
function hasUnseenReach(source, checker) {
|
|
753
|
+
return descendants(source).some((node) => {
|
|
754
|
+
if (ts.isCallExpression(node))
|
|
755
|
+
return isOpaqueCall(node, checker);
|
|
756
|
+
const specifier = ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : undefined;
|
|
757
|
+
return (specifier !== undefined &&
|
|
758
|
+
ts.isStringLiteral(specifier) &&
|
|
759
|
+
specifier.text.startsWith('.') &&
|
|
760
|
+
!checker.getSymbolAtLocation(specifier));
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
/** The relative module specifier a callee is imported from, when TypeScript cannot resolve that module. */
|
|
764
|
+
function unresolvedImportOf(callee, ctx) {
|
|
765
|
+
let current = skipParens(callee);
|
|
766
|
+
while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current))
|
|
767
|
+
current = skipParens(current.expression);
|
|
768
|
+
if (!ts.isIdentifier(current))
|
|
769
|
+
return undefined;
|
|
770
|
+
for (const declaration of ctx.checker.getSymbolAtLocation(current)?.declarations ?? []) {
|
|
771
|
+
const importDeclaration = ts.isImportSpecifier(declaration)
|
|
772
|
+
? declaration.parent.parent.parent
|
|
773
|
+
: ts.isNamespaceImport(declaration)
|
|
774
|
+
? declaration.parent.parent
|
|
775
|
+
: ts.isImportClause(declaration)
|
|
776
|
+
? declaration.parent
|
|
777
|
+
: undefined;
|
|
778
|
+
const specifier = importDeclaration?.moduleSpecifier;
|
|
779
|
+
if (!specifier || !ts.isStringLiteral(specifier) || !specifier.text.startsWith('.'))
|
|
780
|
+
continue;
|
|
781
|
+
// Ask the checker, not resolveModuleName: it applies the importing file's ESM/CJS resolution mode.
|
|
782
|
+
if (!ctx.checker.getSymbolAtLocation(specifier))
|
|
783
|
+
return specifier.text;
|
|
784
|
+
}
|
|
785
|
+
return undefined;
|
|
786
|
+
}
|
|
787
|
+
function projectSymbolId(input, checker, projectSet, root) {
|
|
788
|
+
let symbol = input;
|
|
789
|
+
if (!symbol)
|
|
790
|
+
return undefined;
|
|
791
|
+
if (symbol.flags & ts.SymbolFlags.Alias)
|
|
792
|
+
symbol = checker.getAliasedSymbol(symbol);
|
|
793
|
+
const declaration = symbol.declarations?.find((item) => projectSet.has(path.resolve(item.getSourceFile().fileName)));
|
|
794
|
+
if (!declaration)
|
|
795
|
+
return undefined;
|
|
796
|
+
return symbolId(toPosixRelative(root, declaration.getSourceFile().fileName), symbol.getName());
|
|
797
|
+
}
|
|
798
|
+
const VI_MOCK_APIS = new Set(['mock', 'doMock', 'spyOn', 'fn', 'mocked', 'stubGlobal']);
|
|
799
|
+
/** `vi.<name>(...)` where `vi` is Vitest's (imported from 'vitest' or the ambient global). */
|
|
800
|
+
function viCall(node, checker) {
|
|
801
|
+
if (!ts.isCallExpression(node))
|
|
802
|
+
return undefined;
|
|
803
|
+
const callee = node.expression;
|
|
804
|
+
if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.expression))
|
|
805
|
+
return undefined;
|
|
806
|
+
if (callee.expression.text !== 'vi')
|
|
807
|
+
return undefined;
|
|
808
|
+
const declarations = checker.getSymbolAtLocation(callee.expression)?.declarations ?? [];
|
|
809
|
+
const fromVitest = declarations.every((declaration) => {
|
|
810
|
+
if (!ts.isImportSpecifier(declaration))
|
|
811
|
+
return declaration.getSourceFile().isDeclarationFile;
|
|
812
|
+
const specifier = declaration.parent.parent.parent.moduleSpecifier;
|
|
813
|
+
return ts.isStringLiteral(specifier) && specifier.text === 'vitest';
|
|
814
|
+
});
|
|
815
|
+
return fromVitest ? callee.name.text : undefined;
|
|
816
|
+
}
|
|
817
|
+
function collectMocks(source, ctx) {
|
|
818
|
+
const { checker, projectSet, root } = ctx;
|
|
819
|
+
const records = [];
|
|
820
|
+
const spyTargets = (spy) => {
|
|
821
|
+
const target = skipParens(spy);
|
|
822
|
+
if (!ts.isCallExpression(target))
|
|
823
|
+
return [];
|
|
824
|
+
const api = viCall(target, checker);
|
|
825
|
+
if (api === 'mocked') {
|
|
826
|
+
const argument = target.arguments[0];
|
|
827
|
+
const id = argument && projectSymbolId(checker.getSymbolAtLocation(argument), checker, projectSet, root);
|
|
828
|
+
return id ? [id] : [];
|
|
829
|
+
}
|
|
830
|
+
if (api !== 'spyOn')
|
|
831
|
+
return [];
|
|
832
|
+
const [object, nameNode] = target.arguments;
|
|
833
|
+
const name = literalString(nameNode);
|
|
834
|
+
if (!object || name === undefined)
|
|
835
|
+
return [];
|
|
836
|
+
let owner = checker.getSymbolAtLocation(object);
|
|
837
|
+
if (owner && owner.flags & ts.SymbolFlags.Alias)
|
|
838
|
+
owner = checker.getAliasedSymbol(owner);
|
|
839
|
+
const member = owner && owner.flags & ts.SymbolFlags.ValueModule
|
|
840
|
+
? checker.getExportsOfModule(owner).find((item) => item.getName() === name)
|
|
841
|
+
: checker.getTypeAtLocation(object).getProperty(name);
|
|
842
|
+
const id = projectSymbolId(member, checker, projectSet, root);
|
|
843
|
+
return id ? [id] : [];
|
|
844
|
+
};
|
|
845
|
+
const spyVariable = (identifier) => {
|
|
846
|
+
const declaration = checker.getSymbolAtLocation(identifier)?.valueDeclaration;
|
|
847
|
+
if (!declaration || !ts.isVariableDeclaration(declaration) || !declaration.initializer)
|
|
848
|
+
return undefined;
|
|
849
|
+
const api = viCall(skipParens(declaration.initializer), checker);
|
|
850
|
+
return api === 'spyOn' || api === 'mocked' || api === 'fn'
|
|
851
|
+
? spyTargets(declaration.initializer)
|
|
852
|
+
: undefined;
|
|
853
|
+
};
|
|
854
|
+
for (const node of descendants(source)) {
|
|
855
|
+
if (!ts.isCallExpression(node))
|
|
856
|
+
continue;
|
|
857
|
+
const api = viCall(node, checker);
|
|
858
|
+
if (api && VI_MOCK_APIS.has(api)) {
|
|
859
|
+
const targets = api === 'mock' || api === 'doMock' ? moduleExports(node.arguments[0], ctx) : [];
|
|
860
|
+
records.push({ node, fileWide: api === 'mock', targets });
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
// `<spy>.mockReturnValue(...)` and friends, only on real Vitest spies.
|
|
864
|
+
const callee = node.expression;
|
|
865
|
+
if (!ts.isPropertyAccessExpression(callee) || !/^mock[A-Z]/.test(callee.name.text))
|
|
866
|
+
continue;
|
|
867
|
+
const receiver = skipParens(callee.expression);
|
|
868
|
+
const receiverApi = viCall(receiver, checker);
|
|
869
|
+
if (receiverApi === 'spyOn' || receiverApi === 'mocked' || receiverApi === 'fn')
|
|
870
|
+
records.push({ node, fileWide: false, targets: spyTargets(receiver) });
|
|
871
|
+
else if (ts.isIdentifier(receiver)) {
|
|
872
|
+
const targets = spyVariable(receiver);
|
|
873
|
+
if (targets)
|
|
874
|
+
records.push({ node, fileWide: false, targets });
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
return records;
|
|
878
|
+
}
|
|
879
|
+
/** Project symbols exported by the module a `vi.mock(specifier)` call replaces. */
|
|
880
|
+
function moduleExports(argument, ctx) {
|
|
881
|
+
if (!argument)
|
|
882
|
+
return [];
|
|
883
|
+
let specifierNode = skipParens(argument);
|
|
884
|
+
if (ts.isCallExpression(specifierNode) &&
|
|
885
|
+
specifierNode.expression.kind === ts.SyntaxKind.ImportKeyword &&
|
|
886
|
+
specifierNode.arguments[0])
|
|
887
|
+
specifierNode = specifierNode.arguments[0];
|
|
888
|
+
const specifier = literalString(specifierNode);
|
|
889
|
+
if (specifier === undefined)
|
|
890
|
+
return [];
|
|
891
|
+
const resolved = ts.resolveModuleName(specifier, ctx.file, ctx.compilerOptions, ts.sys).resolvedModule;
|
|
892
|
+
const sourceFile = resolved && ctx.program.getSourceFile(resolved.resolvedFileName);
|
|
893
|
+
const moduleSymbol = sourceFile && ctx.checker.getSymbolAtLocation(sourceFile);
|
|
894
|
+
if (!moduleSymbol)
|
|
895
|
+
return [];
|
|
896
|
+
return ctx.checker
|
|
897
|
+
.getExportsOfModule(moduleSymbol)
|
|
898
|
+
.map((item) => projectSymbolId(item, ctx.checker, ctx.projectSet, ctx.root))
|
|
899
|
+
.filter((id) => id !== undefined);
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* A mock applies to a test when it is inside that test's body, is a hoisted `vi.mock`, or sits
|
|
903
|
+
* outside every test body (module level or a describe/hook) within describes enclosing the test.
|
|
904
|
+
*/
|
|
905
|
+
function mockApplies(mock, registrationCall, callback) {
|
|
906
|
+
if (mock.fileWide)
|
|
907
|
+
return true;
|
|
908
|
+
if (callback && contains(callback, mock.node))
|
|
909
|
+
return true;
|
|
910
|
+
for (let current = mock.node.parent; current; current = current.parent) {
|
|
911
|
+
if (!ts.isCallExpression(current))
|
|
912
|
+
continue;
|
|
913
|
+
const test = testRegistration(current);
|
|
914
|
+
if (test?.callback && isFunction(test.callback) && contains(test.callback, mock.node))
|
|
915
|
+
return false;
|
|
916
|
+
const suite = describeRegistration(current);
|
|
917
|
+
if (suite?.callback && contains(suite.callback, mock.node) && !contains(suite.callback, registrationCall))
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
return true;
|
|
921
|
+
}
|
|
922
|
+
function isAssertionCountCall(node) {
|
|
923
|
+
return (ts.isPropertyAccessExpression(node.expression) &&
|
|
924
|
+
['assertions', 'hasAssertions'].includes(node.expression.name.text));
|
|
925
|
+
}
|
|
926
|
+
/** Values an assertion compares: the expect subject plus matcher arguments, or assert.* arguments. */
|
|
927
|
+
function comparedValues(assertion) {
|
|
928
|
+
const values = [...assertion.arguments];
|
|
929
|
+
if (!isExpectCall(assertion))
|
|
930
|
+
return values;
|
|
931
|
+
let current = assertion;
|
|
932
|
+
while (ts.isPropertyAccessExpression(current.parent) && current.parent.expression === current)
|
|
933
|
+
current = current.parent;
|
|
934
|
+
if (current !== assertion && ts.isCallExpression(current.parent) && current.parent.expression === current)
|
|
935
|
+
values.push(...current.parent.arguments);
|
|
936
|
+
return values;
|
|
937
|
+
}
|
|
938
|
+
/** Literals, and `const` bindings initialised with constants, recursively. */
|
|
939
|
+
function isCompileTimeConstant(node, checker, depth = 0) {
|
|
940
|
+
if (depth > 20)
|
|
941
|
+
return false;
|
|
942
|
+
const expression = skipParens(node);
|
|
943
|
+
if (literalArgument(expression) !== null)
|
|
944
|
+
return true;
|
|
945
|
+
if (ts.isNoSubstitutionTemplateLiteral(expression) || ts.isRegularExpressionLiteral(expression))
|
|
946
|
+
return true;
|
|
947
|
+
if (ts.isPrefixUnaryExpression(expression))
|
|
948
|
+
return isCompileTimeConstant(expression.operand, checker, depth + 1);
|
|
949
|
+
if (ts.isArrayLiteralExpression(expression))
|
|
950
|
+
return expression.elements.every((element) => !ts.isSpreadElement(element) && isCompileTimeConstant(element, checker, depth + 1));
|
|
951
|
+
if (ts.isObjectLiteralExpression(expression))
|
|
952
|
+
return expression.properties.every((property) => ts.isPropertyAssignment(property) &&
|
|
953
|
+
!ts.isComputedPropertyName(property.name) &&
|
|
954
|
+
isCompileTimeConstant(property.initializer, checker, depth + 1));
|
|
955
|
+
if (ts.isIdentifier(expression)) {
|
|
956
|
+
if (expression.text === 'undefined')
|
|
957
|
+
return true;
|
|
958
|
+
const declaration = checker.getSymbolAtLocation(expression)?.valueDeclaration;
|
|
959
|
+
return Boolean(declaration &&
|
|
960
|
+
ts.isVariableDeclaration(declaration) &&
|
|
961
|
+
ts.isVariableDeclarationList(declaration.parent) &&
|
|
962
|
+
declaration.parent.flags & ts.NodeFlags.Const &&
|
|
963
|
+
declaration.initializer &&
|
|
964
|
+
isCompileTimeConstant(declaration.initializer, checker, depth + 1));
|
|
965
|
+
}
|
|
966
|
+
return false;
|
|
967
|
+
}
|
|
968
|
+
function skipParens(node) {
|
|
969
|
+
let current = node;
|
|
970
|
+
while (ts.isParenthesizedExpression(current) ||
|
|
971
|
+
ts.isAsExpression(current) ||
|
|
972
|
+
ts.isNonNullExpression(current))
|
|
973
|
+
current = current.expression;
|
|
974
|
+
return current;
|
|
975
|
+
}
|
|
976
|
+
function nondeterminismFor(node, fakeTimers) {
|
|
977
|
+
const text = node.getText();
|
|
978
|
+
if (!ts.isCallExpression(node) && !ts.isNewExpression(node))
|
|
979
|
+
return [];
|
|
980
|
+
const values = [];
|
|
981
|
+
if (text.includes('Math.random'))
|
|
982
|
+
values.push('Math.random');
|
|
983
|
+
if (text.includes('Date.now'))
|
|
984
|
+
values.push('Date.now');
|
|
985
|
+
if (ts.isNewExpression(node) && text.startsWith('new Date') && node.arguments?.length === 0)
|
|
986
|
+
values.push('new Date()');
|
|
987
|
+
if (text.includes('crypto.randomUUID'))
|
|
988
|
+
values.push('crypto.randomUUID');
|
|
989
|
+
if (!fakeTimers && /\b(setTimeout|setInterval|setImmediate|queueMicrotask)\s*\(/.test(text))
|
|
990
|
+
values.push('timer');
|
|
991
|
+
return values;
|
|
992
|
+
}
|
|
993
|
+
function callsHelperWithAssertion(body, source) {
|
|
994
|
+
if (!body)
|
|
995
|
+
return false;
|
|
996
|
+
const names = new Set();
|
|
997
|
+
for (const node of descendants(body))
|
|
998
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression))
|
|
999
|
+
names.add(node.expression.text);
|
|
1000
|
+
let found = false;
|
|
1001
|
+
const visit = (node) => {
|
|
1002
|
+
if (ts.isFunctionDeclaration(node) && node.name && names.has(node.name.text)) {
|
|
1003
|
+
found ||= descendants(node).some((child) => ts.isCallExpression(child) && (isExpectCall(child) || isAssertCall(child)));
|
|
1004
|
+
}
|
|
1005
|
+
if (ts.isVariableDeclaration(node) &&
|
|
1006
|
+
ts.isIdentifier(node.name) &&
|
|
1007
|
+
names.has(node.name.text) &&
|
|
1008
|
+
node.initializer) {
|
|
1009
|
+
found ||= descendants(node.initializer).some((child) => ts.isCallExpression(child) && (isExpectCall(child) || isAssertCall(child)));
|
|
1010
|
+
}
|
|
1011
|
+
ts.forEachChild(node, visit);
|
|
1012
|
+
};
|
|
1013
|
+
ts.forEachChild(source, visit);
|
|
1014
|
+
return found;
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Function declarations of the file (`function f(...)`, or the declaration of `const f = (...) =>`) mapped to the
|
|
1018
|
+
* parameter positions that the subject of one of their assertions refers to, without comparing it with itself.
|
|
1019
|
+
*/
|
|
1020
|
+
const assertingHelpersCache = new WeakMap();
|
|
1021
|
+
function assertingHelpers(source) {
|
|
1022
|
+
const cached = assertingHelpersCache.get(source);
|
|
1023
|
+
if (cached)
|
|
1024
|
+
return cached;
|
|
1025
|
+
const helpers = new Map();
|
|
1026
|
+
const names = (node) => new Set([node, ...descendants(node)].filter(ts.isIdentifier).map((identifier) => identifier.text));
|
|
1027
|
+
const record = (declaration, fn) => {
|
|
1028
|
+
if (!fn.body)
|
|
1029
|
+
return;
|
|
1030
|
+
const params = fn.parameters.map((p) => (ts.isIdentifier(p.name) ? p.name.text : undefined));
|
|
1031
|
+
const positions = new Set();
|
|
1032
|
+
for (const child of descendants(fn.body)) {
|
|
1033
|
+
if (!ts.isCallExpression(child) || !(isExpectCall(child) || isAssertCall(child)))
|
|
1034
|
+
continue;
|
|
1035
|
+
if (isAssertionCountCall(child))
|
|
1036
|
+
continue;
|
|
1037
|
+
const [subject, ...expected] = comparedValues(child);
|
|
1038
|
+
if (!subject)
|
|
1039
|
+
continue;
|
|
1040
|
+
const inSubject = names(subject);
|
|
1041
|
+
const inExpected = new Set(expected.flatMap((value) => [...names(value)]));
|
|
1042
|
+
params.forEach((param, index) => {
|
|
1043
|
+
// Comparing a parameter with itself (`expect(v).toBe(v)`) always holds and asserts nothing.
|
|
1044
|
+
if (param !== undefined && inSubject.has(param) && !inExpected.has(param))
|
|
1045
|
+
positions.add(index);
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
if (positions.size > 0)
|
|
1049
|
+
helpers.set(declaration, positions);
|
|
1050
|
+
};
|
|
1051
|
+
const visit = (node) => {
|
|
1052
|
+
if (ts.isFunctionDeclaration(node) && node.name)
|
|
1053
|
+
record(node, node);
|
|
1054
|
+
if (ts.isVariableDeclaration(node) &&
|
|
1055
|
+
ts.isIdentifier(node.name) &&
|
|
1056
|
+
node.initializer &&
|
|
1057
|
+
isFunction(node.initializer))
|
|
1058
|
+
record(node, node.initializer);
|
|
1059
|
+
ts.forEachChild(node, visit);
|
|
1060
|
+
};
|
|
1061
|
+
ts.forEachChild(source, visit);
|
|
1062
|
+
assertingHelpersCache.set(source, helpers);
|
|
1063
|
+
return helpers;
|
|
1064
|
+
}
|
|
1065
|
+
function isExpectCall(node) {
|
|
1066
|
+
return rootIdentifier(node.expression) === 'expect';
|
|
1067
|
+
}
|
|
1068
|
+
function isAssertCall(node) {
|
|
1069
|
+
return (ts.isPropertyAccessExpression(node.expression) &&
|
|
1070
|
+
(node.expression.expression.getText() === 'assert' || node.expression.name.text === 'assertions'));
|
|
1071
|
+
}
|
|
1072
|
+
function rootIdentifier(expression) {
|
|
1073
|
+
let current = expression;
|
|
1074
|
+
while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current))
|
|
1075
|
+
current = current.expression;
|
|
1076
|
+
return ts.isIdentifier(current) ? current.text : undefined;
|
|
1077
|
+
}
|
|
1078
|
+
function propertyChain(expression) {
|
|
1079
|
+
const chain = [];
|
|
1080
|
+
let current = expression;
|
|
1081
|
+
while (ts.isPropertyAccessExpression(current)) {
|
|
1082
|
+
chain.push(current.name.text);
|
|
1083
|
+
current = current.expression;
|
|
1084
|
+
}
|
|
1085
|
+
return chain;
|
|
1086
|
+
}
|
|
1087
|
+
function descendants(node) {
|
|
1088
|
+
const result = [];
|
|
1089
|
+
const visit = (current) => {
|
|
1090
|
+
result.push(current);
|
|
1091
|
+
ts.forEachChild(current, visit);
|
|
1092
|
+
};
|
|
1093
|
+
ts.forEachChild(node, visit);
|
|
1094
|
+
return result;
|
|
1095
|
+
}
|
|
1096
|
+
function contains(parent, child) {
|
|
1097
|
+
return child.getStart() >= parent.getStart() && child.getEnd() <= parent.getEnd();
|
|
1098
|
+
}
|
|
1099
|
+
function location(source, node, file) {
|
|
1100
|
+
return {
|
|
1101
|
+
file,
|
|
1102
|
+
range: {
|
|
1103
|
+
start: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
|
|
1104
|
+
end: source.getLineAndCharacterOfPosition(node.getEnd()).line + 1,
|
|
1105
|
+
},
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Source text of a literal argument, or null. Numeric literals are normalised to decimal
|
|
1110
|
+
* (`0x10` -> `'16'`), a leading `-`/`+` on a numeric or bigint literal is folded in (`-1` -> `'-1'`),
|
|
1111
|
+
* and parentheses are ignored.
|
|
1112
|
+
*/
|
|
1113
|
+
/**
|
|
1114
|
+
* The literal text of a call argument, or null. Arrays and object literals of number/boolean literals are
|
|
1115
|
+
* recorded as JSON with numbers as decimal strings (`["1","2"]`, `{"total":"1000","vip":true}`), so they stay exact.
|
|
1116
|
+
*/
|
|
1117
|
+
function literalArgument(input) {
|
|
1118
|
+
const node = skipParens(input);
|
|
1119
|
+
const scalar = (e) => {
|
|
1120
|
+
const text = literalArgument(e);
|
|
1121
|
+
if (text === 'true' || text === 'false')
|
|
1122
|
+
return text === 'true';
|
|
1123
|
+
return text !== null && /^-?\d+(?:\.\d+)?$/.test(text) ? text : null;
|
|
1124
|
+
};
|
|
1125
|
+
if (ts.isArrayLiteralExpression(node)) {
|
|
1126
|
+
const values = node.elements.map((e) => (ts.isSpreadElement(e) ? null : scalar(e)));
|
|
1127
|
+
return values.every((v) => v !== null) ? JSON.stringify(values) : null;
|
|
1128
|
+
}
|
|
1129
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
1130
|
+
const out = {};
|
|
1131
|
+
for (const prop of node.properties) {
|
|
1132
|
+
if (!ts.isPropertyAssignment(prop))
|
|
1133
|
+
return null;
|
|
1134
|
+
const key = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;
|
|
1135
|
+
const value = scalar(prop.initializer);
|
|
1136
|
+
if (key === null || value === null)
|
|
1137
|
+
return null;
|
|
1138
|
+
out[key] = value;
|
|
1139
|
+
}
|
|
1140
|
+
return JSON.stringify(out);
|
|
1141
|
+
}
|
|
1142
|
+
// `text` is the value as a double; plain decimal digits are kept as written so large integers stay exact.
|
|
1143
|
+
const digits = (n) => (/^\d+$/.test(n.getText()) ? n.getText() : n.text);
|
|
1144
|
+
if (ts.isNumericLiteral(node))
|
|
1145
|
+
return digits(node);
|
|
1146
|
+
if (ts.isBigIntLiteral(node))
|
|
1147
|
+
return node.text;
|
|
1148
|
+
if (ts.isPrefixUnaryExpression(node) &&
|
|
1149
|
+
(node.operator === ts.SyntaxKind.MinusToken || node.operator === ts.SyntaxKind.PlusToken)) {
|
|
1150
|
+
const operand = skipParens(node.operand);
|
|
1151
|
+
if (!ts.isNumericLiteral(operand) && !ts.isBigIntLiteral(operand))
|
|
1152
|
+
return null;
|
|
1153
|
+
const text = ts.isNumericLiteral(operand) ? digits(operand) : operand.text;
|
|
1154
|
+
return node.operator === ts.SyntaxKind.MinusToken ? `-${text}` : text;
|
|
1155
|
+
}
|
|
1156
|
+
return ts.isStringLiteral(node) ||
|
|
1157
|
+
ts.isNoSubstitutionTemplateLiteral(node) ||
|
|
1158
|
+
node.kind === ts.SyntaxKind.TrueKeyword ||
|
|
1159
|
+
node.kind === ts.SyntaxKind.FalseKeyword ||
|
|
1160
|
+
node.kind === ts.SyntaxKind.NullKeyword
|
|
1161
|
+
? node.getText()
|
|
1162
|
+
: null;
|
|
1163
|
+
}
|
|
1164
|
+
function literalString(node) {
|
|
1165
|
+
return node && ts.isStringLiteralLike(node) ? node.text : undefined;
|
|
1166
|
+
}
|
|
1167
|
+
function isFunction(node) {
|
|
1168
|
+
return ts.isArrowFunction(node) || ts.isFunctionExpression(node);
|
|
1169
|
+
}
|
|
1170
|
+
function isSourceFile(file) {
|
|
1171
|
+
return /\.(?:[cm]?ts|tsx|[cm]?js|jsx)$/.test(file);
|
|
1172
|
+
}
|
|
1173
|
+
function collectFiles(root, includes, excludes) {
|
|
1174
|
+
const result = [];
|
|
1175
|
+
const walk = (dir) => {
|
|
1176
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
1177
|
+
if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.'))
|
|
1178
|
+
continue;
|
|
1179
|
+
const file = path.join(dir, entry.name);
|
|
1180
|
+
if (entry.isDirectory())
|
|
1181
|
+
walk(file);
|
|
1182
|
+
// Links are not followed: one could point outside the project root.
|
|
1183
|
+
else if (entry.isFile() && isSourceFile(file)) {
|
|
1184
|
+
const relative = toPosixRelative(root, file);
|
|
1185
|
+
if (includes.some((pattern) => expandBraces(pattern).some((expanded) => globMatches(relative, expanded))) &&
|
|
1186
|
+
!excludes.some((pattern) => expandBraces(pattern).some((expanded) => globMatches(relative, expanded))))
|
|
1187
|
+
result.push(file);
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
walk(root);
|
|
1192
|
+
return result.sort();
|
|
1193
|
+
}
|
|
1194
|
+
function globMatches(file, pattern) {
|
|
1195
|
+
const normalized = pattern.split('\\').join('/');
|
|
1196
|
+
let regex = '^';
|
|
1197
|
+
for (let index = 0; index < normalized.length;) {
|
|
1198
|
+
if (normalized.startsWith('**/', index)) {
|
|
1199
|
+
regex += '(?:.*/)?';
|
|
1200
|
+
index += 3;
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
if (normalized.startsWith('**', index)) {
|
|
1204
|
+
regex += '.*';
|
|
1205
|
+
index += 2;
|
|
1206
|
+
continue;
|
|
1207
|
+
}
|
|
1208
|
+
const character = normalized[index];
|
|
1209
|
+
if (character === undefined)
|
|
1210
|
+
break;
|
|
1211
|
+
if (character === '*')
|
|
1212
|
+
regex += '[^/]*';
|
|
1213
|
+
else if (character === '?')
|
|
1214
|
+
regex += '.';
|
|
1215
|
+
else
|
|
1216
|
+
regex += /[.+^${}()|[\]\\]/.test(character) ? `\\${character}` : character;
|
|
1217
|
+
index += 1;
|
|
1218
|
+
}
|
|
1219
|
+
return new RegExp(`${regex}$`).test(file);
|
|
1220
|
+
}
|
|
1221
|
+
function expandBraces(pattern) {
|
|
1222
|
+
const start = pattern.indexOf('{');
|
|
1223
|
+
if (start < 0)
|
|
1224
|
+
return [pattern];
|
|
1225
|
+
const end = pattern.indexOf('}', start);
|
|
1226
|
+
if (end < 0)
|
|
1227
|
+
return [pattern];
|
|
1228
|
+
return pattern
|
|
1229
|
+
.slice(start + 1, end)
|
|
1230
|
+
.split(',')
|
|
1231
|
+
.flatMap((part) => expandBraces(`${pattern.slice(0, start)}${part}${pattern.slice(end + 1)}`));
|
|
1232
|
+
}
|
|
1233
|
+
// Bundler resolution, like Vitest's: extensionless relative imports resolve, and so do `.js` specifiers for `.ts` files.
|
|
1234
|
+
const DEFAULT_COMPILER_OPTIONS = {
|
|
1235
|
+
module: ts.ModuleKind.ESNext,
|
|
1236
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
1237
|
+
target: ts.ScriptTarget.ES2024,
|
|
1238
|
+
allowJs: true,
|
|
1239
|
+
};
|
|
1240
|
+
/**
|
|
1241
|
+
* Compiler options from the project's tsconfig. Only files inside the root are read: a configured tsconfig
|
|
1242
|
+
* outside it (or behind a link leaving it), an `extends` base outside it and parent directories are ignored.
|
|
1243
|
+
*/
|
|
1244
|
+
function readCompilerOptions(root, config) {
|
|
1245
|
+
const inside = (name) => {
|
|
1246
|
+
try {
|
|
1247
|
+
resolveInsideRoot(root, name);
|
|
1248
|
+
return true;
|
|
1249
|
+
}
|
|
1250
|
+
catch {
|
|
1251
|
+
return false;
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
const configFile = path.resolve(root, config.project.tsconfig ?? 'tsconfig.json');
|
|
1255
|
+
if (!inside(configFile) || !ts.sys.fileExists(configFile))
|
|
1256
|
+
return DEFAULT_COMPILER_OPTIONS;
|
|
1257
|
+
const parsed = ts.readConfigFile(configFile, ts.sys.readFile);
|
|
1258
|
+
if (parsed.error)
|
|
1259
|
+
return DEFAULT_COMPILER_OPTIONS;
|
|
1260
|
+
const host = {
|
|
1261
|
+
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
|
|
1262
|
+
readDirectory: (dir, ...rest) => (inside(dir) ? ts.sys.readDirectory(dir, ...rest) : []),
|
|
1263
|
+
fileExists: (name) => inside(name) && ts.sys.fileExists(name),
|
|
1264
|
+
readFile: (name) => (inside(name) ? ts.sys.readFile(name) : undefined),
|
|
1265
|
+
};
|
|
1266
|
+
return ts.parseJsonConfigFileContent(parsed.config, host, path.dirname(configFile)).options;
|
|
1267
|
+
}
|
|
1268
|
+
//# sourceMappingURL=index.js.map
|