targeted-mutation 0.2.3 → 0.3.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/bin/tmt.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, realpathSync } from 'node:fs';
3
- import { relative } from 'node:path';
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, relative, resolve } from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
- import { chooseFormat, renderText, usage } from '../src/cli-output.mjs';
5
+ import { chooseFormat, formatProgressSummary, renderText, usage } from '../src/cli-output.mjs';
6
6
  import { enablePreparedTypeScript } from '../src/typescript-compiler.mjs';
7
7
 
8
8
  try {
@@ -29,12 +29,16 @@ try {
29
29
  project: { type: 'string', multiple: true },
30
30
  config: { type: 'string' },
31
31
  test: { type: 'string', multiple: true },
32
+ related: { type: 'boolean' },
32
33
  'copy-exclude': { type: 'string', multiple: true },
33
34
  'copy-exclude-gitignore': { type: 'boolean' },
34
35
  'exclude-rule': { type: 'string', multiple: true },
36
+ 'type-check': { type: 'boolean' },
35
37
  'no-config': { type: 'boolean' },
36
38
  progress: { type: 'boolean' },
37
39
  format: { type: 'string' },
40
+ 'json-out': { type: 'string' },
41
+ 'sarif-out': { type: 'string' },
38
42
  baseline: { type: 'string' },
39
43
  'write-baseline': { type: 'string' },
40
44
  list: { type: 'boolean' },
@@ -64,6 +68,8 @@ try {
64
68
  const runValues = merged.values;
65
69
  if (runValues.runner !== undefined && !['vitest', 'playwright'].includes(runValues.runner)) throw new Error('Expected --runner vitest|playwright');
66
70
  if (runValues.runner === 'playwright' && runValues['displace-thresholds']) throw new Error('--displace-thresholds requires Vitest');
71
+ if (runValues.related && runValues.runner === 'playwright') throw new Error('--related requires Vitest');
72
+ if (values.related && values.test?.length) throw new Error('--related cannot be combined with --test');
67
73
  if (runValues.mutators !== undefined && !['targeted', 'full'].includes(runValues.mutators)) throw new Error('Expected --mutators targeted|full');
68
74
  const session = runValues.runner !== 'playwright' && !runValues.witnesses && !runValues.audit;
69
75
  if ((runValues['isolated-trials'] || runValues['verify-trials'] !== undefined) && !session) {
@@ -94,6 +100,38 @@ try {
94
100
  runValues['exclude-rule'] = runValues['exclude-rule'].flatMap(entry => entry.split(',')).map(s => s.trim()).filter(Boolean);
95
101
  }
96
102
  const format = chooseFormat(runValues.format, process.stdout.isTTY === true);
103
+ const canonicalOutputKeys = filePath => {
104
+ const abs = resolve(filePath);
105
+ const keys = [];
106
+ // Walk up to the nearest existing ancestor so symlinks above uncreated subdirectories resolve identically.
107
+ const tail = [];
108
+ let cursor = abs;
109
+ while (!existsSync(cursor)) {
110
+ const parent = dirname(cursor);
111
+ if (parent === cursor) break;
112
+ tail.unshift(basename(cursor));
113
+ cursor = parent;
114
+ }
115
+ const resolvedPath = existsSync(cursor) ? resolve(realpathSync(cursor), ...tail) : abs;
116
+ const normPath = process.platform === 'win32' || process.platform === 'darwin' ? resolvedPath.toLowerCase() : resolvedPath;
117
+ keys.push(`path:${normPath}`);
118
+ const st = statSync(abs, { throwIfNoEntry: false });
119
+ if (st?.isFile()) keys.push(`ino:${st.dev}:${st.ino}`);
120
+ return keys;
121
+ };
122
+ const seenOutputs = new Map();
123
+ for (const flag of ['json-out', 'sarif-out', 'write-baseline', 'checkpoint']) {
124
+ if (runValues[flag] === undefined) continue;
125
+ if (!runValues[flag].trim() || runValues[flag].includes('\0')) {
126
+ throw new Error(`Expected --${flag} to be a valid file path`);
127
+ }
128
+ for (const key of canonicalOutputKeys(runValues[flag])) {
129
+ if (seenOutputs.has(key)) {
130
+ throw new Error(`Output paths must be distinct: --${seenOutputs.get(key)} and --${flag} resolve to the same file`);
131
+ }
132
+ seenOutputs.set(key, flag);
133
+ }
134
+ }
97
135
  const { parseShard, parseShardingStrategy, listCandidates } = await import('../src/shard.mjs');
98
136
  const shard = parseShard(runValues.shard);
99
137
  const sharding = parseShardingStrategy(runValues.sharding);
@@ -120,6 +158,23 @@ try {
120
158
  runValues['copy-exclude'] = activeExclusions.map(entry => relative(validated.root, entry));
121
159
  }
122
160
  const logProgress = runValues.progress ? message => process.stderr.write(`[tmt] ${message}\n`) : () => {};
161
+ if (runValues.related && !runValues.list) {
162
+ const { selectScope } = await import('../src/scope.mjs');
163
+ const relatedTargets = selectScope(validated.root, files, runValues).map(subject => subject.file);
164
+ if (relatedTargets.length) {
165
+ const { resolveRelatedVitestSpecs } = await import('../src/vitest.mjs');
166
+ const resolved = await resolveRelatedVitestSpecs(validated.root, relatedTargets, {
167
+ config: runValues.config,
168
+ copyExclude: runValues['copy-exclude'],
169
+ ...(runValues.timeout ? { timeout: runValues.timeout * 1000 } : {}),
170
+ });
171
+ runValues.test = resolved.tests;
172
+ runValues.testSpecs = resolved.specs;
173
+ const projects = [...new Set(resolved.specs.map(spec => spec.project).filter(Boolean))];
174
+ if (projects.length) runValues.testProjects = projects;
175
+ logProgress(`Selected ${resolved.tests.length} related test ${resolved.tests.length === 1 ? 'file' : 'files'}.`);
176
+ }
177
+ }
123
178
  enablePreparedTypeScript();
124
179
  let result;
125
180
  if (runValues.list) {
@@ -157,16 +212,29 @@ try {
157
212
  if (!runValues.list && baselineIds) {
158
213
  result = applyBaseline(result, baselineIds);
159
214
  }
160
- logProgress(`Completed (${result.evaluation}, ${(result.mutants ?? []).length} edits, ${(result.diagnostics ?? []).length} gaps).`);
215
+ logProgress(formatProgressSummary(result));
216
+ const jsonPayload = (format === 'json' || runValues['json-out']) ? JSON.stringify(result, null, 2) : null;
217
+ let sarifPayload = null;
218
+ if (format === 'sarif' || runValues['sarif-out']) {
219
+ const { renderSarif } = await import('../src/sarif.mjs');
220
+ const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
221
+ sarifPayload = JSON.stringify(renderSarif(result, { version }), null, 2);
222
+ }
223
+ if (runValues['json-out']) {
224
+ mkdirSync(dirname(runValues['json-out']), { recursive: true });
225
+ writeFileSync(runValues['json-out'], jsonPayload + '\n', 'utf8');
226
+ }
227
+ if (runValues['sarif-out']) {
228
+ mkdirSync(dirname(runValues['sarif-out']), { recursive: true });
229
+ writeFileSync(runValues['sarif-out'], sarifPayload + '\n', 'utf8');
230
+ }
161
231
  if (format === 'json') {
162
- console.log(JSON.stringify(result, null, 2));
232
+ console.log(jsonPayload);
163
233
  } else if (format === 'jsonl') {
164
234
  const { renderJsonl } = await import('../src/sarif.mjs');
165
235
  console.log(renderJsonl(result));
166
236
  } else if (format === 'sarif') {
167
- const { renderSarif } = await import('../src/sarif.mjs');
168
- const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
169
- console.log(JSON.stringify(renderSarif(result, { version }), null, 2));
237
+ console.log(sarifPayload);
170
238
  } else {
171
239
  console.log(renderText(result));
172
240
  }
package/docs/analysis.md CHANGED
@@ -8,7 +8,7 @@ npx targeted-mutation analyze . --lines src/eligibility.ts:1-8 --audit
8
8
  npx targeted-mutation analyze . --since "$(git merge-base origin/main HEAD)"
9
9
  ```
10
10
 
11
- Arguments after the project root select source files. Without files, the CLI discovers TypeScript and TSX sources. The scope comes from explicit line ranges and added or changed lines relative to a Git commit. The CLI parses each selected file before filtering candidate operator positions. The JSON report has a schema version, extraction outcomes, candidate IDs, trial verdicts and diagnostics. A terminal shows a text summary of the same report; a pipe or `--format json` receives the JSON. `--lines FILE:N` selects a single line. A failed baseline lists the failed tests and their messages under `baseline.failedTests`. An extraction diagnostic or a baseline failure exits with status 1. A successful analysis exits with status 0.
11
+ Arguments after the project root select source files. Without files, the CLI discovers TypeScript and TSX sources. The scope comes from explicit line ranges and added or changed lines relative to a Git commit. The CLI parses each selected file before filtering candidate operator positions. The JSON report has a schema version, extraction outcomes, candidate IDs, trial verdicts and diagnostics. A terminal shows a text summary of the same report; a pipe or `--format json` receives the JSON. Pass `--json-out FILE` and/or `--sarif-out FILE` to write machine-readable report files alongside terminal text output (all output paths, including `--write-baseline` and `--checkpoint`, must be distinct). Under `--mutators full`, the summary distinguishes targeted test gaps from non-targeted survivors (`N targeted gap(s) (M other survivor(s))`). `--lines FILE:N` selects a single line. A failed baseline lists the failed tests and their messages under `baseline.failedTests`. An extraction diagnostic or a baseline failure exits with status 1. A successful analysis exits with status 0.
12
12
 
13
13
  ### Limit a dogfood or CI run
14
14
 
@@ -18,7 +18,7 @@ npx targeted-mutation analyze . packages/example/src/ranges.ts --since HEAD^ \
18
18
  --copy-exclude benchmarks --audit
19
19
  ```
20
20
 
21
- `--config` selects a project-relative Vitest or Playwright config. Repeat `--test FILE` to run specific, project-relative test files in every phase, including witness runs. With Playwright the files are passed to `playwright test` as path filters, so a suite with several browsers and many specs can start with the one spec that covers the source. The report records the selection and errors if the config collects missing or additional test files. Any conclusions from a selected suite apply to that suite. Repeat `--copy-exclude PATH` to omit local assets or build caches from every temporary copy while leaving the original checkout intact. Missing exclusion paths emit a single warning to `stderr` and are skipped so fixed scripts work on clean checkouts before build artifacts exist. A selected suite should retain the files and build outputs it needs. The runner already omits `.worktree` and `.worktrees`. Source discovery skips excluded paths. Provide exclusions inside the project without traversing symbolic links, and keep `node_modules` available for the test runner.
21
+ `--config` selects a project-relative Vitest or Playwright config. Repeat `--test FILE` to run specific, project-relative test files in every phase, including witness runs. For Vitest projects, `--related` (or `related: true` in project configuration) discovers only the test files and Vitest projects related to the scoped source files via Vitest's dependency graph inside a supervised temporary copy, failing with a clear `--test <FILE>` hint if no related tests exist. `--type-check` (or `typeCheck: true` in project configuration) uses TypeScript's type checker when `strictNullChecks` is enabled to skip statically equivalent `nullish-fallback/v1` and `nullish-equality/v1` edits (while preserving unsound cases such as `number | null` with `?? 0`, indexed access without `noUncheckedIndexedAccess`, `{}`, `void`, and shadowed `undefined`). With Playwright the files are passed to `playwright test` as path filters, so a suite with several browsers and many specs can start with the one spec that covers the source. The report records the selection and errors if the config collects missing or additional test files. Any conclusions from a selected suite apply to that suite. Repeat `--copy-exclude PATH` to omit local assets or build caches from every temporary copy while leaving the original checkout intact. Missing exclusion paths emit a single warning to `stderr` and are skipped so fixed scripts work on clean checkouts before build artifacts exist. A selected suite should retain the files and build outputs it needs. The runner already omits `.worktree` and `.worktrees`. Source discovery skips excluded paths. Provide exclusions inside the project without traversing symbolic links, and keep `node_modules` available for the test runner.
22
22
 
23
23
  Automatic scope includes JavaScript and TypeScript source, including JSX and module-specific extensions. It skips conventional test, spec, declaration and runner configuration filenames. With `--since`, Git supplies tracked and changed paths in bulk. Only changed tracked files in scope need a line diff. A new, untracked file counts as changed unless Git ignores it: generated clients and build output under `.gitignore` are left out of discovery, and naming such a file on the command line still selects it.
24
24
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "targeted-mutation",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "description": "Find the tests a JavaScript or TypeScript suite is missing by trying small, targeted source edits against it.",
5
5
  "keywords": [
6
6
  "mutation-testing",
@@ -43,9 +43,9 @@
43
43
  "NOTICE"
44
44
  ],
45
45
  "optionalDependencies": {
46
- "@targeted-mutation/tmt-darwin-arm64": "0.2.3",
47
- "@targeted-mutation/tmt-darwin-x64": "0.2.3",
48
- "@targeted-mutation/tmt-linux-arm64": "0.2.3",
49
- "@targeted-mutation/tmt-linux-x64": "0.2.3"
46
+ "@targeted-mutation/tmt-darwin-arm64": "0.3.0",
47
+ "@targeted-mutation/tmt-darwin-x64": "0.3.0",
48
+ "@targeted-mutation/tmt-linux-arm64": "0.3.0",
49
+ "@targeted-mutation/tmt-linux-x64": "0.3.0"
50
50
  }
51
51
  }
package/src/analysis.mjs CHANGED
@@ -12,6 +12,7 @@ import { inside, runVitest, runVitestAsync, withCopy } from './vitest.mjs';
12
12
  import { createProbePreloadCheck, freshProbeBinding, instrument, installProbe, rewrite } from './probe.mjs';
13
13
  import { runPlaywright } from './playwright.mjs';
14
14
  import { selectScope } from './scope.mjs';
15
+ import { createTypeContext } from './type-equivalence.mjs';
15
16
  import { checkReplay } from './lean-replay.mjs';
16
17
  import { ignoredSwaps, renderBuiltinSwitches } from './builtin-switches.mjs';
17
18
  import { inspectTrace, pendingTraceDirectory, sameObservations } from './trace-buffer.mjs';
@@ -48,11 +49,11 @@ function builtInSites(comparisons, input, file, dialect, selected, options = {})
48
49
  left: [mutant.edit[0], mutant.edit[0]], right: [mutant.edit[1], mutant.edit[1]], source: mutant.source, unobserved: true }));
49
50
  }
50
51
 
51
- function withProfileSites(comparisons, input, file, { mutators, dialect, 'exclude-rule': excludeRules }, selected) {
52
+ function withProfileSites(comparisons, input, file, { mutators, dialect, 'exclude-rule': excludeRules }, selected, typeEquivalence = null) {
52
53
  const start = candidate => (candidate.operatorEdit ?? candidate.edit)[0];
53
54
  // Without a session nothing is recorded, so the targeted or full edits run as plain source edits.
54
- const added = mutators === 'full' ? builtInSites(comparisons, input, file, dialect, selected, { excludeRules })
55
- : mutators === 'targeted' ? builtInSites(comparisons, input, file, dialect, selected, { targeted: true, excludeRules, keep: mutation => mutation.targeted !== undefined })
55
+ const added = mutators === 'full' ? builtInSites(comparisons, input, file, dialect, selected, { excludeRules, typeEquivalence })
56
+ : mutators === 'targeted' ? builtInSites(comparisons, input, file, dialect, selected, { targeted: true, excludeRules, typeEquivalence, keep: mutation => mutation.targeted !== undefined })
56
57
  : [];
57
58
  return added.length ? [...comparisons, ...added].sort((a, b) => start(a) - start(b)) : comparisons;
58
59
  }
@@ -60,7 +61,11 @@ function withProfileSites(comparisons, input, file, { mutators, dialect, 'exclud
60
61
  export function collectComparisons(root, files, options) {
61
62
  const subjects = [];
62
63
  const extraction = [];
63
- for (const { file, selected } of selectScope(root, files, options)) {
64
+ const scoped = selectScope(root, files, options);
65
+ const typeContext = options['type-check'] && ['targeted', 'full'].includes(options.mutators)
66
+ ? createTypeContext(root, scoped.map(subject => subject.file))
67
+ : null;
68
+ for (const { file, selected } of scoped) {
64
69
  const input = readFileSync(inside(root, file));
65
70
  const { path, fallback, reason, candidates: comparisons, diagnostics } = extract(input, { file, mode: options.mode, dialect: options.dialect, logical: options.runner === 'playwright' });
66
71
  extraction.push({ file, path, reason, diagnostics, ...(fallback === undefined ? {} : { fallback }) });
@@ -69,7 +74,9 @@ export function collectComparisons(root, files, options) {
69
74
  const disabled = ignoredSwaps(input, file, { dialect: options.dialect });
70
75
  const kept = disabled.size ? comparisons.filter(candidate => !disabled.has(`${candidate.edit[0]}:${candidate.replacement}`)) : comparisons;
71
76
  if (kept.length !== comparisons.length) extraction.at(-1).ignored = comparisons.length - kept.length;
72
- const candidates = ['targeted', 'full'].includes(options.mutators) ? withProfileSites(kept, input, file, options, selected) : kept;
77
+ const candidates = ['targeted', 'full'].includes(options.mutators)
78
+ ? withProfileSites(kept, input, file, options, selected, typeContext?.forFile(file) ?? null)
79
+ : kept;
73
80
  const positions = byteLocations(input, candidates.map(candidate => (candidate.operatorEdit ?? candidate.edit)[0]));
74
81
  // A comparison is in scope when any line from its left operand to its right operand is: a threshold on its
75
82
  // own line belongs to the comparison whose operator is on the line above.
@@ -163,14 +170,14 @@ export function sourceTrials(root, subjects, options) {
163
170
  ? (workspace, temp) => runPlaywright(workspace, temp, { config: options.config, projects: options.project, original: root,
164
171
  tests: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) })
165
172
  : (workspace, temp, settings) => runVitest(workspace, temp, {
166
- ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
173
+ ...settings, config: options.config, testFiles: options.test, testProjects: options.testProjects, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
167
174
  return settings => makeAttempt(root, subjects, runner, options['copy-exclude'], new Map(), settings);
168
175
  }
169
176
 
170
177
  // Asynchronous Vitest plain-source runs, so independent witness checks can run side by side.
171
178
  export function sourceTrialsAsync(root, subjects, options) {
172
179
  const runner = (workspace, temp, settings) => runVitestAsync(workspace, temp, {
173
- ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
180
+ ...settings, config: options.config, testFiles: options.test, testProjects: options.testProjects, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
174
181
  return settings => withCopy(root, async (workspace, temp) => {
175
182
  const { trial, witness, collect } = settings ?? {};
176
183
  for (const subject of subjects) {
@@ -610,7 +617,7 @@ export function prepareAnalysis(project, files, options) {
610
617
  const specification = options.spec ? JSON.parse(readFileSync(inside(root, options.spec), 'utf8')) : {};
611
618
  if (report.runner === 'playwright') return { report: analyzePlaywright(root, subjects, report, options, specification) };
612
619
  const runner = (workspace, temp, settings) => runVitest(workspace, temp, {
613
- ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}),
620
+ ...settings, config: options.config, testFiles: options.test, testProjects: options.testProjects, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}),
614
621
  });
615
622
  const probeChecks = new Map(subjects.map(subject => [subject, createProbePreloadCheck(subject.input)]));
616
623
  const attempt = settings => makeAttempt(root, subjects, runner, options['copy-exclude'], probeChecks, settings);
@@ -40,7 +40,7 @@ const endSwaps = new Map([['find', 'findLast'], ['findLast', 'find'], ['findInde
40
40
  ['indexOf', 'lastIndexOf'], ['lastIndexOf', 'indexOf']]);
41
41
  const ignoredValue = { '&&': 'true', '||': 'false', '??': 'undefined' };
42
42
 
43
- export function collectMutations(text, file, { dialect, selected = () => true, shifts = false, targeted = false, excludeRules = [], ts = loadTypeScript() } = {}) {
43
+ export function collectMutations(text, file, { dialect, selected = () => true, shifts = false, targeted = false, excludeRules = [], typeEquivalence = null, ts = loadTypeScript() } = {}) {
44
44
  const excludedRuleSet = new Set((excludeRules ?? []).map(r => String(r).trim()).filter(Boolean));
45
45
  const kind = dialect === 'tsx' ? ts.ScriptKind.TSX : dialect === 'ts' ? ts.ScriptKind.TS : undefined;
46
46
  const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
@@ -250,6 +250,17 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
250
250
  ((ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) && inner.text === ''));
251
251
  };
252
252
 
253
+ const falsyLiteralLabel = node => {
254
+ const inner = strip(node);
255
+ const number = ts.isPrefixUnaryExpression(inner) && inner.operator === K.MinusToken ? inner.operand : inner;
256
+ if (inner.kind === K.FalseKeyword) return 'false';
257
+ if (ts.isIdentifier(inner) && inner.text === 'NaN') return 'NaN';
258
+ if (ts.isNumericLiteral(number) && Number(number.text) === 0) return '0';
259
+ if (ts.isBigIntLiteral(number) && /^0[box]?0*n$/i.test(number.text)) return '0n';
260
+ if ((ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) && inner.text === '') return "''";
261
+ return undefined;
262
+ };
263
+
253
264
  const nullishLiteral = node => {
254
265
  const inner = strip(node);
255
266
  return inner.kind === K.NullKeyword ? 'null' : ts.isIdentifier(inner) && inner.text === 'undefined' ? 'undefined' : undefined;
@@ -343,24 +354,35 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
343
354
  // In `typeof x === "object" && x !== null` (or reversed), `x` cannot be `undefined`, so
344
355
  // relaxing `!== null` / `=== null` to loose equality is an unreachable equivalent mutant.
345
356
  if (written[literalSide] === 'null' && isGuardedTypeofObject(node, subjectNode)) return;
357
+ const isNullishEqv = target => Boolean(typeEquivalence?.isNullishEqualityEquivalent(begin(subjectNode), subjectNode.end, target));
346
358
  if (operator.length === 3) {
347
- edit(targetedRules.nullish, 'loose', swapToken(node, token, operator.slice(0, 2)), { literalSide, differsFor: other, subject });
359
+ if (!isNullishEqv(other)) {
360
+ edit(targetedRules.nullish, 'loose', swapToken(node, token, operator.slice(0, 2)), { literalSide, differsFor: other, subject });
361
+ }
348
362
  } else {
349
363
  const strict = operator + '=';
350
- edit(targetedRules.nullish, 'strict', swapToken(node, token, strict), { literalSide, differsFor: other, subject });
351
- edit(targetedRules.nullish, 'other', literalSide ? `${left} ${strict} ${other}` : `${other} ${strict} ${right}`,
352
- { literalSide, differsFor: written[literalSide], subject });
364
+ if (!isNullishEqv(other)) {
365
+ edit(targetedRules.nullish, 'strict', swapToken(node, token, strict), { literalSide, differsFor: other, subject });
366
+ }
367
+ if (!isNullishEqv(written[literalSide])) {
368
+ edit(targetedRules.nullish, 'other', literalSide ? `${left} ${strict} ${other}` : `${other} ${strict} ${right}`,
369
+ { literalSide, differsFor: written[literalSide], subject });
370
+ }
353
371
  }
354
372
  } else if (isLogical(node) && !staysInPlace(node.right)) {
355
373
  const operand = grouped;
374
+ const rightFalsy = falsyLiteralLabel(node.right);
356
375
  const more = { thunk: true, ...(written(node.right) ? { pureRight: true } : {}) };
357
376
  edit(targetedRules.ignored, 'left', `(${left}, ${right})`, more);
358
377
  edit(targetedRules.ignored, 'right', `(${left} ${operator} (${right}, ${ignoredValue[operator]}))`, more);
359
378
  // Where only the truth is used, a written falsy fallback makes `??` and `||` the same for every value.
360
379
  if (boolean && writtenFalsy(node.right)) return;
361
- if (operator === '??') edit(targetedRules.fallback, 'or', `(${operand(node.left)} || ${operand(node.right)})`, { ...more, evidence: true });
380
+ const leftNode = strip(node.left);
381
+ if (typeEquivalence?.isNullishFallbackEquivalent(begin(leftNode), leftNode.end, rightFalsy)) return;
382
+ const fallbackMore = { ...more, ...(rightFalsy ? { rightFalsy } : {}), evidence: true };
383
+ if (operator === '??') edit(targetedRules.fallback, 'or', `(${operand(node.left)} || ${operand(node.right)})`, fallbackMore);
362
384
  // Where only the truth of the value is used, nobody writes `??` for `||`.
363
- else if (operator === '||' && !boolean) edit(targetedRules.fallback, 'nullish', `(${operand(node.left)} ?? ${operand(node.right)})`, { ...more, evidence: true });
385
+ else if (operator === '||' && !boolean) edit(targetedRules.fallback, 'nullish', `(${operand(node.left)} ?? ${operand(node.right)})`, fallbackMore);
364
386
  }
365
387
  }
366
388
 
@@ -633,8 +633,10 @@ export const targetedOrBoundary = (mutation, text) => mutation.targeted !== unde
633
633
  export function prepareBuiltinSwitches(subjects, options = {}) {
634
634
  const sources = [];
635
635
  const mutants = [];
636
+ const { typeContext, ...restOptions } = options;
636
637
  for (const { file, input, selected } of subjects) {
637
- const rendered = renderBuiltinSwitches(input, file, selected, options);
638
+ const typeEquivalence = typeContext?.forFile(file) ?? null;
639
+ const rendered = renderBuiltinSwitches(input, file, selected, { ...restOptions, typeEquivalence });
638
640
  if (!rendered.mutants.length) continue;
639
641
  if (rendered.output !== input.toString()) sources.push({ file, output: rendered.output });
640
642
  mutants.push(...rendered.mutants);
@@ -49,6 +49,7 @@ export function computeCampaignContext(targets, options = {}, root = null) {
49
49
  runner: options.runner ?? 'vitest',
50
50
  config: options.config ?? null,
51
51
  test: options.test ?? null,
52
+ ...(options.testSpecs?.length ? { testSpecs: options.testSpecs } : {}),
52
53
  lines: options.lines ?? null,
53
54
  since: options.since ?? null,
54
55
  shard: options.shard ?? null,
@@ -56,6 +57,7 @@ export function computeCampaignContext(targets, options = {}, root = null) {
56
57
  deterministic: !!options.deterministic,
57
58
  displaceThresholds: !!options['displace-thresholds'],
58
59
  excludeRules: options['exclude-rule'] ?? null,
60
+ ...(options['type-check'] ? { typeCheck: true } : {}),
59
61
  timeout: options.timeout ?? null,
60
62
  copyExclude: options['copy-exclude'] ?? null,
61
63
  isolatedTrials: !!options['isolated-trials'],
@@ -15,6 +15,8 @@ Scope (analyze):
15
15
  --copy-exclude PATH Leave a project path out of the temporary copies (warns and skips if missing). Repeatable.
16
16
  --copy-exclude-gitignore Also exclude gitignored paths (except node_modules) from temporary copies.
17
17
  --exclude-rule RULE Exclude a mutation rule (e.g. nullish-equality/v1). Repeatable.
18
+ --type-check Use TypeScript's type checker (when strictNullChecks is enabled) to skip
19
+ statically equivalent nullish-fallback/v1 and nullish-equality/v1 edits.
18
20
  --no-config Ignore targeted-mutation.config.{json,mjs} and package.json#targetedMutation.
19
21
  --progress Print lightweight progress updates to stderr.
20
22
 
@@ -47,12 +49,15 @@ Runner (analyze):
47
49
  --runner vitest|playwright Test runner (default: vitest).
48
50
  --config FILE Runner configuration file inside the project.
49
51
  --test FILE Run only this test file. Repeatable.
52
+ --related Select only Vitest test files related to the target source files.
50
53
  --timeout SECONDS Time limit for one run of the suite (default: 60).
51
54
  --project NAME Playwright project. Repeatable.
52
55
 
53
56
  Output & Baselines:
54
57
  --format text|json|jsonl|sarif
55
58
  Output format (analyze defaults to text on a terminal and json otherwise).
59
+ --json-out FILE Also write the JSON report to FILE (can be combined with --format text).
60
+ --sarif-out FILE Also write the SARIF report to FILE (can be combined with --format text).
56
61
  --baseline FILE Suppress findings already recorded in FILE.
57
62
  --write-baseline FILE Write this run's findings to FILE for future --baseline runs.
58
63
  --mode script|module extract: parse goal.
@@ -158,6 +163,30 @@ function describeGap(gap) {
158
163
  return lines;
159
164
  }
160
165
 
166
+ const plural = (count, singular, pluralForm = singular + 's') => `${count} ${count === 1 ? singular : pluralForm}`;
167
+
168
+ export function summarizeReport(report) {
169
+ const mutants = report?.mutants ?? [];
170
+ const gaps = report?.diagnostics ?? [];
171
+ const gapSites = new Set(gaps.map(gap => gap.site).filter(Boolean));
172
+ const otherSurvivors = report?.mutators === 'full'
173
+ ? mutants.filter(mutant =>
174
+ mutant.status === 'survived' &&
175
+ !gapSites.has(mutant.id ?? mutant.site) &&
176
+ !String(mutant.mutatorName ?? mutant.rule ?? '').includes('/'))
177
+ .length
178
+ : 0;
179
+ return { edits: mutants.length, gaps: gaps.length, otherSurvivors };
180
+ }
181
+
182
+ export function formatProgressSummary(report) {
183
+ const { edits, gaps, otherSurvivors } = summarizeReport(report);
184
+ const gapPart = otherSurvivors > 0
185
+ ? `${plural(gaps, 'targeted gap')}, ${plural(otherSurvivors, 'other survivor')}`
186
+ : plural(gaps, 'gap');
187
+ return `Completed (${report.evaluation}, ${plural(edits, 'edit')}, ${gapPart}).`;
188
+ }
189
+
161
190
  export function renderText(report) {
162
191
  const lines = [];
163
192
  for (const file of report.extraction ?? []) {
@@ -186,8 +215,12 @@ export function renderText(report) {
186
215
  const tally = [...counts].map(([status, count]) => `${count} ${status}`).join(', ') || 'none';
187
216
  const tests = report.baseline?.tests;
188
217
  const size = Array.isArray(tests) ? tests.length : tests;
189
- lines.push(`${report.runner}${size === undefined ? '' : `, ${size} baseline tests`}: ` +
190
- `${mutants.length} edits (${tally}), ${gaps.length} test gaps` +
218
+ const { otherSurvivors } = summarizeReport(report);
219
+ const gapSummary = otherSurvivors > 0
220
+ ? `${plural(gaps.length, 'targeted gap')} (${plural(otherSurvivors, 'other survivor')})`
221
+ : plural(gaps.length, 'test gap');
222
+ lines.push(`${report.runner}${size === undefined ? '' : `, ${plural(size, 'baseline test')}`}: ` +
223
+ `${plural(mutants.length, 'edit')} (${tally}), ${gapSummary}` +
191
224
  (report.suppressed?.baseline ? `, ${report.suppressed.baseline} suppressed by baseline` : '') +
192
225
  (report.shard ? `, shard ${report.shard.index}/${report.shard.total}` : '') +
193
226
  (report.evaluation === 'evaluated' ? '' : `, evaluation ${report.evaluation}`));
@@ -9,6 +9,7 @@ import { targetedGap } from './targeted-gaps.mjs';
9
9
  import { checkpointKeyForTrial } from './checkpoint.mjs';
10
10
  import { candidateKey } from './shard.mjs';
11
11
  import { selectScope } from './scope.mjs';
12
+ import { createTypeContext } from './type-equivalence.mjs';
12
13
  import { inside, runnerPackage, withCopy } from './vitest.mjs';
13
14
 
14
15
  const supervisor = fileURLToPath(new URL('./runner-process.mjs', import.meta.url));
@@ -50,10 +51,12 @@ export async function analyzeConventional(project, files, options) {
50
51
  }));
51
52
  const originals = new Map(targets.map(({ file, input }) => [file, input]));
52
53
  const awaitsExtras = options.extras !== undefined;
54
+ const typeContext = options['type-check'] ? createTypeContext(root, targets.map(t => t.file)) : null;
53
55
  const { sources, mutants: prepared } = prepareBuiltinSwitches(targets, {
54
56
  dialect: options.dialect,
55
57
  shifts: awaitsExtras,
56
58
  excludeRules: options['exclude-rule'],
59
+ typeContext,
57
60
  ...(profile === 'targeted' ? { keep: targetedOrBoundary, targeted: true } : {}),
58
61
  });
59
62
  const report = {
@@ -125,6 +128,7 @@ export async function analyzeConventional(project, files, options) {
125
128
  ...(options.timeout ? { runTimeout: options.timeout * 1000 } : {}),
126
129
  config: options.config === undefined ? undefined : inside(workspace, options.config),
127
130
  files: [...new Set((options.test ?? []).map(file => inside(workspace, file)))],
131
+ ...(options.testSpecs?.length ? { selectedSpecs: options.testSpecs.map(({ project, file }) => ({ project, file: inside(workspace, file) })) } : {}),
128
132
  }));
129
133
  const limit = 75_000 + (options.timeout ? options.timeout * 1000 : 60_000) * runnable.length;
130
134
  // The focused analysis names its threshold edits once it has recorded the comparisons.
@@ -76,6 +76,8 @@ async function besideSession(project, files, options, run, profile, stopsSession
76
76
  ...(options.shardKeys ? { shardKeys: options.shardKeys } : {}),
77
77
  ...(options.checkpointStore ? { checkpointStore: options.checkpointStore } : {}),
78
78
  ...(options['exclude-rule'] ? { 'exclude-rule': options['exclude-rule'] } : {}),
79
+ ...(options['type-check'] ? { 'type-check': true } : {}),
80
+ ...(options.testSpecs?.length ? { testSpecs: options.testSpecs } : {}),
79
81
  }).then(report => ({ report }), error => ({ error }));
80
82
  let prepared;
81
83
  try {
@@ -174,10 +174,12 @@ export function mergeProjectConfig(configObj, cliValues, cliFiles) {
174
174
  if (values.concurrency === undefined && configObj.concurrency !== undefined) values.concurrency = String(configObj.concurrency);
175
175
  if (values.config === undefined && typeof configObj.config === 'string') values.config = configObj.config;
176
176
  if (values.baseline === undefined && typeof configObj.baseline === 'string') values.baseline = configObj.baseline;
177
- if (!values.test?.length && Array.isArray(configObj.tests)) values.test = configObj.tests.map(String);
177
+ if (values.related === undefined && !values.test?.length && configObj.related === true) values.related = true;
178
+ if (!values.test?.length && !values.related && Array.isArray(configObj.tests)) values.test = configObj.tests.map(String);
178
179
  if (!values['copy-exclude']?.length && Array.isArray(configObj.copyExclude)) values['copy-exclude'] = configObj.copyExclude.map(String);
179
180
  if (values['copy-exclude-gitignore'] === undefined && configObj.copyExcludeGitignore === true) values['copy-exclude-gitignore'] = true;
180
181
  if (!values['exclude-rule']?.length && Array.isArray(configObj.excludeRules)) values['exclude-rule'] = configObj.excludeRules.map(String);
182
+ if (values['type-check'] === undefined && configObj.typeCheck === true) values['type-check'] = true;
181
183
  const files = cliFiles.length ? cliFiles : (Array.isArray(configObj.files) ? configObj.files.map(String) : []);
182
184
  return { files, values };
183
185
  }
package/src/shard.mjs CHANGED
@@ -2,6 +2,7 @@ import { readFileSync, realpathSync } from 'node:fs';
2
2
  import { collectComparisons } from './analysis.mjs';
3
3
  import { prepareBuiltinSwitches, targetedOrBoundary } from './builtin-switches.mjs';
4
4
  import { selectScope } from './scope.mjs';
5
+ import { createTypeContext } from './type-equivalence.mjs';
5
6
  import { inside } from './vitest.mjs';
6
7
 
7
8
  export function parseShard(spec) {
@@ -95,9 +96,11 @@ export function listCandidates(project, files, options = {}) {
95
96
  ...subject,
96
97
  input: readFileSync(inside(root, subject.file)),
97
98
  }));
99
+ const typeContext = options['type-check'] ? createTypeContext(root, targets.map(t => t.file)) : null;
98
100
  const { mutants: prepared } = prepareBuiltinSwitches(targets, {
99
101
  dialect: options.dialect,
100
102
  excludeRules: options['exclude-rule'],
103
+ typeContext,
101
104
  ...(profile === 'targeted' ? { keep: targetedOrBoundary, targeted: true } : {}),
102
105
  });
103
106
  for (const mutant of prepared) {
@@ -9,7 +9,7 @@ import { inside } from './vitest.mjs';
9
9
  // Vitest and Vite are loaded on every run. Node keeps their compiled code between runs when it can.
10
10
  try { enableCompileCache?.(); } catch { /* The cache is an optimisation only. */ }
11
11
  const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
12
- const { workspace, config, files, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000 } = input;
12
+ const { workspace, config, files, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000 } = input;
13
13
  const destination = resolve(temporary, 'coverage.jsonl');
14
14
  const record = event => appendFileSync(output, JSON.stringify(event) + '\n');
15
15
  const lanes = [];
@@ -56,7 +56,13 @@ function follow(path) {
56
56
  async function openLane(index, serial = false) {
57
57
  const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial };
58
58
  lane.context = await createContext(lane);
59
- lane.specs = await lane.context.globTestSpecifications(files);
59
+ const allSpecs = await lane.context.globTestSpecifications(files);
60
+ if (selectedSpecs?.length) {
61
+ const allowed = new Set(selectedSpecs.map(({ project, file }) => JSON.stringify([project ?? '', file])));
62
+ lane.specs = allSpecs.filter(spec => allowed.has(JSON.stringify([spec.project.name ?? '', inside(workspace, spec.moduleId)])));
63
+ } else {
64
+ lane.specs = allSpecs;
65
+ }
60
66
  return lane;
61
67
  }
62
68
 
@@ -25,7 +25,7 @@ const roundingDiffers = { 'floor trunc': 'negative and not a whole number (-0.5)
25
25
  'floor round': 'a number that rounds up (1.5, -1.5)', 'ceil round': 'a number that rounds down (1.4, -1.6)',
26
26
  'round trunc': 'a number that rounds away from zero (1.5, -1.6)', 'ceil floor': 'not a whole number (0.5)' };
27
27
 
28
- function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, key, boundKind, pruned, argName }, expression, rule, replacement) {
28
+ function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, rightFalsy, key, boundKind, pruned, argName }, expression, rule, replacement) {
29
29
  const side = '`' + clip(left) + '`';
30
30
  if (rule === rules.spreadDrop) return `a test in which \`${clip(left)}.${key}\` is missing or differs from its updated value`;
31
31
  if (rule === rules.prefixSubstring) {
@@ -48,7 +48,14 @@ function missingInput({ operator, form, boolean, left, right: rightExpr, differs
48
48
  }
49
49
  if (form === 'true' || form === 'false') return `a test in which \`${clip(expression)}\` is ${form === 'true' ? 'false' : 'true'}`;
50
50
  if (form === 'loose' || form === 'strict' || form === 'other') return `a test in which \`${clip(subject)}\` is ${differsFor}`;
51
- if (form === 'or' || form === 'nullish') return `a test in which ${side} is 0, 0n, '', false or NaN${pureRight ? ' and not the right side\'s value' : ''}`;
51
+ if (form === 'or' || form === 'nullish') {
52
+ if (rightFalsy) {
53
+ const values = ['0', '0n', "''", 'false', 'NaN'].filter(value => value !== rightFalsy);
54
+ const list = `${values.slice(0, -1).join(', ')} or ${values.at(-1)}`;
55
+ return `a test in which ${side} is ${list}`;
56
+ }
57
+ return `a test in which ${side} is 0, 0n, '', false or NaN${pureRight ? ' and not the right side\'s value' : ''}`;
58
+ }
52
59
  const takesRight = { '&&': 'truthy', '||': 'falsy', '??': 'null or undefined' }[operator];
53
60
  if (form === 'left') return `a test in which ${side} is ${{ '&&': 'falsy', '||': 'truthy', '??': 'neither null nor undefined' }[operator]}`;
54
61
  const kept = { '&&': 'true', '||': 'false', '??': 'undefined' }[operator];
@@ -0,0 +1,245 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { loadTypeScript } from './typescript-compiler.mjs';
4
+
5
+ const PRIMITIVE_PROTOTYPE_KEYS = new Set([
6
+ '__proto__',
7
+ ...Object.getOwnPropertyNames(Object.prototype),
8
+ ...Object.getOwnPropertyNames(String.prototype),
9
+ ...Object.getOwnPropertyNames(Number.prototype),
10
+ ...Object.getOwnPropertyNames(Boolean.prototype),
11
+ ...Object.getOwnPropertyNames(BigInt.prototype),
12
+ ...Object.getOwnPropertyNames(Symbol.prototype),
13
+ ]);
14
+
15
+ function isGuaranteedNonPrimitiveObject(ts, checker, type) {
16
+ if (checker.isArrayType(type) || checker.isTupleType(type)) return true;
17
+ if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) return true;
18
+ // Require at least one non-optional property that does not exist on built-in primitive prototypes;
19
+ // `{}` and `{ toString(): string }` accept primitives like `0`, `""`, and `false` in TypeScript.
20
+ for (const prop of type.getProperties()) {
21
+ if (prop.flags & ts.SymbolFlags.Optional) continue;
22
+ if (!PRIMITIVE_PROTOTYPE_KEYS.has(prop.name)) return true;
23
+ }
24
+ return false;
25
+ }
26
+
27
+ function canContainNullish(ts, checker, type, kind, seen = new Set()) {
28
+ if (!type || seen.has(type)) return true;
29
+ seen.add(type);
30
+ const flags = type.flags;
31
+ // `void` can hold arbitrary return values at runtime (e.g. `const f: () => void = () => false`).
32
+ if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Void)) return true;
33
+ if (flags & ts.TypeFlags.Never) return false;
34
+ if (kind === 'null' && (flags & ts.TypeFlags.Null)) return true;
35
+ if (kind === 'undefined' && (flags & ts.TypeFlags.Undefined)) return true;
36
+ if (type.isUnion()) return type.types.some(member => canContainNullish(ts, checker, member, kind, new Set(seen)));
37
+ if (type.isIntersection()) return type.types.every(member => canContainNullish(ts, checker, member, kind, new Set(seen)));
38
+ if (flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess | ts.TypeFlags.Conditional | ts.TypeFlags.Substitution | ts.TypeFlags.TemplateLiteral)) {
39
+ const constraint = checker.getBaseConstraintOfType(type);
40
+ return constraint ? canContainNullish(ts, checker, constraint, kind, seen) : true;
41
+ }
42
+ return false;
43
+ }
44
+
45
+ function collectNonNullishFalsy(ts, checker, type, out = new Set(), seen = new Set()) {
46
+ if (!type || seen.has(type)) return 'any';
47
+ seen.add(type);
48
+ const flags = type.flags;
49
+ // `void` can hold arbitrary return values at runtime (e.g. `() => void` returning `false` or `0`).
50
+ if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Void)) return 'any';
51
+ if (flags & (ts.TypeFlags.Never | ts.TypeFlags.Null | ts.TypeFlags.Undefined)) return out;
52
+ if (type.isUnion()) {
53
+ for (const member of type.types) {
54
+ if (collectNonNullishFalsy(ts, checker, member, out, new Set(seen)) === 'any') return 'any';
55
+ }
56
+ return out;
57
+ }
58
+ if (type.isIntersection()) {
59
+ if (type.types.some(member => member.flags & ts.TypeFlags.Never)) return out;
60
+ // Branded primitives (e.g. `string & { __brand: 'id' }`) still carry the primitive's runtime values,
61
+ // so over-approximating by collecting from all constituents is sound.
62
+ for (const member of type.types) {
63
+ if (collectNonNullishFalsy(ts, checker, member, out, new Set(seen)) === 'any') return 'any';
64
+ }
65
+ return out;
66
+ }
67
+ if (flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess | ts.TypeFlags.Conditional | ts.TypeFlags.Substitution)) {
68
+ const constraint = checker.getBaseConstraintOfType(type);
69
+ return constraint ? collectNonNullishFalsy(ts, checker, constraint, out, seen) : 'any';
70
+ }
71
+ if (flags & (ts.TypeFlags.String | ts.TypeFlags.TemplateLiteral | ts.TypeFlags.StringMapping)) {
72
+ out.add('string');
73
+ return out;
74
+ }
75
+ if (flags & ts.TypeFlags.StringLiteral) {
76
+ if (type.value === '') out.add('string');
77
+ return out;
78
+ }
79
+ if (flags & ts.TypeFlags.Boolean) {
80
+ out.add('boolean');
81
+ return out;
82
+ }
83
+ if (flags & ts.TypeFlags.BooleanLiteral) {
84
+ if (checker.typeToString(type) === 'false') out.add('boolean');
85
+ return out;
86
+ }
87
+ if (flags & ts.TypeFlags.BigInt) {
88
+ out.add('bigint');
89
+ return out;
90
+ }
91
+ if (flags & ts.TypeFlags.BigIntLiteral) {
92
+ if (type.value?.base10Value === '0') out.add('bigint');
93
+ return out;
94
+ }
95
+ if (flags & ts.TypeFlags.Number) {
96
+ out.add('number_zero');
97
+ out.add('number_nan');
98
+ return out;
99
+ }
100
+ if (flags & ts.TypeFlags.NumberLiteral) {
101
+ // Numeric enum types accept arbitrary numbers (including 0 and NaN) without a TypeScript error.
102
+ if ((flags & (ts.TypeFlags.Enum | ts.TypeFlags.EnumLiteral)) || type.value === 0 || Object.is(type.value, -0) || Number.isNaN(type.value)) {
103
+ out.add('number_zero');
104
+ out.add('number_nan');
105
+ }
106
+ return out;
107
+ }
108
+ if (flags & (ts.TypeFlags.ESSymbol | ts.TypeFlags.UniqueESSymbol | ts.TypeFlags.NonPrimitive)) {
109
+ return out;
110
+ }
111
+ if (flags & ts.TypeFlags.Object) {
112
+ return isGuaranteedNonPrimitiveObject(ts, checker, type) ? out : 'any';
113
+ }
114
+ return 'any';
115
+ }
116
+
117
+ function hasLocalUndefinedBinding(ts, checker, node) {
118
+ if (typeof checker.resolveName === 'function') {
119
+ const sym = checker.resolveName('undefined', node, ts.SymbolFlags.Value, false);
120
+ if (sym?.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) return true;
121
+ }
122
+ if (typeof checker.getSymbolsInScope === 'function') {
123
+ const inScope = checker.getSymbolsInScope(node, ts.SymbolFlags.Value);
124
+ for (const sym of inScope) {
125
+ if (sym.name === 'undefined' && sym.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) {
126
+ return true;
127
+ }
128
+ }
129
+ }
130
+ return false;
131
+ }
132
+
133
+ function isUncheckedIndexedRead(ts, checker, node) {
134
+ while (node && ts.isParenthesizedExpression(node)) node = node.expression;
135
+ if (!node) return false;
136
+ if (ts.isElementAccessExpression(node)) return true;
137
+ if (ts.isPropertyAccessExpression(node)) {
138
+ const recvType = checker.getTypeAtLocation(node.expression);
139
+ if (recvType && checker.getIndexTypeOfType(recvType, ts.IndexKind.String) && !recvType.getProperty(node.name.text)) {
140
+ return true;
141
+ }
142
+ }
143
+ if (ts.isIdentifier(node)) {
144
+ const sym = checker.getSymbolAtLocation(node);
145
+ const decl = sym?.valueDeclaration;
146
+ if (decl && ts.isVariableDeclaration(decl) && decl.initializer && isUncheckedIndexedRead(ts, checker, decl.initializer)) {
147
+ return true;
148
+ }
149
+ }
150
+ return false;
151
+ }
152
+
153
+ function indexExpressions(ts, sourceFile) {
154
+ const nodes = new Map();
155
+ (function walk(node) {
156
+ if (!ts.isParenthesizedExpression(node)) {
157
+ const start = node.getStart(sourceFile);
158
+ const key = `${start}:${node.end}`;
159
+ if (!nodes.has(key)) nodes.set(key, node);
160
+ }
161
+ ts.forEachChild(node, walk);
162
+ })(sourceFile);
163
+ return nodes;
164
+ }
165
+
166
+ export function createTypeContext(root, targetFiles = [], { tsconfig, ts = loadTypeScript() } = {}) {
167
+ const realRoot = existsSync(root) ? realpathSync(root) : resolve(root);
168
+ const configPath = tsconfig
169
+ ? resolve(realRoot, tsconfig)
170
+ : ts.findConfigFile(realRoot, ts.sys.fileExists, 'tsconfig.json');
171
+ if (!configPath || !existsSync(configPath)) {
172
+ return { strictNullChecks: false, forFile: () => null };
173
+ }
174
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
175
+ if (read.error || !read.config) {
176
+ return { strictNullChecks: false, forFile: () => null };
177
+ }
178
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(configPath));
179
+ const compilerOptions = parsed.options ?? {};
180
+ const strictNullChecks = compilerOptions.strictNullChecks === true ||
181
+ (compilerOptions.strict === true && compilerOptions.strictNullChecks !== false);
182
+ if (!strictNullChecks) {
183
+ return { strictNullChecks: false, forFile: () => null };
184
+ }
185
+ const noUncheckedIndexedAccess = compilerOptions.noUncheckedIndexedAccess === true;
186
+
187
+ const absTargets = targetFiles.map(file => {
188
+ const resolved = resolve(realRoot, file);
189
+ return existsSync(resolved) ? realpathSync(resolved) : resolved;
190
+ });
191
+ const ambientDts = (parsed.fileNames ?? []).filter(file => file.endsWith('.d.ts'));
192
+ const rootNames = [...new Set([...absTargets, ...ambientDts])];
193
+ if (!rootNames.length) {
194
+ return { strictNullChecks: true, forFile: () => null };
195
+ }
196
+
197
+ const program = ts.createProgram(rootNames, { ...compilerOptions, noEmit: true });
198
+ const checker = program.getTypeChecker();
199
+ const fileCache = new Map();
200
+
201
+ function forFile(file) {
202
+ const resolved = resolve(realRoot, file);
203
+ const absFile = existsSync(resolved) ? realpathSync(resolved) : resolved;
204
+ if (fileCache.has(absFile)) return fileCache.get(absFile);
205
+ const sourceFile = program.getSourceFile(absFile) ?? program.getSourceFile(resolved);
206
+ if (!sourceFile) {
207
+ fileCache.set(absFile, null);
208
+ return null;
209
+ }
210
+ const nodes = indexExpressions(ts, sourceFile);
211
+ const helper = {
212
+ isNullishEqualityEquivalent(subjectStart, subjectEnd, differsFor) {
213
+ if (differsFor !== 'null' && differsFor !== 'undefined') return false;
214
+ const node = nodes.get(`${subjectStart}:${subjectEnd}`);
215
+ if (!node) return false;
216
+ // Without `noUncheckedIndexedAccess`, indexed reads (`xs[i]`, `rec.missing`, or variables initialized from them) can evaluate to `undefined` at runtime.
217
+ if (!noUncheckedIndexedAccess && differsFor === 'undefined' && isUncheckedIndexedRead(ts, checker, node)) return false;
218
+ // If `undefined` is locally shadowed in scope, `x === undefined` / `=== undefined` does not compare against the built-in value.
219
+ if (hasLocalUndefinedBinding(ts, checker, node)) return false;
220
+ const type = checker.getTypeAtLocation(node);
221
+ if (!type) return false;
222
+ return !canContainNullish(ts, checker, type, differsFor);
223
+ },
224
+ isNullishFallbackEquivalent(leftStart, leftEnd, rightFalsy) {
225
+ const node = nodes.get(`${leftStart}:${leftEnd}`);
226
+ if (!node) return false;
227
+ const type = checker.getTypeAtLocation(node);
228
+ if (!type) return false;
229
+ const falsy = collectNonNullishFalsy(ts, checker, type);
230
+ if (falsy === 'any') return false;
231
+ if (falsy.size === 0) return true;
232
+ if (falsy.size === 1) {
233
+ if (falsy.has('string') && rightFalsy === "''") return true;
234
+ if (falsy.has('boolean') && rightFalsy === 'false') return true;
235
+ if (falsy.has('bigint') && rightFalsy === '0n') return true;
236
+ }
237
+ return false;
238
+ },
239
+ };
240
+ fileCache.set(absFile, helper);
241
+ return helper;
242
+ }
243
+
244
+ return { strictNullChecks: true, forFile };
245
+ }
@@ -0,0 +1,47 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { relative } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { inside, runnerPackage } from './vitest.mjs';
6
+
7
+ const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
8
+ const { workspace, config, targets, output } = input;
9
+
10
+ const manifest = runnerPackage(workspace, 'vitest');
11
+ const vitestNode = createRequire(manifest).resolve('vitest/node');
12
+ const { createVitest } = await import(pathToFileURL(vitestNode).href);
13
+
14
+ const vitest = await createVitest('test', {
15
+ root: workspace,
16
+ ...(config === undefined ? {} : { config: inside(workspace, config) }),
17
+ watch: false,
18
+ api: false,
19
+ ui: false,
20
+ cache: false,
21
+ related: targets.map(file => inside(workspace, file)),
22
+ });
23
+
24
+ let specs;
25
+ try {
26
+ if (typeof vitest.getRelevantTestSpecifications !== 'function') {
27
+ throw new Error('Installed Vitest version does not support programmatic related test resolution; specify test files with --test <FILE>');
28
+ }
29
+ specs = await vitest.getRelevantTestSpecifications();
30
+ } finally {
31
+ await vitest.close();
32
+ }
33
+
34
+ const resolved = [];
35
+ const seen = new Set();
36
+ for (const spec of specs ?? []) {
37
+ if (!spec?.moduleId) continue;
38
+ const project = spec.project?.name ?? '';
39
+ const file = relative(workspace, inside(workspace, spec.moduleId));
40
+ const key = JSON.stringify([project, file]);
41
+ if (!seen.has(key)) {
42
+ seen.add(key);
43
+ resolved.push({ project, file });
44
+ }
45
+ }
46
+ resolved.sort((a, b) => a.file.localeCompare(b.file) || a.project.localeCompare(b.project));
47
+ writeFileSync(output, JSON.stringify({ specs: resolved }), 'utf8');
package/src/vitest.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
- import { constants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync } from 'node:fs';
2
+ import { constants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
7
 
8
8
  const reporter = fileURLToPath(new URL('./vitest-reporter.mjs', import.meta.url));
9
9
  const supervisor = fileURLToPath(new URL('./runner-process.mjs', import.meta.url));
10
+ const relatedWorker = fileURLToPath(new URL('./vitest-related-worker.mjs', import.meta.url));
10
11
  const toolDependencies = [
11
12
  { name: 'vitest', bin: 'vitest.mjs', command: 'vitest' },
12
13
  { name: '@playwright/test', bin: 'cli.js', command: 'playwright' },
@@ -208,9 +209,10 @@ export function withCopy(project, action, { exclude = [] } = {}) {
208
209
  }
209
210
 
210
211
  // How one Vitest run is started, shared by the blocking and the concurrent form.
211
- function vitestCommand(root, temp, { trace, config, testFiles = [], product = false, active, probePreload, synchronousTrace, timeout = 60_000 } = {}) {
212
+ function vitestCommand(root, temp, { trace, config, testFiles = [], testProjects = [], product = false, active, probePreload, synchronousTrace, timeout = 60_000 } = {}) {
212
213
  const vitest = resolve(dirname(runnerPackage(root, 'vitest')), 'vitest.mjs');
213
214
  const testsToRun = [...new Set(testFiles.map(file => inside(root, file)))];
215
+ const projectArgs = [...new Set(testProjects.filter(Boolean))].flatMap(name => ['--project', name]);
214
216
  const configuration = config === undefined ? [] : ['--config', inside(root, config)];
215
217
  const report = resolve(temp, 'vitest.json');
216
218
  rmSync(report, { force: true });
@@ -219,7 +221,7 @@ function vitestCommand(root, temp, { trace, config, testFiles = [], product = fa
219
221
  return { report, testsToRun, product, args: [
220
222
  supervisor, resolve(temp, 'vitest.pid'), String(timeout),
221
223
  vitest, 'run', '--maxWorkers=1', '--maxConcurrency=1', '--no-file-parallelism', '--no-cache',
222
- ...configuration, ...(product ? ['--reporter', reporter] : ['--reporter=json', '--outputFile', report]),
224
+ ...configuration, ...projectArgs, ...(product ? ['--reporter', reporter] : ['--reporter=json', '--outputFile', report]),
223
225
  ...testsToRun,
224
226
  ], options: {
225
227
  cwd: root,
@@ -274,6 +276,55 @@ function vitestOutcome(root, { report, testsToRun, product }, result) {
274
276
  return { status, tests, output: result.stderr + result.stdout };
275
277
  }
276
278
 
279
+ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000 } = {}) {
280
+ const root = realpathSync(project);
281
+ const relTargets = [...new Set(targetFiles.map(file => relative(root, inside(root, file))))];
282
+ if (!relTargets.length) return { tests: [], specs: [] };
283
+ // Validate Vitest availability up front before copying.
284
+ runnerPackage(root, 'vitest');
285
+ return withCopy(root, (workspace, temp) => {
286
+ const cache = resolve(temp, 'vite-cache');
287
+ mkdirSync(cache, { recursive: true });
288
+ const manifestPath = resolve(temp, 'related-request.json');
289
+ const outputPath = resolve(temp, 'related-output.json');
290
+ writeFileSync(manifestPath, JSON.stringify({
291
+ workspace,
292
+ config,
293
+ targets: relTargets,
294
+ output: outputPath,
295
+ }), 'utf8');
296
+ const run = spawnSync(process.execPath, [
297
+ supervisor, resolve(temp, 'related.pid'), String(timeout),
298
+ relatedWorker, manifestPath,
299
+ ], {
300
+ cwd: workspace,
301
+ env: { ...process.env, CI: 'true', VITEST: '1', NODE_ENV: 'test', VITE_CACHE_DIR: cache },
302
+ encoding: 'utf8',
303
+ timeout: timeout + 5_000,
304
+ maxBuffer: 4 * 1024 * 1024,
305
+ });
306
+ if (run.status === 124 || run.error?.code === 'ETIMEDOUT') {
307
+ throw new Error(`Vitest related test discovery timed out after ${Math.round(timeout / 1000)}s. Try increasing --timeout or specifying --test <FILE>.`);
308
+ }
309
+ if (run.status !== 0 || !existsSync(outputPath)) {
310
+ const detail = (run.stderr || run.stdout || run.error?.message || '').trim();
311
+ throw new Error(detail || 'Failed to resolve related Vitest tests');
312
+ }
313
+ const { specs = [] } = JSON.parse(readFileSync(outputPath, 'utf8'));
314
+ const tests = [...new Set(specs.map(spec => spec.file))].sort();
315
+ if (!tests.length) {
316
+ const shown = targetFiles.slice(0, 5).join(', ') + (targetFiles.length > 5 ? `, ... (${targetFiles.length} files)` : '');
317
+ throw new Error(`No Vitest test files are related to ${shown}. Specify test files explicitly with --test <FILE>.`);
318
+ }
319
+ return { tests, specs };
320
+ }, { exclude: copyExclude });
321
+ }
322
+
323
+ export async function resolveRelatedVitestTests(project, targetFiles = [], options = {}) {
324
+ const { tests } = await resolveRelatedVitestSpecs(project, targetFiles, options);
325
+ return tests;
326
+ }
327
+
277
328
  export function runVitest(root, temp, settings) {
278
329
  const command = vitestCommand(root, temp, settings);
279
330
  return vitestOutcome(root, command, spawnSync(process.execPath, command.args, command.options));