targeted-mutation 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 +201 -0
- package/NOTICE +21 -0
- package/README.md +111 -2
- package/bin/tmt-compile.mjs +46 -0
- package/bin/tmt.mjs +117 -0
- package/build/typescript-syntax/LICENSE.txt +55 -0
- package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
- package/build/typescript-syntax/typescript-syntax.cjs +43 -0
- package/docs/analysis.md +218 -0
- package/docs/compiler.md +462 -0
- package/docs/development.md +61 -0
- package/docs/how-it-works.svg +188 -0
- package/docs/l1.md +94 -0
- package/docs/performance.md +647 -0
- package/docs/releasing.md +48 -0
- package/package.json +49 -4
- package/src/analysis.mjs +689 -0
- package/src/assertion-session.mjs +93 -0
- package/src/assertion-strength.mjs +795 -0
- package/src/builtin-mutations.mjs +755 -0
- package/src/builtin-switches.mjs +642 -0
- package/src/change-undone.mjs +524 -0
- package/src/cli-output.mjs +166 -0
- package/src/compiler-compat.cjs +108 -0
- package/src/compiler-maps.cjs +60 -0
- package/src/compiler-routes.cjs +391 -0
- package/src/compiler.cjs +98 -0
- package/src/compiler.mjs +1 -0
- package/src/conventional.mjs +172 -0
- package/src/displacement.mjs +19 -0
- package/src/extract.mjs +135 -0
- package/src/fallback-process.mjs +14 -0
- package/src/in-parallel.mjs +20 -0
- package/src/lean-replay.mjs +39 -0
- package/src/operator-analysis.mjs +123 -0
- package/src/playwright.mjs +139 -0
- package/src/probe-runtime.mjs +50 -0
- package/src/probe.mjs +170 -0
- package/src/prototype.mjs +230 -0
- package/src/regex-mutations.mjs +102 -0
- package/src/runner-process.mjs +59 -0
- package/src/runtime-binaries.mjs +50 -0
- package/src/scope.mjs +202 -0
- package/src/source-text.mjs +49 -0
- package/src/standard-plan.mjs +308 -0
- package/src/standard-runner.mjs +185 -0
- package/src/standard-session.mjs +362 -0
- package/src/standard-setup.mjs +20 -0
- package/src/targeted-gaps.mjs +85 -0
- package/src/threshold.mjs +185 -0
- package/src/trace-buffer.mjs +126 -0
- package/src/typescript-bindings.mjs +243 -0
- package/src/typescript-compiler.mjs +59 -0
- package/src/typescript-extraction.mjs +354 -0
- package/src/typescript-grammar.mjs +923 -0
- package/src/vitest-reporter.mjs +64 -0
- package/src/vitest.mjs +262 -0
- package/src/witness-analysis.mjs +234 -0
- package/src/witness-contracts.mjs +110 -0
- package/src/witness-discovery.mjs +239 -0
- package/src/witness-fixtures.mjs +148 -0
- package/src/witness-order.mjs +83 -0
- package/src/witness-rules.mjs +254 -0
|
@@ -0,0 +1,795 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
4
|
+
import { availableParallelism } from 'node:os';
|
|
5
|
+
import { dirname, posix, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { sourceTrialsAsync } from './analysis.mjs';
|
|
8
|
+
import { inParallel } from './in-parallel.mjs';
|
|
9
|
+
import { loadTypeScript } from './typescript-compiler.mjs';
|
|
10
|
+
import { inside, withCopy } from './vitest.mjs';
|
|
11
|
+
|
|
12
|
+
// A test can make the very call that tells an edit from the original and still pass, because its assertion does
|
|
13
|
+
// not pin the result down: `expect(bucket(3)).not.toBe('none')`, `expect(total(1, 2)).toBeGreaterThan(0)`, a call
|
|
14
|
+
// whose result is not looked at. For a finding that names such tests, the call is run where the test makes it,
|
|
15
|
+
// once as it is and once with the edit, and where the two values differ the report gives the value to compare with.
|
|
16
|
+
const pinning = new Set(['toBe', 'toEqual', 'toStrictEqual', 'toBeNull', 'toBeUndefined', 'toBeNaN', 'toBeCloseTo',
|
|
17
|
+
'toMatchSnapshot', 'toMatchInlineSnapshot', 'toMatchObject']);
|
|
18
|
+
const extension = /\.(?:[cm]?[jt]s|[jt]sx)$/;
|
|
19
|
+
const sourceExtensions = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
|
|
20
|
+
const defaultRun = { sourceTrialsAsync };
|
|
21
|
+
const sessionWorker = fileURLToPath(new URL('./assertion-session.mjs', import.meta.url));
|
|
22
|
+
|
|
23
|
+
function loadTsPaths(root, fromFile, ts, cache) {
|
|
24
|
+
let dir = dirname(resolve(root, fromFile));
|
|
25
|
+
const visited = [];
|
|
26
|
+
while (true) {
|
|
27
|
+
if (cache.tsconfigs.has(dir)) {
|
|
28
|
+
const found = cache.tsconfigs.get(dir);
|
|
29
|
+
for (const seen of visited) cache.tsconfigs.set(seen, found);
|
|
30
|
+
return found;
|
|
31
|
+
}
|
|
32
|
+
visited.push(dir);
|
|
33
|
+
const candidate = resolve(dir, 'tsconfig.json');
|
|
34
|
+
if (existsSync(candidate) && statSync(candidate).isFile()) {
|
|
35
|
+
let info = null;
|
|
36
|
+
try {
|
|
37
|
+
const read = ts.readConfigFile(candidate, file => readFileSync(file, 'utf8'));
|
|
38
|
+
if (!read.error && read.config) {
|
|
39
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dir, undefined, candidate);
|
|
40
|
+
const opts = parsed.options ?? {};
|
|
41
|
+
const paths = opts.paths && typeof opts.paths === 'object' ? opts.paths : null;
|
|
42
|
+
const baseDir = opts.baseUrl ? resolve(dir, opts.baseUrl) : (opts.pathsBasePath ?? dir);
|
|
43
|
+
if (paths || opts.baseUrl) info = { paths, baseDir, hasBaseUrl: Boolean(opts.baseUrl) };
|
|
44
|
+
}
|
|
45
|
+
} catch { /* ignore unreadable tsconfig */ }
|
|
46
|
+
for (const seen of visited) cache.tsconfigs.set(seen, info);
|
|
47
|
+
return info;
|
|
48
|
+
}
|
|
49
|
+
if (dir === root) break;
|
|
50
|
+
const parent = dirname(dir);
|
|
51
|
+
if (parent === dir || relative(root, parent).startsWith('..')) break;
|
|
52
|
+
dir = parent;
|
|
53
|
+
}
|
|
54
|
+
for (const seen of visited) cache.tsconfigs.set(seen, null);
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function candidatePathsFor(root, fromFile, specifier, ts, cache) {
|
|
59
|
+
const candidates = [];
|
|
60
|
+
if (specifier.startsWith('.')) {
|
|
61
|
+
candidates.push(resolve(dirname(resolve(root, fromFile)), specifier));
|
|
62
|
+
return candidates;
|
|
63
|
+
}
|
|
64
|
+
const tsPaths = loadTsPaths(root, fromFile, ts, cache);
|
|
65
|
+
if (!tsPaths) return candidates;
|
|
66
|
+
if (tsPaths.paths) {
|
|
67
|
+
// Follow TypeScript's `paths` precedence: an exact match wins immediately; otherwise the single wildcard
|
|
68
|
+
// pattern with the longest prefix (breaking ties by declaration order) wins, without falling back to other
|
|
69
|
+
// `paths` patterns if its substitutions are missing.
|
|
70
|
+
let bestExact = null;
|
|
71
|
+
let bestWildcard = null;
|
|
72
|
+
for (const [pattern, targets] of Object.entries(tsPaths.paths)) {
|
|
73
|
+
if (!Array.isArray(targets)) continue;
|
|
74
|
+
const star = pattern.indexOf('*');
|
|
75
|
+
if (star === -1) {
|
|
76
|
+
if (specifier === pattern && !bestExact) {
|
|
77
|
+
bestExact = targets.map(target => resolve(tsPaths.baseDir, target));
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
const prefix = pattern.slice(0, star);
|
|
81
|
+
const suffix = pattern.slice(star + 1);
|
|
82
|
+
if (specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length) {
|
|
83
|
+
if (!bestWildcard || prefix.length > bestWildcard.prefixLen) {
|
|
84
|
+
const matched = specifier.slice(prefix.length, specifier.length - suffix.length);
|
|
85
|
+
bestWildcard = { prefixLen: prefix.length, paths: targets.map(target => resolve(tsPaths.baseDir, target.replace('*', matched))) };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (bestExact) candidates.push(...bestExact);
|
|
91
|
+
else if (bestWildcard) candidates.push(...bestWildcard.paths);
|
|
92
|
+
}
|
|
93
|
+
if (tsPaths.hasBaseUrl) candidates.push(resolve(tsPaths.baseDir, specifier));
|
|
94
|
+
return candidates;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function resolveModuleInRoot(root, fromFile, specifier, ts, cache) {
|
|
98
|
+
const cacheKey = `${fromFile}\0${specifier}`;
|
|
99
|
+
if (cache.resolved.has(cacheKey)) return cache.resolved.get(cacheKey);
|
|
100
|
+
let found = null;
|
|
101
|
+
for (const base of candidatePathsFor(root, fromFile, specifier, ts, cache)) {
|
|
102
|
+
const stripped = base.replace(extension, '');
|
|
103
|
+
const tries = [base, ...sourceExtensions.map(ext => stripped + ext), ...sourceExtensions.map(ext => resolve(stripped, 'index' + ext))];
|
|
104
|
+
for (const file of tries) {
|
|
105
|
+
try {
|
|
106
|
+
if (!existsSync(file) || !statSync(file).isFile()) continue;
|
|
107
|
+
const safe = inside(root, file);
|
|
108
|
+
found = relative(root, safe).split(sep).join('/');
|
|
109
|
+
break;
|
|
110
|
+
} catch { /* escapes root or unreadable */ }
|
|
111
|
+
}
|
|
112
|
+
if (found) break;
|
|
113
|
+
}
|
|
114
|
+
cache.resolved.set(cacheKey, found);
|
|
115
|
+
return found;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function collectExportedLocalNames(tree, ts) {
|
|
119
|
+
const explicit = new Set();
|
|
120
|
+
const hasExportModifier = node => Boolean(node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword));
|
|
121
|
+
const hasDefaultModifier = node => Boolean(node.modifiers?.some(m => m.kind === ts.SyntaxKind.DefaultKeyword));
|
|
122
|
+
const collectBinding = binding => {
|
|
123
|
+
if (!binding) return;
|
|
124
|
+
if (ts.isIdentifier(binding)) explicit.add(binding.text);
|
|
125
|
+
else if (ts.isObjectBindingPattern(binding) || ts.isArrayBindingPattern(binding)) {
|
|
126
|
+
for (const el of binding.elements) if (ts.isBindingElement(el)) collectBinding(el.name);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
for (const stmt of tree.statements) {
|
|
130
|
+
if (ts.isExportDeclaration(stmt) && !stmt.isTypeOnly) {
|
|
131
|
+
if (stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
|
|
132
|
+
for (const el of stmt.exportClause.elements) if (!el.isTypeOnly) explicit.add(el.name.text);
|
|
133
|
+
} else if (stmt.exportClause && ts.isNamespaceExport(stmt.exportClause)) {
|
|
134
|
+
explicit.add(stmt.exportClause.name.text);
|
|
135
|
+
}
|
|
136
|
+
} else if (hasExportModifier(stmt) && !hasDefaultModifier(stmt)) {
|
|
137
|
+
if (ts.isVariableStatement(stmt)) {
|
|
138
|
+
for (const decl of stmt.declarationList.declarations) collectBinding(decl.name);
|
|
139
|
+
} else if ((ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt)) && stmt.name) {
|
|
140
|
+
explicit.add(stmt.name.text);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return explicit;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function exportsFromSubject(root, filePosix, subjectPosix, ts, cache, depth = 0, visiting = new Set()) {
|
|
148
|
+
if (filePosix === subjectPosix) {
|
|
149
|
+
return { all: true, excluded: new Set(), names: new Set(), defaultExport: true, namespaces: new Map() };
|
|
150
|
+
}
|
|
151
|
+
if (depth >= 4 || visiting.has(filePosix)) {
|
|
152
|
+
return { all: false, excluded: new Set(), names: new Set(), defaultExport: false, namespaces: new Map() };
|
|
153
|
+
}
|
|
154
|
+
const key = `${filePosix}\0${subjectPosix}`;
|
|
155
|
+
if (depth === 0 && cache.exports.has(key)) return cache.exports.get(key);
|
|
156
|
+
let tree = cache.asts.get(filePosix);
|
|
157
|
+
if (!tree) {
|
|
158
|
+
try {
|
|
159
|
+
const abs = inside(root, filePosix);
|
|
160
|
+
tree = ts.createSourceFile(filePosix, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true);
|
|
161
|
+
cache.asts.set(filePosix, tree);
|
|
162
|
+
} catch {
|
|
163
|
+
return { all: false, excluded: new Set(), names: new Set(), defaultExport: false, namespaces: new Map() };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const nextVisiting = new Set(visiting);
|
|
167
|
+
nextVisiting.add(filePosix);
|
|
168
|
+
// Explicit exports in this barrel override `export *` re-exports of the same name.
|
|
169
|
+
const explicitInBarrel = collectExportedLocalNames(tree, ts);
|
|
170
|
+
const info = { all: false, excluded: new Set(), names: new Set(), defaultExport: false, namespaces: new Map() };
|
|
171
|
+
const starChildren = [];
|
|
172
|
+
for (const statement of tree.statements) {
|
|
173
|
+
if (!ts.isExportDeclaration(statement) || statement.isTypeOnly || !statement.moduleSpecifier || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
174
|
+
const target = resolveModuleInRoot(root, filePosix, statement.moduleSpecifier.text, ts, cache);
|
|
175
|
+
if (!target) continue;
|
|
176
|
+
const child = exportsFromSubject(root, target, subjectPosix, ts, cache, depth + 1, nextVisiting);
|
|
177
|
+
if (!child.all && !child.defaultExport && !child.names.size && !child.namespaces.size) continue;
|
|
178
|
+
const clause = statement.exportClause;
|
|
179
|
+
if (!clause) {
|
|
180
|
+
starChildren.push(child);
|
|
181
|
+
} else if (ts.isNamespaceExport(clause)) {
|
|
182
|
+
if (child.all) info.namespaces.set(clause.name.text, child.excluded.size ? { all: true, excluded: new Set(child.excluded) } : null);
|
|
183
|
+
else if (child.names.size) info.namespaces.set(clause.name.text, new Set(child.names));
|
|
184
|
+
} else if (ts.isNamedExports(clause)) {
|
|
185
|
+
for (const element of clause.elements) {
|
|
186
|
+
if (element.isTypeOnly) continue;
|
|
187
|
+
const orig = (element.propertyName ?? element.name).text;
|
|
188
|
+
const exported = element.name.text;
|
|
189
|
+
const childHas = orig === 'default'
|
|
190
|
+
? child.defaultExport
|
|
191
|
+
: (child.names.has(orig) || (child.all && !child.excluded.has(orig)));
|
|
192
|
+
if (orig !== 'default' && child.namespaces.has(orig)) {
|
|
193
|
+
info.namespaces.set(exported, child.namespaces.get(orig));
|
|
194
|
+
} else if (childHas) {
|
|
195
|
+
if (exported === 'default') info.defaultExport = true;
|
|
196
|
+
else info.names.add(exported);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// Apply `export *` only for names not explicitly overridden by another export in this barrel.
|
|
202
|
+
for (const child of starChildren) {
|
|
203
|
+
if (child.all) {
|
|
204
|
+
if (!info.all) {
|
|
205
|
+
info.all = true;
|
|
206
|
+
for (const name of child.excluded) info.excluded.add(name);
|
|
207
|
+
} else {
|
|
208
|
+
for (const name of [...info.excluded]) if (!child.excluded.has(name)) info.excluded.delete(name);
|
|
209
|
+
}
|
|
210
|
+
} else {
|
|
211
|
+
for (const name of child.names) if (!explicitInBarrel.has(name)) info.names.add(name);
|
|
212
|
+
for (const [ns, members] of child.namespaces) if (!explicitInBarrel.has(ns)) info.namespaces.set(ns, members);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (info.all) {
|
|
216
|
+
for (const name of explicitInBarrel) {
|
|
217
|
+
if (!info.names.has(name) && !info.namespaces.has(name)) info.excluded.add(name);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (depth === 0) cache.exports.set(key, info);
|
|
221
|
+
return info;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// The calls of the subject's exported functions (named, default, or namespace-imported, directly or via
|
|
225
|
+
// tsconfig path aliases and barrel re-exports, optionally awaited) with written arguments that a test of the
|
|
226
|
+
// given names makes directly in its body without pinning the result down.
|
|
227
|
+
export function weakCalls(text, testFile, subjectFile, testNames, ts = loadTypeScript(), context = {}) {
|
|
228
|
+
const tree = ts.createSourceFile(testFile, text, ts.ScriptTarget.Latest, true);
|
|
229
|
+
const K = ts.SyntaxKind;
|
|
230
|
+
const testPosix = testFile.split(sep).join('/');
|
|
231
|
+
const subjectPosix = subjectFile.split(sep).join('/');
|
|
232
|
+
const subjectStem = subjectPosix.replace(extension, '');
|
|
233
|
+
const root = context.root ? realpathSync(context.root) : null;
|
|
234
|
+
const cache = context.cache ?? { tsconfigs: new Map(), resolved: new Map(), asts: new Map(), exports: new Map() };
|
|
235
|
+
const imported = new Set();
|
|
236
|
+
// Map of namespace identifier -> null (any member) or Set of member names originating from subjectFile.
|
|
237
|
+
const namespaces = new Map();
|
|
238
|
+
const addNamespace = (name, members) => {
|
|
239
|
+
if (!namespaces.has(name) || members === null) { namespaces.set(name, members); return; }
|
|
240
|
+
const existing = namespaces.get(name);
|
|
241
|
+
if (existing === null) return;
|
|
242
|
+
if (existing instanceof Set && members instanceof Set) {
|
|
243
|
+
for (const member of members) existing.add(member);
|
|
244
|
+
} else {
|
|
245
|
+
namespaces.set(name, members);
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
for (const statement of tree.statements) {
|
|
249
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.importClause?.isTypeOnly) continue;
|
|
250
|
+
const specifier = statement.moduleSpecifier.text;
|
|
251
|
+
let info = null;
|
|
252
|
+
if (root) {
|
|
253
|
+
const resolved = resolveModuleInRoot(root, testPosix, specifier, ts, cache);
|
|
254
|
+
if (resolved) info = exportsFromSubject(root, resolved, subjectPosix, ts, cache);
|
|
255
|
+
}
|
|
256
|
+
if (!info && specifier.startsWith('.')) {
|
|
257
|
+
const target = posix.join(posix.dirname(testPosix), specifier).replace(extension, '');
|
|
258
|
+
if (target === subjectStem || target + '/index' === subjectStem) {
|
|
259
|
+
info = { all: true, excluded: new Set(), names: new Set(), defaultExport: true, namespaces: new Map() };
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (!info) continue;
|
|
263
|
+
if (statement.importClause?.name && info.defaultExport) imported.add(statement.importClause.name.text);
|
|
264
|
+
const bindings = statement.importClause?.namedBindings;
|
|
265
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
266
|
+
for (const element of bindings.elements) {
|
|
267
|
+
if (element.isTypeOnly) continue;
|
|
268
|
+
const orig = (element.propertyName ?? element.name).text;
|
|
269
|
+
const local = element.name.text;
|
|
270
|
+
if (info.namespaces.has(orig)) addNamespace(local, info.namespaces.get(orig));
|
|
271
|
+
else if (orig === 'default' ? info.defaultExport : (info.names.has(orig) || (info.all && !info.excluded.has(orig)))) imported.add(local);
|
|
272
|
+
}
|
|
273
|
+
} else if (bindings && ts.isNamespaceImport(bindings)) {
|
|
274
|
+
if (info.all) addNamespace(bindings.name.text, info.excluded.size ? { all: true, excluded: new Set(info.excluded) } : null);
|
|
275
|
+
else if (info.names.size) addNamespace(bindings.name.text, new Set(info.names));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (!imported.size && !namespaces.size) return [];
|
|
279
|
+
const strip = node => {
|
|
280
|
+
while (ts.isParenthesizedExpression(node)) node = node.expression;
|
|
281
|
+
return node;
|
|
282
|
+
};
|
|
283
|
+
const up = node => {
|
|
284
|
+
let child = node;
|
|
285
|
+
while (ts.isParenthesizedExpression(child.parent)) child = child.parent;
|
|
286
|
+
return [child.parent, child];
|
|
287
|
+
};
|
|
288
|
+
function written(node) {
|
|
289
|
+
const inner = strip(node);
|
|
290
|
+
if (ts.isNumericLiteral(inner) || ts.isBigIntLiteral(inner) || ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner) ||
|
|
291
|
+
[K.TrueKeyword, K.FalseKeyword, K.NullKeyword].includes(inner.kind) || (ts.isIdentifier(inner) && inner.text === 'undefined')) return true;
|
|
292
|
+
if (ts.isPrefixUnaryExpression(inner) && inner.operator === K.MinusToken) return ts.isNumericLiteral(inner.operand) || ts.isBigIntLiteral(inner.operand);
|
|
293
|
+
if (ts.isArrayLiteralExpression(inner)) return inner.elements.every(written);
|
|
294
|
+
if (ts.isObjectLiteralExpression(inner)) {
|
|
295
|
+
return inner.properties.every(property => ts.isPropertyAssignment(property) && !ts.isComputedPropertyName(property.name) && written(property.initializer));
|
|
296
|
+
}
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
function collectBindingNames(binding, out) {
|
|
300
|
+
if (!binding) return;
|
|
301
|
+
if (ts.isIdentifier(binding)) out.add(binding.text);
|
|
302
|
+
else if (ts.isObjectBindingPattern(binding) || ts.isArrayBindingPattern(binding)) {
|
|
303
|
+
for (const element of binding.elements) {
|
|
304
|
+
if (ts.isBindingElement(element)) collectBindingNames(element.name, out);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function collectHoistedVars(node, out) {
|
|
309
|
+
if (!node) return;
|
|
310
|
+
if (ts.isVariableDeclarationList(node) && (node.flags & ts.NodeFlags.BlockScoped) === 0) {
|
|
311
|
+
for (const decl of node.declarations) collectBindingNames(decl.name, out);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (ts.isFunctionLike(node) || ts.isClassLike(node) || ts.isModuleDeclaration(node)) return;
|
|
315
|
+
ts.forEachChild(node, child => collectHoistedVars(child, out));
|
|
316
|
+
}
|
|
317
|
+
function localBindingsIn(container) {
|
|
318
|
+
const names = new Set();
|
|
319
|
+
const record = statement => {
|
|
320
|
+
if (ts.isVariableStatement(statement)) {
|
|
321
|
+
for (const decl of statement.declarationList.declarations) collectBindingNames(decl.name, names);
|
|
322
|
+
} else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) {
|
|
323
|
+
names.add(statement.name.text);
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
if (ts.isSourceFile(container)) {
|
|
327
|
+
for (const statement of container.statements) collectHoistedVars(statement, names);
|
|
328
|
+
} else if (ts.isBlock(container) || ts.isModuleBlock(container)) {
|
|
329
|
+
for (const statement of container.statements) record(statement);
|
|
330
|
+
} else if (ts.isCaseClause(container) || ts.isDefaultClause(container)) {
|
|
331
|
+
for (const statement of container.statements) record(statement);
|
|
332
|
+
} else if (ts.isFunctionLike(container)) {
|
|
333
|
+
if (container.name && ts.isIdentifier(container.name)) names.add(container.name.text);
|
|
334
|
+
for (const param of container.parameters) collectBindingNames(param.name, names);
|
|
335
|
+
if (container.body) collectHoistedVars(container.body, names);
|
|
336
|
+
} else if (ts.isCatchClause(container) && container.variableDeclaration) {
|
|
337
|
+
collectBindingNames(container.variableDeclaration.name, names);
|
|
338
|
+
} else if ((ts.isForStatement(container) || ts.isForInStatement(container) || ts.isForOfStatement(container)) &&
|
|
339
|
+
container.initializer && ts.isVariableDeclarationList(container.initializer)) {
|
|
340
|
+
for (const decl of container.initializer.declarations) collectBindingNames(decl.name, names);
|
|
341
|
+
}
|
|
342
|
+
return names;
|
|
343
|
+
}
|
|
344
|
+
function isSubjectCall(node, shadowed) {
|
|
345
|
+
if (!ts.isCallExpression(node) || node.questionDotToken) return false;
|
|
346
|
+
if (ts.isIdentifier(node.expression)) return imported.has(node.expression.text) && !shadowed.has(node.expression.text);
|
|
347
|
+
if (ts.isPropertyAccessExpression(node.expression) && !node.expression.questionDotToken &&
|
|
348
|
+
ts.isIdentifier(node.expression.expression) && ts.isIdentifier(node.expression.name)) {
|
|
349
|
+
const ns = node.expression.expression.text;
|
|
350
|
+
if (!namespaces.has(ns) || shadowed.has(ns)) return false;
|
|
351
|
+
const allowed = namespaces.get(ns);
|
|
352
|
+
const member = node.expression.name.text;
|
|
353
|
+
if (allowed === null) return true;
|
|
354
|
+
if (allowed instanceof Set) return allowed.has(member);
|
|
355
|
+
return allowed.all && !allowed.excluded.has(member);
|
|
356
|
+
}
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
// The matcher an `expect(call)` is checked with, or nothing when the chain is not a plain matcher call.
|
|
360
|
+
function weakExpectation(expectCall) {
|
|
361
|
+
const names = [];
|
|
362
|
+
let [parent, child] = up(expectCall);
|
|
363
|
+
while (ts.isPropertyAccessExpression(parent) && parent.expression === child) {
|
|
364
|
+
names.push(parent.name.text);
|
|
365
|
+
[parent, child] = up(parent);
|
|
366
|
+
}
|
|
367
|
+
if (!names.length || !ts.isCallExpression(parent) || parent.expression !== child || names.includes('resolves') || names.includes('rejects')) return false;
|
|
368
|
+
if (!ts.isExpressionStatement(up(parent)[0])) return false;
|
|
369
|
+
return names.includes('not') || !pinning.has(names.at(-1));
|
|
370
|
+
}
|
|
371
|
+
// The titles of the suites around a test, outermost first, or nothing where one of them is not written out.
|
|
372
|
+
function suitesOf(call) {
|
|
373
|
+
const titles = [];
|
|
374
|
+
for (let node = call.parent; node; node = node.parent) {
|
|
375
|
+
// The callback is the last argument: options may stand before it.
|
|
376
|
+
if (!ts.isCallExpression(node) || !node.arguments.some(argument => ts.isArrowFunction(argument) || ts.isFunctionExpression(argument))) continue;
|
|
377
|
+
// `describe.skip(...)`, and `describe.each(rows)(...)`, whose title is a pattern filled in per row.
|
|
378
|
+
let callee = node.expression;
|
|
379
|
+
let each = false;
|
|
380
|
+
while (ts.isCallExpression(callee) || ts.isPropertyAccessExpression(callee)) {
|
|
381
|
+
each ||= ts.isCallExpression(callee);
|
|
382
|
+
callee = callee.expression;
|
|
383
|
+
}
|
|
384
|
+
if (!ts.isIdentifier(callee) || !['describe', 'suite'].includes(callee.text)) continue;
|
|
385
|
+
if (each || !node.arguments[0] || !ts.isStringLiteralLike(node.arguments[0])) return undefined;
|
|
386
|
+
titles.unshift(node.arguments[0].text);
|
|
387
|
+
}
|
|
388
|
+
return titles;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// The title of the test whose body holds the statement directly, with the suites around it.
|
|
392
|
+
function testOf(statement) {
|
|
393
|
+
const body = statement.parent;
|
|
394
|
+
const callback = ts.isBlock(body) ? body.parent : null;
|
|
395
|
+
if (!callback || !(ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) || !ts.isCallExpression(callback.parent)) return undefined;
|
|
396
|
+
const call = callback.parent;
|
|
397
|
+
const title = call.arguments[0];
|
|
398
|
+
// Options may stand before the callback and a timeout after it.
|
|
399
|
+
if (!ts.isIdentifier(call.expression) || !['it', 'test'].includes(call.expression.text) || call.arguments.indexOf(callback) < 1 ||
|
|
400
|
+
!title || !ts.isStringLiteralLike(title)) return undefined;
|
|
401
|
+
return { title: title.text, suites: suitesOf(call) };
|
|
402
|
+
}
|
|
403
|
+
const found = [];
|
|
404
|
+
// Every test of the file whose name is written out in full, with or without a call to take.
|
|
405
|
+
const spelled = new Set();
|
|
406
|
+
(function visit(node, shadowed) {
|
|
407
|
+
const locals = localBindingsIn(node);
|
|
408
|
+
const scope = locals.size ? new Set([...shadowed, ...locals]) : shadowed;
|
|
409
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && ['it', 'test'].includes(node.expression.text) && node.arguments[0] &&
|
|
410
|
+
ts.isStringLiteralLike(node.arguments[0])) {
|
|
411
|
+
const suites = suitesOf(node);
|
|
412
|
+
if (suites) spelled.add([...suites, node.arguments[0].text].join(' > '));
|
|
413
|
+
}
|
|
414
|
+
if (isSubjectCall(node, scope) && node.arguments.every(written)) {
|
|
415
|
+
let target = node;
|
|
416
|
+
let awaited = false;
|
|
417
|
+
let [parent, child] = up(node);
|
|
418
|
+
if (ts.isAwaitExpression(parent) && parent.expression === child) {
|
|
419
|
+
target = parent;
|
|
420
|
+
awaited = true;
|
|
421
|
+
[parent, child] = up(target);
|
|
422
|
+
}
|
|
423
|
+
let statement;
|
|
424
|
+
let bound;
|
|
425
|
+
if (ts.isExpressionStatement(parent)) statement = parent;
|
|
426
|
+
else if (ts.isVariableDeclaration(parent) && parent.initializer === child && ts.isVariableStatement(parent.parent.parent)) {
|
|
427
|
+
statement = parent.parent.parent;
|
|
428
|
+
if (ts.isIdentifier(parent.name)) bound = parent.name.text;
|
|
429
|
+
} else if (ts.isCallExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'expect' &&
|
|
430
|
+
parent.arguments.length === 1 && weakExpectation(parent)) {
|
|
431
|
+
let outer = parent;
|
|
432
|
+
while (!ts.isExpressionStatement(outer)) outer = outer.parent;
|
|
433
|
+
statement = outer;
|
|
434
|
+
}
|
|
435
|
+
const { title, suites } = (statement && testOf(statement)) ?? {};
|
|
436
|
+
const start = target.getStart(tree);
|
|
437
|
+
const call = text.slice(start, target.end);
|
|
438
|
+
if (title !== undefined && !/[\n\r]/.test(call)) {
|
|
439
|
+
const { line, character } = tree.getLineAndCharacterOfPosition(start);
|
|
440
|
+
found.push({ start, end: target.end, text: call, test: title, full: suites && [...suites, title].join(' > '), line: line + 1, column: character + 1,
|
|
441
|
+
...(bound ? { bound } : {}), ...(awaited ? { awaited: true } : {}) });
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
ts.forEachChild(node, childNode => visit(childNode, scope));
|
|
445
|
+
})(tree, new Set());
|
|
446
|
+
// A test is named with its suites. Where a suite's title is not written out, the test's own title has to do,
|
|
447
|
+
// for the names that no fully written test of the file has.
|
|
448
|
+
return found.filter(call => (call.full !== undefined ? testNames.includes(call.full)
|
|
449
|
+
: testNames.some(name => !spelled.has(name) && (name === call.test || name.endsWith(' > ' + call.test)))))
|
|
450
|
+
.map(({ full: _full, ...call }) => call);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// The test file with one call wrapped so that every value it gives is written beside the file.
|
|
454
|
+
// Supports primitives (`toBe`) and plain, acyclic, bounded arrays and objects (`toStrictEqual`) without invoking getters or Proxy traps.
|
|
455
|
+
export function recordingCall(text, call, key) {
|
|
456
|
+
const name = `__tmtValue_${key}`;
|
|
457
|
+
// The file system and `node:util` are taken from Node itself, when the file has loaded or else at the first call: a test may
|
|
458
|
+
// replace the module with a mock, or `process` with something else for a while.
|
|
459
|
+
const helper = `
|
|
460
|
+
var __tmtFiles_${key};
|
|
461
|
+
var __tmtUtil_${key};
|
|
462
|
+
try { __tmtFiles_${key} = globalThis.process.getBuiltinModule('node:fs'); } catch (error) { /* taken at the first call */ }
|
|
463
|
+
try { __tmtUtil_${key} = globalThis.process.getBuiltinModule('node:util'); } catch (error) { /* taken at the first call */ }
|
|
464
|
+
function ${name}(value) {
|
|
465
|
+
if (!__tmtUtil_${key}) {
|
|
466
|
+
try { __tmtUtil_${key} = globalThis.process.getBuiltinModule('node:util'); } catch (error) { /* unavailable */ }
|
|
467
|
+
}
|
|
468
|
+
var isProxy = __tmtUtil_${key} && __tmtUtil_${key}.types && typeof __tmtUtil_${key}.types.isProxy === 'function' ? __tmtUtil_${key}.types.isProxy : null;
|
|
469
|
+
function fmt(v, depth, seen) {
|
|
470
|
+
var type = typeof v;
|
|
471
|
+
if (v === null || type === 'boolean' || type === 'undefined') return String(v);
|
|
472
|
+
if (type === 'number') return Object.is(v, -0) ? '-0' : String(v);
|
|
473
|
+
if (type === 'string') return JSON.stringify(v);
|
|
474
|
+
if (type === 'bigint') return v + 'n';
|
|
475
|
+
if (type !== 'object' || depth >= 4 || !isProxy || isProxy(v)) return null;
|
|
476
|
+
if (seen.indexOf(v) >= 0) return null;
|
|
477
|
+
var nextSeen = seen.concat([v]);
|
|
478
|
+
if (Array.isArray(v)) {
|
|
479
|
+
if (Object.getPrototypeOf(v) !== Array.prototype) return null;
|
|
480
|
+
if (v.length > 20 || Object.getOwnPropertySymbols(v).length > 0 || Object.getOwnPropertyNames(v).length !== v.length + 1) return null;
|
|
481
|
+
var items = [];
|
|
482
|
+
for (var i = 0; i < v.length; i++) {
|
|
483
|
+
var d = Object.getOwnPropertyDescriptor(v, i);
|
|
484
|
+
if (!d || !('value' in d) || !d.enumerable) return null;
|
|
485
|
+
var item = fmt(d.value, depth + 1, nextSeen);
|
|
486
|
+
if (item === null) return null;
|
|
487
|
+
items.push(item);
|
|
488
|
+
}
|
|
489
|
+
return '[' + items.join(', ') + ']';
|
|
490
|
+
}
|
|
491
|
+
if (Object.getOwnPropertySymbols(v).length > 0) return null;
|
|
492
|
+
if (Object.getPrototypeOf(v) !== Object.prototype) return null;
|
|
493
|
+
var keys = Object.keys(v);
|
|
494
|
+
if (keys.length > 20 || Object.getOwnPropertyNames(v).length !== keys.length) return null;
|
|
495
|
+
keys.sort();
|
|
496
|
+
var pairs = [];
|
|
497
|
+
for (var j = 0; j < keys.length; j++) {
|
|
498
|
+
var k = keys[j], desc = Object.getOwnPropertyDescriptor(v, k);
|
|
499
|
+
if (k === '__proto__' || !desc || !('value' in desc)) return null;
|
|
500
|
+
var val = fmt(desc.value, depth + 1, nextSeen);
|
|
501
|
+
if (val === null) return null;
|
|
502
|
+
var label = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
|
|
503
|
+
pairs.push(label + ': ' + val);
|
|
504
|
+
}
|
|
505
|
+
return pairs.length ? '{ ' + pairs.join(', ') + ' }' : '{}';
|
|
506
|
+
}
|
|
507
|
+
var shown = null;
|
|
508
|
+
try { shown = fmt(value, 0, []); } catch (error) { shown = null; }
|
|
509
|
+
(__tmtFiles_${key} || (__tmtFiles_${key} = globalThis.process.getBuiltinModule('node:fs'))).appendFileSync(new URL('./.tmt-values-${key}.jsonl', import.meta.url), JSON.stringify(shown) + '\\n');
|
|
510
|
+
return value;
|
|
511
|
+
}
|
|
512
|
+
`;
|
|
513
|
+
return text.slice(0, call.start) + `${name}(${call.text})` + text.slice(call.end) + helper;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const valuesOf = run => (run.collected ?? '').split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
517
|
+
const matcherFor = formatted => (formatted.startsWith('[') || formatted.startsWith('{')) ? 'toStrictEqual' : 'toBe';
|
|
518
|
+
|
|
519
|
+
function parseFormattedObject(formatted, ts) {
|
|
520
|
+
if (typeof formatted !== 'string' || !formatted.startsWith('{') || !formatted.endsWith('}')) return null;
|
|
521
|
+
const wrapped = `(${formatted})`;
|
|
522
|
+
const tree = ts.createSourceFile('value.js', wrapped, ts.ScriptTarget.Latest, false);
|
|
523
|
+
if (tree.parseDiagnostics.length || tree.statements.length !== 1 || !ts.isExpressionStatement(tree.statements[0])) return null;
|
|
524
|
+
let expr = tree.statements[0].expression;
|
|
525
|
+
while (ts.isParenthesizedExpression(expr)) expr = expr.expression;
|
|
526
|
+
if (!ts.isObjectLiteralExpression(expr)) return null;
|
|
527
|
+
const entries = new Map();
|
|
528
|
+
for (const prop of expr.properties) {
|
|
529
|
+
if (!ts.isPropertyAssignment(prop)) return null;
|
|
530
|
+
const name = prop.name;
|
|
531
|
+
let key;
|
|
532
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) key = name.text;
|
|
533
|
+
else return null;
|
|
534
|
+
if (key === '__proto__' || entries.has(key)) return null;
|
|
535
|
+
entries.set(key, wrapped.slice(prop.initializer.getStart(tree), prop.initializer.end));
|
|
536
|
+
}
|
|
537
|
+
return entries;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export function narrowSiblingPath(originalText, editedText, ts = loadTypeScript()) {
|
|
541
|
+
const origMap = parseFormattedObject(originalText, ts);
|
|
542
|
+
const editMap = parseFormattedObject(editedText, ts);
|
|
543
|
+
if (!origMap || !editMap || origMap.size < 2) return null;
|
|
544
|
+
const keys = new Set([...origMap.keys(), ...editMap.keys()]);
|
|
545
|
+
const diffKeys = [];
|
|
546
|
+
for (const key of keys) {
|
|
547
|
+
if (!origMap.has(key) || !editMap.has(key) || origMap.get(key) !== editMap.get(key)) diffKeys.push(key);
|
|
548
|
+
}
|
|
549
|
+
if (diffKeys.length !== 1) return null;
|
|
550
|
+
const [key] = diffKeys;
|
|
551
|
+
if (!origMap.has(key) || !editMap.has(key)) return null;
|
|
552
|
+
const origChild = origMap.get(key);
|
|
553
|
+
const editChild = editMap.get(key);
|
|
554
|
+
if (origChild.startsWith('{') && editChild.startsWith('{')) {
|
|
555
|
+
const deeper = narrowSiblingPath(origChild, editChild, ts);
|
|
556
|
+
if (deeper) return { path: [key, ...deeper.path], original: deeper.original, edited: deeper.edited };
|
|
557
|
+
}
|
|
558
|
+
return { path: [key], original: origChild, edited: editChild };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function formatTargetPath(base, path, awaited = false) {
|
|
562
|
+
let expr = path.length && (awaited || /^\s*await\b/.test(base)) ? `(${base})` : base;
|
|
563
|
+
for (const key of path) {
|
|
564
|
+
expr += /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
|
|
565
|
+
}
|
|
566
|
+
return expr;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Reuses one temporary project copy and one warm Vitest 4 child process (`cwd: workspace`, dedicated IPC channel,
|
|
570
|
+
// `isolate: true` per run) across all assertion-strength value recordings, terminating the child process group
|
|
571
|
+
// cleanly on timeout or exit.
|
|
572
|
+
async function withWarmAssertionSession(root, subjectsByFile, options, action) {
|
|
573
|
+
return withCopy(root, async workspace => {
|
|
574
|
+
const configArg = options.config ?? '';
|
|
575
|
+
const child = spawn(process.execPath, [sessionWorker, workspace, configArg], {
|
|
576
|
+
cwd: workspace,
|
|
577
|
+
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
|
578
|
+
detached: process.platform !== 'win32',
|
|
579
|
+
});
|
|
580
|
+
const exited = new Promise(resolveExit => child.once('exit', resolveExit));
|
|
581
|
+
const killGroup = () => {
|
|
582
|
+
if (!child.pid) return;
|
|
583
|
+
try {
|
|
584
|
+
// On POSIX always signal the process group even if the group leader already exited, so surviving
|
|
585
|
+
// worker descendants are terminated before `withCopy` deletes `workspace`.
|
|
586
|
+
if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL');
|
|
587
|
+
else if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
|
588
|
+
} catch { /* group already gone */ }
|
|
589
|
+
};
|
|
590
|
+
const pending = new Map();
|
|
591
|
+
let readyResolve;
|
|
592
|
+
const readyPromise = new Promise(resolveReady => { readyResolve = resolveReady; });
|
|
593
|
+
let broken = false;
|
|
594
|
+
child.on('message', msg => {
|
|
595
|
+
if (!msg || typeof msg !== 'object') return;
|
|
596
|
+
if ('ready' in msg && readyResolve) {
|
|
597
|
+
const done = readyResolve;
|
|
598
|
+
readyResolve = null;
|
|
599
|
+
done(msg.ready === true);
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
const waiter = pending.get(msg.id);
|
|
603
|
+
if (waiter) {
|
|
604
|
+
pending.delete(msg.id);
|
|
605
|
+
waiter(msg);
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
const failPending = () => {
|
|
609
|
+
broken = true;
|
|
610
|
+
if (readyResolve) { const done = readyResolve; readyResolve = null; done(false); }
|
|
611
|
+
for (const waiter of pending.values()) waiter({ closed: true });
|
|
612
|
+
pending.clear();
|
|
613
|
+
};
|
|
614
|
+
child.once('exit', failPending);
|
|
615
|
+
child.once('disconnect', failPending);
|
|
616
|
+
const timeoutMs = (options.timeout ?? 60) * 1000;
|
|
617
|
+
try {
|
|
618
|
+
let bootTimer;
|
|
619
|
+
const ready = await Promise.race([
|
|
620
|
+
readyPromise,
|
|
621
|
+
new Promise(resolveTimeout => { bootTimer = setTimeout(() => resolveTimeout(false), Math.min(timeoutMs, 30_000)); }),
|
|
622
|
+
]);
|
|
623
|
+
clearTimeout(bootTimer);
|
|
624
|
+
if (!ready) return null;
|
|
625
|
+
let nextId = 1;
|
|
626
|
+
const runInSession = async ({ testFile, rewriteContent, collect, trial }) => {
|
|
627
|
+
if (broken || !child.connected) return null;
|
|
628
|
+
const id = nextId++;
|
|
629
|
+
const subject = trial ? subjectsByFile.get(trial.site.location.file) : null;
|
|
630
|
+
let timer;
|
|
631
|
+
const response = await new Promise(resolveWait => {
|
|
632
|
+
pending.set(id, resolveWait);
|
|
633
|
+
timer = setTimeout(() => {
|
|
634
|
+
pending.delete(id);
|
|
635
|
+
resolveWait({ timedOut: true });
|
|
636
|
+
}, timeoutMs);
|
|
637
|
+
try {
|
|
638
|
+
child.send({
|
|
639
|
+
id, testFile, rewriteContent, collect,
|
|
640
|
+
...(trial ? { trial: { edit: trial.edit, replacement: trial.replacement }, subjectFile: subject.file, subjectDigest: subject.digest } : {}),
|
|
641
|
+
});
|
|
642
|
+
} catch {
|
|
643
|
+
pending.delete(id);
|
|
644
|
+
resolveWait({ closed: true });
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
clearTimeout(timer);
|
|
648
|
+
if (response.timedOut) {
|
|
649
|
+
broken = true;
|
|
650
|
+
killGroup();
|
|
651
|
+
await exited;
|
|
652
|
+
return { collected: '' };
|
|
653
|
+
}
|
|
654
|
+
if (response.closed || response.unsupported || response.error) {
|
|
655
|
+
return null;
|
|
656
|
+
}
|
|
657
|
+
return { collected: response.collected ?? '' };
|
|
658
|
+
};
|
|
659
|
+
return await action(runInSession);
|
|
660
|
+
} finally {
|
|
661
|
+
if (child.connected) {
|
|
662
|
+
try { child.send({ close: true }); } catch { /* ignore */ }
|
|
663
|
+
}
|
|
664
|
+
let closeTimer;
|
|
665
|
+
await Promise.race([
|
|
666
|
+
exited,
|
|
667
|
+
new Promise(resolveWait => { closeTimer = setTimeout(() => { killGroup(); resolveWait(); }, 5_000); }),
|
|
668
|
+
]);
|
|
669
|
+
clearTimeout(closeTimer);
|
|
670
|
+
killGroup();
|
|
671
|
+
await exited;
|
|
672
|
+
}
|
|
673
|
+
}, { exclude: options['copy-exclude'] });
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
export async function strengthenAssertions(root, report, options, run = defaultRun) {
|
|
677
|
+
const runnerFactory = run.sourceTrialsAsync ?? run.sourceTrials;
|
|
678
|
+
const concurrency = options.concurrency ?? Math.max(1, Math.min(8, availableParallelism() - 1));
|
|
679
|
+
const ts = loadTypeScript();
|
|
680
|
+
const resolveContext = { root, cache: { tsconfigs: new Map(), resolved: new Map(), asts: new Map(), exports: new Map() } };
|
|
681
|
+
const subjectsByFile = new Map();
|
|
682
|
+
const candidates = [];
|
|
683
|
+
for (const gap of report.diagnostics ?? []) {
|
|
684
|
+
const mutation = gap.mutations?.[0];
|
|
685
|
+
if (!gap.tests?.length || !mutation || gap.suggestedTest || !gap.location?.file) continue;
|
|
686
|
+
let subject = subjectsByFile.get(gap.location.file);
|
|
687
|
+
if (!subject) {
|
|
688
|
+
const input = readFileSync(inside(root, gap.location.file));
|
|
689
|
+
subject = { file: gap.location.file, input, digest: createHash('sha256').update(input).digest('hex'), sites: [] };
|
|
690
|
+
subjectsByFile.set(gap.location.file, subject);
|
|
691
|
+
}
|
|
692
|
+
const trial = { site: { location: gap.location }, edit: mutation.source?.edit ?? mutation.edit, replacement: mutation.source?.replacement ?? mutation.replacement };
|
|
693
|
+
const calls = [];
|
|
694
|
+
for (const testFile of [...new Set(gap.tests.map(test => test.file))].slice(0, 2)) {
|
|
695
|
+
const text = readFileSync(inside(root, testFile), 'utf8');
|
|
696
|
+
const names = gap.tests.filter(test => test.file === testFile).map(test => test.name);
|
|
697
|
+
const attempt = runnerFactory(root, [subject], { ...options, test: [testFile] });
|
|
698
|
+
for (const call of weakCalls(text, testFile, gap.location.file, names, ts, resolveContext)) {
|
|
699
|
+
if (calls.length >= 4) break;
|
|
700
|
+
const id = `${testFile}:${call.start}`;
|
|
701
|
+
calls.push({ id, testFile, text, call, attempt });
|
|
702
|
+
}
|
|
703
|
+
if (calls.length >= 4) break;
|
|
704
|
+
}
|
|
705
|
+
if (calls.length) candidates.push({ gap, trial, calls });
|
|
706
|
+
}
|
|
707
|
+
if (!candidates.length) return report;
|
|
708
|
+
|
|
709
|
+
const originalPromises = new Map();
|
|
710
|
+
let tried = 0;
|
|
711
|
+
const evaluateCandidate = async ({ gap, trial, calls }, sessionRun) => {
|
|
712
|
+
for (const { id, testFile, text, call, attempt } of calls) {
|
|
713
|
+
if (tried >= 24) break;
|
|
714
|
+
let originalPromise = originalPromises.get(id);
|
|
715
|
+
if (!originalPromise) {
|
|
716
|
+
originalPromise = (async () => {
|
|
717
|
+
const key = randomUUID().replaceAll('-', '');
|
|
718
|
+
const collect = posix.join(posix.dirname(testFile.split(sep).join('/')), `.tmt-values-${key}.jsonl`);
|
|
719
|
+
const rewriteContent = recordingCall(text, call, key);
|
|
720
|
+
const sessionOutcome = sessionRun ? await sessionRun({ testFile, rewriteContent, collect }) : null;
|
|
721
|
+
const outcome = sessionOutcome ?? await attempt({ witness: { rewrite: { file: testFile, content: rewriteContent } }, collect });
|
|
722
|
+
return valuesOf(outcome);
|
|
723
|
+
})();
|
|
724
|
+
originalPromises.set(id, originalPromise);
|
|
725
|
+
originalPromise.catch(() => { if (originalPromises.get(id) === originalPromise) originalPromises.delete(id); });
|
|
726
|
+
}
|
|
727
|
+
const original = await originalPromise;
|
|
728
|
+
if (!original?.length || original.includes(null)) continue;
|
|
729
|
+
if (tried >= 24) break;
|
|
730
|
+
tried++;
|
|
731
|
+
const key = randomUUID().replaceAll('-', '');
|
|
732
|
+
const collect = posix.join(posix.dirname(testFile.split(sep).join('/')), `.tmt-values-${key}.jsonl`);
|
|
733
|
+
const rewriteContent = recordingCall(text, call, key);
|
|
734
|
+
const sessionOutcome = sessionRun ? await sessionRun({ testFile, rewriteContent, collect, trial }) : null;
|
|
735
|
+
const outcome = sessionOutcome ?? await attempt({ witness: { rewrite: { file: testFile, content: rewriteContent } }, collect, trial });
|
|
736
|
+
const edited = valuesOf(outcome);
|
|
737
|
+
// The first time the call gives another comparable value with the edit. Where the edit keeps a test from making
|
|
738
|
+
// the call, or returns an unformattable value, nothing is suggested.
|
|
739
|
+
// The values are matched by their order, so the call has to be made as often with the edit as without.
|
|
740
|
+
const at = edited.length === original.length
|
|
741
|
+
? original.findIndex((value, index) => edited[index] !== null && edited[index] !== value)
|
|
742
|
+
: -1;
|
|
743
|
+
if (at === -1) continue;
|
|
744
|
+
// A result the test keeps is compared where it is kept: calling again may give another value.
|
|
745
|
+
// When a multi-key plain object differs along a single sibling field path, narrow the suggestion to that path.
|
|
746
|
+
const narrowed = narrowSiblingPath(original[at], edited[at], ts);
|
|
747
|
+
const baseExpr = call.bound ?? call.text;
|
|
748
|
+
const targetExpr = narrowed ? formatTargetPath(baseExpr, narrowed.path, !call.bound && call.awaited) : baseExpr;
|
|
749
|
+
const expectedText = narrowed ? narrowed.original : original[at];
|
|
750
|
+
const editedText = narrowed ? narrowed.edited : edited[at];
|
|
751
|
+
gap.suggestedTest = `expect(${targetExpr}).${matcherFor(expectedText)}(${expectedText})`;
|
|
752
|
+
gap.strengthens = {
|
|
753
|
+
file: testFile, test: call.test, line: call.line, column: call.column, call: call.text,
|
|
754
|
+
original: expectedText, edited: editedText, ...(narrowed ? { path: narrowed.path } : {}),
|
|
755
|
+
};
|
|
756
|
+
break;
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
const useWarmSession = run === defaultRun && options.runner !== 'playwright' && !options['isolated-trials'];
|
|
761
|
+
if (useWarmSession) {
|
|
762
|
+
const completed = await withWarmAssertionSession(root, subjectsByFile, options, async sessionRun => {
|
|
763
|
+
for (const candidate of candidates) {
|
|
764
|
+
if (tried >= 24) break;
|
|
765
|
+
await evaluateCandidate(candidate, sessionRun);
|
|
766
|
+
}
|
|
767
|
+
return true;
|
|
768
|
+
});
|
|
769
|
+
if (completed) return report;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// Fallback path (custom runner, --isolated-trials, non-Vitest-4, or unit tests): run candidates in deterministic
|
|
773
|
+
// order while parallelizing safe batches whose worst-case cost fits the remaining budget.
|
|
774
|
+
let cursor = 0;
|
|
775
|
+
while (cursor < candidates.length && tried < 24) {
|
|
776
|
+
const remaining = 24 - tried;
|
|
777
|
+
const batch = [];
|
|
778
|
+
let reserved = 0;
|
|
779
|
+
while (cursor < candidates.length && batch.length < concurrency) {
|
|
780
|
+
const worstCase = candidates[cursor].calls.length;
|
|
781
|
+
if (batch.length > 0 && reserved + worstCase > remaining) break;
|
|
782
|
+
batch.push(candidates[cursor++]);
|
|
783
|
+
reserved += worstCase;
|
|
784
|
+
if (reserved >= remaining) break;
|
|
785
|
+
}
|
|
786
|
+
await inParallel(batch, batch.length, candidate => evaluateCandidate(candidate, null));
|
|
787
|
+
}
|
|
788
|
+
return report;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// The plain source edits are for the runs above and are not part of the report.
|
|
792
|
+
export function withoutSourceEdits(report) {
|
|
793
|
+
for (const gap of report.diagnostics ?? []) for (const mutation of gap.mutations ?? []) delete mutation.source;
|
|
794
|
+
return report;
|
|
795
|
+
}
|