targeted-mutation 0.0.0-stage → 0.1.1

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.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +111 -2
  4. package/bin/tmt-compile.mjs +46 -0
  5. package/bin/tmt.mjs +117 -0
  6. package/build/typescript-syntax/LICENSE.txt +55 -0
  7. package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
  8. package/build/typescript-syntax/typescript-syntax.cjs +43 -0
  9. package/docs/analysis.md +218 -0
  10. package/docs/compiler.md +462 -0
  11. package/docs/development.md +61 -0
  12. package/docs/how-it-works.svg +188 -0
  13. package/docs/l1.md +94 -0
  14. package/docs/performance.md +647 -0
  15. package/docs/releasing.md +48 -0
  16. package/package.json +49 -4
  17. package/src/analysis.mjs +689 -0
  18. package/src/assertion-session.mjs +93 -0
  19. package/src/assertion-strength.mjs +795 -0
  20. package/src/builtin-mutations.mjs +755 -0
  21. package/src/builtin-switches.mjs +642 -0
  22. package/src/change-undone.mjs +524 -0
  23. package/src/cli-output.mjs +166 -0
  24. package/src/compiler-compat.cjs +108 -0
  25. package/src/compiler-maps.cjs +60 -0
  26. package/src/compiler-routes.cjs +391 -0
  27. package/src/compiler.cjs +98 -0
  28. package/src/compiler.mjs +1 -0
  29. package/src/conventional.mjs +172 -0
  30. package/src/displacement.mjs +19 -0
  31. package/src/extract.mjs +135 -0
  32. package/src/fallback-process.mjs +14 -0
  33. package/src/in-parallel.mjs +20 -0
  34. package/src/lean-replay.mjs +39 -0
  35. package/src/operator-analysis.mjs +123 -0
  36. package/src/playwright.mjs +139 -0
  37. package/src/probe-runtime.mjs +50 -0
  38. package/src/probe.mjs +170 -0
  39. package/src/prototype.mjs +230 -0
  40. package/src/regex-mutations.mjs +102 -0
  41. package/src/runner-process.mjs +59 -0
  42. package/src/runtime-binaries.mjs +50 -0
  43. package/src/scope.mjs +202 -0
  44. package/src/source-text.mjs +49 -0
  45. package/src/standard-plan.mjs +308 -0
  46. package/src/standard-runner.mjs +185 -0
  47. package/src/standard-session.mjs +362 -0
  48. package/src/standard-setup.mjs +20 -0
  49. package/src/targeted-gaps.mjs +85 -0
  50. package/src/threshold.mjs +185 -0
  51. package/src/trace-buffer.mjs +126 -0
  52. package/src/typescript-bindings.mjs +243 -0
  53. package/src/typescript-compiler.mjs +59 -0
  54. package/src/typescript-extraction.mjs +354 -0
  55. package/src/typescript-grammar.mjs +923 -0
  56. package/src/vitest-reporter.mjs +64 -0
  57. package/src/vitest.mjs +262 -0
  58. package/src/witness-analysis.mjs +234 -0
  59. package/src/witness-contracts.mjs +110 -0
  60. package/src/witness-discovery.mjs +239 -0
  61. package/src/witness-fixtures.mjs +149 -0
  62. package/src/witness-order.mjs +83 -0
  63. package/src/witness-rules.mjs +254 -0
@@ -0,0 +1,391 @@
1
+ 'use strict';
2
+
3
+ let validUtf8;
4
+ let types;
5
+ function optionalAddon(specifier, allowIncompatible = false) {
6
+ const addon = { exports: {} };
7
+ try {
8
+ process.dlopen(addon, __dirname + '/' + specifier);
9
+ return addon.exports;
10
+ } catch (error) {
11
+ if (error.code !== 'ERR_DLOPEN_FAILED') throw error;
12
+ }
13
+ try {
14
+ return require(specifier);
15
+ } catch (error) {
16
+ if (error.code === 'MODULE_NOT_FOUND' || (allowIncompatible && error.code === 'ERR_DLOPEN_FAILED')) return null;
17
+ throw error;
18
+ }
19
+ }
20
+
21
+ let directAddon;
22
+ function loadDirectAddon() {
23
+ if (directAddon === undefined) directAddon = optionalAddon('../build/compiler.node');
24
+ return directAddon;
25
+ }
26
+
27
+ let fullAddon;
28
+ function loadModuleAddon() {
29
+ if (fullAddon === undefined) fullAddon = optionalAddon('../build/compiler-module.node');
30
+ return fullAddon;
31
+ }
32
+ let javascriptAddon;
33
+ function javascriptValidators() {
34
+ if (javascriptAddon === undefined) javascriptAddon = optionalAddon('../build/compiler-js.node', true) ?? {};
35
+ return javascriptAddon;
36
+ }
37
+ function javascriptTextValidator() {
38
+ return javascriptValidators().validModule ?? null;
39
+ }
40
+ const extensions = /\.(?:[cm]?[jt]s|[jt]sx)$/i;
41
+ const declarations = /\.d\.[cm]?ts$/i;
42
+ const targets = new Set(['es6', 'esnext', ...Array.from({ length: 11 }, (_, index) => 'es' + (2015 + index))]);
43
+ const modules = new Set(['preserve', 'esm', 'cjs']);
44
+ const jsxModes = new Set(['automatic', 'classic', 'preserve']);
45
+
46
+ function fail(backend, diagnostics) {
47
+ return { backend, code: null, sourceMap: null, diagnostics };
48
+ }
49
+
50
+ function inputError(file, code, message) {
51
+ return fail('input', [{ file, code, severity: 'error', message, start: 0, end: 0 }]);
52
+ }
53
+
54
+ function outputFormat(file, module) {
55
+ if (module !== 'preserve') return module;
56
+ if (/\.c[jt]s$/i.test(file)) return 'cjs';
57
+ if (/\.m[jt]s$/i.test(file)) return 'esm';
58
+ return 'preserve';
59
+ }
60
+
61
+ function hasSplitDeclare(source, code) {
62
+ return source.includes('declare') && require('./compiler-compat.cjs').hasSplitDeclare(source, code);
63
+ }
64
+
65
+ function transformCompatibility(source, options) {
66
+ return require('./compiler-compat.cjs').transform(source, options, verifyRuntimeExports, fail);
67
+ }
68
+
69
+ function strip(source, file) {
70
+ try {
71
+ const code = require('node:module').stripTypeScriptTypes(source);
72
+ if (hasSplitDeclare(source, code)) {
73
+ return fail('node-strip', [{
74
+ file, code: 'AMBIGUOUS_TYPE_ERASURE', severity: 'error',
75
+ message: 'Position-preserving erasure would remove a declaration after a line break', start: 0, end: 0,
76
+ }]);
77
+ }
78
+ return { backend: 'node-strip', code, sourceMap: null, diagnostics: [] };
79
+ } catch (error) {
80
+ if (error.code !== 'ERR_INVALID_TYPESCRIPT_SYNTAX' && error.code !== 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX') throw error;
81
+ return fail('node-strip', [{ file, code: error.code, severity: 'error', message: error.message, start: 0, end: 0 }]);
82
+ }
83
+ }
84
+
85
+ function verifyRuntimeExports(result, file, addon, bytes) {
86
+ if (!/\bexport(?:\s|\/\*[^]*?\*\/|\/\/[^\r\n\u2028\u2029]*)*\{/.test(result.code)) return result;
87
+ const checker = addon ?? loadModuleAddon();
88
+ if (!checker?.unboundExport?.(bytes ?? Buffer.from(result.code))) return result;
89
+ return fail(result.backend, [...result.diagnostics, {
90
+ file, code: 'UNBOUND_RUNTIME_EXPORT', severity: 'error',
91
+ message: 'A local export has no runtime binding after type erasure', start: 0, end: 0,
92
+ }]);
93
+ }
94
+
95
+ function hasModuleMarker(addon, code, bytes = Buffer.from(code)) {
96
+ return addon.moduleMarker(bytes, false) ||
97
+ (code.includes('\u2002') && addon.moduleMarker(Buffer.from(code.replaceAll('\u2002', ' ')), false));
98
+ }
99
+
100
+ function strictScript(source, file) {
101
+ if (source.includes('<!--') || (source.includes('-->') && /(?:^|\*\/)[^\S\r\n\u2028\u2029]*-->/m.test(source))) return null;
102
+ const hashbang = source.startsWith('#!') ? source.search(/[\r\n]/) + 1 : 0;
103
+ const trivia = /(?:\s+|\/\/[^\r\n\u2028\u2029]*|\/\*[\s\S]*?\*\/)*/y;
104
+ trivia.lastIndex = hashbang;
105
+ trivia.exec(source);
106
+ if (source.slice(0, trivia.lastIndex).includes('///')) return null;
107
+ const first = source[trivia.lastIndex];
108
+ const directive = /(["'])use strict\1[ \t]*;/y;
109
+ directive.lastIndex = trivia.lastIndex;
110
+ const strict = directive.test(source);
111
+ if ((first === '"' || first === "'") && !strict) return null;
112
+ const code = strict ? source : source.slice(0, hashbang) + '"use strict";\n' + source.slice(hashbang);
113
+ // Node can abort while decorating a syntax error from vm.Script. The addon asks V8 directly.
114
+ const valid = javascriptValidators().validScript;
115
+ if (valid) return valid(code) ? code : null;
116
+ try {
117
+ new (require('node:vm').Script)(code, { filename: file });
118
+ return code;
119
+ } catch (error) {
120
+ if (!(error instanceof SyntaxError)) throw error;
121
+ return null;
122
+ }
123
+ }
124
+
125
+ function eraseScript(addon, source, bytes, file) {
126
+ if (/\b(?:import|export)\b/.test(source) || !addon.plainScript(bytes)) return null;
127
+ const result = strip(source, file);
128
+ if (result.code === null || addon.triviaOnly(Buffer.from(result.code))) return null;
129
+ const code = strictScript(result.code, file);
130
+ return code === null ? null : { ...result, code };
131
+ }
132
+
133
+ const moduleTrivia = /(?:\s+|\/\/[^\r\n\u2028\u2029]*|\/\*[\s\S]*?\*\/)*/y;
134
+
135
+ function moduleTriviaEnd(source, at) {
136
+ moduleTrivia.lastIndex = at;
137
+ moduleTrivia.test(source);
138
+ return moduleTrivia.lastIndex;
139
+ }
140
+
141
+ function javascriptModuleStart(source) {
142
+ const hashbang = source.startsWith('#!') ? /^#![^\r\n\u2028\u2029]*/.exec(source)[0].length : 0;
143
+ return moduleTriviaEnd(source, hashbang);
144
+ }
145
+
146
+ function startsStaticModule(source, start) {
147
+ const after = start + 6;
148
+ const follower = source[after] ?? '';
149
+ if (source.startsWith('export', start)) return /^[\s{/*]$/.test(follower);
150
+ if (!source.startsWith('import', start) || !/^[\s/'"{*]$/.test(follower)) return false;
151
+ const specifier = source[moduleTriviaEnd(source, after)] ?? '';
152
+ return /^[A-Za-z_$'"{*]$/.test(specifier);
153
+ }
154
+
155
+ // V8 does not parse decorators yet. The certified parse does, and the entry asks it first, so a module
156
+ // that V8 refuses is published when that parse accepts it unchanged.
157
+ function certifiedModule(source, bytes) {
158
+ const emit = loadModuleAddon()?.emitJavaScriptModule;
159
+ return emit !== undefined && emit(bytes ?? Buffer.from(source), true) !== undefined ? source : null;
160
+ }
161
+
162
+ function modernJavaScript(source, file, format) {
163
+ const moduleFile = format === 'esm' && /\.mjs$/i.test(file);
164
+ const start = moduleFile ? undefined : javascriptModuleStart(source);
165
+ const staticHead = start !== undefined && startsStaticModule(source, start);
166
+ const script = format === 'preserve' && !staticHead ? strictScript(source, file) : null;
167
+ if (script !== null) return script;
168
+ let bytes;
169
+ const directive = source.indexOf('///');
170
+ if (directive !== -1) {
171
+ if (directive < (start ?? javascriptModuleStart(source))) return null;
172
+ bytes = Buffer.from(source);
173
+ if (loadDirectAddon()?.leadingDirective(bytes) !== false) return null;
174
+ }
175
+ if (moduleFile || staticHead) {
176
+ const validate = javascriptTextValidator();
177
+ if (validate) {
178
+ const valid = validate(source);
179
+ if (valid) return source;
180
+ if (moduleFile) return certifiedModule(source, bytes);
181
+ }
182
+ }
183
+ const addon = loadModuleAddon();
184
+ if (!addon) return null;
185
+ bytes ??= Buffer.from(source);
186
+ if (moduleFile && addon.validModule) {
187
+ return addon.validModule(bytes) ? source : certifiedModule(source, bytes);
188
+ }
189
+ if (!moduleFile && !staticHead) {
190
+ const validate = javascriptTextValidator();
191
+ if (validate && addon.moduleMarker(bytes, false) && validate(source)) return source;
192
+ }
193
+ return addon.moduleMarker(bytes, true) && strip(source, file).code === source ? source : null;
194
+ }
195
+
196
+ function eraseLoweredModule(addon, source, file, format) {
197
+ let result = strip(source, file);
198
+ const diagnostic = result.diagnostics[0];
199
+ if (diagnostic?.code === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' &&
200
+ /^(?:\s*x\s*)?TypeScript enum is not supported/.test(diagnostic.message)) {
201
+ const code = addon.lower(Buffer.from(source), false, true, false, true);
202
+ if (code !== null) result = strip(code, file);
203
+ }
204
+ if (result.code === null) return null;
205
+ let code = result.code;
206
+ if (!hasModuleMarker(addon, code)) {
207
+ if (format !== 'preserve' || /\b(?:import|export)\b/.test(source)) return null;
208
+ code = strictScript(code, file);
209
+ if (code === null) return null;
210
+ }
211
+ return verifyRuntimeExports({ ...result, code, backend: 'pulse+node-strip' }, file, addon);
212
+ }
213
+
214
+ function eraseModule(addon, source, file, format, parameterProperty) {
215
+ const transformAllowed = () => !/\benum\b|\bnamespace\b(?![ \t]*:)/.test(source);
216
+ const directTransform = parameterProperty && transformAllowed();
217
+ let result = directTransform ? null : strip(source, file);
218
+ const diagnostic = result?.diagnostics[0];
219
+ if (directTransform || (diagnostic?.code === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' &&
220
+ /^(?:\s*x\s*)?TypeScript parameter property is not supported/.test(diagnostic.message) && transformAllowed())) {
221
+ if (hasSplitDeclare(source)) return null;
222
+ try {
223
+ const code = require('node:module').stripTypeScriptTypes(source, { mode: 'transform' });
224
+ result = { backend: 'node-transform', code, sourceMap: null, diagnostics: [] };
225
+ } catch (error) {
226
+ if (!['ERR_INVALID_ARG_VALUE', 'ERR_INVALID_TYPESCRIPT_SYNTAX', 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX'].includes(error.code)) throw error;
227
+ }
228
+ }
229
+ if (result?.code == null) return null;
230
+ const emitted = Buffer.from(result.code);
231
+ if (hasModuleMarker(addon, result.code, emitted)) return verifyRuntimeExports(result, file, addon, emitted);
232
+ if (!addon.triviaOnly(emitted)) return null;
233
+ if (format === 'esm') result.code += '\nexport {};\n';
234
+ return result;
235
+ }
236
+
237
+ function snapshot(input) {
238
+ types ??= require('node:util').types;
239
+ if (types.isSharedArrayBuffer(input)) return Buffer.from(new Uint8Array(input));
240
+ if (ArrayBuffer.isView(input) && types.isSharedArrayBuffer(input.buffer)) {
241
+ return Buffer.from(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));
242
+ }
243
+ return input;
244
+ }
245
+
246
+ let sourceDecoder;
247
+ function compilerSource(input) {
248
+ if (typeof input === 'string') return input.isWellFormed() ? input : null;
249
+ try {
250
+ sourceDecoder ??= new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
251
+ return sourceDecoder.decode(input);
252
+ } catch {
253
+ return null;
254
+ }
255
+ }
256
+
257
+ // A script is published as a strict-mode directive followed by a projection of the source.
258
+ // Its map is the projection's map moved down by the directive's line.
259
+ function mappedScript(input, options) {
260
+ const { file = 'input.ts' } = options;
261
+ if (!/\.ts$/.test(file) || file.includes('\\')) return undefined;
262
+ const source = Buffer.isBuffer(input) ? input : typeof input === 'string' && input.isWellFormed() ? Buffer.from(input) : null;
263
+ const addon = source === null || source[0] === 0xEF ? null : loadModuleAddon();
264
+ if (!addon?.projectionMappings || addon.moduleMarker(source, false)) return undefined;
265
+ const plain = compile(input, { ...options, sourceMap: false });
266
+ const directive = '"use strict";\n';
267
+ if (plain.backend !== 'pulse' || !plain.code.startsWith(directive)) return undefined;
268
+ const mappings = addon.projectionMappings(source, Buffer.from(plain.code.slice(directive.length)));
269
+ if (mappings === undefined) return undefined;
270
+ return { ...plain, sourceMap: require('./compiler-maps.cjs').sourceMapObject(file, ';' + mappings, source.toString()) };
271
+ }
272
+
273
+ function compile(input, options = {}) {
274
+ const { file = 'input.ts', mode = 'transform', target = 'esnext', module = 'preserve', jsx = 'automatic',
275
+ sourceMap = false } = options;
276
+ if (typeof file !== 'string' || !extensions.test(file)) throw new TypeError('Expected a JS, TS, JSX or TSX filename');
277
+ if (!targets.has(target) || !modules.has(module) || !jsxModes.has(jsx) || typeof sourceMap !== 'boolean') {
278
+ throw new TypeError('Invalid compiler target, module, JSX or source-map option');
279
+ }
280
+ if (mode !== 'transform' && mode !== 'strip') throw new TypeError('Expected transform or strip compilation mode');
281
+ if (mode === 'strip' && (target !== 'esnext' || module !== 'preserve' || sourceMap || options.jsx !== undefined)) {
282
+ throw new TypeError('strip mode only supports position-preserving type erasure');
283
+ }
284
+ if (declarations.test(file)) return inputError(file, 'DECLARATION_INPUT', 'A declaration file cannot emit JavaScript');
285
+ if (mode === 'strip' && !/\.[cm]?ts$/i.test(file)) {
286
+ return inputError(file, 'STRIP_DIALECT', 'strip mode requires a non-JSX TypeScript filename');
287
+ }
288
+ const format = outputFormat(file, module);
289
+ const typed = /\.(?:m?ts|tsx)$/i.test(file);
290
+ const jsxFile = /\.[jt]sx$/i.test(file);
291
+ if (sourceMap && typed && jsx !== 'preserve' && target === 'esnext' && format !== 'cjs') {
292
+ // The entry calls the same function, so both callers publish the same result.
293
+ const mapper = loadModuleAddon();
294
+ const result = mapper ? require('./compiler-maps.cjs').mappedTypeScript(input, file,
295
+ (format === 'esm' ? 2 : 0) | (jsxFile ? 1 : 0) | (jsxFile && jsx === 'classic' ? 4 : 0), mapper) : undefined;
296
+ if (result !== undefined) return result;
297
+ const script = mappedScript(input, options);
298
+ if (script !== undefined) return script;
299
+ }
300
+ let direct;
301
+ if (typed && !jsxFile && target === 'esnext' && format !== 'cjs' && !sourceMap &&
302
+ Buffer.isBuffer(input) && input.length > 0 && input.length <= 512) {
303
+ direct = loadDirectAddon()?.compileAscii?.(input);
304
+ if (typeof direct === 'string') return { backend: 'pulse', code: direct, sourceMap: null, diagnostics: [] };
305
+ }
306
+ const stableInput = snapshot(input);
307
+ if ((typed || jsxFile) && target === 'esnext' && format !== 'cjs' && !sourceMap) {
308
+ const source = Buffer.isBuffer(stableInput) ? stableInput :
309
+ typeof stableInput === 'string' && stableInput.isWellFormed() ? Buffer.from(stableInput) : null;
310
+ // The direct grammar starts at an export after trivia. Imports and interfaces cannot use it.
311
+ const skipsDirectAddon = typed && mode === 'transform' && source?.[0] === 105;
312
+ const native = source && !skipsDirectAddon ? loadDirectAddon() : null;
313
+ const wellFormed = source && (skipsDirectAddon || native) && (validUtf8 ??= require('node:buffer').isUtf8)(source);
314
+ // 0 without a leading triple-slash comment, 1 for notes and well-formed references, 2 for anything else.
315
+ const slashes = wellFormed && !skipsDirectAddon && mode !== 'strip' ? native.leadingTripleSlash(source) : 0;
316
+ if (wellFormed && slashes !== 2) {
317
+ // Behind a well-formed directive only the module emitters run. They keep it as a comment.
318
+ // TypeScript reports a malformed one, so that case skips the native routes.
319
+ const directive = slashes === 1;
320
+ const simple = native && !directive && typed && !jsxFile && direct !== null ? native.compile(source) : null;
321
+ if (simple !== null) return { backend: 'pulse', code: simple, sourceMap: null, diagnostics: [] };
322
+ // Whole-source scans are deferred. The native emitters find enum declarations themselves.
323
+ let scanned;
324
+ const runtime = () => scanned ??= mode === 'transform' && (jsxFile ? jsx !== 'preserve' &&
325
+ // A source with @jsx text is native only for one import-source pragma, which the addon recognizes.
326
+ (!source.includes('@') || !/@jsx/i.test(source.toString('latin1')) ||
327
+ loadModuleAddon()?.jsxPragmaSupported?.(source, jsx === 'classic') === true) && !source.includes('_tmt') :
328
+ typed && source.includes('enum') && /\benum\b/.test(typeof stableInput === 'string' ? stableInput : source.toString()));
329
+ // The single-declaration emitter accepts a TypeScript file only when it starts with an enum.
330
+ if (mode === 'transform' && native && !directive && (jsxFile ? runtime() : typed)) {
331
+ const code = native.lower(source, jsxFile, typed, jsx === 'classic', false);
332
+ if (code !== null) return { backend: 'pulse', code, sourceMap: null, diagnostics: [] };
333
+ }
334
+ if (mode === 'transform' && (typed || runtime())) {
335
+ const addon = loadModuleAddon();
336
+ if (addon) {
337
+ const moduleProjection = typed && (!jsxFile || !source.includes('<'));
338
+ const empty = moduleProjection ? addon.eraseTypeModule(source, format === 'esm') : null;
339
+ if (empty !== null) return { backend: 'pulse', code: empty, sourceMap: null, diagnostics: [] };
340
+ const annotated = moduleProjection ?
341
+ addon.emitAnnotatedModule(source, jsxFile ? runtime() : undefined, format === 'esm', format === 'preserve' && !jsxFile) : null;
342
+ if (typeof annotated === 'string') {
343
+ return { backend: 'pulse', code: annotated, sourceMap: null, diagnostics: [] };
344
+ }
345
+ if (!directive && typeof annotated?.script === 'string') {
346
+ const code = strictScript(annotated.script, file);
347
+ if (code !== null) return { backend: 'pulse', code, sourceMap: null, diagnostics: [] };
348
+ }
349
+ if (!directive && annotated?.reference === true) {
350
+ const text = typeof stableInput === 'string' ? stableInput : source.toString();
351
+ return transformCompatibility(text, { file, target, outputModule: format, jsx, sourceMap });
352
+ }
353
+ if (!directive && annotated?.code !== undefined) {
354
+ const result = eraseLoweredModule(addon, annotated.code, file, format);
355
+ if (result) return result;
356
+ }
357
+ if (runtime() && (!jsxFile || !source.includes('\\u'))) {
358
+ const mixed = addon.lower(source, jsxFile, typed, jsx === 'classic', true);
359
+ if (mixed !== null) {
360
+ if (typeof mixed !== 'string') {
361
+ const backend = !typed && !source.includes('<') ? 'javascript' : 'pulse';
362
+ return { backend, code: mixed.code, sourceMap: null, diagnostics: [] };
363
+ }
364
+ if (typed && !directive) {
365
+ const result = eraseLoweredModule(addon, mixed, file, format);
366
+ if (result) return result;
367
+ }
368
+ }
369
+ }
370
+ if (typed && !jsxFile && !directive) {
371
+ const text = typeof stableInput === 'string' ? stableInput : source.toString();
372
+ const property = annotated?.parameterProperty === true;
373
+ const result = (property || annotated === true || addon.moduleMarker(source, true)) ? eraseModule(addon, text, file, format, property) :
374
+ format === 'preserve' ? eraseScript(addon, text, source, file) : null;
375
+ if (result) return result;
376
+ }
377
+ }
378
+ }
379
+ }
380
+ }
381
+ const source = compilerSource(stableInput);
382
+ if (source === null) return inputError(file, 'INVALID_ENCODING', 'Expected well-formed UTF-8');
383
+ if (mode === 'strip') return strip(source, file);
384
+ if (target === 'esnext' && format !== 'cjs' && !sourceMap && /\.m?js$/i.test(file)) {
385
+ const code = modernJavaScript(source, file, format);
386
+ if (code !== null) return { backend: 'javascript', code, sourceMap: null, diagnostics: [] };
387
+ }
388
+ return transformCompatibility(source, { file, target, outputModule: format, jsx, sourceMap });
389
+ }
390
+
391
+ exports.compile = compile;
@@ -0,0 +1,98 @@
1
+ 'use strict';
2
+
3
+ // Loading and first execution of JavaScript dominate a cold compile, so the default TypeScript and
4
+ // JavaScript routes are one native call each. Every other option, input and outcome takes the
5
+ // complete router, which decides each case again from the start.
6
+ const unavailable = {};
7
+ function nativeAddon(name) {
8
+ try {
9
+ const addon = { exports: {} };
10
+ process.dlopen(addon, __dirname + '/../build/' + name);
11
+ return addon.exports;
12
+ } catch {
13
+ // The router reports a missing or incompatible addon.
14
+ return unavailable;
15
+ }
16
+ }
17
+
18
+ let pulse;
19
+ let v8;
20
+
21
+ const tsx = 1;
22
+ const esm = 2;
23
+ const classic = 4;
24
+ const script = 8;
25
+
26
+ // Returns the native flags for .ts, .mts, .tsx, .js and .mjs names, and -1 for declarations and
27
+ // other dialects. JavaScript names carry the script bit, and .mjs also the module bit.
28
+ function sourceKind(file) {
29
+ const size = file.length;
30
+ if (size < 3) return -1;
31
+ const last = file.charCodeAt(size - 1) | 32;
32
+ const middle = file.charCodeAt(size - 2) | 32;
33
+ // Folding case would also map the control character 0x0e to a dot, so the dot is compared as is.
34
+ const third = file.charCodeAt(size - 3);
35
+ const first = third | 32;
36
+ if (third === 46 && last === 115) {
37
+ if (middle === 106) return script;
38
+ if (middle !== 116) return -1;
39
+ return size >= 5 && file.charCodeAt(size - 5) === 46 && (file.charCodeAt(size - 4) | 32) === 100 ? -1 : 0;
40
+ }
41
+ if (size < 4 || file.charCodeAt(size - 4) !== 46) return -1;
42
+ if (first === 116 && middle === 115 && last === 120) return tsx;
43
+ if (first === 109 && last === 115) {
44
+ if (middle === 106) return script | esm;
45
+ if (middle !== 116) return -1;
46
+ return size >= 6 && file.charCodeAt(size - 6) === 46 && (file.charCodeAt(size - 5) | 32) === 100 ? -1 : esm;
47
+ }
48
+ return -1;
49
+ }
50
+
51
+ let routes;
52
+ function compile(input, options) {
53
+ let file = 'input.ts';
54
+ let flags = 0;
55
+ let defaults = options === undefined;
56
+ if (!defaults && options !== null && typeof options === 'object') {
57
+ if (options.mode === undefined && options.target === undefined && options.module === undefined && options.sourceMap === undefined) {
58
+ const name = options.file;
59
+ const jsx = options.jsx;
60
+ if ((name === undefined || typeof name === 'string') && (jsx === undefined || jsx === 'automatic' || jsx === 'classic')) {
61
+ defaults = true;
62
+ if (name !== undefined) file = name;
63
+ if (jsx === 'classic') flags = classic;
64
+ }
65
+ } else {
66
+ // Spelled-out options are rarer. Their handling lives in a file that a default compile never loads.
67
+ const result = require('./compiler-maps.cjs').compileExplicit(input, options, compile, sourceKind,
68
+ () => pulse ??= nativeAddon('compiler-module.node'));
69
+ if (result !== undefined) return result;
70
+ }
71
+ }
72
+ if (defaults) {
73
+ const kind = sourceKind(file);
74
+ if (kind >= script) {
75
+ if (Buffer.isBuffer(input)) {
76
+ // A module that the certified parse leaves unedited needs no second parse. V8 decides the rest.
77
+ const module = (pulse ??= nativeAddon('compiler-module.node')).emitJavaScriptModule;
78
+ let code = module === undefined ? undefined : module(input, kind !== script);
79
+ if (code === undefined) {
80
+ const emit = (v8 ??= nativeAddon('compiler-js.node')).emitJavaScript;
81
+ if (emit !== undefined) code = emit(input, kind >> 1 & 1);
82
+ }
83
+ if (code !== undefined) return { backend: 'javascript', code, sourceMap: null, diagnostics: [] };
84
+ }
85
+ } else if (kind >= 0) {
86
+ const source = Buffer.isBuffer(input) ? input :
87
+ typeof input === 'string' && input.isWellFormed() ? Buffer.from(input) : null;
88
+ const emit = source === null ? undefined : (pulse ??= nativeAddon('compiler-module.node')).emitTypeScript;
89
+ if (emit !== undefined) {
90
+ const code = emit(source, kind | flags);
91
+ if (code !== undefined) return { backend: 'pulse', code, sourceMap: null, diagnostics: [] };
92
+ }
93
+ }
94
+ }
95
+ return (routes ??= require('./compiler-routes.cjs').compile)(input, options);
96
+ }
97
+
98
+ exports.compile = compile;
@@ -0,0 +1 @@
1
+ export { compile } from './compiler.cjs';
@@ -0,0 +1,172 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { closeSync, copyFileSync, existsSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
4
+ import { availableParallelism } from 'node:os';
5
+ import { resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { prepareBuiltinSwitches, targetedOrBoundary } from './builtin-switches.mjs';
8
+ import { targetedGap } from './targeted-gaps.mjs';
9
+ import { selectScope } from './scope.mjs';
10
+ import { inside, runnerPackage, withCopy } from './vitest.mjs';
11
+
12
+ const supervisor = fileURLToPath(new URL('./runner-process.mjs', import.meta.url));
13
+ const session = fileURLToPath(new URL('./standard-session.mjs', import.meta.url));
14
+ const setupSource = new URL('./standard-setup.mjs', import.meta.url);
15
+ const runnerSource = new URL('./standard-runner.mjs', import.meta.url);
16
+
17
+ function readEvents(path) {
18
+ if (!existsSync(path)) return [];
19
+ const input = readFileSync(path, 'utf8');
20
+ return input.split('\n').slice(0, -1).filter(Boolean).map(line => JSON.parse(line));
21
+ }
22
+
23
+ // The session runs beside its caller, which may block while it waits for other runs.
24
+ function superviseSession(workspace, temp, manifest, limit, signal) {
25
+ const log = resolve(temp, 'mutation-session.stderr');
26
+ const descriptor = openSync(log, 'w');
27
+ return new Promise(settle => {
28
+ const child = spawn(process.execPath, [supervisor, resolve(temp, 'mutation-session.pid'), String(limit), session, manifest], {
29
+ cwd: workspace, stdio: ['ignore', 'ignore', descriptor], timeout: limit + 5_000, signal,
30
+ env: { ...process.env, CI: 'true', VITEST: '1', NODE_ENV: 'test' },
31
+ });
32
+ const finish = result => {
33
+ closeSync(descriptor);
34
+ settle({ ...result, stderr: readFileSync(log, 'utf8').slice(0, 4 * 1024 * 1024) });
35
+ };
36
+ let failure;
37
+ child.once('error', error => { failure = error; });
38
+ child.once('close', (status, stopped) => finish({ status, signal: stopped, error: failure }));
39
+ });
40
+ }
41
+
42
+ export async function analyzeConventional(project, files, options) {
43
+ const root = realpathSync(project);
44
+ const profile = options.mutators ?? 'targeted';
45
+ const prefix = '.tmt-session-' + randomUUID();
46
+ const targets = selectScope(root, files, options).map(subject => ({
47
+ ...subject, input: readFileSync(inside(root, subject.file)),
48
+ }));
49
+ const originals = new Map(targets.map(({ file, input }) => [file, input]));
50
+ const awaitsExtras = options.extras !== undefined;
51
+ const { sources, mutants: prepared } = prepareBuiltinSwitches(targets, {
52
+ dialect: options.dialect,
53
+ shifts: awaitsExtras,
54
+ ...(profile === 'targeted' ? { keep: targetedOrBoundary, targeted: true } : {}),
55
+ });
56
+ const report = {
57
+ schemaVersion: 1, runner: 'vitest', mutators: profile,
58
+ extraction: [], mutants: [], diagnostics: [], evaluation: 'no_sites',
59
+ selection: { config: options.config, tests: options.test, copyExclude: options['copy-exclude'] },
60
+ };
61
+ // Shift switches belong to the session and not to the report.
62
+ const mutants = prepared.filter(mutant => !mutant.parametric);
63
+ const runnable = prepared.filter(mutant => mutant.status === undefined);
64
+ if (!mutants.length) return report;
65
+ if (!runnable.length) return { ...report, evaluation: 'evaluated', mutants: mutants.map(({ targeted: _rule, ...mutant }) => mutant) };
66
+
67
+ return withCopy(root, async (workspace, temp) => {
68
+ runnerPackage(workspace, 'vitest');
69
+ for (const { file, output } of sources) {
70
+ const path = inside(workspace, file);
71
+ if (!readFileSync(path).equals(originals.get(file))) throw new Error(`Source changed during analysis: ${file}`);
72
+ writeFileSync(path, output);
73
+ }
74
+ const setup = resolve(workspace, prefix + '-setup.mjs');
75
+ const workerRunner = resolve(workspace, prefix + '-runner.mjs');
76
+ copyFileSync(setupSource, setup);
77
+ copyFileSync(runnerSource, workerRunner);
78
+ const manifest = resolve(temp, 'mutation-session.json');
79
+ const output = resolve(temp, 'mutation-session.jsonl');
80
+ writeFileSync(manifest, JSON.stringify({
81
+ workspace, setup, workerRunner, output, temporary: temp, awaitsExtras,
82
+ mutants: runnable.map(({ id, parametric, targeted }) => ({
83
+ id,
84
+ ...(parametric ? { parametric } : {}),
85
+ ...(targeted?.evidence ? { evidence: true } : {}),
86
+ ...(targeted?.operator === 'idx0' ? { sequenceIndex: true } : {}),
87
+ ...(targeted ? { effects: true } : {}),
88
+ })),
89
+ isolatedTrials: options['isolated-trials'] === true,
90
+ concurrency: options.concurrency ?? Math.max(1, availableParallelism() - 1),
91
+ verifyTrials: options['verify-trials'] ?? 0,
92
+ ...(options.timeout ? { runTimeout: options.timeout * 1000 } : {}),
93
+ config: options.config === undefined ? undefined : inside(workspace, options.config),
94
+ files: [...new Set((options.test ?? []).map(file => inside(workspace, file)))],
95
+ }));
96
+ const limit = 75_000 + (options.timeout ? options.timeout * 1000 : 60_000) * runnable.length;
97
+ // The focused analysis names its threshold edits once it has recorded the comparisons.
98
+ // Guarded by `finished` so a late resolution never writes after `withCopy` deletes `temp`,
99
+ // while a write error during a live session aborts the child and propagates to the caller.
100
+ const extras = resolve(temp, 'extras.json');
101
+ const sessionAbort = new AbortController();
102
+ const onAbort = () => sessionAbort.abort();
103
+ options.signal?.addEventListener('abort', onAbort, { once: true });
104
+ if (options.signal?.aborted) sessionAbort.abort();
105
+ let finished = false;
106
+ let extrasError = null;
107
+ if (awaitsExtras) {
108
+ Promise.resolve(options.extras).then(list => list ?? [], () => []).then(list => {
109
+ if (finished || sessionAbort.signal.aborted) return;
110
+ try {
111
+ writeFileSync(extras + '.part', JSON.stringify(list));
112
+ renameSync(extras + '.part', extras);
113
+ } catch (writeError) {
114
+ if (!finished && !sessionAbort.signal.aborted) {
115
+ extrasError = writeError;
116
+ sessionAbort.abort();
117
+ }
118
+ }
119
+ });
120
+ }
121
+ let run;
122
+ try {
123
+ run = await superviseSession(workspace, temp, manifest, limit, sessionAbort.signal);
124
+ } finally {
125
+ finished = true;
126
+ options.signal?.removeEventListener('abort', onAbort);
127
+ }
128
+ if (extrasError) throw extrasError;
129
+ const events = readEvents(output);
130
+ const error = events.findLast(event => event.error)?.error ?? run.error?.message ??
131
+ (run.stderr?.trim() || `Vitest session stopped (exit ${run.status ?? run.signal})`);
132
+ const baseline = events.find(event => event.baseline)?.baseline ?? { status: 'error', output: error };
133
+ if (baseline.status !== 'passed') return { ...report, evaluation: 'baseline_error', baseline };
134
+ const results = new Map(events.filter(event => event.id !== undefined).map(event => [event.id, event]));
135
+ const completed = run.status === 0 && events.at(-1)?.complete === true;
136
+ const observed = events.find(event => event.observed)?.observed ?? {};
137
+ // The expressions behind the switches an edit's tests newly reach or no longer reach, without the edit's own.
138
+ const places = new Map(prepared.map(mutant => [mutant.id, mutant]));
139
+ const expressionsOf = (entries, own, plain) => {
140
+ const seen = new Map();
141
+ for (const { id, test } of entries) {
142
+ const { location, original } = places.get(id) ?? {};
143
+ if (!location || (location.file === own.file && own.start === location.start && location.end === own.end)) continue;
144
+ // An edit without a probe is plain text: what stands inside it is evaluated without a switch to show it.
145
+ if (plain && location.file === own.file && own.start <= location.start && location.end <= own.end) continue;
146
+ seen.set(`${test}:${location.file}:${location.start}:${location.end}`, { ...(test === undefined ? {} : { test }),
147
+ location: { file: location.file, line: location.line, column: location.column }, expression: original });
148
+ }
149
+ return [...seen.values()].slice(0, 3);
150
+ };
151
+ const withEffects = (gap, mutant) => {
152
+ if (!gap || !mutant.effects) return gap;
153
+ const plain = mutant.targeted?.operator === 'await' || mutant.targeted?.operator === 'cleanup';
154
+ const nowRuns = expressionsOf(mutant.effects.now, mutant.location, plain);
155
+ const noLongerRuns = expressionsOf(mutant.effects.gone, mutant.location, plain);
156
+ return nowRuns.length || noLongerRuns.length ? { ...gap, effects: { nowRuns, noLongerRuns } } : gap;
157
+ };
158
+ const judged = mutants.map(mutant => {
159
+ const result = results.get(mutant.id);
160
+ // An edit the session left out was not run.
161
+ if (result?.status === 'ignored') return { ...mutant, ...result };
162
+ if (result) return { ...mutant, ...result, evidence: result.evidence ?? (result.status === 'unreached' ? 'coverage' : 'reexecuted') };
163
+ return mutant.status ? mutant : { ...mutant, status: 'unevaluated', statusReason: error || 'Mutation session ended early' };
164
+ });
165
+ return {
166
+ ...report, baseline, evaluation: completed ? 'evaluated' : 'incomplete', trials: events.find(event => event.trials)?.trials,
167
+ ...(awaitsExtras ? { extras: events.filter(event => event.extra !== undefined) } : {}),
168
+ mutants: judged.map(({ targeted: _rule, effects: _effects, ...mutant }) => mutant),
169
+ diagnostics: judged.flatMap(mutant => withEffects(targetedGap(mutant, observed[mutant.id]), mutant) ?? []),
170
+ };
171
+ }, { exclude: options['copy-exclude'] });
172
+ }