targeted-mutation 0.4.0 → 0.4.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.
package/bin/tmt.mjs CHANGED
@@ -181,54 +181,76 @@ try {
181
181
  };
182
182
  runValues.onTypeCheckWarning = onTypeCheckWarning;
183
183
  if (runValues.progress) runValues.onProgress = logProgress;
184
- if (runValues.related && !runValues.list) {
185
- const { selectScope } = await import('../src/scope.mjs');
186
- const relatedTargets = selectScope(validated.root, files, runValues).map(subject => subject.file);
187
- if (relatedTargets.length) {
188
- const { inside, resolveRelatedVitestSpecs } = await import('../src/vitest.mjs');
189
- const relatedTimeoutSeconds = runValues['baseline-timeout'] ?? runValues.timeout;
190
- const resolved = await resolveRelatedVitestSpecs(validated.root, relatedTargets, {
191
- config: runValues.config,
192
- copyExclude: runValues['copy-exclude'],
193
- onProgress: runValues.onProgress,
194
- ...(relatedTimeoutSeconds ? { timeout: relatedTimeoutSeconds * 1000 } : {}),
195
- });
196
- let selectedTests = resolved.tests;
197
- let selectedSpecs = resolved.specs;
198
- if (runValues.test?.length) {
199
- const allowedTests = new Set(runValues.test.map(file => relative(validated.root, inside(validated.root, file))));
200
- selectedTests = resolved.tests.filter(file => allowedTests.has(file));
201
- selectedSpecs = resolved.specs.filter(spec => allowedTests.has(spec.file));
202
- if (!selectedTests.length) {
203
- throw new Error(`No Vitest test files matched both --related (${resolved.tests.length} related) and --test. Widen --test <file|glob> or omit --related.`);
184
+ let relatedCopy = null;
185
+ let result;
186
+ try {
187
+ if (runValues.related && !runValues.list) {
188
+ const { selectScope } = await import('../src/scope.mjs');
189
+ const relatedTargets = selectScope(validated.root, files, runValues).map(subject => subject.file);
190
+ if (relatedTargets.length) {
191
+ const { createCopy, inside, resolveRelatedVitestSpecs, runnerPackage } = await import('../src/vitest.mjs');
192
+ const relatedTimeoutSeconds = runValues['baseline-timeout'] ?? runValues.timeout;
193
+ runnerPackage(validated.root, 'vitest');
194
+ relatedCopy = createCopy(validated.root, {
195
+ exclude: runValues['copy-exclude'],
196
+ onProgress: runValues.onProgress,
197
+ });
198
+ const resolved = await resolveRelatedVitestSpecs(validated.root, relatedTargets, {
199
+ config: runValues.config,
200
+ copyExclude: runValues['copy-exclude'],
201
+ onProgress: runValues.onProgress,
202
+ copy: relatedCopy,
203
+ ...(relatedTimeoutSeconds ? { timeout: relatedTimeoutSeconds * 1000 } : {}),
204
+ });
205
+ let selectedTests = resolved.tests;
206
+ let selectedSpecs = resolved.specs;
207
+ if (runValues.test?.length) {
208
+ const allowedTests = new Set(runValues.test.map(file => relative(validated.root, inside(validated.root, file))));
209
+ selectedTests = resolved.tests.filter(file => allowedTests.has(file));
210
+ selectedSpecs = resolved.specs.filter(spec => allowedTests.has(spec.file));
211
+ if (!selectedTests.length) {
212
+ throw new Error(`No Vitest test files matched both --related (${resolved.tests.length} related) and --test. Widen --test <file|glob> or omit --related.`);
213
+ }
214
+ }
215
+ runValues.test = selectedTests;
216
+ runValues.testSpecs = selectedSpecs;
217
+ const allNamedProjects = selectedSpecs.length > 0 && selectedSpecs.every(spec => Boolean(spec.project));
218
+ if (allNamedProjects) {
219
+ runValues.testProjects = [...new Set(selectedSpecs.map(spec => spec.project))];
220
+ }
221
+ logProgress(`Selected ${selectedTests.length} related test ${selectedTests.length === 1 ? 'file' : 'files'}.`);
222
+ if (selectedTests.length > 20) {
223
+ const tuningHint = runValues.witnesses
224
+ ? 'or tuning --timeout <seconds>'
225
+ : runValues.audit
226
+ ? 'or tuning --baseline-timeout <seconds>'
227
+ : 'or tuning --baseline-timeout <seconds> and --baseline-workers <N>';
228
+ process.stderr.write(`Warning: --related selected ${selectedTests.length} test files. Consider narrowing with --test <glob>, ${tuningHint}.\n`);
204
229
  }
205
- }
206
- runValues.test = selectedTests;
207
- runValues.testSpecs = selectedSpecs;
208
- const allNamedProjects = selectedSpecs.length > 0 && selectedSpecs.every(spec => Boolean(spec.project));
209
- if (allNamedProjects) {
210
- runValues.testProjects = [...new Set(selectedSpecs.map(spec => spec.project))];
211
- }
212
- logProgress(`Selected ${selectedTests.length} related test ${selectedTests.length === 1 ? 'file' : 'files'}.`);
213
- if (selectedTests.length > 20) {
214
- process.stderr.write(`Warning: --related selected ${selectedTests.length} test files. Consider narrowing with --test <glob>, or tuning --baseline-timeout <seconds> and --baseline-workers <N>.\n`);
215
230
  }
216
231
  }
217
- }
218
- enablePreparedTypeScript();
219
- let result;
220
- if (runValues.list) {
221
- result = listCandidates(project, files, { ...runValues, mutators: runValues.mutators ?? 'targeted', shard: runValues.shard, sharding });
222
- } else if (runValues.witnesses) {
223
- if (runValues.runner === 'playwright' || runValues.mutators !== undefined ||
224
- runValues.deterministic || runValues.project || runValues.audit || runValues['displace-thresholds']) throw new Error('--witnesses runs its own Vitest source trials');
225
- logProgress('Running witness analysis...');
226
- const { analyzeWitnesses } = await import('../src/witness-analysis.mjs');
227
- result = await analyzeWitnesses(project, files, runValues);
228
- } else {
229
- logProgress(`Analyzing ${files.length ? `${files.length} file(s)` : 'project'} (${runValues.mutators ?? 'targeted'})...`);
230
- const { analyzeOperators } = await import('../src/operator-analysis.mjs');
231
- result = await analyzeOperators(project, files, { ...runValues, mutators: runValues.mutators ?? 'targeted', shard, sharding });
232
+ enablePreparedTypeScript();
233
+ if (runValues.list) {
234
+ result = listCandidates(project, files, { ...runValues, mutators: runValues.mutators ?? 'targeted', shard: runValues.shard, sharding });
235
+ } else if (runValues.witnesses) {
236
+ if (runValues.runner === 'playwright' || runValues.mutators !== undefined ||
237
+ runValues.deterministic || runValues.project || runValues.audit || runValues['displace-thresholds']) throw new Error('--witnesses runs its own Vitest source trials');
238
+ logProgress('Running witness analysis...');
239
+ const { analyzeWitnesses } = await import('../src/witness-analysis.mjs');
240
+ result = await analyzeWitnesses(project, files, runValues);
241
+ } else {
242
+ logProgress(`Analyzing ${files.length ? `${files.length} file(s)` : 'project'} (${runValues.mutators ?? 'targeted'})...`);
243
+ const { analyzeOperators } = await import('../src/operator-analysis.mjs');
244
+ result = await analyzeOperators(project, files, {
245
+ ...runValues,
246
+ ...(relatedCopy ? { reusableCopy: relatedCopy } : {}),
247
+ mutators: runValues.mutators ?? 'targeted',
248
+ shard,
249
+ sharding,
250
+ });
251
+ }
252
+ } finally {
253
+ relatedCopy?.dispose();
232
254
  }
233
255
  if (!runValues.witnesses && !runValues.list) {
234
256
  const { strengthenAssertions, withoutSourceEdits } = await import('../src/assertion-strength.mjs');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "targeted-mutation",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
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.4.0",
47
- "@targeted-mutation/tmt-darwin-x64": "0.4.0",
48
- "@targeted-mutation/tmt-linux-arm64": "0.4.0",
49
- "@targeted-mutation/tmt-linux-x64": "0.4.0"
46
+ "@targeted-mutation/tmt-darwin-arm64": "0.4.1",
47
+ "@targeted-mutation/tmt-darwin-x64": "0.4.1",
48
+ "@targeted-mutation/tmt-linux-arm64": "0.4.1",
49
+ "@targeted-mutation/tmt-linux-x64": "0.4.1"
50
50
  }
51
51
  }
@@ -371,7 +371,11 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
371
371
  }
372
372
  } else if (isLogical(node) && !staysInPlace(node.right)) {
373
373
  const operand = grouped;
374
- const rightFalsy = falsyLiteralLabel(node.right);
374
+ const rightNode = strip(node.right);
375
+ const rawRightFalsy = falsyLiteralLabel(node.right);
376
+ const rightFalsy = rawRightFalsy === 'NaN' && typeEquivalence?.hasLocalNaNBinding?.(begin(rightNode), rightNode.end)
377
+ ? undefined
378
+ : rawRightFalsy;
375
379
  const more = { thunk: true, ...(written(node.right) ? { pureRight: true } : {}) };
376
380
  edit(targetedRules.ignored, 'left', `(${left}, ${right})`, more);
377
381
  edit(targetedRules.ignored, 'right', `(${left} ${operator} (${right}, ${ignoredValue[operator]}))`, more);
@@ -379,7 +383,8 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
379
383
  if (boolean && writtenFalsy(node.right)) return;
380
384
  const leftNode = strip(node.left);
381
385
  if (typeEquivalence?.isNullishFallbackEquivalent(begin(leftNode), leftNode.end, rightFalsy)) return;
382
- const fallbackMore = { ...more, ...(rightFalsy ? { rightFalsy } : {}), evidence: true };
386
+ const possibleFalsy = typeEquivalence?.possibleNullishFallbackFalsy?.(begin(leftNode), leftNode.end) ?? null;
387
+ const fallbackMore = { ...more, ...(rightFalsy ? { rightFalsy } : {}), ...(possibleFalsy?.length ? { possibleFalsy } : {}), evidence: true };
383
388
  if (operator === '??') edit(targetedRules.fallback, 'or', `(${operand(node.left)} || ${operand(node.right)})`, fallbackMore);
384
389
  // Where only the truth of the value is used, nobody writes `??` for `||`.
385
390
  else if (operator === '||' && !boolean) edit(targetedRules.fallback, 'nullish', `(${operand(node.left)} ?? ${operand(node.right)})`, fallbackMore);
@@ -136,6 +136,7 @@ export async function analyzeConventional(project, files, options) {
136
136
  runTimeout: runTimeoutMs,
137
137
  baselineTimeout: baselineTimeoutMs,
138
138
  ...(options['baseline-workers'] !== undefined ? { baselineWorkers: options['baseline-workers'] } : {}),
139
+ ...(options.progressIntervalMs !== undefined ? { progressIntervalMs: options.progressIntervalMs } : {}),
139
140
  config: options.config === undefined ? undefined : inside(workspace, options.config),
140
141
  files: [...new Set((options.test ?? []).map(file => inside(workspace, file)))],
141
142
  ...(options.testSpecs?.length ? { selectedSpecs: options.testSpecs.map(({ project, file }) => ({ project, file: inside(workspace, file) })) } : {}),
@@ -167,27 +168,53 @@ export async function analyzeConventional(project, files, options) {
167
168
  }
168
169
  let progressTimer = null;
169
170
  if (options.onProgress) {
171
+ const progressIntervalMs = options.progressIntervalMs ?? 5_000;
172
+ const pollIntervalMs = Math.min(1_000, Math.max(50, Math.floor(progressIntervalMs / 2)));
173
+ const baselineStartedAt = Date.now();
174
+ let baselineDoneAt = baselineStartedAt;
175
+ let lastReportAt = baselineStartedAt;
170
176
  options.onProgress('Running baseline tests...');
171
177
  let baselineReported = false;
172
178
  let lastDone = -1;
173
179
  const pollProgress = () => {
180
+ const now = Date.now();
174
181
  const current = readEvents(output);
175
182
  if (!baselineReported) {
176
183
  const base = current.find(event => event.baseline)?.baseline;
177
184
  if (base?.status === 'passed') {
178
185
  baselineReported = true;
186
+ baselineDoneAt = now;
187
+ lastReportAt = now;
179
188
  options.onProgress(`Baseline passed (${base.tests} tests). Running ${totalRunnable} mutant(s)...`);
189
+ } else if (now - lastReportAt >= progressIntervalMs) {
190
+ lastReportAt = now;
191
+ const elapsed = Math.max(1, Math.round((now - baselineStartedAt) / 1000));
192
+ options.onProgress(`Running baseline tests... (${elapsed}s elapsed)`);
180
193
  }
181
194
  }
182
195
  if (baselineReported && totalRunnable > 0) {
183
- const done = current.filter(event => event.id !== undefined).length;
184
- if (done !== lastDone && done > 0) {
196
+ const sessionComplete = current.some(event => event.complete === true);
197
+ const recordedDone = current.filter(event => event.id !== undefined).length;
198
+ let latestProgress = 0;
199
+ for (const event of current) {
200
+ if (typeof event.progress?.completed === 'number' && event.progress.completed > latestProgress) {
201
+ latestProgress = event.progress.completed;
202
+ }
203
+ }
204
+ const provisionalCap = Math.max(0, totalRunnable - 1);
205
+ const done = Math.min(totalRunnable, Math.max(recordedDone, Math.min(latestProgress, provisionalCap)));
206
+ if (done > lastDone && done > 0) {
185
207
  lastDone = done;
186
- options.onProgress(`Mutants: ${Math.min(done, totalRunnable)}/${totalRunnable} completed`);
208
+ lastReportAt = now;
209
+ options.onProgress(`Mutants: ${done}/${totalRunnable} completed`);
210
+ } else if (!sessionComplete && now - lastReportAt >= progressIntervalMs) {
211
+ lastReportAt = now;
212
+ const elapsed = Math.max(1, Math.round((now - baselineDoneAt) / 1000));
213
+ options.onProgress(`Mutants: ${Math.max(0, done)}/${totalRunnable} completed (${elapsed}s elapsed)`);
187
214
  }
188
215
  }
189
216
  };
190
- progressTimer = setInterval(pollProgress, 1_000);
217
+ progressTimer = setInterval(pollProgress, pollIntervalMs);
191
218
  progressTimer.unref?.();
192
219
  }
193
220
  let run;
@@ -256,5 +283,5 @@ export async function analyzeConventional(project, files, options) {
256
283
  mutants: judged.map(({ targeted: _rule, effects: _effects, _cachedDiagnostic: _cd, ...mutant }) => mutant),
257
284
  diagnostics,
258
285
  };
259
- }, { exclude: options['copy-exclude'], onProgress: options.onProgress });
286
+ }, { exclude: options['copy-exclude'], onProgress: options.onProgress, reuseCopy: options.reusableCopy });
260
287
  }
@@ -83,6 +83,8 @@ async function besideSession(project, files, options, run, profile, stopsSession
83
83
  ...(options['baseline-timeout'] !== undefined ? { 'baseline-timeout': options['baseline-timeout'] } : {}),
84
84
  ...(options['baseline-workers'] !== undefined ? { 'baseline-workers': options['baseline-workers'] } : {}),
85
85
  ...(options.testSpecs?.length ? { testSpecs: options.testSpecs } : {}),
86
+ ...(options.reusableCopy ? { reusableCopy: options.reusableCopy } : {}),
87
+ ...(options.progressIntervalMs !== undefined ? { progressIntervalMs: options.progressIntervalMs } : {}),
86
88
  }).then(report => ({ report }), error => ({ error }));
87
89
  let prepared;
88
90
  try {
@@ -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, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000, baselineTimeout = runTimeout, baselineWorkers } = input;
12
+ const { workspace, config, files, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000, baselineTimeout = runTimeout, baselineWorkers, progressIntervalMs } = input;
13
13
  const destination = resolve(temporary, 'coverage.jsonl');
14
14
  const record = event => appendFileSync(output, JSON.stringify(event) + '\n');
15
15
  const lanes = [];
@@ -68,7 +68,7 @@ async function openLane(index, serial = false, workerOverride = undefined) {
68
68
 
69
69
  // Runs a lane's share of the planned mutations inside its worker, one Vitest run per round. A worker that stops
70
70
  // answering is replaced, its mutation is a timeout, and the rest continue in the next round.
71
- async function runInThread(lane, plans, limit, deadline) {
71
+ async function runInThread(lane, plans, limit, deadline, onEvent, onTick) {
72
72
  const events = [];
73
73
  let remaining = plans;
74
74
  while (Object.keys(remaining).length) {
@@ -87,10 +87,12 @@ async function runInThread(lane, plans, limit, deadline) {
87
87
  const ended = finished;
88
88
  for (const event of read()) {
89
89
  round.push(event);
90
+ onEvent?.(event);
90
91
  if (event.start !== undefined) started.set(event.module, { id: event.start, at: Date.now() });
91
92
  else if (event.control !== undefined) started.set(event.module, { id: event.control, at: Date.now(), control: true });
92
93
  else started.delete(event.module);
93
94
  }
95
+ onTick?.();
94
96
  if (ended) break;
95
97
  stuck = [...started].find(([, { at }]) => Date.now() - at > limit);
96
98
  if (!stuck) await Promise.race([running, new Promise(resolvePoll => setTimeout(resolvePoll, 50))]);
@@ -240,11 +242,13 @@ try {
240
242
  unknown: seen.unknown, ...(seen.realCopy ? { realCopy: true } : {}), ...(seen.nonArray ? { nonArray: true } : {}), ...(seen.nonPlain ? { nonPlain: true } : {}) }])) });
241
243
  }
242
244
  const pending = [];
245
+ let settledBeforeDecide = 0;
243
246
  for (const mutant of mutants.filter(candidate => !candidate.parametric)) {
244
247
  const { id } = mutant;
245
248
  const plan = baselineCoverage(id);
246
249
  if (!plan.hits) {
247
250
  record({ id, status: 'unreached' });
251
+ settledBeforeDecide++;
248
252
  continue;
249
253
  }
250
254
  // `??` and `||` give the same for null, undefined and every object. Where no test gave the left side a value
@@ -252,12 +256,14 @@ try {
252
256
  const seen = agreement.get(id);
253
257
  if (mutant.evidence && seen && !seen.differing.size && !seen.unsure.size && !seen.outside && !seen.outsideUnsure && !seen.typed) {
254
258
  record({ id, status: 'ignored', statusReason: 'No test gives the left side a number, a string or a boolean, so both operators are taken to behave alike here' });
259
+ settledBeforeDecide++;
255
260
  continue;
256
261
  }
257
262
  // `expr[0]` on a plain map or `arguments` object is not a sequence: mutating to `.at(-1)` would only raise
258
263
  // a TypeError noise kill. Never skip if any baseline evaluation threw (exception behavior is unverified).
259
264
  if (mutant.sequenceIndex && seen && !seen.sequence && seen.nonSequence && !seen.threw && !seen.differing.size && !seen.outside) {
260
265
  record({ id, status: 'ignored', statusReason: 'No test passes a sequence (array, string, or typed array) to this index expression' });
266
+ settledBeforeDecide++;
261
267
  continue;
262
268
  }
263
269
  pending.push({ mutant, plan });
@@ -271,7 +277,7 @@ try {
271
277
  const { now, gone } = changedReach(reach, runs);
272
278
  return { now: named(now), gone: named(gone) };
273
279
  };
274
- const decide = async (pending, report) => {
280
+ const decide = async (pending, report, trackProgress = false) => {
275
281
  const plans = isolatedTrials ? null : planInThread(baseline.records, tests, pending, workspace, baselineTiming);
276
282
  let settled = new Map();
277
283
  let reasons = new Map();
@@ -281,11 +287,55 @@ try {
281
287
  const sampled = new Set();
282
288
  if (plans) {
283
289
  const limit = 15_000 + 3 * baselineTime;
290
+ let onTrialEvent = null;
291
+ let onProgressTick = null;
292
+ if (trackProgress) {
293
+ const remainingFiles = new Map();
294
+ for (const list of Object.values(plans)) {
295
+ for (const plan of list) {
296
+ remainingFiles.set(plan.id, (remainingFiles.get(plan.id) ?? 0) + 1);
297
+ }
298
+ }
299
+ const completedInWorker = new Set();
300
+ const seenModuleAnswer = new Set();
301
+ const maxProvisional = Math.max(0, pending.length - 1);
302
+ const emitIntervalMs = Math.min(2_000, Math.max(50, Math.floor((progressIntervalMs ?? 5_000) / 2)));
303
+ let lastEmitted = 0;
304
+ let lastEmitAt = Date.now();
305
+ const flushProgress = () => {
306
+ const reportedCount = Math.min(completedInWorker.size, maxProvisional);
307
+ const now = Date.now();
308
+ if (reportedCount > lastEmitted && now - lastEmitAt >= emitIntervalMs) {
309
+ lastEmitted = reportedCount;
310
+ lastEmitAt = now;
311
+ record({ progress: { completed: settledBeforeDecide + reportedCount } });
312
+ }
313
+ };
314
+ onProgressTick = flushProgress;
315
+ onTrialEvent = event => {
316
+ if (event.id === undefined || !remainingFiles.has(event.id)) return;
317
+ const cleanAnswer = event.elapsed !== undefined && event.hits > 0 && !event.unhandled &&
318
+ !(event.errors?.length) && !event.foreign && !event.missing;
319
+ const isKilled = cleanAnswer && Array.isArray(event.failed) && event.failed.length > 0;
320
+ if (isKilled) {
321
+ completedInWorker.add(event.id);
322
+ } else if (cleanAnswer) {
323
+ const key = JSON.stringify([event.module, event.id]);
324
+ if (!seenModuleAnswer.has(key)) {
325
+ seenModuleAnswer.add(key);
326
+ const left = remainingFiles.get(event.id) - 1;
327
+ remainingFiles.set(event.id, left);
328
+ if (left <= 0) completedInWorker.add(event.id);
329
+ }
330
+ }
331
+ flushProgress();
332
+ };
333
+ }
284
334
  // The first lane starts alone with a deadline. Most plans end within it. What is left is timed by then, and a
285
335
  // further lane, which costs a Vitest instance, its transforms and an environment per test file, opens for
286
336
  // every six seconds of measured work in the longest test file.
287
337
  const inLanes = async step => {
288
- const events = await runInThread(lanes[0], step, limit, Date.now() + 2_000);
338
+ const events = await runInThread(lanes[0], step, limit, Date.now() + 2_000, onTrialEvent, onProgressTick);
289
339
  // Each further round takes what is left: entries the deadline cut off, and test files that start again
290
340
  // in a new worker after a control run differed.
291
341
  for (let round = 0; round < 12; round++) {
@@ -304,7 +354,7 @@ try {
304
354
  (_, index) => openLane(lanes.length + index).catch(() => null)));
305
355
  lanes.push(...opened.filter(Boolean));
306
356
  const shares = sharePlans(left, Math.min(wanted, lanes.length));
307
- const answered = (await Promise.all(shares.map((share, index) => runInThread(lanes[index], share, limit)))).flat();
357
+ const answered = (await Promise.all(shares.map((share, index) => runInThread(lanes[index], share, limit, undefined, onTrialEvent, onProgressTick)))).flat();
308
358
  if (!answered.some(event => event.id !== undefined || event.stop !== undefined)) break;
309
359
  events.push(...answered);
310
360
  }
@@ -353,7 +403,7 @@ try {
353
403
  totals.sampled += sampled.size;
354
404
  totals.inWorkerUsed ||= plans !== null;
355
405
  };
356
- await decide(pending, (mutant, result) => record({ id: mutant.id, ...result }));
406
+ await decide(pending, (mutant, result) => record({ id: mutant.id, ...result }), true);
357
407
  if (awaitsExtras) {
358
408
  // Threshold edits of the focused analysis: each names a comparison and how far its right side moves.
359
409
  const extras = [];
@@ -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, rightFalsy, key, boundKind, pruned, argName }, expression, rule, replacement) {
28
+ function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, rightFalsy, possibleFalsy, 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) {
@@ -49,12 +49,21 @@ function missingInput({ operator, form, boolean, left, right: rightExpr, differs
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
51
  if (form === 'or' || form === 'nullish') {
52
+ const allFalsy = ['0', '0n', "''", 'false', 'NaN'];
53
+ const baseValues = Array.isArray(possibleFalsy) && possibleFalsy.length ? possibleFalsy : allFalsy;
54
+ const formatList = values => values.length === 1
55
+ ? values[0]
56
+ : `${values.slice(0, -1).join(', ')} or ${values.at(-1)}`;
52
57
  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}`;
58
+ const filtered = baseValues.filter(value => value !== rightFalsy);
59
+ const values = filtered.length
60
+ ? filtered
61
+ : baseValues.length === 1 && baseValues[0] === '0' && rightFalsy === '0'
62
+ ? ['-0']
63
+ : allFalsy.filter(value => value !== rightFalsy);
64
+ return `a test in which ${side} is ${formatList(values)}`;
56
65
  }
57
- return `a test in which ${side} is 0, 0n, '', false or NaN${pureRight ? ' and not the right side\'s value' : ''}`;
66
+ return `a test in which ${side} is ${formatList(baseValues)}${pureRight ? ' and not the right side\'s value' : ''}`;
58
67
  }
59
68
  const takesRight = { '&&': 'truthy', '||': 'falsy', '??': 'null or undefined' }[operator];
60
69
  if (form === 'left') return `a test in which ${side} is ${{ '&&': 'falsy', '||': 'truthy', '??': 'neither null nor undefined' }[operator]}`;
@@ -99,9 +99,13 @@ function collectNonNullishFalsy(ts, checker, type, out = new Set(), seen = new S
99
99
  }
100
100
  if (flags & ts.TypeFlags.NumberLiteral) {
101
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)) {
102
+ if (flags & (ts.TypeFlags.Enum | ts.TypeFlags.EnumLiteral)) {
103
103
  out.add('number_zero');
104
104
  out.add('number_nan');
105
+ } else if (type.value === 0 || Object.is(type.value, -0)) {
106
+ out.add('number_zero');
107
+ } else if (Number.isNaN(type.value)) {
108
+ out.add('number_nan');
105
109
  }
106
110
  return out;
107
111
  }
@@ -114,15 +118,26 @@ function collectNonNullishFalsy(ts, checker, type, out = new Set(), seen = new S
114
118
  return 'any';
115
119
  }
116
120
 
117
- function hasLocalUndefinedBinding(ts, checker, node) {
121
+ function falsyLabelsFromSet(falsy) {
122
+ if (falsy === 'any') return null;
123
+ const labels = [];
124
+ if (falsy.has('number_zero')) labels.push('0');
125
+ if (falsy.has('bigint')) labels.push('0n');
126
+ if (falsy.has('string')) labels.push("''");
127
+ if (falsy.has('boolean')) labels.push('false');
128
+ if (falsy.has('number_nan')) labels.push('NaN');
129
+ return labels;
130
+ }
131
+
132
+ function hasLocalValueBinding(ts, checker, node, name) {
118
133
  if (typeof checker.resolveName === 'function') {
119
- const sym = checker.resolveName('undefined', node, ts.SymbolFlags.Value, false);
134
+ const sym = checker.resolveName(name, node, ts.SymbolFlags.Value, false);
120
135
  if (sym?.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) return true;
121
136
  }
122
137
  if (typeof checker.getSymbolsInScope === 'function') {
123
138
  const inScope = checker.getSymbolsInScope(node, ts.SymbolFlags.Value);
124
139
  for (const sym of inScope) {
125
- if (sym.name === 'undefined' && sym.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) {
140
+ if (sym.name === name && sym.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) {
126
141
  return true;
127
142
  }
128
143
  }
@@ -130,6 +145,10 @@ function hasLocalUndefinedBinding(ts, checker, node) {
130
145
  return false;
131
146
  }
132
147
 
148
+ function hasLocalUndefinedBinding(ts, checker, node) {
149
+ return hasLocalValueBinding(ts, checker, node, 'undefined');
150
+ }
151
+
133
152
  function isUncheckedIndexedRead(ts, checker, node) {
134
153
  while (node && ts.isParenthesizedExpression(node)) node = node.expression;
135
154
  if (!node) return false;
@@ -316,6 +335,17 @@ function buildGroupContext(ts, info, absTargets) {
316
335
  }
317
336
  return false;
318
337
  },
338
+ possibleNullishFallbackFalsy(leftStart, leftEnd) {
339
+ const node = nodes.get(`${leftStart}:${leftEnd}`);
340
+ if (!node) return null;
341
+ const type = checker.getTypeAtLocation(node);
342
+ if (!type) return null;
343
+ return falsyLabelsFromSet(collectNonNullishFalsy(ts, checker, type));
344
+ },
345
+ hasLocalNaNBinding(nodeStart, nodeEnd) {
346
+ const node = nodes.get(`${nodeStart}:${nodeEnd}`);
347
+ return node ? hasLocalValueBinding(ts, checker, node, 'NaN') : false;
348
+ },
319
349
  };
320
350
  fileCache.set(absFile, helper);
321
351
  return helper;
package/src/vitest.mjs CHANGED
@@ -264,7 +264,39 @@ function formatBytes(bytes) {
264
264
  export const DEFAULT_LARGE_COPY_BYTES = 500 * 1024 * 1024;
265
265
  export const DEFAULT_LARGE_COPY_FILES = 10_000;
266
266
 
267
- export function withCopy(project, action, {
267
+ function snapshotWorkspaceTree(root) {
268
+ const entries = new Map();
269
+ const walk = (dir, insideNodeModules = false) => {
270
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
271
+ const full = resolve(dir, entry.name);
272
+ const rel = relative(root, full);
273
+ const st = lstatSync(full, { bigint: true });
274
+ const kind = st.isSymbolicLink() ? 'l' : st.isDirectory() ? 'd' : 'f';
275
+ entries.set(rel, kind === 'd' ? `d:${st.mode}` : `${kind}:${st.mode}:${st.size}:${st.mtimeNs}`);
276
+ if (kind === 'd') {
277
+ if (entry.name === 'node_modules') {
278
+ // Only inspect real (copied/synthesized) node_modules entries without following symlinks into shared installs.
279
+ walk(full, true);
280
+ } else if (!insideNodeModules || entry.name.startsWith('@') || entry.name === '.bin') {
281
+ walk(full, insideNodeModules);
282
+ }
283
+ }
284
+ }
285
+ };
286
+ walk(root);
287
+ return entries;
288
+ }
289
+
290
+ function workspaceTreeChanged(before, root) {
291
+ const after = snapshotWorkspaceTree(root);
292
+ if (after.size !== before.size) return true;
293
+ for (const [rel, sig] of before) {
294
+ if (after.get(rel) !== sig) return true;
295
+ }
296
+ return false;
297
+ }
298
+
299
+ export function createCopy(project, {
268
300
  exclude = [],
269
301
  onProgress,
270
302
  onLargeCopy,
@@ -276,13 +308,28 @@ export function withCopy(project, action, {
276
308
  const temp = realpathSync(mkdtempSync(resolve(tmpdir(), 'tmt-')));
277
309
  registerActiveCopy(temp);
278
310
  let removed = false;
279
- const remove = () => {
311
+ let claimed = false;
312
+ let busy = false;
313
+ const dispose = () => {
280
314
  if (removed) return;
281
315
  removed = true;
316
+ busy = false;
282
317
  unregisterActiveCopy(temp);
283
318
  rmSync(temp, { recursive: true, force: true });
284
319
  };
285
- let pending = false;
320
+ const claim = () => {
321
+ if (claimed || removed || busy) return false;
322
+ claimed = true;
323
+ return true;
324
+ };
325
+ const beginUse = () => {
326
+ if (claimed || removed || busy) return false;
327
+ busy = true;
328
+ return true;
329
+ };
330
+ const endUse = () => {
331
+ busy = false;
332
+ };
286
333
  try {
287
334
  const root = resolve(temp, 'project');
288
335
  const moduleTrees = [];
@@ -336,12 +383,32 @@ export function withCopy(project, action, {
336
383
  linkInstalledModules(source, root, modules, resolve(root, relative(source, modules)), modules === projectModules ? tools : []);
337
384
  }
338
385
  if (!hasLocalModules) linkModules(resolve(root, 'node_modules'), tools);
339
- const result = action(root, temp);
386
+ return { root, temp, dispose, claim, beginUse, endUse };
387
+ } catch (error) {
388
+ dispose();
389
+ throw error;
390
+ }
391
+ }
392
+
393
+ export function withCopy(project, action, {
394
+ reuseCopy,
395
+ exclude = [],
396
+ onProgress,
397
+ onLargeCopy,
398
+ largeCopyBytes = DEFAULT_LARGE_COPY_BYTES,
399
+ largeCopyFiles = DEFAULT_LARGE_COPY_FILES,
400
+ } = {}) {
401
+ const copy = reuseCopy?.claim?.()
402
+ ? reuseCopy
403
+ : createCopy(project, { exclude, onProgress, onLargeCopy, largeCopyBytes, largeCopyFiles });
404
+ let pending = false;
405
+ try {
406
+ const result = action(copy.root, copy.temp);
340
407
  // An action that is still running keeps its copy until it settles.
341
408
  pending = typeof result?.then === 'function';
342
- return pending ? result.finally(remove) : result;
409
+ return pending ? result.finally(copy.dispose) : result;
343
410
  } finally {
344
- if (!pending) remove();
411
+ if (!pending) copy.dispose();
345
412
  }
346
413
  }
347
414
 
@@ -416,18 +483,19 @@ function vitestOutcome(root, { report, testsToRun, product }, result) {
416
483
  return { status, tests, output: result.stderr + result.stdout };
417
484
  }
418
485
 
419
- export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000, onProgress, onLargeCopy } = {}) {
486
+ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000, onProgress, onLargeCopy, copy } = {}) {
420
487
  const root = realpathSync(project);
421
488
  const relTargets = [...new Set(targetFiles.map(file => relative(root, inside(root, file))))];
422
489
  if (!relTargets.length) return { tests: [], specs: [] };
423
490
  // Validate Vitest availability up front before copying.
424
491
  runnerPackage(root, 'vitest');
425
- return withCopy(root, async (workspace, temp) => {
492
+ const resolveInWorkspace = async (workspace, temp) => {
426
493
  onProgress?.('Resolving related Vitest test files...');
427
494
  const cache = resolve(temp, 'vite-cache');
428
495
  mkdirSync(cache, { recursive: true });
429
496
  const manifestPath = resolve(temp, 'related-request.json');
430
497
  const outputPath = resolve(temp, 'related-output.json');
498
+ const pidPath = resolve(temp, 'related.pid');
431
499
  writeFileSync(manifestPath, JSON.stringify({
432
500
  workspace,
433
501
  config,
@@ -435,36 +503,42 @@ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { con
435
503
  output: outputPath,
436
504
  }), 'utf8');
437
505
  const maxBuffer = 4 * 1024 * 1024;
438
- const run = await new Promise(settle => {
439
- const child = spawn(process.execPath, [
440
- supervisor, resolve(temp, 'related.pid'), String(timeout),
441
- relatedWorker, manifestPath,
442
- ], {
443
- cwd: workspace,
444
- env: { ...process.env, CI: 'true', VITEST: '1', NODE_ENV: 'test', VITE_CACHE_DIR: cache },
445
- stdio: ['ignore', 'pipe', 'pipe'],
446
- });
447
- const out = { stdout: '', stderr: '' };
448
- for (const stream of ['stdout', 'stderr']) {
449
- child[stream].setEncoding('utf8');
450
- child[stream].on('data', chunk => { if (out[stream].length < maxBuffer) out[stream] += chunk; });
451
- }
452
- const killTimer = setTimeout(() => {
453
- try { child.kill('SIGKILL'); } catch { /* ignore */ }
454
- }, timeout + 5_000);
455
- killTimer.unref?.();
456
- let failure;
457
- child.once('error', error => { failure = error; });
458
- child.once('close', (status, signal) => {
459
- clearTimeout(killTimer);
460
- settle({
461
- status,
462
- signal,
463
- ...out,
464
- error: failure ?? (signal && status === null ? Object.assign(new Error('Vitest related discovery did not finish in time'), { code: 'ETIMEDOUT' }) : undefined),
506
+ let run;
507
+ try {
508
+ run = await new Promise(settle => {
509
+ const child = spawn(process.execPath, [
510
+ supervisor, pidPath, String(timeout),
511
+ relatedWorker, manifestPath,
512
+ ], {
513
+ cwd: workspace,
514
+ env: { ...process.env, CI: 'true', VITEST: '1', NODE_ENV: 'test', VITE_CACHE_DIR: cache },
515
+ stdio: ['ignore', 'pipe', 'pipe'],
516
+ });
517
+ const out = { stdout: '', stderr: '' };
518
+ for (const stream of ['stdout', 'stderr']) {
519
+ child[stream].setEncoding('utf8');
520
+ child[stream].on('data', chunk => { if (out[stream].length < maxBuffer) out[stream] += chunk; });
521
+ }
522
+ const killTimer = setTimeout(() => {
523
+ try { child.kill('SIGKILL'); } catch { /* ignore */ }
524
+ }, timeout + 5_000);
525
+ killTimer.unref?.();
526
+ let failure;
527
+ child.once('error', error => { failure = error; });
528
+ child.once('close', (status, signal) => {
529
+ clearTimeout(killTimer);
530
+ settle({
531
+ status,
532
+ signal,
533
+ ...out,
534
+ error: failure ?? (signal && status === null ? Object.assign(new Error('Vitest related discovery did not finish in time'), { code: 'ETIMEDOUT' }) : undefined),
535
+ });
465
536
  });
466
537
  });
467
- });
538
+ } finally {
539
+ // Remove the finished worker PID file so a reused copy's signal handler never targets a recycled PID.
540
+ rmSync(pidPath, { force: true });
541
+ }
468
542
  if (run.status === 124 || run.error?.code === 'ETIMEDOUT') {
469
543
  throw new Error(`Vitest related test discovery timed out after ${Math.round(timeout / 1000)}s. Try increasing --timeout or specifying --test <FILE>.`);
470
544
  }
@@ -479,7 +553,21 @@ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { con
479
553
  throw new Error(`No Vitest test files are related to ${shown}. Specify test files explicitly with --test <FILE>.`);
480
554
  }
481
555
  return { tests, specs };
482
- }, { exclude: copyExclude, onProgress, onLargeCopy });
556
+ };
557
+ if (copy?.beginUse?.()) {
558
+ try {
559
+ const before = snapshotWorkspaceTree(copy.root);
560
+ const result = await resolveInWorkspace(copy.root, copy.temp);
561
+ if (workspaceTreeChanged(before, copy.root)) {
562
+ // Vitest config or plugins modified the workspace during discovery; discard so analysis gets a clean copy.
563
+ copy.dispose();
564
+ }
565
+ return result;
566
+ } finally {
567
+ copy.endUse();
568
+ }
569
+ }
570
+ return withCopy(root, resolveInWorkspace, { exclude: copyExclude, onProgress, onLargeCopy });
483
571
  }
484
572
 
485
573
  export async function resolveRelatedVitestTests(project, targetFiles = [], options = {}) {