@hughescr/stryker-bun-runner 1.6.0 → 1.6.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/dist/index.js CHANGED
@@ -2,10 +2,10 @@
2
2
  import { PluginKind, declareClassPlugin } from "@stryker-mutator/api/plugin";
3
3
 
4
4
  // src/bun-test-runner.ts
5
- import { randomBytes as randomBytes2 } from "node:crypto";
6
- import * as fsPromises2 from "node:fs/promises";
5
+ import { randomBytes as randomBytes4 } from "node:crypto";
6
+ import * as fsPromises3 from "node:fs/promises";
7
7
  import { tmpdir as tmpdir2 } from "node:os";
8
- import path9 from "node:path";
8
+ import path15 from "node:path";
9
9
  import { tokens, commonTokens } from "@stryker-mutator/api/plugin";
10
10
  import {
11
11
  DryRunStatus,
@@ -15,11 +15,15 @@ import {
15
15
  toMutantRunResult
16
16
  } from "@stryker-mutator/api/test-runner";
17
17
 
18
- // src/coverage/preload-generator.ts
19
- import { unlink, readFile } from "node:fs/promises";
18
+ // src/coverage/dry-run-files.ts
19
+ import { createHash as createHash2, randomBytes } from "node:crypto";
20
+ import * as fsPromises from "node:fs/promises";
20
21
  import path2 from "node:path";
21
- import { fileURLToPath } from "node:url";
22
- import { glob } from "tinyglobby";
22
+
23
+ // src/utils/is-plain-record.ts
24
+ function isPlainRecord(value) {
25
+ return typeof value === "object" && value !== null && !Array.isArray(value);
26
+ }
23
27
 
24
28
  // src/utils/private-temp-dir.ts
25
29
  import { createHash } from "node:crypto";
@@ -34,9 +38,9 @@ class UnsafeTempDirError extends Error {
34
38
  this.name = "UnsafeTempDirError";
35
39
  }
36
40
  }
37
- function readLinuxPidSpaceIds() {
38
- const bootId = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
39
- return `${bootId}:${readlinkSync("/proc/self/ns/pid")}`;
41
+ function readLinuxPidSpaceIds(readFile = readFileSync, readLink = readlinkSync) {
42
+ const bootId = readFile("/proc/sys/kernel/random/boot_id", "utf8").trim();
43
+ return `${bootId}:${readLink("/proc/self/ns/pid")}`;
40
44
  }
41
45
  function computePidSpace(platform = process.platform, readIds = readLinuxPidSpaceIds) {
42
46
  if (platform !== "linux") {
@@ -269,6 +273,1003 @@ function removeRunTempDirsOnExit(proc = process) {
269
273
  });
270
274
  }
271
275
 
276
+ // src/coverage/dry-run-files.ts
277
+ function watchListFileFor(generation) {
278
+ return `watch-list-${generation}.json`;
279
+ }
280
+ var ABORT_MARKER_FILE = "abort-marker.json";
281
+ function newGeneration() {
282
+ return randomBytes(16).toString("hex");
283
+ }
284
+ function newLaunchFile(dir, prefix) {
285
+ return path2.join(dir, `${prefix}-${process.pid}-${randomBytes(8).toString("hex")}.json`);
286
+ }
287
+ function newRecordFile(dir) {
288
+ return newLaunchFile(dir, "dry-run-record");
289
+ }
290
+ async function readRecordFile(file) {
291
+ try {
292
+ return { text: await fsPromises.readFile(file, "utf8") };
293
+ } catch (error) {
294
+ const code = error.code;
295
+ return { problem: code === "ENOENT" ? "was not written" : `cannot be read (${error.message})` };
296
+ }
297
+ }
298
+ async function removeQuietly(file) {
299
+ await fsPromises.rm(file, { force: true }).catch(() => {
300
+ return;
301
+ });
302
+ }
303
+ async function campaignFingerprint(files) {
304
+ const stats = await Promise.all(files.map(async (file) => {
305
+ try {
306
+ const stat2 = await fsPromises.stat(file, { bigint: true });
307
+ return `${file}\x00${stat2.dev}\x00${stat2.ino}\x00${stat2.size}\x00${stat2.mtimeNs}`;
308
+ } catch {
309
+ return `${file}\x00missing`;
310
+ }
311
+ }));
312
+ return createHash2("sha256").update(stats.join(`
313
+ `)).digest("hex");
314
+ }
315
+ async function writeAbortMarker(dir, marker) {
316
+ const file = path2.join(dir, ABORT_MARKER_FILE);
317
+ const temporary = `${file}.${process.pid}.tmp`;
318
+ await writePrivateFile(temporary, JSON.stringify(marker));
319
+ try {
320
+ await fsPromises.rename(temporary, file);
321
+ } catch (error) {
322
+ await removeQuietly(temporary);
323
+ throw error;
324
+ }
325
+ }
326
+ async function readAbortMarker(dir) {
327
+ let value;
328
+ try {
329
+ value = JSON.parse(await fsPromises.readFile(path2.join(dir, ABORT_MARKER_FILE), "utf8"));
330
+ } catch {}
331
+ if (!isPlainRecord(value)) {
332
+ return;
333
+ }
334
+ const { generation, message } = value;
335
+ return typeof generation === "string" && generation !== "" && typeof message === "string" && message !== "" ? { generation, message } : undefined;
336
+ }
337
+ function parseCampaignState(value) {
338
+ if (typeof value !== "object" || value === null) {
339
+ return;
340
+ }
341
+ const { generation, watchList, watchListFile, fingerprint } = value;
342
+ const isList = Array.isArray(watchList) && watchList.every((file) => typeof file === "string" && file !== "");
343
+ if (typeof generation !== "string" || generation === "" || !isList || fingerprint !== null && typeof fingerprint !== "string") {
344
+ return;
345
+ }
346
+ const expectedFile = watchList.length === 0 ? null : watchListFileFor(generation);
347
+ if (watchListFile !== expectedFile) {
348
+ return;
349
+ }
350
+ return { generation, watchList, watchListFile: expectedFile, fingerprint };
351
+ }
352
+ async function readRegistryCampaign(registryFile) {
353
+ try {
354
+ return parseCampaignState(JSON.parse(await fsPromises.readFile(registryFile, "utf8")).campaign);
355
+ } catch {
356
+ return;
357
+ }
358
+ }
359
+
360
+ // src/coverage/dry-run-messages.ts
361
+ import path3 from "node:path";
362
+
363
+ // src/utils/redact-secrets.ts
364
+ var REDACTED = "[redacted]";
365
+ var INSPECTOR_URL_PATH_RE = /\b(wss?:\/\/[^\s/]+)\/[^\s,)"']+/gi;
366
+ var INSPECTOR_BROWSER_URL_RE = /\b(https?:\/\/debug\.bun\.sh\/#)[^\s,)"']+/gi;
367
+ var ANSI_RE = /\u001B\[[0-9:;<=>?]*[ -/]*[@-~]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g;
368
+ function stripAnsiForDiagnostics(text) {
369
+ return text.replaceAll(ANSI_RE, "");
370
+ }
371
+ function cleanDiagnosticText(text, secrets = []) {
372
+ return redactSecrets(stripAnsiForDiagnostics(text), secrets);
373
+ }
374
+ function redactSecrets(text, secrets = []) {
375
+ let redacted = text.replaceAll(INSPECTOR_URL_PATH_RE, `$1/${REDACTED}`).replaceAll(INSPECTOR_BROWSER_URL_RE, `$1${REDACTED}`);
376
+ for (const secret of secrets.filter((s) => s !== "").toSorted((a, b) => b.length - a.length)) {
377
+ redacted = redacted.replaceAll(secret, REDACTED);
378
+ }
379
+ return redacted;
380
+ }
381
+ function escapeControlCharacters(text) {
382
+ return text.replaceAll(/[\u0000-\u001F\u007F-\u009F]/g, (char) => String.raw`\x${char.codePointAt(0).toString(16).padStart(2, "0")}`);
383
+ }
384
+
385
+ // src/coverage/dry-run-messages.ts
386
+ var LISTED_ENTRIES = 10;
387
+ function projectPath(file, projectDir) {
388
+ const relative = path3.relative(projectDir, file);
389
+ return relative === "" || relative === ".." || relative.startsWith(`..${path3.sep}`) ? file : relative.split(path3.sep).join("/");
390
+ }
391
+ var NEEDS_QUOTES_RE = /[,"']|[^\S ]| {2}|^ | $|[\u0000-\u001F\u007F-\u009F]/;
392
+ function quoted(text) {
393
+ return escapeControlCharacters(JSON.stringify(text));
394
+ }
395
+ function displayName(name) {
396
+ return NEEDS_QUOTES_RE.test(name) ? quoted(name) : name;
397
+ }
398
+ function shownPath(file, projectDir) {
399
+ return displayName(projectPath(file, projectDir));
400
+ }
401
+ function displayError(text) {
402
+ return escapeControlCharacters(cleanDiagnosticText(text));
403
+ }
404
+ function listText(entries) {
405
+ const shown = entries.slice(0, LISTED_ENTRIES).join(", ");
406
+ const more = entries.length - LISTED_ENTRIES;
407
+ return more > 0 ? `${shown} and ${more} more` : shown;
408
+ }
409
+ function listOverflow(entries) {
410
+ return entries.slice(LISTED_ENTRIES);
411
+ }
412
+ function count(n, singular, plural = `${singular}s`) {
413
+ return `${n} ${n === 1 ? singular : plural}`;
414
+ }
415
+ function joinParts(parts) {
416
+ if (parts.length <= 1) {
417
+ return parts.join("");
418
+ }
419
+ return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
420
+ }
421
+ var INCREMENTAL_ADVICE = " Results saved before the change are reused: run once with --force over the whole mutate scope, not only the files named here.";
422
+ function incrementalAdvice(incremental) {
423
+ return incremental ? INCREMENTAL_ADVICE : "";
424
+ }
425
+ var UNSEEN_LOAD_ADVICE = "If the tests do load one of those in a way the runner cannot see (through a package, a worker or a child process), add it to bun.alwaysImport.";
426
+ function leftOutText(summary, imported) {
427
+ const verb = imported === 0 ? "It does not import any of them itself" : `It does not import the other ${summary.left.length} itself`;
428
+ return `${verb}: ${listText(summary.left)}. ${UNSEEN_LOAD_ADVICE}${incrementalAdvice(summary.incremental)}`;
429
+ }
430
+ function importListOneRunMessage(summary, sources) {
431
+ const imported = sources.statically + sources.named + sources.always;
432
+ const parts = [];
433
+ if (sources.statically > 0) {
434
+ parts.push(`${sources.statically} that the test files or preloads import statically`);
435
+ }
436
+ if (sources.named > 0) {
437
+ parts.push(`${sources.named} that they reach only through a literal import() or require()`);
438
+ }
439
+ if (sources.always > 0) {
440
+ parts.push(`${sources.always} kept by bun.alwaysImport`);
441
+ }
442
+ const head = imported === 0 ? `Dry run: of the ${summary.matched} files matched by mutate, the runner imports none before the tests.` : `Dry run: of the ${summary.matched} files matched by mutate, the runner imports ${imported} before the tests: ${joinParts(parts)}.`;
443
+ return `${head} ${leftOutText(summary, imported)}`;
444
+ }
445
+ function importListTwoRunMessage(summary, sources, published, discovery) {
446
+ const imported = sources.observed + sources.always;
447
+ const observed = sources.always === 0 ? `the ${sources.observed}` : `${sources.observed}`;
448
+ const parts = [`${observed} that a ${discovery} run of the tests was seen to load`];
449
+ if (sources.always > 0) {
450
+ parts.push(`${sources.always} kept by bun.alwaysImport`);
451
+ }
452
+ const head = imported === 0 ? `Dry run: of the ${summary.matched} files matched by mutate, the runner imports none before the tests of the ${published} run.` : `Dry run: of the ${summary.matched} files matched by mutate, the runner imports ${imported} before the tests of the ${published} run: ${joinParts(parts)}.`;
453
+ return `${head} ${leftOutText(summary, imported)}`;
454
+ }
455
+ var SCAN_NEXT = {
456
+ full: "One run of the tests, with every file matched by mutate imported first.",
457
+ static: "One run of the tests, with those files imported first and the rest watched.",
458
+ dynamic: "A plain run of the tests is observed first, then the run that publishes results."
459
+ };
460
+ function scanMessage(scan) {
461
+ const sets = `${scan.statically.length} imported statically [${scan.statically.join(", ")}], ${scan.named.length} named in import() or require() [${scan.named.join(", ")}], ${scan.always.length} kept by bun.alwaysImport [${scan.always.join(", ")}]`;
462
+ const reasons = scan.reasons.length === 0 ? "" : `; reasons: ${escapeControlCharacters(scan.reasons.join("; "))}`;
463
+ const notes = scan.notes.length === 0 ? "" : `; notes: ${escapeControlCharacters(scan.notes.join("; "))}`;
464
+ return `Import scan: ${scan.answer} in ${Math.round(scan.wallMs)} ms over ${scan.scannedFiles} files; of the ${scan.matched} files matched by mutate, ${sets}${reasons}${notes}. ${SCAN_NEXT[scan.next]}`;
465
+ }
466
+ function scanUnusableMessage(reason, started) {
467
+ const what = started ? "The import scan gave no usable answer" : "The import scan was not started";
468
+ return `${what}: ${escapeControlCharacters(reason)}. ${SCAN_NEXT.dynamic}`;
469
+ }
470
+ var MISS_DISCARDED = "The run is discarded, and the dry run starts again with a plain run of the tests that observes what they load; if that run is accepted, the runner attempts a third run to publish the results.";
471
+ function missMessage(files, testFiles, incremental) {
472
+ const sentences = [];
473
+ if (files.length === 1) {
474
+ sentences.push(`${files[0]} was loaded during the dry run, but the scan of the test files' imports found no route to it.`);
475
+ } else if (files.length > 0) {
476
+ sentences.push(`${files.length} files matched by mutate were loaded during the dry run, but the scan of the test files' imports found no route to them: ${listText(files)}.`);
477
+ }
478
+ if (testFiles.length === 1) {
479
+ sentences.push(`${testFiles[0]} ran tests but was not among the test files the runner scanned.`);
480
+ } else if (testFiles.length > 0) {
481
+ sentences.push(`${testFiles.length} test files ran tests but were not among the test files the runner scanned: ${listText(testFiles)}.`);
482
+ }
483
+ sentences.push(MISS_DISCARDED);
484
+ if (files.length > 0) {
485
+ const which = files.length === 1 ? "the file" : "those files";
486
+ sentences.push(`To avoid that, add ${which} to bun.alwaysImport or set bun.importDiscovery to 'run'.${incrementalAdvice(incremental)}`);
487
+ } else {
488
+ sentences.push(`To avoid that, set bun.importDiscovery to 'run'.${incrementalAdvice(incremental)}`);
489
+ }
490
+ return sentences.join(" ");
491
+ }
492
+ function namedMessage(namedCount, notLoaded, kept, incremental) {
493
+ const head = `The first run of the dry run failed while the runner imported first, among others, ${count(namedCount, "file")} that test files or preloads reach only through a literal import() or require().`;
494
+ if (notLoaded.length === 0) {
495
+ return `${head} A plain run of the tests then passed, loading every one of them, so importing them is not shown to be the cause. This took three runs.`;
496
+ }
497
+ let imports = notLoaded.length === 1 ? "The runner no longer imports it." : "The runner no longer imports them.";
498
+ if (kept.length === notLoaded.length) {
499
+ imports = `bun.alwaysImport keeps ${notLoaded.length === 1 ? "it" : "them"}, so the runner still imports ${notLoaded.length === 1 ? "it" : "them"} first.`;
500
+ } else if (kept.length > 0) {
501
+ imports = `The runner no longer imports them, except ${kept.length} that bun.alwaysImport keeps: ${listText(kept)}.`;
502
+ }
503
+ return `${head} A plain run of the tests then passed without loading ${notLoaded.length} of them, the likely cause: ${listText(notLoaded)}. ${imports} ` + `This took three runs; remove the import() or require() that never runs, or set bun.importDiscovery to 'run'.${incrementalAdvice(incremental)}`;
504
+ }
505
+ function discoveryFailedMessage(discovery, reasons) {
506
+ const next = discovery === "first" ? "second" : "third";
507
+ return `stryker-bun-runner: the ${discovery} run of the dry run (a plain run of the tests, with no mutated file imported first) did not complete cleanly: ${reasons.join("; ")}. The ${next} run was not made.`;
508
+ }
509
+ function discoveryAfterFailedRunMessage(reasons) {
510
+ return "The second run of the dry run (a plain run of the tests, with no mutated file imported first, made because the first run failed) " + `did not complete cleanly either: ${reasons.join("; ")}. The first run's result is returned.`;
511
+ }
512
+ function publishedFailedMessage(published, discovery, imported, observed, failures) {
513
+ if (imported.length === 0) {
514
+ return `The ${published} run of the dry run failed although the ${discovery}, a plain run of the same tests, passed. ` + "It imported no mutated file first, so the difference is not an import: a test that does not pass on every run can do this.";
515
+ }
516
+ const always = imported.length - observed;
517
+ const which = always === 0 ? `the ${count(observed, "mutated file")} the plain run loaded` : `${count(observed, "mutated file")} the plain run loaded and ${count(always, "file")} kept by bun.alwaysImport`;
518
+ const threw = failures.length === 0 ? "" : ` Imports that threw: ${listText(failures)}.`;
519
+ return `The ${published} run of the dry run failed although the ${discovery}, a plain run of the same tests, passed. ` + `The ${published} run imports ${which} before the tests, so that their module-level code is not credited to whichever test loads them first; ` + `one of those imports probably broke the tests: ${listText(imported)}.${threw} Make that file importable before the tests, or remove it from mutate.`;
520
+ }
521
+ function loadedByListMessage(files) {
522
+ const cause = "(a file imported first, including one only bun.alwaysImport keeps, or a preload can cause this)";
523
+ if (files.length === 1) {
524
+ return `${files[0]} was not loaded in the plain run of the tests, but in the run that publishes it was loaded before the tests, while the runner imported its list first ${cause}. ` + "It ran before the tests, as in earlier versions.";
525
+ }
526
+ return `${listText(files)} were not loaded in the plain run of the tests, but in the run that publishes they were loaded before the tests, while the runner imported its list first ${cause}. ` + "They ran before the tests, as in earlier versions.";
527
+ }
528
+ function lateWhere(load) {
529
+ if (load.test !== null) {
530
+ return `inside test ${quoted(load.test)}`;
531
+ }
532
+ return load.sensor === "header" ? "after the imports, outside a test" : "after the imports";
533
+ }
534
+ function lateLoadEntries(loads) {
535
+ return loads.map((load) => `${load.file} (${lateWhere(load)})`);
536
+ }
537
+ function lateLoadMessage(loads, published, discovery, incremental) {
538
+ if (loads.length === 1) {
539
+ return `stryker-bun-runner: ${loads[0].file} was loaded during the ${published} run of the dry run (${lateWhere(loads[0])}) but not during the ${discovery}, ` + `so the runner had not imported it before the tests. Add it to bun.alwaysImport. No mutant was scored.${incrementalAdvice(incremental)}`;
540
+ }
541
+ const listed = listText(lateLoadEntries(loads));
542
+ return `stryker-bun-runner: ${loads.length} files matched by mutate were loaded during the ${published} run of the dry run but not during the ${discovery}, ` + `so the runner had not imported them before the tests: ${listed}. Add them to bun.alwaysImport. No mutant was scored.${incrementalAdvice(incremental)}`;
543
+ }
544
+ function eagerFailureMessage(file, error) {
545
+ return `Importing ${file} before the tests failed: ${displayError(error)}. The dry run continued, as earlier versions did without saying so. A test that loads this file afterwards gets the same error.`;
546
+ }
547
+ function lostImportedText(report) {
548
+ if (report.always === 0) {
549
+ return `the ${count(report.imported, "file")} the tests load ${report.imported === 1 ? "was" : "were"}`;
550
+ }
551
+ return `${count(report.imported - report.always, "file")} the tests load and ${count(report.always, "file")} kept by bun.alwaysImport were`;
552
+ }
553
+ function lostMessage(report) {
554
+ const where = report.files.length === 0 ? "" : ` in ${listText(report.files)}`;
555
+ const verb = report.ids.length === 1 ? "was" : "were";
556
+ return `stryker-bun-runner: ${count(report.ids.length, "mutant")}${where} (ids ${listText(report.ids)}) ${verb} reached when the tests ran on their own, ` + `and not reached when ${lostImportedText(report)} imported first, in the ${report.published} run. ` + `${count(report.leftOut.length, "file")} matched by mutate ${report.leftOut.length === 1 ? "was" : "were"} left out of that import because the run of the tests on their own did not load ${report.leftOut.length === 1 ? "it" : "them"}: ${listText(report.leftOut)}. ` + "Either module-level code depends on one of the files left out (add it to bun.alwaysImport), or the tests do not execute the same code on every run " + "(a random order without a seed can do this). bun.alwaysImport: 'all' imports every mutated file first, in one run, as earlier versions did. " + `No mutant was scored.${incrementalAdvice(report.incremental)}`;
557
+ }
558
+ function refuseMessage(problems, incremental) {
559
+ return `stryker-bun-runner: cannot tell which mutated files the tests load: ${problems.join("; ")}. ` + `Set bun.alwaysImport to 'all' to import every mutated file first, as earlier versions did. No mutant was scored.${incrementalAdvice(incremental)}`;
560
+ }
561
+ function unpublishedCampaignMessage(file, cause, watched) {
562
+ return `stryker-bun-runner: cannot write ${escapeControlCharacters(file)} (${displayError(cause)}). The mutant runs need it to watch the ${count(watched, "file")} matched by mutate that the dry run ` + "neither imported before the tests nor saw load, so the dry run stops here. No mutant was scored. " + "Make the run's temporary directory writable, or set bun.alwaysImport to 'all' to import every mutated file first, as earlier versions did.";
563
+ }
564
+ function seconds(ms) {
565
+ return (ms / 1000).toFixed(1);
566
+ }
567
+ function budgetMessage(usedMs, remainingMs, budgetMinutes, suggestedMinutes) {
568
+ return `The dry run has used ${seconds(usedMs)} s and ${seconds(remainingMs)} s remain of dryRunTimeoutMinutes (${budgetMinutes}); it now runs the tests again. ` + `If the initial test run times out, raise dryRunTimeoutMinutes to at least ${suggestedMinutes}.`;
569
+ }
570
+ function witnessMessage(report) {
571
+ const one = report.files.length === 1;
572
+ const files = listText(report.files);
573
+ const force = report.incremental ? " with --force over the whole mutate scope, not only the files named here" : "";
574
+ return `stryker-bun-runner: ${files} ${one ? "was" : "were"} present in bun's module cache in this mutant run (mutant ${report.mutantId}, tests: ${report.scope}) when the mutant first executed, ` + `and the dry run neither imported ${one ? "it" : "them"} before the tests nor saw ${one ? "it" : "them"} load. ` + "The coverage plan for this run may be incomplete, so the run is stopped: Stryker writes no final report and no incremental file for it " + "(results already reported for earlier mutants, and files from earlier runs, are left as they are). " + `Add ${files} to bun.alwaysImport, or set bun.importDiscovery to 'run', and run again${force}; ` + `a mock.module() of ${one ? "that file" : "those files"} that only some tests make has the same effect and the same remedy.`;
575
+ }
576
+
577
+ // src/coverage/dry-run-plan.ts
578
+ import path4 from "node:path";
579
+ import picomatch from "picomatch";
580
+
581
+ // src/coverage/preload-logic.ts
582
+ import { appendFileSync, closeSync, constants, openSync, readFileSync as readFileSync2, realpathSync as realpathSync2, renameSync, unlinkSync, writeSync } from "node:fs";
583
+ var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
584
+ var PRELOAD_TIMINGS_ENV = "__STRYKER_PRELOAD_TIMINGS__";
585
+ var PRELOAD_TIMINGS_PREFIX = "[Stryker Timings] ";
586
+ function readPreloadTimings(stderr) {
587
+ const start = stderr.lastIndexOf(`
588
+ ${PRELOAD_TIMINGS_PREFIX}`);
589
+ if (start === -1) {
590
+ return;
591
+ }
592
+ const jsonStart = start + 1 + PRELOAD_TIMINGS_PREFIX.length;
593
+ const end = stderr.indexOf(`
594
+ `, jsonStart);
595
+ try {
596
+ const parsed = JSON.parse(stderr.slice(jsonStart, end === -1 ? stderr.length : end));
597
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
598
+ return;
599
+ }
600
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "number"));
601
+ } catch {
602
+ return;
603
+ }
604
+ }
605
+ var HIT_LIMIT_SENTINEL = "__STRYKER_HIT_LIMIT_REACHED__";
606
+ var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
607
+ var DRY_RUN_PLAN_ENV = "__STRYKER_DRY_RUN_PLAN__";
608
+ var PLAN_FIELDS = new Set(["mode", "eager", "candidates", "recordFile", "nonce"]);
609
+ function latestSightings(observations) {
610
+ const kept = new Map;
611
+ for (const sighting of observations) {
612
+ const known = kept.get(sighting.file);
613
+ if (known === undefined || known.time === "by-eager-end" && sighting.time === "later") {
614
+ kept.set(sighting.file, sighting);
615
+ }
616
+ }
617
+ return observations.filter((sighting) => kept.get(sighting.file) === sighting);
618
+ }
619
+ var PRIVATE_CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
620
+ var WATCH_LIST_ENV = "__STRYKER_WATCH_LIST__";
621
+ var WITNESS_SENTINEL = "__STRYKER_UNIMPORTED_LOADED__";
622
+ var WATCH_LIST_PROBLEM_SENTINEL = "__STRYKER_WATCH_LIST_UNREADABLE__";
623
+ var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
624
+
625
+ // src/coverage/dry-run-plan.ts
626
+ function selectAlways(eagerList, option, projectDir) {
627
+ if (option === "all") {
628
+ return { files: [...eagerList], unmatched: [] };
629
+ }
630
+ const patterns = option ?? [];
631
+ const relative = eagerList.map((file) => path4.relative(projectDir, file).split(path4.sep).join("/"));
632
+ const matched = new Set;
633
+ const unmatched = [];
634
+ for (const pattern of patterns) {
635
+ const matches = picomatch(pattern, { dot: true });
636
+ const hits = eagerList.filter((_file, index) => matches(relative[index]));
637
+ if (hits.length === 0) {
638
+ unmatched.push(pattern);
639
+ }
640
+ for (const file of hits) {
641
+ matched.add(file);
642
+ }
643
+ }
644
+ return { files: eagerList.filter((file) => matched.has(file)), unmatched };
645
+ }
646
+ function selectList(eagerList, sets) {
647
+ return eagerList.filter((file) => sets.some((set) => set.has(file)));
648
+ }
649
+ function legacyReason(eagerList, always) {
650
+ if (eagerList.length === 0) {
651
+ return "empty";
652
+ }
653
+ const kept = new Set(always);
654
+ return eagerList.every((file) => kept.has(file)) ? "always-covers" : null;
655
+ }
656
+ function decideFromScan(scan, eagerList, always, importDiscovery) {
657
+ const legacy = legacyReason(eagerList, always);
658
+ if (legacy !== null) {
659
+ return { kind: "legacy", reason: legacy };
660
+ }
661
+ const mandatory = new Set(scan.mandatory);
662
+ const named = new Set(scan.named);
663
+ const kept = new Set(always);
664
+ const sources = {
665
+ statically: eagerList.filter((file) => mandatory.has(file)),
666
+ named: eagerList.filter((file) => named.has(file) && !mandatory.has(file)),
667
+ always: eagerList.filter((file) => kept.has(file) && !mandatory.has(file) && !named.has(file))
668
+ };
669
+ const list = selectList(eagerList, [mandatory, named, kept]);
670
+ if (list.length === eagerList.length) {
671
+ return { kind: "full", list, sources };
672
+ }
673
+ if (scan.answer !== "static" || scan.reasons.length > 0) {
674
+ const reasons = scan.reasons.length > 0 ? scan.reasons : [`the scan answered ${scan.answer} without a reason`];
675
+ return { kind: "dynamic", cause: "scan", reasons, sources };
676
+ }
677
+ if (importDiscovery === "run") {
678
+ return { kind: "dynamic", cause: "importDiscovery", reasons: ["bun.importDiscovery is 'run'"], sources };
679
+ }
680
+ return { kind: "static", list, sources };
681
+ }
682
+ function publishPlan(eagerList, list, recordFile, nonce) {
683
+ const imported = new Set(list);
684
+ const candidates = eagerList.filter((file) => !imported.has(file));
685
+ if (candidates.length === 0) {
686
+ return list.length === 0 ? { mode: "publish", eager: [], candidates: null, recordFile: null, nonce: null } : { mode: "publish", eager: [...list], candidates: null, recordFile, nonce };
687
+ }
688
+ return { mode: "publish", eager: [...list], candidates, recordFile, nonce };
689
+ }
690
+ function discoveryPlan(eagerList, recordFile, nonce) {
691
+ return { mode: "discover", eager: [], candidates: [...eagerList], recordFile, nonce };
692
+ }
693
+ function outsideCandidates(observations, list) {
694
+ const imported = new Set(list);
695
+ const kept = latestSightings(observations.filter((observation) => !imported.has(observation.file)));
696
+ return {
697
+ byEagerEnd: kept.filter((observation) => observation.time === "by-eager-end"),
698
+ later: kept.filter((observation) => observation.time === "later")
699
+ };
700
+ }
701
+ function lostIds(reachedInDiscovery, rawCoverage) {
702
+ const hit = new Set;
703
+ for (const counts of [rawCoverage.static, ...Object.values(rawCoverage.perTest)]) {
704
+ for (const [id, count] of Object.entries(counts)) {
705
+ if (count > 0) {
706
+ hit.add(id);
707
+ }
708
+ }
709
+ }
710
+ return [...new Set(reachedInDiscovery)].filter((id) => !hit.has(id));
711
+ }
712
+ function watchList(eagerList, list, seen) {
713
+ const known = new Set([...list, ...seen]);
714
+ return eagerList.filter((file) => !known.has(file));
715
+ }
716
+ function isDuration(value) {
717
+ return Number.isFinite(value) && value >= 0;
718
+ }
719
+ function timeoutCorrection(extraMs, elapsedMs, publishedTestDurations) {
720
+ if (!isDuration(extraMs) || !isDuration(elapsedMs) || extraMs > elapsedMs || !publishedTestDurations.every((duration) => isDuration(duration))) {
721
+ return 0;
722
+ }
723
+ const testsMs = publishedTestDurations.reduce((sum, duration) => sum + duration, 0);
724
+ const overheadMs = Math.max(0, elapsedMs - testsMs);
725
+ return Math.floor(Math.min(extraMs, overheadMs));
726
+ }
727
+ function signedPayloads(stderr, marker, token) {
728
+ const payloads = [];
729
+ if (token === "") {
730
+ return payloads;
731
+ }
732
+ const prefix = `${marker} ${token} `;
733
+ let from = 0;
734
+ for (;; ) {
735
+ const at = stderr.indexOf(prefix, from);
736
+ if (at === -1) {
737
+ return payloads;
738
+ }
739
+ const end = stderr.indexOf(`
740
+ `, at);
741
+ if (at === 0 || stderr[at - 1] === `
742
+ `) {
743
+ payloads.push(stderr.slice(at + prefix.length, end === -1 ? stderr.length : end));
744
+ }
745
+ from = at + prefix.length;
746
+ }
747
+ }
748
+ function readWitnessReport(stderr, token, watched) {
749
+ for (const payload of signedPayloads(stderr, WITNESS_SENTINEL, token)) {
750
+ let value;
751
+ try {
752
+ value = JSON.parse(payload);
753
+ } catch {}
754
+ if (Array.isArray(value) && value.length > 0 && value.every((file) => watched.has(file))) {
755
+ return value;
756
+ }
757
+ }
758
+ return;
759
+ }
760
+ function readWatchListProblem(stderr, token) {
761
+ for (const payload of signedPayloads(stderr, WATCH_LIST_PROBLEM_SENTINEL, token)) {
762
+ try {
763
+ const value = JSON.parse(payload);
764
+ if (typeof value === "string") {
765
+ return value;
766
+ }
767
+ } catch {}
768
+ }
769
+ return;
770
+ }
771
+ var isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
772
+ function isCount(value) {
773
+ return Number.isSafeInteger(value) && value >= 0;
774
+ }
775
+ function isObservation(value, eager) {
776
+ if (!isPlainRecord(value)) {
777
+ return false;
778
+ }
779
+ const { file, time, sensor, testKey } = value;
780
+ return typeof file === "string" && eager.has(file) && (time === "by-eager-end" || time === "later") && (sensor === "header" || sensor === "cache") && (testKey === null || typeof testKey === "string");
781
+ }
782
+ function isEagerFailure(value, eager) {
783
+ if (!isPlainRecord(value)) {
784
+ return false;
785
+ }
786
+ const { file, error } = value;
787
+ return typeof file === "string" && eager.has(file) && typeof error === "string";
788
+ }
789
+ function recordObject(text) {
790
+ let value;
791
+ try {
792
+ value = JSON.parse(text);
793
+ } catch {
794
+ return { problem: "is not valid JSON" };
795
+ }
796
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
797
+ return { problem: "is not a JSON object" };
798
+ }
799
+ return { value };
800
+ }
801
+ function observationProblem(value, eager) {
802
+ if (typeof value.nonce !== "string" || value.nonce === "") {
803
+ return "has no nonce";
804
+ }
805
+ if (value.complete !== true) {
806
+ return "is not marked complete";
807
+ }
808
+ if (!Array.isArray(value.observed) || !value.observed.every((entry) => isObservation(entry, eager))) {
809
+ return "has an observed list that is not a list of sightings of files matched by mutate";
810
+ }
811
+ if (!isStringList(value.problems)) {
812
+ return "has problems that are not a list of strings";
813
+ }
814
+ if (!Array.isArray(value.eagerFailures) || !value.eagerFailures.every((entry) => isEagerFailure(entry, eager))) {
815
+ return "has eagerFailures that are not a list of failed imports of files matched by mutate";
816
+ }
817
+ if (!Number.isFinite(value.sensorMs) || value.sensorMs < 0) {
818
+ return "has a sensorMs that is not a non-negative number";
819
+ }
820
+ return;
821
+ }
822
+ function readObservationRecord(text, eagerList) {
823
+ const parsed = recordObject(text);
824
+ if ("problem" in parsed) {
825
+ return parsed;
826
+ }
827
+ const problem = observationProblem(parsed.value, new Set(eagerList));
828
+ return problem === undefined ? { record: parsed.value } : { problem };
829
+ }
830
+ function ownRecord(read, nonce) {
831
+ return "problem" in read || read.record.nonce === nonce ? read : { problem: "carries another launch's nonce" };
832
+ }
833
+ function readDiscoveryRecord(text, eagerList) {
834
+ const observation = readObservationRecord(text, eagerList);
835
+ if ("problem" in observation) {
836
+ return observation;
837
+ }
838
+ const { startedTests, reached } = observation.record;
839
+ if (!isCount(startedTests)) {
840
+ return { problem: "has a startedTests that is not a count" };
841
+ }
842
+ if (!isStringList(reached)) {
843
+ return { problem: "has a reached list that is not a list of mutant ids" };
844
+ }
845
+ return { record: observation.record };
846
+ }
847
+ function endReasons(facts) {
848
+ if (facts.spawnError !== undefined) {
849
+ return [`bun test could not be started (${facts.spawnError})`];
850
+ }
851
+ if (facts.timedOut) {
852
+ return [facts.memoryLimitExceeded ? "the runner killed it for exceeding bun.maxChildRss" : "the runner killed it at bun.timeout"];
853
+ }
854
+ if (facts.signal !== null) {
855
+ return [`it was terminated by signal ${facts.signal}`];
856
+ }
857
+ return facts.exitCode === 0 ? [] : [`bun exited with code ${String(facts.exitCode)}`];
858
+ }
859
+ function summaryReasons(facts) {
860
+ if (!facts.summaryPrinted) {
861
+ return ["bun printed no summary"];
862
+ }
863
+ const reasons = [];
864
+ if (facts.summaryFailed > 0) {
865
+ reasons.push(`${facts.summaryFailed} failing test(s)`);
866
+ }
867
+ if (facts.summaryErrors > 0) {
868
+ reasons.push(`${facts.summaryErrors} error(s) outside tests`);
869
+ }
870
+ return reasons;
871
+ }
872
+ function recordReasons(facts) {
873
+ if ("problem" in facts.record) {
874
+ return [`no completion record of this run (the record ${facts.record.problem})`];
875
+ }
876
+ const { nonce, startedTests } = facts.record.record;
877
+ if (nonce !== facts.nonce) {
878
+ return ["no completion record of this run (the record carries another launch's nonce)"];
879
+ }
880
+ if (facts.summaryPrinted && startedTests < facts.summaryPassed) {
881
+ return [`the completion record counts ${startedTests} test start(s), fewer than bun's ${facts.summaryPassed} passing test(s)`];
882
+ }
883
+ return [];
884
+ }
885
+ function acceptDiscovery(facts) {
886
+ const reasons = [...endReasons(facts), ...summaryReasons(facts), ...recordReasons(facts)];
887
+ if (reasons.length > 0) {
888
+ return { kind: "rejected", reasons };
889
+ }
890
+ const { record } = facts.record;
891
+ return record.problems.length > 0 ? { kind: "refused", problems: record.problems } : { kind: "accepted", record };
892
+ }
893
+ function sensorProblems(facts) {
894
+ if (facts.record === undefined) {
895
+ return [];
896
+ }
897
+ if ("problem" in facts.record) {
898
+ return facts.watched && facts.green ? [`the published run's observation record ${facts.record.problem}`] : [];
899
+ }
900
+ return [...facts.record.record.problems];
901
+ }
902
+ function outsideOf(facts) {
903
+ return facts.record === undefined || "problem" in facts.record ? { byEagerEnd: [], later: [] } : outsideCandidates(facts.record.record.observed, facts.list);
904
+ }
905
+ function eagerFailuresOf(record) {
906
+ return record === undefined || "problem" in record ? [] : record.record.eagerFailures;
907
+ }
908
+ function oneRunOutcome(facts, unscanned, named) {
909
+ const problems = sensorProblems(facts);
910
+ if (problems.length > 0) {
911
+ return { kind: "refuse", problems };
912
+ }
913
+ const outside = outsideOf(facts);
914
+ const files = [...outside.byEagerEnd, ...outside.later];
915
+ if (files.length > 0 || unscanned.length > 0) {
916
+ return { kind: "miss", files, testFiles: [...unscanned] };
917
+ }
918
+ if (!facts.green) {
919
+ return { kind: "failed", discover: named.length > 0 };
920
+ }
921
+ return { kind: "publish" };
922
+ }
923
+ function twoRunOutcome(facts, lost) {
924
+ const problems = sensorProblems(facts);
925
+ if (problems.length > 0) {
926
+ return { kind: "refuse", problems };
927
+ }
928
+ const outside = outsideOf(facts);
929
+ if (outside.later.length > 0) {
930
+ return { kind: "late", files: outside.later };
931
+ }
932
+ if (!facts.green) {
933
+ return { kind: "failed" };
934
+ }
935
+ if (lost.length > 0) {
936
+ return { kind: "lost", ids: [...lost] };
937
+ }
938
+ return { kind: "publish", early: outside.byEagerEnd };
939
+ }
940
+ function unscannedTestFiles(testFiles, roots, projectDir) {
941
+ const scanned = new Set(roots);
942
+ const unscanned = new Set;
943
+ for (const file of testFiles) {
944
+ if (file !== undefined && !scanned.has(path4.resolve(projectDir, file))) {
945
+ unscanned.add(file);
946
+ }
947
+ }
948
+ return [...unscanned];
949
+ }
950
+ var SCAN_NEUTRAL_FLAGS = new Set([
951
+ "--bail",
952
+ "--dots",
953
+ "--expose-gc",
954
+ "--isolate",
955
+ "--no-deprecation",
956
+ "--no-install",
957
+ "--no-isolate",
958
+ "--no-macros",
959
+ "--no-orphans",
960
+ "--only",
961
+ "--only-failures",
962
+ "--prefer-latest",
963
+ "--prefer-offline",
964
+ "--randomize",
965
+ "--silent",
966
+ "--smol",
967
+ "--throw-deprecation",
968
+ "--todo",
969
+ "--update-timings",
970
+ "--zero-fill-buffers"
971
+ ]);
972
+ var SCAN_NEUTRAL_VALUE_FLAGS = new Set([
973
+ "--bail",
974
+ "--console-depth",
975
+ "--dns-result-order",
976
+ "--elide-lines",
977
+ "--env-file",
978
+ "--max-http-header-size",
979
+ "--reporter",
980
+ "--reporter-outfile",
981
+ "--seed",
982
+ "--timeout",
983
+ "--timings",
984
+ "--title",
985
+ "--unhandled-rejections"
986
+ ]);
987
+ var PRELOAD_FLAGS = ["--preload", "--require", "--import", "-r"];
988
+ var NODE_LOADING_FLAGS = ["--require", "-r", "--import", "--loader", "--experimental-loader", "--conditions", "-C"];
989
+ function preloadAt(args, index) {
990
+ const arg = args[index];
991
+ if (PRELOAD_FLAGS.includes(arg)) {
992
+ const value = args.at(index + 1);
993
+ return { file: value === undefined || value.startsWith("-") ? undefined : value, tokens: 2 };
994
+ }
995
+ const flag = PRELOAD_FLAGS.find((spelling) => arg.startsWith(spelling.startsWith("--") ? `${spelling}=` : spelling));
996
+ if (flag === undefined) {
997
+ return;
998
+ }
999
+ const value = arg.slice(flag.length).replace(/^=/, "");
1000
+ return { file: value === "" ? undefined : value, tokens: 1 };
1001
+ }
1002
+ function neutralTokens(args, index) {
1003
+ const arg = args[index];
1004
+ if (SCAN_NEUTRAL_FLAGS.has(arg)) {
1005
+ return 1;
1006
+ }
1007
+ if (SCAN_NEUTRAL_VALUE_FLAGS.has(arg)) {
1008
+ return 2;
1009
+ }
1010
+ const equals = arg.indexOf("=");
1011
+ return equals !== -1 && SCAN_NEUTRAL_VALUE_FLAGS.has(arg.slice(0, equals)) ? 1 : 0;
1012
+ }
1013
+ function readScanArguments(args, source, cwd) {
1014
+ const preloads = [];
1015
+ for (let index = 0;index < args.length; ) {
1016
+ const preload = preloadAt(args, index);
1017
+ if (preload !== undefined) {
1018
+ if (preload.file === undefined) {
1019
+ return { problem: `${source} contains "${args[index]}" without a file the import scan can name` };
1020
+ }
1021
+ preloads.push(path4.resolve(cwd, preload.file));
1022
+ index += preload.tokens;
1023
+ continue;
1024
+ }
1025
+ const tokens = neutralTokens(args, index);
1026
+ if (tokens === 0) {
1027
+ return { problem: `${source} contains "${args[index]}", which can change what the tests load or how their imports resolve, and the import scan cannot account for it` };
1028
+ }
1029
+ index += tokens;
1030
+ }
1031
+ return { preloads };
1032
+ }
1033
+ function scanLaunchArguments(bunArgs, env, cwd) {
1034
+ const bunOptions = (env.BUN_OPTIONS ?? "").split(/\s/).filter((token) => token !== "");
1035
+ const fromEnv = readScanArguments(bunOptions, "the BUN_OPTIONS environment variable", cwd);
1036
+ if ("problem" in fromEnv) {
1037
+ return fromEnv;
1038
+ }
1039
+ if (fromEnv.preloads.length > 0) {
1040
+ return { problem: "the BUN_OPTIONS environment variable adds a preload, which the import scan cannot account for" };
1041
+ }
1042
+ const nodeOptions = env.NODE_OPTIONS ?? "";
1043
+ const nodeOption = nodeOptions.split(/\s/).find((token) => NODE_LOADING_FLAGS.some((flag) => token === flag || token.startsWith(`${flag}=`)));
1044
+ if (nodeOption !== undefined) {
1045
+ return { problem: `the NODE_OPTIONS environment variable contains "${nodeOption}", which the import scan cannot account for` };
1046
+ }
1047
+ return readScanArguments(bunArgs, "bun.bunArgs", cwd);
1048
+ }
1049
+ function correctStrykerTimeout(strykerTimeoutMs, correctionMs) {
1050
+ const correction = correctionMs;
1051
+ if (Number.isFinite(correction) && correction >= 0 && correction < strykerTimeoutMs) {
1052
+ return { timeoutMs: strykerTimeoutMs - correction, applied: true };
1053
+ }
1054
+ return { timeoutMs: strykerTimeoutMs, applied: false };
1055
+ }
1056
+ function budgetWarning(usedMs, budgetMs) {
1057
+ const budget = budgetMs;
1058
+ if (!Number.isFinite(budget) || budget <= 0 || !Number.isFinite(usedMs)) {
1059
+ return;
1060
+ }
1061
+ const remainingMs = budget - usedMs;
1062
+ if (remainingMs >= usedMs) {
1063
+ return;
1064
+ }
1065
+ return { usedMs, remainingMs: Math.max(0, remainingMs), suggestedMinutes: Math.ceil(2 * usedMs / 60000) };
1066
+ }
1067
+
1068
+ // src/coverage/import-scan-runner.ts
1069
+ import { spawn } from "node:child_process";
1070
+ import { randomBytes as randomBytes2 } from "node:crypto";
1071
+ import { rm as rm3 } from "node:fs/promises";
1072
+ import path5 from "node:path";
1073
+ import { fileURLToPath } from "node:url";
1074
+ var IMPORT_SCAN_TIMEOUT_MS = 5000;
1075
+ var STDERR_EXCERPT_CHARS = 2000;
1076
+ var IMPORT_SCAN_STDERR_LIMIT_BYTES = 64 * 1024;
1077
+ var STDOUT_BASE_BYTES = 1024 * 1024;
1078
+ function scanOutputLimits(input) {
1079
+ const eagerBytes = input.eager.reduce((sum, file) => sum + Buffer.byteLength(file) + 3, 0);
1080
+ return { stdout: STDOUT_BASE_BYTES + 6 * eagerBytes, stderr: IMPORT_SCAN_STDERR_LIMIT_BYTES };
1081
+ }
1082
+ function resolveBunExecutable(bunPath, cwd) {
1083
+ const hasDirectory = bunPath.includes("/") || path5.sep === "\\" && bunPath.includes("\\");
1084
+ return hasDirectory && !path5.isAbsolute(bunPath) ? path5.resolve(cwd, bunPath) : bunPath;
1085
+ }
1086
+ var PRELOADING_ENV = ["BUN_OPTIONS", "NODE_OPTIONS"];
1087
+ function resolveImportScanScript(moduleDir) {
1088
+ const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1089
+ return isBundled ? path5.join(moduleDir, "templates/import-scan.js") : path5.join(moduleDir, "import-scan.ts");
1090
+ }
1091
+ function failedScanResult(reason) {
1092
+ return { answer: "dynamic", mandatory: [], named: [], reasons: [reason], notes: [], scannedFiles: 0, elapsedMs: 0 };
1093
+ }
1094
+ var isStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
1095
+ function parseImportScanOutput(stdout, eagerList) {
1096
+ let value;
1097
+ try {
1098
+ value = JSON.parse(stdout);
1099
+ } catch (error) {
1100
+ return { problem: `its output is not JSON (${error.message})` };
1101
+ }
1102
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1103
+ return { problem: "its output is not a JSON object" };
1104
+ }
1105
+ const output = value;
1106
+ const problem = outputProblem(output, new Set(eagerList));
1107
+ if (problem !== undefined) {
1108
+ return { problem };
1109
+ }
1110
+ const { answer, mandatory, named, reasons, notes, scannedFiles, elapsedMs } = output;
1111
+ const mandatorySet = new Set(mandatory);
1112
+ const namedSet = new Set(named);
1113
+ return {
1114
+ result: {
1115
+ answer,
1116
+ mandatory: eagerList.filter((file) => mandatorySet.has(file)),
1117
+ named: eagerList.filter((file) => namedSet.has(file)),
1118
+ reasons,
1119
+ notes,
1120
+ scannedFiles,
1121
+ elapsedMs
1122
+ }
1123
+ };
1124
+ }
1125
+ function outputProblem(output, eager) {
1126
+ if (output.answer !== "full" && output.answer !== "static" && output.answer !== "dynamic") {
1127
+ return `its answer ${JSON.stringify(output.answer)} is not full, static or dynamic`;
1128
+ }
1129
+ for (const name of ["mandatory", "named"]) {
1130
+ const list = output[name];
1131
+ if (!isStringArray(list) || !list.every((file) => eager.has(file))) {
1132
+ return `its ${name} list is not a list of files of the eager list`;
1133
+ }
1134
+ }
1135
+ for (const name of ["reasons", "notes"]) {
1136
+ if (!isStringArray(output[name])) {
1137
+ return `its ${name} are not a list of strings`;
1138
+ }
1139
+ }
1140
+ for (const name of ["scannedFiles", "elapsedMs"]) {
1141
+ const value = output[name];
1142
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
1143
+ return `its ${name} is not a non-negative number`;
1144
+ }
1145
+ }
1146
+ return;
1147
+ }
1148
+
1149
+ class BoundedStream {
1150
+ limit;
1151
+ chunks = [];
1152
+ bytes = 0;
1153
+ constructor(limit) {
1154
+ this.limit = limit;
1155
+ }
1156
+ add(chunk) {
1157
+ this.bytes += chunk.length;
1158
+ if (this.bytes > this.limit) {
1159
+ return false;
1160
+ }
1161
+ this.chunks.push(chunk);
1162
+ return true;
1163
+ }
1164
+ text() {
1165
+ return Buffer.concat(this.chunks).toString("utf8");
1166
+ }
1167
+ }
1168
+ function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
1169
+ const env = { ...process.env };
1170
+ for (const name of PRELOADING_ENV) {
1171
+ delete env[name];
1172
+ }
1173
+ return new Promise((resolve) => {
1174
+ const streams = { stdout: new BoundedStream(maxBytes.stdout), stderr: new BoundedStream(maxBytes.stderr) };
1175
+ let timedOut = false;
1176
+ let overflow;
1177
+ let error;
1178
+ const ended = (exitCode, signal) => {
1179
+ resolve({ stdout: streams.stdout.text(), stderr: streams.stderr.text(), exitCode, signal, timedOut, overflow, error });
1180
+ };
1181
+ let child;
1182
+ try {
1183
+ child = spawn(bunPath, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
1184
+ } catch (spawnError) {
1185
+ error = spawnError instanceof Error ? spawnError : new Error(String(spawnError));
1186
+ ended(null, null);
1187
+ return;
1188
+ }
1189
+ const abandon = () => {
1190
+ child.kill("SIGKILL");
1191
+ child.stdout?.destroy();
1192
+ child.stderr?.destroy();
1193
+ ended(null, null);
1194
+ };
1195
+ const timer = setTimeout(() => {
1196
+ timedOut = true;
1197
+ abandon();
1198
+ }, timeoutMs);
1199
+ const collect = (name) => (chunk) => {
1200
+ if (!streams[name].add(chunk) && overflow === undefined) {
1201
+ overflow = name;
1202
+ clearTimeout(timer);
1203
+ abandon();
1204
+ }
1205
+ };
1206
+ child.stdout?.on("data", collect("stdout"));
1207
+ child.stderr?.on("data", collect("stderr"));
1208
+ child.on("error", (spawnError) => {
1209
+ error = spawnError;
1210
+ });
1211
+ child.on("close", (exitCode, signal) => {
1212
+ clearTimeout(timer);
1213
+ ended(exitCode, signal);
1214
+ });
1215
+ });
1216
+ }
1217
+ function helperFailure(exit, timeoutMs, maxBytes) {
1218
+ if (exit.error !== undefined) {
1219
+ return `the scan helper could not be started (${exit.error.message})`;
1220
+ }
1221
+ if (exit.overflow !== undefined) {
1222
+ return `the scan helper printed more than ${maxBytes[exit.overflow]} bytes on ${exit.overflow}`;
1223
+ }
1224
+ if (exit.timedOut) {
1225
+ return `the scan helper did not finish within ${timeoutMs} ms`;
1226
+ }
1227
+ if (exit.exitCode !== 0) {
1228
+ const how = exit.exitCode === null ? `was ended by ${exit.signal}` : `exited with code ${exit.exitCode}`;
1229
+ const said = exit.stderr.trim().slice(0, STDERR_EXCERPT_CHARS);
1230
+ return said === "" ? `the scan helper ${how}` : `the scan helper ${how}: ${said}`;
1231
+ }
1232
+ return;
1233
+ }
1234
+ async function runImportScan(input, launch) {
1235
+ const started = performance.now();
1236
+ const timeoutMs = launch.timeoutMs ?? IMPORT_SCAN_TIMEOUT_MS;
1237
+ const maxBytes = launch.maxBytes ?? scanOutputLimits(input);
1238
+ const scriptPath = launch.scriptPath ?? resolveImportScanScript(path5.dirname(fileURLToPath(import.meta.url)));
1239
+ const stem = path5.join(launch.workDir, `import-scan-${process.pid}-${randomBytes2(8).toString("hex")}`);
1240
+ const inputFile = `${stem}.json`;
1241
+ const configFile = `${stem}.bunfig.toml`;
1242
+ const report = (result, failure) => ({ result, failure, wallMs: performance.now() - started });
1243
+ const fail = (failure) => report(failedScanResult(failure), failure);
1244
+ try {
1245
+ try {
1246
+ await ensurePrivateDir(launch.workDir);
1247
+ await writePrivateFile(inputFile, JSON.stringify(input));
1248
+ await writePrivateFile(configFile, "");
1249
+ } catch (error) {
1250
+ return fail(`the scan's input could not be written (${error.message})`);
1251
+ }
1252
+ const bunPath = resolveBunExecutable(launch.bunPath, process.cwd());
1253
+ const exit = await runHelper(bunPath, ["--no-macros", "--no-install", `--config=${configFile}`, scriptPath, inputFile], launch.workDir, timeoutMs, maxBytes);
1254
+ const failure = helperFailure(exit, timeoutMs, maxBytes);
1255
+ if (failure !== undefined) {
1256
+ return fail(failure);
1257
+ }
1258
+ const parsed = parseImportScanOutput(exit.stdout, input.eager);
1259
+ return "problem" in parsed ? fail(`the scan helper's answer cannot be used: ${parsed.problem}`) : report(parsed.result, null);
1260
+ } finally {
1261
+ await Promise.all([inputFile, configFile].map((file) => rm3(file).catch(() => {
1262
+ return;
1263
+ })));
1264
+ }
1265
+ }
1266
+
1267
+ // src/coverage/preload-generator.ts
1268
+ import { unlink, readFile as readFile2, realpath as realpath2 } from "node:fs/promises";
1269
+ import path6 from "node:path";
1270
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
1271
+ import { glob } from "tinyglobby";
1272
+
272
1273
  // src/utils/test-name-pattern.ts
273
1274
  var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
274
1275
  var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.(?:[jt]sx?|[mc][jt]s)`;
@@ -334,7 +1335,7 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
334
1335
  const sourceFileRe = /\.(?:tsx?|[cm]?js)$/;
335
1336
  const dtsRe = /\.d\.[cm]?ts$/;
336
1337
  const filtered = paths.filter((p) => sourceFileRe.test(p) && !dtsRe.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
337
- const resolved = filtered.map((p) => path2.resolve(p));
1338
+ const resolved = filtered.map((p) => path6.resolve(p));
338
1339
  resolved.sort((a, b) => a.localeCompare(b));
339
1340
  return resolved;
340
1341
  }
@@ -342,44 +1343,48 @@ function resolvePreloadTemplate(moduleDir) {
342
1343
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
343
1344
  if (isBundled) {
344
1345
  return {
345
- templatePath: path2.join(moduleDir, "templates/coverage-preload.js"),
1346
+ templatePath: path6.join(moduleDir, "templates/coverage-preload.js"),
346
1347
  preloadLogicPath: undefined,
347
1348
  extension: "js"
348
1349
  };
349
1350
  }
350
1351
  return {
351
- templatePath: path2.join(moduleDir, "../templates/coverage-preload.ts"),
352
- preloadLogicPath: path2.join(moduleDir, "preload-logic.ts"),
1352
+ templatePath: path6.join(moduleDir, "../templates/coverage-preload.ts"),
1353
+ preloadLogicPath: path6.join(moduleDir, "preload-logic.ts"),
353
1354
  extension: "ts"
354
1355
  };
355
1356
  }
356
- async function generatePreloadScript(options, moduleDir = path2.dirname(fileURLToPath(import.meta.url))) {
1357
+ async function generatePreloadScript(options, moduleDir = path6.dirname(fileURLToPath2(import.meta.url))) {
357
1358
  await ensurePrivateDir(options.tempDir);
358
1359
  const { templatePath, preloadLogicPath, extension } = resolvePreloadTemplate(moduleDir);
359
- const preloadPath = path2.join(options.tempDir, `stryker-coverage-preload-${process.pid}.${extension}`);
360
- const template = await readFile(templatePath, "utf8");
361
- const eagerModules = options.eagerModules ?? [];
362
- const eagerModulesFile = eagerModules.length > 0 ? eagerModulesFileFor(preloadPath) : null;
363
- const withLogic = preloadLogicPath === undefined ? template : template.replace("__PRELOAD_LOGIC_PATH__", () => preloadLogicPath);
364
- const content = withLogic.replace("__EAGER_MODULES_FILE__", () => JSON.stringify(eagerModulesFile));
1360
+ const preloadPath = path6.join(options.tempDir, `stryker-coverage-preload-${process.pid}.${extension}`);
1361
+ const template = await readFile2(templatePath, "utf8");
1362
+ const content = preloadLogicPath === undefined ? template : template.replace("__PRELOAD_LOGIC_PATH__", () => preloadLogicPath);
365
1363
  await writePrivateFile(preloadPath, content);
366
- if (eagerModulesFile !== null) {
367
- await writePrivateFile(eagerModulesFile, JSON.stringify(eagerModules));
1364
+ if (options.dryRunPlan !== undefined) {
1365
+ await writeDryRunPlan(dryRunPlanFileFor(preloadPath), options.dryRunPlan);
368
1366
  }
369
1367
  return preloadPath;
370
1368
  }
371
- function eagerModulesFileFor(preloadPath) {
372
- return `${preloadPath.replace(/\.[jt]s$/, "")}.eager-modules.json`;
1369
+ async function writeDryRunPlan(file, plan) {
1370
+ await writePrivateFile(file, JSON.stringify(plan));
1371
+ }
1372
+ async function writeWatchList(file, paths, resolve = realpath2) {
1373
+ const entries = await Promise.all(paths.map(async (watched) => ({ file: watched, realpath: await resolve(watched).catch(() => watched) })));
1374
+ await writePrivateFile(file, JSON.stringify(entries));
1375
+ }
1376
+ function dryRunPlanFileFor(preloadPath) {
1377
+ return `${preloadPath.replace(/\.[jt]s$/, "")}.dry-run-plan.json`;
373
1378
  }
374
1379
  async function cleanupPreloadScript(preloadPath) {
375
- for (const file of [preloadPath, eagerModulesFileFor(preloadPath)]) {
1380
+ for (const file of [preloadPath, dryRunPlanFileFor(preloadPath)]) {
376
1381
  try {
377
1382
  await unlink(file);
378
1383
  } catch {}
379
1384
  }
380
1385
  }
381
1386
  // src/coverage/collector.ts
382
- import { readFile as readFile2, unlink as unlink2 } from "node:fs/promises";
1387
+ import { readFile as readFile3, unlink as unlink2 } from "node:fs/promises";
383
1388
  function addHitCounts(into, from) {
384
1389
  for (const [mutantId, count] of Object.entries(from)) {
385
1390
  into[mutantId] = (into[mutantId] ?? 0) + count;
@@ -429,7 +1434,7 @@ async function readCoverageFileDataShared(coverageFile, logger) {
429
1434
  }
430
1435
  async function readCoverageFileData(coverageFile, logger) {
431
1436
  try {
432
- const content = await readFile2(coverageFile, "utf8");
1437
+ const content = await readFile3(coverageFile, "utf8");
433
1438
  const trimmed = content.trim();
434
1439
  const lines = trimmed.split(`
435
1440
  `).filter((line) => line.length > 0);
@@ -706,9 +1711,7 @@ function buildMappedCoverage(counterIds, resolved, rawCoverage, testHierarchy) {
706
1711
  creditHits(incoming, writable, staticIds, staticCounts);
707
1712
  }
708
1713
  const perTest = nonEmptyTests(creditedByName, orphaned.length > 0);
709
- if (orphaned.length > 0) {
710
- creditOrphanedHits(orphaned, staticCounts, perTest);
711
- }
1714
+ creditOrphanedHits(orphaned, staticCounts, perTest);
712
1715
  return { static: staticCounts, perTest };
713
1716
  }
714
1717
  function creditHits(incoming, credited, staticIds, staticCounts) {
@@ -738,7 +1741,7 @@ function holdsAny(counts, mutantIds) {
738
1741
  }
739
1742
  return false;
740
1743
  }
741
- function creditOrphanedHits(orphaned, staticCounts, perTest) {
1744
+ function firstHolders(staticCounts, perTest) {
742
1745
  const firstHolder = new Map;
743
1746
  for (const counts of [staticCounts, ...Object.values(perTest)]) {
744
1747
  for (const mutantId of Object.keys(counts)) {
@@ -747,7 +1750,12 @@ function creditOrphanedHits(orphaned, staticCounts, perTest) {
747
1750
  }
748
1751
  }
749
1752
  }
1753
+ return firstHolder;
1754
+ }
1755
+ function creditOrphanedHits(orphaned, staticCounts, perTest) {
1756
+ let firstHolder;
750
1757
  for (const counts of orphaned) {
1758
+ firstHolder ??= firstHolders(staticCounts, perTest);
751
1759
  for (const mutantId of Object.keys(counts)) {
752
1760
  const holder = firstHolder.get(mutantId);
753
1761
  if (holder) {
@@ -873,34 +1881,6 @@ function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger
873
1881
  orphanedKeyCount: counterIds.length - creditedKeyCount
874
1882
  };
875
1883
  }
876
- // src/coverage/preload-logic.ts
877
- import { appendFileSync, closeSync, constants, openSync, writeSync } from "node:fs";
878
- var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
879
- var PRELOAD_TIMINGS_ENV = "__STRYKER_PRELOAD_TIMINGS__";
880
- var PRELOAD_TIMINGS_PREFIX = "[Stryker Timings] ";
881
- function readPreloadTimings(stderr) {
882
- const start = stderr.lastIndexOf(`
883
- ${PRELOAD_TIMINGS_PREFIX}`);
884
- if (start === -1) {
885
- return;
886
- }
887
- const jsonStart = start + 1 + PRELOAD_TIMINGS_PREFIX.length;
888
- const end = stderr.indexOf(`
889
- `, jsonStart);
890
- try {
891
- const parsed = JSON.parse(stderr.slice(jsonStart, end === -1 ? stderr.length : end));
892
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
893
- return;
894
- }
895
- return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "number"));
896
- } catch {
897
- return;
898
- }
899
- }
900
- var HIT_LIMIT_SENTINEL = "__STRYKER_HIT_LIMIT_REACHED__";
901
- var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
902
- var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
903
-
904
1884
  // src/inspector/types.ts
905
1885
  var TEST_STATUSES = ["pass", "fail", "timeout", "skip", "todo", "skipped_because_label"];
906
1886
  function isTestReporterFoundEvent(message) {
@@ -1350,10 +2330,10 @@ class InspectorClient {
1350
2330
  }
1351
2331
  }
1352
2332
  // src/parsers/console-parser.ts
1353
- import path4 from "node:path";
2333
+ import path9 from "node:path";
1354
2334
 
1355
2335
  // src/process-runner.ts
1356
- import { spawn as spawn2 } from "node:child_process";
2336
+ import { spawn as spawn3 } from "node:child_process";
1357
2337
 
1358
2338
  // src/utils/process-group.ts
1359
2339
  function killProcessGroup(pid, signal) {
@@ -1366,8 +2346,8 @@ function killProcessGroup(pid, signal) {
1366
2346
  }
1367
2347
 
1368
2348
  // src/utils/process-rss.ts
1369
- import { spawn } from "node:child_process";
1370
- import { readFile as readFile3 } from "node:fs/promises";
2349
+ import { spawn as spawn2 } from "node:child_process";
2350
+ import { readFile as readFile4 } from "node:fs/promises";
1371
2351
  async function getProcessRssBytes(pid) {
1372
2352
  return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
1373
2353
  }
@@ -1377,7 +2357,7 @@ function parseVmRss(statusContent) {
1377
2357
  }
1378
2358
  async function getLinuxRss(pid) {
1379
2359
  try {
1380
- const status = await readFile3(`/proc/${pid}/status`, "utf8");
2360
+ const status = await readFile4(`/proc/${pid}/status`, "utf8");
1381
2361
  return parseVmRss(status);
1382
2362
  } catch {
1383
2363
  return null;
@@ -1395,7 +2375,7 @@ async function getPsRss(pid) {
1395
2375
  return new Promise((resolve) => {
1396
2376
  let child;
1397
2377
  try {
1398
- child = spawn("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
2378
+ child = spawn2("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
1399
2379
  } catch {
1400
2380
  resolve(null);
1401
2381
  return;
@@ -1413,21 +2393,40 @@ async function getPsRss(pid) {
1413
2393
  });
1414
2394
  }
1415
2395
 
2396
+ // src/utils/project-dir.ts
2397
+ import path7 from "node:path";
2398
+ var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
2399
+ var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
2400
+ function recordProjectDirectory() {
2401
+ const inherited = process.env[PROJECT_DIR_ENV];
2402
+ const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
2403
+ if (isWorker && inherited !== undefined && path7.isAbsolute(inherited)) {
2404
+ return inherited;
2405
+ }
2406
+ const here = process.cwd();
2407
+ process.env[PROJECT_DIR_ENV] = here;
2408
+ return here;
2409
+ }
2410
+ var projectDirectory = recordProjectDirectory();
2411
+ function resolveAgainstProject(file) {
2412
+ return path7.resolve(projectDirectory, file);
2413
+ }
2414
+
1416
2415
  // src/utils/test-file-args.ts
1417
- import path3 from "node:path";
2416
+ import path8 from "node:path";
1418
2417
  var MAX_TEST_FILE_ARGS_BYTES = 131072;
1419
2418
  var ENTRY_OVERHEAD_BYTES = 1 + 8;
1420
2419
  var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
1421
2420
  function shortestSpelling(absolute, cwd) {
1422
- const relative = path3.relative(cwd, absolute);
2421
+ const relative = path8.relative(cwd, absolute);
1423
2422
  if (relative === "" || relative === "..") {
1424
2423
  return absolute;
1425
2424
  }
1426
- const spelled = relative.startsWith(`..${path3.sep}`) ? relative : `.${path3.sep}${relative}`;
2425
+ const spelled = relative.startsWith(`..${path8.sep}`) ? relative : `.${path8.sep}${relative}`;
1427
2426
  return spelled.length < absolute.length ? spelled : absolute;
1428
2427
  }
1429
2428
  function computeTestFileArgs(files, cwd, budget) {
1430
- const absolute = files.map((file) => path3.resolve(cwd, file));
2429
+ const absolute = files.map((file) => path8.resolve(cwd, file));
1431
2430
  const absoluteBytes = bytesOf(absolute);
1432
2431
  if (absoluteBytes <= budget) {
1433
2432
  return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
@@ -1441,7 +2440,7 @@ function sameEntries(a, b) {
1441
2440
  }
1442
2441
  var lastBuild;
1443
2442
  function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
1444
- if (!path3.isAbsolute(cwd)) {
2443
+ if (!path8.isAbsolute(cwd)) {
1445
2444
  return computeTestFileArgs(files, cwd, budget);
1446
2445
  }
1447
2446
  const cached = lastBuild;
@@ -1571,6 +2570,8 @@ function buildChildEnv(options, spawnDepth) {
1571
2570
  __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
1572
2571
  __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
1573
2572
  [SYNC_TOKEN_ENV]: options.syncToken,
2573
+ [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
2574
+ [WATCH_LIST_ENV]: options.watchList,
1574
2575
  [LIFELINE_FD_ENV]: String(LIFELINE_FD)
1575
2576
  };
1576
2577
  for (const [name, value] of Object.entries(preloadVars)) {
@@ -1581,6 +2582,7 @@ function buildChildEnv(options, spawnDepth) {
1581
2582
  }
1582
2583
  }
1583
2584
  env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
2585
+ delete env[PROJECT_DIR_ENV];
1584
2586
  if (options.profile) {
1585
2587
  delete env[PROFILE_ENV];
1586
2588
  }
@@ -1644,7 +2646,10 @@ async function spawnBunTests(options, spawnDepth) {
1644
2646
  cwd: process.cwd(),
1645
2647
  detached: true
1646
2648
  };
1647
- const childProcess = spawn2(options.bunPath, args, spawnOpts);
2649
+ try {
2650
+ options.onSpawn?.([options.bunPath, ...args]);
2651
+ } catch {}
2652
+ const childProcess = spawn3(options.bunPath, args, spawnOpts);
1648
2653
  profile?.mark("spawned");
1649
2654
  liveChildren.add(childProcess);
1650
2655
  ensureSignalCleanup();
@@ -1788,11 +2793,11 @@ function headerFilter(lines, testFiles) {
1788
2793
  if (testFiles === undefined) {
1789
2794
  return () => true;
1790
2795
  }
1791
- const roots = new Set(testFiles.map((file) => path4.resolve(file)));
2796
+ const roots = new Set(testFiles.map((file) => path9.resolve(file)));
1792
2797
  const isRunFile = (file) => {
1793
- let candidate = path4.resolve(file);
2798
+ let candidate = path9.resolve(file);
1794
2799
  while (!roots.has(candidate)) {
1795
- const parent = path4.dirname(candidate);
2800
+ const parent = path9.dirname(candidate);
1796
2801
  if (parent === candidate) {
1797
2802
  return false;
1798
2803
  }
@@ -2004,7 +3009,7 @@ ${stderr}`;
2004
3009
  blockStart: 0,
2005
3010
  lastFailed: undefined
2006
3011
  };
2007
- for (let index = 0;index < lines.length; index++) {
3012
+ for (const index of lines.keys()) {
2008
3013
  readLine(reader, index);
2009
3014
  }
2010
3015
  const summaryCounts = parseSummaryLines(output);
@@ -2026,9 +3031,303 @@ ${stderr}`;
2026
3031
  };
2027
3032
  }
2028
3033
 
3034
+ // src/parsers/unhandled-errors.ts
3035
+ var MAX_BLOCKS_SHOWN = 20;
3036
+ var MAX_DIAGNOSTIC_CHARS = 16000;
3037
+ var MAX_SNIPPET_LINE_CHARS = 300;
3038
+ var MAX_NAMED = 3;
3039
+ var MAX_NAME_CHARS = 200;
3040
+ var BLOCK_MARKER = "# Unhandled error between tests";
3041
+ var BLOCK_RULE = "-".repeat(31);
3042
+ var LATE_CALL_RE = /^error: Cannot call ([\w$.]+)\(\) after the test run has completed\.?$/;
3043
+ var FILE_HEADER_RE = new RegExp(String.raw`^(?:::group::)?((?:[a-z]:)?[^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
3044
+ var FRAME_LOCATION_RE = /^(.+):\d+:\d+$/;
3045
+ var SNIPPET_LINE_RE = /^\s*\d+ \|/;
3046
+ var SNIPPET_CARET_RE = /^\s*\^+$/;
3047
+ var isDrivePath = (path) => /^[a-z]:[\\/]/i.test(path);
3048
+ function pathKey(path) {
3049
+ return isDrivePath(path) ? `${path.charAt(0).toLowerCase()}${path.slice(1).replaceAll("\\", "/")}` : path;
3050
+ }
3051
+ function percentDecode(text) {
3052
+ try {
3053
+ return decodeURIComponent(text);
3054
+ } catch {
3055
+ return text;
3056
+ }
3057
+ }
3058
+ function locationPath(location) {
3059
+ if (/^file:\/\//i.test(location)) {
3060
+ const path = percentDecode(location.slice("file://".length).replace(/^localhost(?=\/)/i, "").replace(/\?.*/s, ""));
3061
+ return /^\/[a-z]:[\\/]/i.test(path) ? path.slice(1) : path;
3062
+ }
3063
+ return /^[a-z][\w+.-]+:/i.test(location) && !isDrivePath(location) ? undefined : location;
3064
+ }
3065
+ function frameFile(line) {
3066
+ const trimmed = line.trim();
3067
+ if (!trimmed.startsWith("at ")) {
3068
+ return;
3069
+ }
3070
+ let location = trimmed.slice(3).trim();
3071
+ const open = location.lastIndexOf(" (");
3072
+ if (open !== -1 && location.endsWith(")")) {
3073
+ location = location.slice(open + 2, -1);
3074
+ }
3075
+ const file = FRAME_LOCATION_RE.exec(location)?.[1];
3076
+ return file === undefined ? undefined : locationPath(file);
3077
+ }
3078
+ function buildBlock(printed, headerFile) {
3079
+ const body = printed.slice(printed.findIndex((line) => line !== ""), printed.findLastIndex((line) => line !== "") + 1);
3080
+ const errorLine = body.find((line) => line.startsWith("error: "));
3081
+ return {
3082
+ headerFile,
3083
+ lines: body,
3084
+ frames: body.flatMap((line) => {
3085
+ const path = frameFile(line);
3086
+ return path === undefined ? [] : [{ path, line }];
3087
+ }),
3088
+ lateCall: errorLine === undefined ? undefined : LATE_CALL_RE.exec(errorLine)?.[1]
3089
+ };
3090
+ }
3091
+ function parseUnhandledErrorBlocks(stderr, secrets = []) {
3092
+ const lines = cleanDiagnosticText(stderr, secrets).split(/\r?\n/).map((line) => line.trimEnd());
3093
+ const starts = lines.flatMap((line, i) => line === BLOCK_MARKER && lines[i + 1] === BLOCK_RULE ? [i] : []);
3094
+ const blocks = [];
3095
+ let headerFile;
3096
+ let scanned = 0;
3097
+ for (const [n, start] of starts.entries()) {
3098
+ for (const line of lines.slice(scanned, start)) {
3099
+ headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
3100
+ }
3101
+ const following = lines.slice(start + 2, starts[n + 1] ?? lines.length);
3102
+ const closingRule = following.indexOf(BLOCK_RULE);
3103
+ blocks.push(buildBlock(closingRule === -1 ? following : following.slice(0, closingRule), headerFile));
3104
+ scanned = closingRule === -1 ? start + 2 + following.length : start + 2 + closingRule + 1;
3105
+ }
3106
+ return blocks;
3107
+ }
3108
+ var isSnippetLine = (line) => SNIPPET_LINE_RE.test(line) || SNIPPET_CARET_RE.test(line);
3109
+ function renderBlock(block, index, total) {
3110
+ const heading = ` Unhandled error block ${index + 1} of ${total}:`;
3111
+ if (block.lines.length === 0) {
3112
+ const empty = `${heading}
3113
+ (empty)`;
3114
+ return { full: empty, bare: empty };
3115
+ }
3116
+ const full = [];
3117
+ const bare = [];
3118
+ let omittedRun = 0;
3119
+ const endRun = () => {
3120
+ if (omittedRun > 0) {
3121
+ bare.push(` ... [${omittedRun} source line(s) omitted]`);
3122
+ omittedRun = 0;
3123
+ }
3124
+ };
3125
+ for (const line of block.lines) {
3126
+ if (isSnippetLine(line)) {
3127
+ omittedRun++;
3128
+ full.push(line.length > MAX_SNIPPET_LINE_CHARS ? ` ${line.slice(0, MAX_SNIPPET_LINE_CHARS)}... [${line.length - MAX_SNIPPET_LINE_CHARS} more character(s) of this line omitted]` : ` ${line}`);
3129
+ } else {
3130
+ endRun();
3131
+ full.push(` ${line}`);
3132
+ bare.push(` ${line}`);
3133
+ }
3134
+ }
3135
+ endRun();
3136
+ return { full: [heading, ...full].join(`
3137
+ `), bare: [heading, ...bare].join(`
3138
+ `) };
3139
+ }
3140
+ function nameOf(text, secrets) {
3141
+ const redacted = redactSecrets(text, secrets);
3142
+ return redacted.length > MAX_NAME_CHARS ? `${redacted.slice(0, MAX_NAME_CHARS)}... [${redacted.length - MAX_NAME_CHARS} more character(s) omitted]` : redacted;
3143
+ }
3144
+ function nameList(names) {
3145
+ const shown = names.slice(0, MAX_NAMED).join(", ");
3146
+ return names.length > MAX_NAMED ? `${shown} and ${names.length - MAX_NAMED} more` : shown;
3147
+ }
3148
+ function matchesHeader(framePath, header) {
3149
+ const frame = pathKey(framePath);
3150
+ const wanted = pathKey(header).replace(/^\.\//, "");
3151
+ return frame === wanted || frame.endsWith(`/${wanted}`);
3152
+ }
3153
+ function testFileFrame(block) {
3154
+ const { headerFile, frames } = block;
3155
+ const inEffect = headerFile === undefined ? undefined : frames.find((frame) => matchesHeader(frame.path, headerFile));
3156
+ return inEffect ?? frames.find((frame) => TEST_FILE_SUFFIX_RE.test(frame.path));
3157
+ }
3158
+ function lateCalls(blocks, secrets) {
3159
+ const seen = new Set;
3160
+ return blocks.flatMap((block, index) => {
3161
+ if (block.lateCall === undefined) {
3162
+ return [];
3163
+ }
3164
+ const frame = testFileFrame(block);
3165
+ const header = block.headerFile === undefined ? undefined : nameOf(block.headerFile, secrets);
3166
+ const call = nameOf(block.lateCall, secrets);
3167
+ const key = `${call}\x00${frame?.path ?? ""}\x00${frame === undefined ? header ?? "" : ""}`;
3168
+ if (seen.has(key)) {
3169
+ return [];
3170
+ }
3171
+ seen.add(key);
3172
+ return [{ call, block: index, header, frame: frame === undefined ? undefined : { block: index, name: nameOf(frame.path, secrets), line: frame.line } }];
3173
+ });
3174
+ }
3175
+ function eagerClaims(blocks, eagerModules, secrets) {
3176
+ const eagerByKey = new Map(eagerModules.map((module) => [pathKey(module), module]));
3177
+ const seen = new Set;
3178
+ return blocks.flatMap((block, index) => block.lateCall === undefined ? block.frames.flatMap((frame) => {
3179
+ const module = eagerByKey.get(pathKey(frame.path));
3180
+ if (module === undefined || seen.has(module)) {
3181
+ return [];
3182
+ }
3183
+ seen.add(module);
3184
+ return [{ block: index, name: nameOf(module, secrets), line: frame.line }];
3185
+ }) : []);
3186
+ }
3187
+ function describeLateCall(late) {
3188
+ const error = `\`Cannot call ${late.call}() after the test run has completed\``;
3189
+ if (late.frame !== undefined) {
3190
+ return `${error} for test file ${late.frame.name} (block ${late.block + 1})`;
3191
+ }
3192
+ if (late.header !== undefined) {
3193
+ return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
3194
+ }
3195
+ return `${error} (block ${late.block + 1})`;
3196
+ }
3197
+ var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
3198
+ function lateCallSentences(lates, blocks) {
3199
+ if (lates.length === 0) {
3200
+ return [];
3201
+ }
3202
+ const named = lates.slice(0, MAX_NAMED);
3203
+ const fileKnown = named.every((late) => late.frame !== undefined);
3204
+ const consequence = fileKnown ? "bun had already ended that file's run when the call was made, so tests registered from that point were not run." : "bun's message says the call came after the test run had completed, so tests registered from that point were not run.";
3205
+ const precededByOtherBlock = blocks.findIndex((block) => block.lateCall !== undefined) > 0;
3206
+ return [
3207
+ [
3208
+ `bun reported ${nameList(lates.map((late) => describeLateCall(late)))}.`,
3209
+ consequence,
3210
+ ...precededByOtherBlock ? ["An error raised outside any test, such as those in the blocks shown, is what makes bun end a run early."] : []
3211
+ ].join(" ")
3212
+ ];
3213
+ }
3214
+ function eagerSentences(modules) {
3215
+ if (modules.length === 0) {
3216
+ return [];
3217
+ }
3218
+ const named = nameList(modules.map((claim) => `${claim.name} (block ${claim.block + 1})`));
3219
+ return [
3220
+ `Stack frames point at ${named}. The module(s) named here are in the list of files this run's coverage preload imports before any test runs: ` + "files matched by your Stryker 'mutate' globs that the tests load or name in import() or require(), and any that bun.alwaysImport keeps. " + "If no test needs one of them imported first (typically an entry point with top-level side effects), take it out of bun.alwaysImport, " + "remove the import() or require() of it that never runs, or exclude it from 'mutate' (add a '!<path>' glob) and re-run."
3221
+ ];
3222
+ }
3223
+ var CUT_NOTE_RESERVE = 200;
3224
+ var joinedLength = (parts) => parts.reduce((sum, part) => sum + part.length, 0) + Math.max(0, parts.length - 1);
3225
+ function describeUnhandledErrors(stderr, eagerModules, secrets = []) {
3226
+ const blocks = parseUnhandledErrorBlocks(stderr, secrets);
3227
+ if (blocks.length === 0) {
3228
+ return;
3229
+ }
3230
+ const lates = lateCalls(blocks, secrets);
3231
+ const modules = eagerClaims(blocks, eagerModules, secrets);
3232
+ const dropped = new Set;
3233
+ for (let attempt = 0;attempt < 8; attempt++) {
3234
+ const claims = {
3235
+ lates: lates.map((late) => late.frame !== undefined && dropped.has(keyOf(late.frame)) ? { ...late, frame: undefined } : late),
3236
+ modules: modules.filter((claim) => !dropped.has(keyOf(claim)))
3237
+ };
3238
+ const result = layOut(blocks, claims);
3239
+ const lost = [...claims.lates.slice(0, MAX_NAMED).flatMap((late) => late.frame ?? []), ...claims.modules.slice(0, MAX_NAMED)].filter((claim) => !result.shown(claim));
3240
+ if (lost.length === 0) {
3241
+ return result.text;
3242
+ }
3243
+ for (const claim of lost) {
3244
+ dropped.add(keyOf(claim));
3245
+ }
3246
+ }
3247
+ return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
3248
+ }
3249
+ function selectBlocks(blockCount, required) {
3250
+ const shown = new Set(required);
3251
+ for (let i = 0;i < blockCount && shown.size < MAX_BLOCKS_SHOWN; i++) {
3252
+ shown.add(i);
3253
+ }
3254
+ return [...shown].toSorted((a, b) => a - b);
3255
+ }
3256
+ function cutBlock(text, share) {
3257
+ const [heading, ...body] = text.split(`
3258
+ `);
3259
+ const kept = [heading];
3260
+ let used = heading.length;
3261
+ for (const line of body) {
3262
+ if (used + 1 + line.length > share) {
3263
+ if (kept.length === 1) {
3264
+ const head = Math.max(0, share - used - 1);
3265
+ kept.push(`${line.slice(0, head)}... [${line.length - head} more character(s) of this line omitted]`);
3266
+ }
3267
+ break;
3268
+ }
3269
+ used += 1 + line.length;
3270
+ kept.push(line);
3271
+ }
3272
+ const left = body.length - (kept.length - 1);
3273
+ return left > 0 ? [...kept, ` ... [${left} more line(s) of this block omitted]`].join(`
3274
+ `) : kept.join(`
3275
+ `);
3276
+ }
3277
+ function layOut(blocks, claims) {
3278
+ const named = [...claims.lates.slice(0, MAX_NAMED).map((late) => late.block), ...claims.modules.slice(0, MAX_NAMED).map((claim) => claim.block)];
3279
+ const required = new Set([0, ...named]);
3280
+ const intro = `bun's stderr holds ${blocks.length} "Unhandled error between tests" block(s), errors raised outside any individual test:`;
3281
+ let selected = selectBlocks(blocks.length, required);
3282
+ const texts = new Map(selected.map((index) => [index, renderBlock(blocks[index], index, blocks.length)]));
3283
+ const noSnippets = new Set;
3284
+ const shownText = (index) => noSnippets.has(index) ? texts.get(index).bare : texts.get(index).full;
3285
+ const summary = [
3286
+ ...lateCallSentences(claims.lates, blocks),
3287
+ ...eagerSentences(claims.modules)
3288
+ ];
3289
+ const parts = () => {
3290
+ const omitted = blocks.length - selected.length;
3291
+ return [
3292
+ intro,
3293
+ ...selected.map((index) => shownText(index)),
3294
+ ...omitted > 0 ? [` ... [${omitted} more block(s) omitted]`] : [],
3295
+ ...summary
3296
+ ];
3297
+ };
3298
+ const fits = () => joinedLength(parts()) <= MAX_DIAGNOSTIC_CHARS;
3299
+ for (const index of selected.toReversed()) {
3300
+ if (fits()) {
3301
+ break;
3302
+ }
3303
+ noSnippets.add(index);
3304
+ }
3305
+ for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
3306
+ if (fits()) {
3307
+ break;
3308
+ }
3309
+ selected = selected.filter((index) => index !== dropped);
3310
+ }
3311
+ if (!fits()) {
3312
+ const outside = parts().filter((_, position) => position === 0 || position > selected.length);
3313
+ const share = Math.max(0, Math.floor((MAX_DIAGNOSTIC_CHARS - joinedLength(outside) - selected.length) / selected.length) - CUT_NOTE_RESERVE);
3314
+ for (const index of selected) {
3315
+ const text = texts.get(index).bare;
3316
+ texts.set(index, { full: text, bare: cutBlock(text, share) });
3317
+ }
3318
+ }
3319
+ const shownLines = new Map(selected.map((index) => [index, new Set(shownText(index).split(`
3320
+ `))]));
3321
+ return {
3322
+ text: parts().join(`
3323
+ `),
3324
+ shown: (claim) => shownLines.get(claim.block).has(` ${claim.line}`)
3325
+ };
3326
+ }
3327
+
2029
3328
  // src/run-profile.ts
2030
3329
  import { appendFileSync as appendFileSync2 } from "node:fs";
2031
- import path5 from "node:path";
3330
+ import path10 from "node:path";
2032
3331
  import { StringDecoder } from "node:string_decoder";
2033
3332
  var PROFILE_FORMAT_VERSION = 1;
2034
3333
  var SPAWN_MARKS = ["spawnStart", "spawned", "firstStderr", "inspector", "firstFile", "decisive", "exit", "close"];
@@ -2162,6 +3461,7 @@ class RunProfile {
2162
3461
  scope;
2163
3462
  files;
2164
3463
  patternBytes;
3464
+ launches = 0;
2165
3465
  constructor(owner, kind, mutantId, clock) {
2166
3466
  this.owner = owner;
2167
3467
  this.kind = kind;
@@ -2170,6 +3470,15 @@ class RunProfile {
2170
3470
  this.requestedAt = clock.now();
2171
3471
  this.scope = kind === "dry" ? "dry" : undefined;
2172
3472
  }
3473
+ countLaunch() {
3474
+ this.launches++;
3475
+ }
3476
+ restartLaunch() {
3477
+ this.spawnStates.length = 0;
3478
+ for (const name of Object.keys(this.details)) {
3479
+ delete this.details[name];
3480
+ }
3481
+ }
2173
3482
  setScope(scope) {
2174
3483
  this.scope = scope;
2175
3484
  }
@@ -2282,6 +3591,7 @@ class RunProfile {
2282
3591
  files: this.files,
2283
3592
  patternBytes: this.patternBytes,
2284
3593
  spawns: this.spawnStates.length,
3594
+ launches: this.kind === "dry" ? this.launches : undefined,
2285
3595
  bail: last?.bail,
2286
3596
  decisive: last?.decisive,
2287
3597
  fileHeaders: last?.fileHeaders,
@@ -2375,7 +3685,7 @@ function createWorkerProfiler(logger, env = process.env) {
2375
3685
  if (value === undefined || value === "" || value === "0" || value === "false") {
2376
3686
  return;
2377
3687
  }
2378
- if (!path5.isAbsolute(value)) {
3688
+ if (!path10.isAbsolute(value)) {
2379
3689
  logger.warn("%s must be the absolute path of a JSONL file to append to (got %s); profiling is off", PROFILE_ENV, value);
2380
3690
  return;
2381
3691
  }
@@ -2474,7 +3784,7 @@ function assertSupportedBunArgs(bunArgs) {
2474
3784
  throw new Error(`stryker-bun-runner: bun.bunArgs contains unsupported flags: ${list}. Remove them.`);
2475
3785
  }
2476
3786
  // src/utils/bun-version.ts
2477
- import { spawn as spawn3 } from "node:child_process";
3787
+ import { spawn as spawn4 } from "node:child_process";
2478
3788
  var MIN_BUN_VERSION = "1.4.0";
2479
3789
  var VERSION_CHECK_TIMEOUT_MS = 1e4;
2480
3790
  function parseBunVersion(output) {
@@ -2493,7 +3803,7 @@ function compareVersions(a, b) {
2493
3803
  function probeBunVersion(bunPath, env, timeoutMs) {
2494
3804
  return new Promise((resolve) => {
2495
3805
  try {
2496
- const child = spawn3(bunPath, ["--version"], {
3806
+ const child = spawn4(bunPath, ["--version"], {
2497
3807
  env: { ...process.env, ...env },
2498
3808
  stdio: ["ignore", "pipe", "pipe"]
2499
3809
  });
@@ -2540,7 +3850,7 @@ async function checkBunVersion(bunPath, env, timeoutMs = VERSION_CHECK_TIMEOUT_M
2540
3850
  return version;
2541
3851
  }
2542
3852
  // src/utils/sync-server.ts
2543
- import { randomBytes, timingSafeEqual } from "node:crypto";
3853
+ import { randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
2544
3854
  import { createRequire } from "node:module";
2545
3855
  import { WebSocketServer, WebSocket as WebSocket3 } from "ws";
2546
3856
  var { createServer } = createRequire(import.meta.url)("node:http");
@@ -2559,7 +3869,7 @@ function rawDataToString(data) {
2559
3869
  }
2560
3870
 
2561
3871
  class SyncServer {
2562
- token = randomBytes(16).toString("hex");
3872
+ token = randomBytes3(16).toString("hex");
2563
3873
  httpServer = null;
2564
3874
  wss = null;
2565
3875
  clients = new Set;
@@ -2696,8 +4006,8 @@ class SyncServer {
2696
4006
  }
2697
4007
  }
2698
4008
  // src/utils/bunfig-sanitizer.ts
2699
- import { readFile as readFile4, unlink as unlink3 } from "node:fs/promises";
2700
- import path6 from "node:path";
4009
+ import { readFile as readFile5, unlink as unlink3 } from "node:fs/promises";
4010
+ import path11 from "node:path";
2701
4011
  import { parse, stringify } from "smol-toml";
2702
4012
  var SAFE_TEST_KEYS = new Set([
2703
4013
  "preload",
@@ -2731,7 +4041,7 @@ function absolutizePath(value, projectCwd) {
2731
4041
  if (typeof value !== "string") {
2732
4042
  return value;
2733
4043
  }
2734
- return path6.isAbsolute(value) ? value : path6.resolve(projectCwd, value);
4044
+ return path11.isAbsolute(value) ? value : path11.resolve(projectCwd, value);
2735
4045
  }
2736
4046
  function absolutizePathValue(value, projectCwd) {
2737
4047
  if (Array.isArray(value)) {
@@ -2740,9 +4050,9 @@ function absolutizePathValue(value, projectCwd) {
2740
4050
  return absolutizePath(value, projectCwd);
2741
4051
  }
2742
4052
  async function readSourceBunfig(projectCwd, sourceBunfig) {
2743
- const bunfigPath = sourceBunfig === undefined ? path6.join(projectCwd, "bunfig.toml") : path6.resolve(projectCwd, sourceBunfig);
4053
+ const bunfigPath = sourceBunfig === undefined ? path11.join(projectCwd, "bunfig.toml") : path11.resolve(projectCwd, sourceBunfig);
2744
4054
  try {
2745
- const content = await readFile4(bunfigPath, "utf8");
4055
+ const content = await readFile5(bunfigPath, "utf8");
2746
4056
  return parse(content);
2747
4057
  } catch (err) {
2748
4058
  if (sourceBunfig === undefined && err.code === "ENOENT") {
@@ -2752,15 +4062,63 @@ async function readSourceBunfig(projectCwd, sourceBunfig) {
2752
4062
  throw new Error(`Failed to read ${what} at ${bunfigPath}: ${String(err)}`, { cause: err });
2753
4063
  }
2754
4064
  }
2755
- async function readBunfigTestRoot(projectCwd, sourceBunfig) {
2756
- const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
2757
- const root = rawConfig.test?.root;
2758
- return typeof root === "string" ? path6.resolve(projectCwd, root) : undefined;
4065
+ async function readBunfigTestRoot(projectCwd, sourceBunfig) {
4066
+ const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
4067
+ const root = rawConfig.test?.root;
4068
+ return typeof root === "string" ? path11.resolve(projectCwd, root) : undefined;
4069
+ }
4070
+ async function readBunfigTestPreloads(projectCwd, sourceBunfig) {
4071
+ return testPreloadsOf(await readSourceBunfig(projectCwd, sourceBunfig), projectCwd);
4072
+ }
4073
+ function testPreloadsOf(rawConfig, projectCwd) {
4074
+ const preload = rawConfig.test?.preload;
4075
+ return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path11.resolve(projectCwd, entry));
4076
+ }
4077
+ var SCAN_NEUTRAL_BUNFIG_KEYS = new Set(["preload", "smol", "logLevel", "telemetry", "env", "console", "serve", "install", "run", "conditions", "test"]);
4078
+ var JSX_BUNFIG_KEYS = new Set(["jsx", "jsxImportSource", "jsxFactory", "jsxFragment"]);
4079
+ function isLiteralDefine(value) {
4080
+ if (typeof value !== "string") {
4081
+ return false;
4082
+ }
4083
+ if (value === "undefined" || /^'[^']*'$/.test(value)) {
4084
+ return true;
4085
+ }
4086
+ try {
4087
+ const parsed = JSON.parse(value);
4088
+ return parsed === null || ["string", "number", "boolean"].includes(typeof parsed);
4089
+ } catch {
4090
+ return false;
4091
+ }
4092
+ }
4093
+ function topLevelScanProblem(key, value) {
4094
+ if (key === "loader") {
4095
+ return isTable(value) && Object.keys(value).length === 0 ? undefined : "the bunfig's [loader] maps file extensions to loaders, which the import scan does not model";
4096
+ }
4097
+ if (key === "define") {
4098
+ const expression = isTable(value) ? Object.entries(value).find(([, replacement]) => !isLiteralDefine(replacement)) : [key, value];
4099
+ return expression === undefined ? undefined : `the bunfig's define replaces ${JSON.stringify(expression[0])} with ${JSON.stringify(expression[1])}, an expression the import scan does not model`;
4100
+ }
4101
+ if (JSX_BUNFIG_KEYS.has(key)) {
4102
+ return `the bunfig sets ${key}, which chooses the JSX runtime the tests import, and the import scan does not read the bunfig`;
4103
+ }
4104
+ return SCAN_NEUTRAL_BUNFIG_KEYS.has(key) ? undefined : `the bunfig sets ${JSON.stringify(key)}, which the import scan does not know, so it cannot tell whether it changes what the tests load or how their imports resolve`;
4105
+ }
4106
+ function bunfigScanProblem(rawConfig) {
4107
+ for (const [key, value] of Object.entries(rawConfig)) {
4108
+ const problem = topLevelScanProblem(key, value);
4109
+ if (problem !== undefined) {
4110
+ return problem;
4111
+ }
4112
+ }
4113
+ const ignored = isTable(rawConfig.test) ? rawConfig.test.pathIgnorePatterns : undefined;
4114
+ if (ignored !== undefined && [ignored].flat().length > 0) {
4115
+ return "the bunfig's [test].pathIgnorePatterns makes bun skip matching test files even when the runner names them, and the runner does not reproduce bun's matching";
4116
+ }
4117
+ return;
2759
4118
  }
2760
- async function readBunfigTestPreloads(projectCwd, sourceBunfig) {
4119
+ async function readBunfigForScan(projectCwd, sourceBunfig) {
2761
4120
  const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
2762
- const preload = rawConfig.test?.preload;
2763
- return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path6.resolve(projectCwd, entry));
4121
+ return { preloads: testPreloadsOf(rawConfig, projectCwd), problem: bunfigScanProblem(rawConfig) };
2764
4122
  }
2765
4123
  function sanitizeTestSection(sourceTest, projectCwd, dropped) {
2766
4124
  const sanitizedTest = {};
@@ -2796,7 +4154,7 @@ async function generateSanitizedBunfig(projectCwd, tmpDir, sourceBunfig, onDropp
2796
4154
  dropped.push({ key: `test.${key}`, reason: RANDOM_ORDER_REASON, warn: false, mutantRunsOnly: true });
2797
4155
  }
2798
4156
  onDropped?.(dropped);
2799
- const outPath = path6.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
4157
+ const outPath = path11.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
2800
4158
  await writePrivateFile(outPath, stringify(sanitized));
2801
4159
  const mutantRunTest = { ...sanitizedTest, onlyFailures: true };
2802
4160
  if (randomOrderKeys.length > 0) {
@@ -2820,8 +4178,8 @@ async function cleanupSanitizedBunfig(filePath) {
2820
4178
  await unlinkIfPresent(mutantRunBunfigPath(filePath));
2821
4179
  }
2822
4180
  // src/utils/test-file-discovery.ts
2823
- import * as fsPromises from "node:fs/promises";
2824
- import path7 from "node:path";
4181
+ import * as fsPromises2 from "node:fs/promises";
4182
+ import path12 from "node:path";
2825
4183
  function isExcludedDirName(name) {
2826
4184
  return name.startsWith(".") || name.toLowerCase() === "node_modules";
2827
4185
  }
@@ -2831,14 +4189,14 @@ function hasExcludedAncestor(absolutePath) {
2831
4189
  }
2832
4190
  async function tryRealpath(p) {
2833
4191
  try {
2834
- return await fsPromises.realpath(p);
4192
+ return await fsPromises2.realpath(p);
2835
4193
  } catch {
2836
4194
  return;
2837
4195
  }
2838
4196
  }
2839
4197
  async function tryStat(p) {
2840
4198
  try {
2841
- return await fsPromises.stat(p);
4199
+ return await fsPromises2.stat(p);
2842
4200
  } catch {
2843
4201
  return;
2844
4202
  }
@@ -2867,7 +4225,7 @@ async function handleSymlinkFile(fullPath, entryName, ctx) {
2867
4225
  }
2868
4226
  const resolvedTarget = await tryRealpath(fullPath);
2869
4227
  if (resolvedTarget && !hasExcludedAncestor(resolvedTarget)) {
2870
- ctx.results.push(path7.relative(ctx.cwd, fullPath));
4228
+ ctx.results.push(path12.relative(ctx.cwd, fullPath));
2871
4229
  }
2872
4230
  }
2873
4231
  async function handleSymlink(fullPath, entryName, ctx) {
@@ -2883,7 +4241,7 @@ async function handleSymlink(fullPath, entryName, ctx) {
2883
4241
  }
2884
4242
  }
2885
4243
  async function processEntry(entry, dir, ctx) {
2886
- const fullPath = path7.join(dir, entry.name);
4244
+ const fullPath = path12.join(dir, entry.name);
2887
4245
  if (entry.isDirectory()) {
2888
4246
  if (!isExcludedDirName(entry.name)) {
2889
4247
  await ctx.walk(fullPath);
@@ -2891,10 +4249,20 @@ async function processEntry(entry, dir, ctx) {
2891
4249
  } else if (entry.isSymbolicLink()) {
2892
4250
  await handleSymlink(fullPath, entry.name, ctx);
2893
4251
  } else if (entry.isFile() && TEST_FILE_SUFFIX_RE.test(entry.name)) {
2894
- ctx.results.push(path7.relative(ctx.cwd, fullPath));
4252
+ ctx.results.push(path12.relative(ctx.cwd, fullPath));
2895
4253
  }
2896
4254
  }
2897
4255
  async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
4256
+ const walkRoot = await readBunfigTestRoot(cwd, sourceBunfig) ?? cwd;
4257
+ const results = await walkTestFiles(walkRoot, cwd, logger);
4258
+ if (results.length === 0) {
4259
+ logger?.warn("discoverTestFiles: no test files found in %s; falling back to Bun discovery", walkRoot);
4260
+ return;
4261
+ }
4262
+ logger?.debug("discoverTestFiles: found %d test files in %s", results.length, cwd);
4263
+ return results;
4264
+ }
4265
+ async function walkTestFiles(walkRoot, cwd, logger) {
2898
4266
  const results = [];
2899
4267
  const visitedRealPaths = new Set;
2900
4268
  const ctx = { cwd, results, visitedRealPaths, logger, walk };
@@ -2910,7 +4278,7 @@ async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
2910
4278
  visitedRealPaths.add(realDir);
2911
4279
  let entries;
2912
4280
  try {
2913
- entries = await fsPromises.readdir(dir, { withFileTypes: true });
4281
+ entries = await fsPromises2.readdir(dir, { withFileTypes: true });
2914
4282
  } catch {
2915
4283
  return;
2916
4284
  }
@@ -2919,16 +4287,29 @@ async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
2919
4287
  await processEntry(entry, dir, ctx);
2920
4288
  }
2921
4289
  }
2922
- const walkRoot = await readBunfigTestRoot(cwd, sourceBunfig) ?? cwd;
2923
4290
  await walk(walkRoot);
2924
- if (results.length === 0) {
2925
- logger?.warn("discoverTestFiles: no test files found in %s; falling back to Bun discovery", walkRoot);
2926
- return;
2927
- }
2928
4291
  results.sort((a, b) => a.localeCompare(b));
2929
- logger?.debug("discoverTestFiles: found %d test files in %s", results.length, cwd);
2930
4292
  return results;
2931
4293
  }
4294
+ async function expandTestFileEntries(entries, cwd, logger) {
4295
+ const expanded = await Promise.all(entries.map(async (entry) => {
4296
+ const absolute = path12.resolve(cwd, entry);
4297
+ const stat = await tryStat(absolute);
4298
+ if (stat?.isFile()) {
4299
+ return [absolute];
4300
+ }
4301
+ if (stat?.isDirectory()) {
4302
+ const found = await walkTestFiles(absolute, cwd, logger);
4303
+ return found.map((file) => path12.resolve(cwd, file));
4304
+ }
4305
+ return entry;
4306
+ }));
4307
+ const missing = expanded.find((item) => typeof item === "string");
4308
+ if (missing !== undefined) {
4309
+ return { problem: `the test file entry ${missing} is neither an existing file nor an existing directory` };
4310
+ }
4311
+ return { files: [...new Set(expanded.flat())] };
4312
+ }
2932
4313
  // src/utils/mutant-warn-aggregator.ts
2933
4314
  var MAX_LISTED_MUTANT_IDS = 5;
2934
4315
 
@@ -2958,7 +4339,7 @@ class MutantWarnAggregator {
2958
4339
  }
2959
4340
  }
2960
4341
  // src/utils/likely-killer-order.ts
2961
- import path8 from "node:path";
4342
+ import path13 from "node:path";
2962
4343
  var MUTANT_SWITCH_RE = /stryMutAct_9fa48\("([^"\\]+)"\)/g;
2963
4344
  function mutantIdsInInstrumentedSource(code) {
2964
4345
  return new Set(Array.from(code.matchAll(MUTANT_SWITCH_RE), (match) => match[1]));
@@ -3033,8 +4414,8 @@ function namedAfter(sourceFile) {
3033
4414
  if (sourceFile === undefined) {
3034
4415
  return () => false;
3035
4416
  }
3036
- const sourceStem = path8.parse(sourceFile).name.toLowerCase();
3037
- return (testFile) => path8.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
4417
+ const sourceStem = path13.parse(sourceFile).name.toLowerCase();
4418
+ return (testFile) => path13.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
3038
4419
  }
3039
4420
  function compareKillerRanks(a, b) {
3040
4421
  return a.coverage - b.coverage || b.sourceMutants - a.sourceMutants || Number(b.namedAfter) - Number(a.namedAfter);
@@ -3043,6 +4424,134 @@ function orderLikelyKillersFirst(files, rankOf) {
3043
4424
  const ranks = new Map(files.map((file) => [file, rankOf(file)]));
3044
4425
  return files.toSorted((a, b) => compareKillerRanks(ranks.get(a), ranks.get(b)));
3045
4426
  }
4427
+ // src/utils/dry-run-output-log.ts
4428
+ import { randomUUID } from "node:crypto";
4429
+ import { lstat as lstat2, mkdir as mkdir2, open, rename as rename2, rm as rm4 } from "node:fs/promises";
4430
+ import path14 from "node:path";
4431
+ var MAX_LOG_STREAM_CHARS = 16 * 1024 * 1024;
4432
+ var MAX_LOG_COMMAND_CHARS = 4000;
4433
+ function capStream(text, max) {
4434
+ if (text.length <= max) {
4435
+ return { text, cut: 0 };
4436
+ }
4437
+ const head = Math.floor(max / 2);
4438
+ const tail = max - head;
4439
+ const cut = text.length - max;
4440
+ return { text: `${text.slice(0, head)}
4441
+ [... ${cut} characters omitted here: the size cap is ${max} characters per stream; the first ${head} and the last ${tail} are kept ...]
4442
+ ${text.slice(-tail)}`, cut };
4443
+ }
4444
+ var quoteArg = (arg) => /^[\w@%+=:,./-]+$/.test(arg) ? arg : JSON.stringify(arg);
4445
+ function describeStream(name, original, cut, max, incomplete) {
4446
+ const parts = [`${original} characters${incomplete ? " captured" : ""}`];
4447
+ if (incomplete) {
4448
+ parts.push("INCOMPLETE capture (not the whole output)");
4449
+ }
4450
+ if (cut > 0) {
4451
+ parts.push(`CUT to ${max} (${cut} omitted from the middle, see the marker in the text)`);
4452
+ }
4453
+ if (!incomplete && cut === 0) {
4454
+ parts.push("saved in full");
4455
+ }
4456
+ return `${name}: ${parts.join(", ")}`;
4457
+ }
4458
+ function formatDryRunOutputLog(output, now, maxStreamChars = MAX_LOG_STREAM_CHARS) {
4459
+ const clean = (text) => cleanDiagnosticText(text, output.secrets);
4460
+ const stdout = clean(output.stdout);
4461
+ const stderr = clean(output.stderr);
4462
+ const cappedStdout = capStream(stdout, maxStreamChars);
4463
+ const cappedStderr = capStream(stderr, maxStreamChars);
4464
+ const incomplete = output.outputIncomplete === true;
4465
+ const fullCommand = (output.command ?? []).map((arg) => quoteArg(clean(arg))).join(" ") || "(not recorded)";
4466
+ const command = fullCommand.length > MAX_LOG_COMMAND_CHARS ? `${fullCommand.slice(0, MAX_LOG_COMMAND_CHARS)}... [${fullCommand.length - MAX_LOG_COMMAND_CHARS} more characters omitted]` : fullCommand;
4467
+ const ended = output.signal ? `terminated by signal ${output.signal}` : `exit code ${output.exitCode ?? "none"}`;
4468
+ return [
4469
+ "stryker-bun-runner: output of the dry run's bun test process",
4470
+ "Written because the dry run's data-completeness check failed and the bun.dryRunOutputFile option is set; the next such failure replaces this file. The error message holds only a bounded part of this.",
4471
+ `Time: ${now.toISOString()}`,
4472
+ `Bun version: ${output.bunVersion ?? "unknown"}`,
4473
+ `Working directory: ${clean(output.cwd)}`,
4474
+ `Command: ${command}`,
4475
+ `Ended: ${ended}`,
4476
+ ...incomplete ? ["Output capture: INCOMPLETE. bun test exited, but its stdout or stderr was still held open by a process it started, so the runner stopped reading; the text below may be missing its end."] : [],
4477
+ "Removed from this file: ANSI colour codes, the paths of inspector ws:// addresses, the fragment of debug.bun.sh links and this run's tokens. Nothing else: whatever the tests or the command line print, credentials included, is here as printed.",
4478
+ describeStream("stdout", stdout.length, cappedStdout.cut, maxStreamChars, incomplete),
4479
+ describeStream("stderr", stderr.length, cappedStderr.cut, maxStreamChars, incomplete),
4480
+ "",
4481
+ "===== stdout =====",
4482
+ cappedStdout.text,
4483
+ "",
4484
+ "===== stderr =====",
4485
+ cappedStderr.text,
4486
+ ""
4487
+ ].join(`
4488
+ `);
4489
+ }
4490
+ async function checkTarget(file) {
4491
+ let existing;
4492
+ try {
4493
+ existing = await lstat2(file);
4494
+ } catch (error) {
4495
+ if (error.code === "ENOENT") {
4496
+ return;
4497
+ }
4498
+ throw error;
4499
+ }
4500
+ if (existing.isSymbolicLink()) {
4501
+ throw new Error(`refusing to write through a symbolic link at ${file}`);
4502
+ }
4503
+ if (!existing.isFile()) {
4504
+ throw new Error(`${file} exists and is not a regular file`);
4505
+ }
4506
+ }
4507
+ function throwIfAbandoned(signal) {
4508
+ if (signal?.aborted) {
4509
+ throw new Error("saving was abandoned");
4510
+ }
4511
+ }
4512
+ function errorText(error) {
4513
+ try {
4514
+ return error instanceof Error ? error.message : String(error);
4515
+ } catch {
4516
+ return "an error that cannot be converted to text";
4517
+ }
4518
+ }
4519
+ function oneLine(error) {
4520
+ return escapeControlCharacters(errorText(error).replaceAll(/\s+/g, " ").trim());
4521
+ }
4522
+ async function saveDryRunOutput(file, output, options = {}) {
4523
+ try {
4524
+ const text = formatDryRunOutputLog(output, new Date(options.now ?? Date.now()), options.maxStreamChars);
4525
+ const directory = path14.dirname(file);
4526
+ await mkdir2(directory, { recursive: true });
4527
+ throwIfAbandoned(options.signal);
4528
+ await checkTarget(file);
4529
+ const temporary = path14.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
4530
+ const handle = await open(temporary, "wx", 384);
4531
+ try {
4532
+ try {
4533
+ await (options.write ?? ((target, data) => target.writeFile(data, "utf8")))(handle, text);
4534
+ await handle.chmod(384).catch(() => {
4535
+ return;
4536
+ });
4537
+ } finally {
4538
+ await handle.close().catch(() => {
4539
+ return;
4540
+ });
4541
+ }
4542
+ throwIfAbandoned(options.signal);
4543
+ await rename2(temporary, file);
4544
+ } catch (error) {
4545
+ await rm4(temporary).catch(() => {
4546
+ return;
4547
+ });
4548
+ throw error;
4549
+ }
4550
+ return { path: file };
4551
+ } catch (error) {
4552
+ return { error: redactSecrets(oneLine(error), output.secrets) };
4553
+ }
4554
+ }
3046
4555
  // src/bun-test-runner.ts
3047
4556
  function createInspectorUrlWaiter() {
3048
4557
  let url = null;
@@ -3112,7 +4621,7 @@ function formatDrainSettleReason(reason) {
3112
4621
  function formatSpawnErrorMessage(spawnError) {
3113
4622
  return `could not start bun test: ${spawnError}`;
3114
4623
  }
3115
- function formatInspectorTimeoutMessage(inspectorTimeoutMs, child) {
4624
+ function formatInspectorTimeoutMessage(inspectorTimeoutMs, child, secrets) {
3116
4625
  if (child.spawnError !== undefined) {
3117
4626
  return formatSpawnErrorMessage(child.spawnError);
3118
4627
  }
@@ -3121,10 +4630,10 @@ function formatInspectorTimeoutMessage(inspectorTimeoutMs, child) {
3121
4630
  ended = "killed by the runner after the run timeout (bun.timeout)";
3122
4631
  }
3123
4632
  const prefix = `Timeout waiting for inspector URL after ${inspectorTimeoutMs}ms (raise bun.inspectorTimeout if bun is slow to start)`;
3124
- return `${prefix}; bun test ${ended}; last stderr: ${formatStderrTail(child)}`;
4633
+ return `${prefix}; bun test ${ended}; last stderr: ${formatStderrTail(child, secrets)}`;
3125
4634
  }
3126
- function formatStderrTail(child) {
3127
- const tail = child.stderr.trim().slice(-1000) || "(empty)";
4635
+ function formatStderrTail(child, secrets) {
4636
+ const tail = cleanDiagnosticText(child.stderr, secrets).trim().slice(-1000) || "(empty)";
3128
4637
  return child.outputIncomplete ? `${tail} (possibly cut short: ${formatOutputIncomplete()})` : tail;
3129
4638
  }
3130
4639
  function redactInspectorUrl(url) {
@@ -3134,8 +4643,8 @@ function redactInspectorUrl(url) {
3134
4643
  function formatOutputIncomplete() {
3135
4644
  return `bun test exited, but its output was still held open ${STDIO_CLOSE_GRACE_MS}ms later by a process it started, so the run did not wait for the rest`;
3136
4645
  }
3137
- function formatInspectorConnectMessage(error, child) {
3138
- return `Failed to connect to Bun inspector: ${error}; last stderr: ${formatStderrTail(child)}`;
4646
+ function formatInspectorConnectMessage(error, child, secrets) {
4647
+ return `Failed to connect to Bun inspector: ${error}; last stderr: ${formatStderrTail(child, secrets)}`;
3139
4648
  }
3140
4649
  function collectAbnormalDrainProblems(data) {
3141
4650
  const problems = [];
@@ -3151,6 +4660,32 @@ function collectAbnormalDrainProblems(data) {
3151
4660
  }
3152
4661
  return problems;
3153
4662
  }
4663
+ function nonEmptyString(value) {
4664
+ return typeof value === "string" && value !== "" ? value : undefined;
4665
+ }
4666
+ var SAVE_TIME_LIMIT_MS = 5000;
4667
+ var OUTPUT_FILE_HINT = "To save the full output of the bun test process when this happens, set the bun.dryRunOutputFile option to a file path in your Stryker configuration and run again.";
4668
+ var REGISTRY_FILE = "registry.json";
4669
+
4670
+ class WriteFailure extends Error {
4671
+ file;
4672
+ constructor(file, cause) {
4673
+ super(errorText(cause), { cause });
4674
+ this.file = file;
4675
+ }
4676
+ }
4677
+ async function writingTo(file, write) {
4678
+ try {
4679
+ return await write();
4680
+ } catch (error) {
4681
+ throw new WriteFailure(file, error);
4682
+ }
4683
+ }
4684
+ var MISSING_COVERAGE_FOR_RULE_3_3 = "the run that publishes left no coverage data, so the runner cannot check that it reached every mutant the plain run of the tests reached";
4685
+ var RUN_ORDINALS = ["first", "second", "third"];
4686
+ function isGreen(result) {
4687
+ return result.status === DryRunStatus.Complete && !result.tests.some((test) => test.status === TestStatus.Failed);
4688
+ }
3154
4689
  function buildTestNameIndex(tests, bunNames) {
3155
4690
  const testNameIndex = new Map;
3156
4691
  for (const [i, test] of tests.entries()) {
@@ -3162,6 +4697,17 @@ function buildTestNameIndex(tests, bunNames) {
3162
4697
  return testNameIndex;
3163
4698
  }
3164
4699
  var ZERO_MATCH_TEST_PATTERN_RE = /matched 0 tests\./;
4700
+ var CHILD_EXIT_WAIT_MS = 5000;
4701
+ async function awaitChildExit(child, limitMs) {
4702
+ let timer;
4703
+ try {
4704
+ await Promise.race([child, new Promise((resolve) => {
4705
+ timer = setTimeout(resolve, limitMs);
4706
+ })]);
4707
+ } catch {} finally {
4708
+ clearTimeout(timer);
4709
+ }
4710
+ }
3165
4711
  function defaultFailureMessage(testInfo) {
3166
4712
  return testInfo.status === "timeout" ? "Test timed out" : "Test failed";
3167
4713
  }
@@ -3236,7 +4782,7 @@ function emptyMutantRunCounts() {
3236
4782
  };
3237
4783
  }
3238
4784
  function newHitLimitToken() {
3239
- return randomBytes2(16).toString("hex");
4785
+ return randomBytes4(16).toString("hex");
3240
4786
  }
3241
4787
  function readReportedHitCount(stderr, token) {
3242
4788
  const match = new RegExp(String.raw`^${HIT_LIMIT_SENTINEL} ${token} (\d+)$`, "m").exec(stderr);
@@ -3276,6 +4822,7 @@ class BunTestRunner {
3276
4822
  maxChildRss;
3277
4823
  rssCheckIntervalMs;
3278
4824
  maxSpawnDepth;
4825
+ dryRunOutputFile;
3279
4826
  coverageAnalysis;
3280
4827
  preloadScriptPath;
3281
4828
  coverageFilePath;
@@ -3305,6 +4852,14 @@ class BunTestRunner {
3305
4852
  mutantRunsByStatus = emptyMutantRunCounts();
3306
4853
  fullSuiteFallbacks = 0;
3307
4854
  profiler;
4855
+ alwaysImport;
4856
+ importDiscovery;
4857
+ incremental;
4858
+ inPlace;
4859
+ timeoutCorrectionMs;
4860
+ loggedUnusableCorrection = false;
4861
+ campaign;
4862
+ warnedWatchListProblem = false;
3308
4863
  currentAbortController;
3309
4864
  constructor(logger, options) {
3310
4865
  this.logger = logger;
@@ -3322,6 +4877,7 @@ class BunTestRunner {
3322
4877
  this.maxChildRss = bunOptions.maxChildRss;
3323
4878
  this.rssCheckIntervalMs = bunOptions.rssCheckIntervalMs;
3324
4879
  this.maxSpawnDepth = bunOptions.maxSpawnDepth;
4880
+ this.dryRunOutputFile = nonEmptyString(bunOptions.dryRunOutputFile);
3325
4881
  if (bunOptions.testFiles?.length === 0) {
3326
4882
  this.logger.warn("bun.testFiles was set to an empty array — treating as undefined and falling back to auto-discovery");
3327
4883
  this.testFilesOverride = undefined;
@@ -3331,6 +4887,10 @@ class BunTestRunner {
3331
4887
  this.mutateGlobs = options.mutate ?? [];
3332
4888
  this.coverageAnalysis = options.coverageAnalysis;
3333
4889
  this.disableBail = options.disableBail;
4890
+ this.incremental = options.incremental === true;
4891
+ this.inPlace = options.inPlace === true;
4892
+ this.alwaysImport = bunOptions.alwaysImport;
4893
+ this.importDiscovery = bunOptions.importDiscovery;
3334
4894
  this.mutantWarnings = new MutantWarnAggregator(logger);
3335
4895
  this.profiler = createWorkerProfiler(logger);
3336
4896
  this.logger.debug("BunTestRunner initialized with options: %o", {
@@ -3342,9 +4902,10 @@ class BunTestRunner {
3342
4902
  smol: this.smol,
3343
4903
  maxChildRss: this.maxChildRss,
3344
4904
  rssCheckIntervalMs: this.rssCheckIntervalMs,
3345
- maxSpawnDepth: this.maxSpawnDepth
4905
+ maxSpawnDepth: this.maxSpawnDepth,
4906
+ dryRunOutputFile: this.dryRunOutputFile
3346
4907
  });
3347
- if (this.testFilesOverride?.some((p) => path9.isAbsolute(p))) {
4908
+ if (this.testFilesOverride?.some((p) => path15.isAbsolute(p))) {
3348
4909
  const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
3349
4910
  if (isSandbox) {
3350
4911
  this.logger.warn("bun.testFiles contains absolute path(s) and the current working directory appears to be a Stryker sandbox (%s). " + "Absolute paths point at the ORIGINAL (unmutated) source files — mutations will be silently bypassed. " + "Use relative paths so that Bun resolves them against the sandbox copy.", process.cwd());
@@ -3353,7 +4914,7 @@ class BunTestRunner {
3353
4914
  }
3354
4915
  async resolveRegistryPath() {
3355
4916
  this.assertRunOwnerIsParent();
3356
- return path9.join(await resolveRunTempDir(), "registry.json");
4917
+ return path15.join(await resolveRunTempDir(), REGISTRY_FILE);
3357
4918
  }
3358
4919
  assertRunOwnerIsParent() {
3359
4920
  if (this.runOwnerPid !== undefined && process.ppid !== this.runOwnerPid) {
@@ -3445,7 +5006,7 @@ class BunTestRunner {
3445
5006
  }
3446
5007
  let mutantIds = new Set;
3447
5008
  try {
3448
- mutantIds = mutantIdsInInstrumentedSource(await fsPromises2.readFile(sandboxFileName, "utf8"));
5009
+ mutantIds = mutantIdsInInstrumentedSource(await fsPromises3.readFile(sandboxFileName, "utf8"));
3449
5010
  } catch (error) {
3450
5011
  this.logger.debug("Could not read %s for its mutant ids (%s); its full-suite runs rank test files without same-file coverage", sandboxFileName, error instanceof Error ? error.message : String(error));
3451
5012
  }
@@ -3484,7 +5045,7 @@ class BunTestRunner {
3484
5045
  this.logger.debug("Stryker passed an empty testFiles array; ignoring it");
3485
5046
  }
3486
5047
  } else {
3487
- const files = [...new Set(requested.map((file) => path9.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
5048
+ const files = [...new Set(requested.map((file) => path15.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
3488
5049
  this.strykerTestFiles = { cwd, files };
3489
5050
  this.warnIfTestFilesOverridden(files, cwd);
3490
5051
  }
@@ -3546,7 +5107,7 @@ class BunTestRunner {
3546
5107
  if (this.warnedTestFilesConflict || this.testFilesOverride === undefined) {
3547
5108
  return;
3548
5109
  }
3549
- const configured = [...new Set(this.testFilesOverride.map((file) => path9.resolve(cwd, file)))];
5110
+ const configured = [...new Set(this.testFilesOverride.map((file) => path15.resolve(cwd, file)))];
3550
5111
  const selectedSet = new Set(selected);
3551
5112
  if (configured.length === selectedSet.size && configured.every((file) => selectedSet.has(file))) {
3552
5113
  return;
@@ -3619,7 +5180,7 @@ class BunTestRunner {
3619
5180
  this.runOwnerPid ??= process.ppid;
3620
5181
  const tempDir = await this.ensureRunTempDir();
3621
5182
  this.tempDirTouchedAt = Date.now();
3622
- this.coverageFilePath = path9.join(tempDir, `coverage-${Date.now()}.json`);
5183
+ this.coverageFilePath = path15.join(tempDir, `coverage-${Date.now()}.json`);
3623
5184
  this.logger.debug("Generating coverage preload script...");
3624
5185
  const eagerCwd = process.cwd();
3625
5186
  const testFilesPending = this.getOrDiscoverTestFiles();
@@ -3631,16 +5192,33 @@ class BunTestRunner {
3631
5192
  this.cachedEagerModulesCwd = eagerCwd;
3632
5193
  this.logger.debug("Resolved %d eager modules from mutate globs", this.cachedEagerModules.length);
3633
5194
  }
5195
+ await this.rejectIfCampaignStopped(tempDir, this.cachedEagerModules);
3634
5196
  this.preloadScriptPath = await generatePreloadScript({
3635
5197
  tempDir,
3636
- coverageFile: this.coverageFilePath,
3637
- eagerModules: this.cachedEagerModules
5198
+ coverageFile: this.coverageFilePath
3638
5199
  });
3639
5200
  this.logger.debug("Preload script generated at: %s", this.preloadScriptPath);
3640
5201
  await this.ensureSanitizedBunfig();
3641
5202
  const testFiles = await testFilesPending;
3642
5203
  this.logStartSummary(testFiles);
3643
5204
  }
5205
+ async rejectIfCampaignStopped(runDir, eager) {
5206
+ const marker = await readAbortMarker(runDir);
5207
+ if (marker === undefined) {
5208
+ return;
5209
+ }
5210
+ const campaign = await readRegistryCampaign(path15.join(runDir, REGISTRY_FILE));
5211
+ if (campaign?.generation !== marker.generation) {
5212
+ this.logger.debug("Ignoring the abort marker in %s: it belongs to an earlier campaign", runDir);
5213
+ return;
5214
+ }
5215
+ if (campaign.fingerprint !== null && campaign.fingerprint !== await campaignFingerprint(eager)) {
5216
+ this.logger.debug("Ignoring the abort marker in %s: the files matched by mutate changed since its campaign's dry run, so this is a new campaign", runDir);
5217
+ return;
5218
+ }
5219
+ this.logger.error("%s", marker.message);
5220
+ throw new Error(marker.message);
5221
+ }
3644
5222
  async ensureRunTempDir() {
3645
5223
  this.assertRunOwnerIsParent();
3646
5224
  this.tempDir = await resolveRunTempDir();
@@ -3682,7 +5260,7 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
3682
5260
  async loadRegistryFile(mutantId) {
3683
5261
  const registryPath = await this.resolveRegistryPath();
3684
5262
  try {
3685
- const raw = await fsPromises2.readFile(registryPath, "utf8");
5263
+ const raw = await fsPromises3.readFile(registryPath, "utf8");
3686
5264
  const parsed = JSON.parse(raw);
3687
5265
  if (parsed.version !== 2) {
3688
5266
  this.mutantWarnings.warn(MUTANT_WARN_KIND.registryVersion, mutantId, "dryRun registry file has unexpected version %s; skipping", String(parsed.version));
@@ -3705,6 +5283,9 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
3705
5283
  }
3706
5284
  this.testFileDurations = parseTestFileDurations(parsed.testFileDurations);
3707
5285
  this.setTestFileCoverage(TestFileCoverage.fromJson(parsed.mutantTestFiles));
5286
+ this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5287
+ const campaign = parseCampaignState(parsed.campaign);
5288
+ this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
3708
5289
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
3709
5290
  } catch (err) {
3710
5291
  const code = err.code;
@@ -3838,11 +5419,473 @@ ${stack}` : baseFailureMessage;
3838
5419
  return result;
3839
5420
  }
3840
5421
  async executeDryRun(options, profile) {
5422
+ const startedAt = performance.now();
3841
5423
  const coverageAnalysis = this.resolveCoverageAnalysis(options);
3842
5424
  this.applyDryRunTestFiles(options);
3843
5425
  this.logger.debug("Running dry run with inspector-based coverage collection...");
5426
+ const cwd = process.cwd();
5427
+ const eager = this.cachedEagerModules ?? [];
5428
+ const always = this.selectAlwaysImported(eager, cwd);
5429
+ const ctx = {
5430
+ options,
5431
+ coverageAnalysis,
5432
+ cwd,
5433
+ eager,
5434
+ always,
5435
+ runDir: this.tempDir ?? tmpdir2(),
5436
+ startedAt,
5437
+ profile,
5438
+ extraMs: 0,
5439
+ launches: 0
5440
+ };
5441
+ if (this.inPlace && this.tempDir !== undefined) {
5442
+ await removeQuietly(path15.join(this.tempDir, ABORT_MARKER_FILE));
5443
+ }
5444
+ const legacy = legacyReason(eager, always);
5445
+ if (legacy !== null) {
5446
+ this.logger.debug("Dry run: %s, so the runner imports all of them before the tests, with no import scan", legacy === "empty" ? "mutate matches no file" : "bun.alwaysImport keeps every file mutate matches");
5447
+ const launch = await this.runPublished(ctx, eager);
5448
+ this.warnEagerFailures(ctx, launch.record);
5449
+ return this.publishDryRun(ctx, launch);
5450
+ }
5451
+ const { decision, roots } = await this.decideShape(ctx);
5452
+ if (decision.kind === "full") {
5453
+ return this.runFullShape(ctx, decision);
5454
+ }
5455
+ if (decision.kind === "static") {
5456
+ return this.runStaticShape(ctx, decision, roots);
5457
+ }
5458
+ return this.runTwoRuns(ctx, { kind: "scan" });
5459
+ }
5460
+ selectAlwaysImported(eager, cwd) {
5461
+ const selection = selectAlways(eager, this.alwaysImport, cwd);
5462
+ for (const pattern of selection.unmatched) {
5463
+ this.logger.warn("bun.alwaysImport pattern %s matches none of the %d files matched by mutate", JSON.stringify(pattern), eager.length);
5464
+ }
5465
+ return selection.files;
5466
+ }
5467
+ projectPathsOf(ctx, files) {
5468
+ return files.map((file) => shownPath(file, ctx.cwd));
5469
+ }
5470
+ logListed(level, message, lists) {
5471
+ this.logger[level]("%s", message);
5472
+ for (const [what, entries] of lists) {
5473
+ const overflow = listOverflow(entries);
5474
+ if (overflow.length > 0) {
5475
+ this.logger.debug("The rest of %s: %s", what, overflow.join(", "));
5476
+ }
5477
+ }
5478
+ }
5479
+ async decideShape(ctx) {
5480
+ const started = performance.now();
5481
+ try {
5482
+ const input = await this.importScanInput(ctx);
5483
+ if ("problem" in input) {
5484
+ this.logger.debug("%s", scanUnusableMessage(input.problem, false));
5485
+ return { decision: decideFromScan(failedScanResult(input.problem), ctx.eager, ctx.always, this.importDiscovery), roots: [] };
5486
+ }
5487
+ const report = await runImportScan(input.input, { bunPath: this.bunPath, workDir: ctx.runDir });
5488
+ const decision = decideFromScan(report.result, ctx.eager, ctx.always, this.importDiscovery);
5489
+ if (report.failure === null) {
5490
+ this.logger.debug("%s", scanMessage({
5491
+ answer: report.result.answer,
5492
+ wallMs: report.wallMs,
5493
+ scannedFiles: report.result.scannedFiles,
5494
+ matched: ctx.eager.length,
5495
+ statically: this.projectPathsOf(ctx, decision.sources.statically),
5496
+ named: this.projectPathsOf(ctx, decision.sources.named),
5497
+ always: this.projectPathsOf(ctx, decision.sources.always),
5498
+ reasons: decision.kind === "dynamic" ? decision.reasons : report.result.reasons,
5499
+ notes: report.result.notes,
5500
+ next: decision.kind
5501
+ }));
5502
+ } else {
5503
+ this.logger.info("%s", scanUnusableMessage(report.failure, true));
5504
+ }
5505
+ return { decision, roots: input.input.roots };
5506
+ } finally {
5507
+ ctx.extraMs += performance.now() - started;
5508
+ }
5509
+ }
5510
+ async importScanInput(ctx) {
5511
+ const { testFiles } = await this.dryRunFiles(ctx.cwd);
5512
+ if (testFiles === undefined) {
5513
+ return { problem: "the dry run hands bun no list of test files (bun finds them itself), so the runner cannot name the test files to scan" };
5514
+ }
5515
+ const launch = scanLaunchArguments(this.bunArgs ?? [], { ...process.env, ...this.env }, ctx.cwd);
5516
+ if ("problem" in launch) {
5517
+ return launch;
5518
+ }
5519
+ const expanded = await expandTestFileEntries(testFiles, ctx.cwd, this.logger);
5520
+ if ("problem" in expanded) {
5521
+ return expanded;
5522
+ }
5523
+ let bunfig;
5524
+ try {
5525
+ bunfig = await readBunfigForScan(ctx.cwd, this.sourceBunfig);
5526
+ } catch (error) {
5527
+ return { problem: `the bunfig's [test].preload cannot be read (${errorText(error)})` };
5528
+ }
5529
+ if (bunfig.problem !== undefined) {
5530
+ return { problem: bunfig.problem };
5531
+ }
5532
+ const { preloads } = bunfig;
5533
+ return {
5534
+ input: {
5535
+ eager: ctx.eager,
5536
+ roots: [...new Set([...expanded.files, ...preloads, ...launch.preloads])],
5537
+ always: ctx.always,
5538
+ tsconfig: await this.applicableTsconfig(ctx.cwd),
5539
+ projectDir: ctx.cwd
5540
+ }
5541
+ };
5542
+ }
5543
+ async applicableTsconfig(cwd) {
5544
+ for (const name of ["tsconfig.json", "jsconfig.json"]) {
5545
+ const file = path15.join(cwd, name);
5546
+ const stat = await fsPromises3.stat(file).catch(() => {
5547
+ return;
5548
+ });
5549
+ if (stat?.isFile()) {
5550
+ return file;
5551
+ }
5552
+ }
5553
+ return null;
5554
+ }
5555
+ async dryRunFiles(cwd) {
5556
+ const bunfigPath = await this.ensureSanitizedBunfig();
5557
+ const listed = this.testFilesCacheHit(cwd) ?? await this.getOrDiscoverTestFiles();
5558
+ return { bunfigPath, testFiles: this.fitTestFiles(listed, this.explicitTestFilesSource(cwd)) };
5559
+ }
5560
+ beforeLaunch(ctx) {
5561
+ const budgetMs = ctx.options?.timeout;
5562
+ const warning = ctx.launches === 0 ? undefined : budgetWarning(performance.now() - ctx.startedAt, budgetMs);
5563
+ if (warning !== undefined) {
5564
+ this.logger.warn("%s", budgetMessage(warning.usedMs, warning.remainingMs, budgetMs / 60000, warning.suggestedMinutes));
5565
+ }
5566
+ ctx.launches++;
5567
+ ctx.profile?.countLaunch();
5568
+ }
5569
+ async runPublished(ctx, list) {
5570
+ this.beforeLaunch(ctx);
5571
+ const started = performance.now();
5572
+ const files = this.launchFiles(ctx);
5573
+ const nonce = newGeneration();
5574
+ const plan = publishPlan(ctx.eager, list, files.recordFile, nonce);
5575
+ try {
5576
+ const written = plan.eager.length === 0 && plan.candidates === null ? { planFile: undefined } : await this.writePlan(files.planFile, plan);
5577
+ if ("result" in written) {
5578
+ return { result: written.result, list, record: undefined, elapsedMs: performance.now() - started };
5579
+ }
5580
+ const pass = await this.runInspectedPass(ctx, list, written.planFile);
5581
+ const record = plan.recordFile === null ? undefined : ownRecord(await this.readRecord(plan.recordFile, (text) => readObservationRecord(text, ctx.eager)), nonce);
5582
+ return { ...pass, list, record, elapsedMs: performance.now() - started };
5583
+ } finally {
5584
+ await this.removeLaunchFiles(files);
5585
+ }
5586
+ }
5587
+ launchFiles(ctx) {
5588
+ return {
5589
+ planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path15.dirname(this.preloadScriptPath), "dry-run-plan"),
5590
+ recordFile: newRecordFile(ctx.runDir)
5591
+ };
5592
+ }
5593
+ async removeLaunchFiles(files) {
5594
+ const plan = files.planFile === undefined ? [] : [files.planFile];
5595
+ await Promise.all([...plan, files.recordFile, `${files.recordFile}.tmp`].map(async (file) => removeQuietly(file)));
5596
+ }
5597
+ async writePlan(planFile, plan) {
5598
+ if (planFile === undefined) {
5599
+ return { planFile };
5600
+ }
5601
+ try {
5602
+ await writeDryRunPlan(planFile, plan);
5603
+ return { planFile };
5604
+ } catch (error) {
5605
+ const errorMessage = `stryker-bun-runner: cannot write the dry-run plan ${planFile} (${errorText(error)})`;
5606
+ this.logger.error("%s", errorMessage);
5607
+ return { result: { status: DryRunStatus.Error, errorMessage } };
5608
+ }
5609
+ }
5610
+ async readRecord(file, parse) {
5611
+ const read = await readRecordFile(file);
5612
+ await removeQuietly(file);
5613
+ return "problem" in read ? read : parse(read.text);
5614
+ }
5615
+ launchFacts(ctx, launch) {
5616
+ return { list: launch.list, watched: launch.list.length < ctx.eager.length, record: launch.record, green: isGreen(launch.result) };
5617
+ }
5618
+ warnEagerFailures(ctx, record) {
5619
+ const failures = eagerFailuresOf(record);
5620
+ for (const failure of failures.slice(0, LISTED_ENTRIES)) {
5621
+ this.logger.warn("%s", eagerFailureMessage(shownPath(failure.file, ctx.cwd), failure.error));
5622
+ }
5623
+ const rest = failures.slice(LISTED_ENTRIES);
5624
+ if (rest.length > 0) {
5625
+ this.logger.warn("%d more imports before the tests failed (listed at debug)", rest.length);
5626
+ this.logger.debug("The other imports before the tests that failed: %s", rest.map((failure) => `${shownPath(failure.file, ctx.cwd)}: ${displayError(failure.error)}`).join("; "));
5627
+ }
5628
+ }
5629
+ async runFullShape(ctx, decision) {
5630
+ const launch = await this.runPublished(ctx, decision.list);
5631
+ if (isGreen(launch.result) || decision.sources.named.length === 0) {
5632
+ this.warnEagerFailures(ctx, launch.record);
5633
+ return this.publishDryRun(ctx, launch);
5634
+ }
5635
+ ctx.extraMs += launch.elapsedMs;
5636
+ return this.runTwoRuns(ctx, { kind: "failed", attempt: launch, named: decision.sources.named });
5637
+ }
5638
+ async runStaticShape(ctx, decision, roots) {
5639
+ const launch = await this.runPublished(ctx, decision.list);
5640
+ const testFiles = launch.result.status === DryRunStatus.Complete ? launch.result.tests.map((test) => test.fileName) : [];
5641
+ const outcome = oneRunOutcome(this.launchFacts(ctx, launch), unscannedTestFiles(testFiles, roots, ctx.cwd), decision.sources.named);
5642
+ if (outcome.kind === "refuse") {
5643
+ return this.refuseDryRun(outcome.problems);
5644
+ }
5645
+ if (outcome.kind === "miss") {
5646
+ const files = this.projectPathsOf(ctx, outcome.files.map((observation) => observation.file));
5647
+ const unscanned = outcome.testFiles.map((file) => displayName(file));
5648
+ this.logListed("warn", missMessage(files, unscanned, this.incremental), [["the files loaded outside the list", files], ["the test files the runner did not scan", unscanned]]);
5649
+ ctx.extraMs += launch.elapsedMs;
5650
+ return this.runTwoRuns(ctx, { kind: "miss" });
5651
+ }
5652
+ if (outcome.kind === "failed" && outcome.discover) {
5653
+ ctx.extraMs += launch.elapsedMs;
5654
+ return this.runTwoRuns(ctx, { kind: "failed", attempt: launch, named: decision.sources.named });
5655
+ }
5656
+ this.warnEagerFailures(ctx, launch.record);
5657
+ if (outcome.kind === "publish") {
5658
+ const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !decision.list.includes(file)));
5659
+ this.logListed("info", importListOneRunMessage({ matched: ctx.eager.length, left, incremental: this.incremental }, { statically: decision.sources.statically.length, named: decision.sources.named.length, always: decision.sources.always.length }), [["the files the runner does not import", left]]);
5660
+ }
5661
+ return this.publishDryRun(ctx, launch);
5662
+ }
5663
+ async runTwoRuns(ctx, cause) {
5664
+ this.beforeLaunch(ctx);
5665
+ const discoveryOrdinal = RUN_ORDINALS[ctx.launches - 1];
5666
+ const started = performance.now();
5667
+ const files = this.launchFiles(ctx);
5668
+ const nonce = newGeneration();
5669
+ let discovery;
5670
+ try {
5671
+ const written = await this.writePlan(files.planFile, discoveryPlan(ctx.eager, files.recordFile, nonce));
5672
+ if ("result" in written) {
5673
+ return written.result;
5674
+ }
5675
+ discovery = await this.runDiscovery(ctx, written.planFile, files.recordFile, nonce);
5676
+ } finally {
5677
+ await this.removeLaunchFiles(files);
5678
+ ctx.extraMs += performance.now() - started;
5679
+ }
5680
+ if (discovery.verdict.kind === "refused") {
5681
+ return this.refuseDryRun(discovery.verdict.problems);
5682
+ }
5683
+ if (discovery.verdict.kind === "rejected") {
5684
+ if (cause.kind === "failed") {
5685
+ this.logger.warn("%s", discoveryAfterFailedRunMessage(discovery.verdict.reasons));
5686
+ this.warnEagerFailures(ctx, cause.attempt.record);
5687
+ return this.publishDryRun(ctx, cause.attempt);
5688
+ }
5689
+ return this.discoveryError(ctx, discovery, discoveryOrdinal, discovery.verdict.reasons);
5690
+ }
5691
+ return this.runAfterDiscovery(ctx, cause, discovery.verdict.record, discoveryOrdinal);
5692
+ }
5693
+ async runAfterDiscovery(ctx, cause, discovered, discoveryOrdinal) {
5694
+ const observed = new Set(discovered.observed.map((observation) => observation.file));
5695
+ const list = selectList(ctx.eager, [observed, new Set(ctx.always)]);
5696
+ const launch = await this.runPublished(ctx, list);
5697
+ const publishedOrdinal = RUN_ORDINALS[ctx.launches - 1];
5698
+ const facts = this.launchFacts(ctx, launch);
5699
+ const rawCoverage = launch.publication?.rawCoverage;
5700
+ const lost = facts.watched && rawCoverage !== undefined ? lostIds(discovered.reached, rawCoverage) : [];
5701
+ const outcome = twoRunOutcome(facts, lost);
5702
+ if (outcome.kind === "refuse") {
5703
+ return this.refuseDryRun(outcome.problems);
5704
+ }
5705
+ if (outcome.kind === "late") {
5706
+ return this.lateLoadError(ctx, launch, outcome.files, publishedOrdinal, discoveryOrdinal);
5707
+ }
5708
+ if (outcome.kind === "failed") {
5709
+ const failures = eagerFailuresOf(launch.record).map((failure) => `${shownPath(failure.file, ctx.cwd)}: ${displayError(failure.error)}`);
5710
+ const imported = this.projectPathsOf(ctx, list);
5711
+ const fromObservation = list.filter((file) => observed.has(file)).length;
5712
+ this.logListed("error", publishedFailedMessage(publishedOrdinal, discoveryOrdinal, imported, fromObservation, failures), [["the files imported first", imported], ["the imports that threw", failures]]);
5713
+ this.warnEagerFailures(ctx, launch.record);
5714
+ return this.publishDryRun(ctx, launch);
5715
+ }
5716
+ if (outcome.kind === "lost") {
5717
+ return this.lostError(ctx, outcome.ids, list, list.filter((file) => !observed.has(file)).length, publishedOrdinal);
5718
+ }
5719
+ if (facts.watched && rawCoverage === undefined) {
5720
+ return this.refuseDryRun([MISSING_COVERAGE_FOR_RULE_3_3]);
5721
+ }
5722
+ const early = outcome.early.map((observation) => observation.file);
5723
+ this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched }, publishedOrdinal, discoveryOrdinal);
5724
+ this.warnEagerFailures(ctx, launch.record);
5725
+ return this.publishDryRun(ctx, launch, early);
5726
+ }
5727
+ reportTwoRunPublication(ctx, run, publishedOrdinal, discoveryOrdinal) {
5728
+ if (run.early.length > 0) {
5729
+ const files = this.projectPathsOf(ctx, run.early);
5730
+ this.logListed("warn", loadedByListMessage(files), [["the files loaded before the tests", files]]);
5731
+ }
5732
+ const kept = new Set(run.list);
5733
+ if (run.watched) {
5734
+ const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !kept.has(file)));
5735
+ const fromObservation = run.list.filter((file) => run.observed.has(file)).length;
5736
+ this.logListed("info", importListTwoRunMessage({ matched: ctx.eager.length, left, incremental: this.incremental }, { observed: fromObservation, always: run.list.length - fromObservation }, publishedOrdinal, discoveryOrdinal), [["the files the runner does not import", left]]);
5737
+ }
5738
+ if (run.cause.kind === "failed") {
5739
+ const unloaded = run.cause.named.filter((file) => !run.observed.has(file));
5740
+ const notLoaded = this.projectPathsOf(ctx, unloaded);
5741
+ const keptAnyway = this.projectPathsOf(ctx, unloaded.filter((file) => kept.has(file)));
5742
+ this.logListed("warn", namedMessage(run.cause.named.length, notLoaded, keptAnyway, this.incremental), [
5743
+ ["the named files the plain run did not load", notLoaded],
5744
+ ["the named files bun.alwaysImport keeps", keptAnyway]
5745
+ ]);
5746
+ }
5747
+ }
5748
+ async runDiscovery(ctx, planFile, recordFile, nonce) {
5749
+ const { bunfigPath, testFiles } = await this.dryRunFiles(ctx.cwd);
5750
+ const abortController = new AbortController;
5751
+ this.currentAbortController = abortController;
5752
+ const spawned = {};
5753
+ let result;
5754
+ try {
5755
+ result = await runBunTests({
5756
+ bunPath: this.bunPath,
5757
+ timeout: this.timeout,
5758
+ env: this.env,
5759
+ bunArgs: this.bunArgs,
5760
+ bunfigPath,
5761
+ preloadScript: this.preloadScriptPath,
5762
+ dryRunPlan: planFile,
5763
+ sequentialMode: true,
5764
+ testFiles,
5765
+ signal: abortController.signal,
5766
+ smol: this.smol,
5767
+ maxChildRss: this.maxChildRss,
5768
+ rssCheckIntervalMs: this.rssCheckIntervalMs,
5769
+ maxSpawnDepth: this.maxSpawnDepth,
5770
+ onMemoryLimitExceeded: (rssBytes) => {
5771
+ this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during the dry run's plain run of the tests — killing it", rssBytes);
5772
+ },
5773
+ onSpawn: (command) => {
5774
+ spawned.command = command;
5775
+ }
5776
+ });
5777
+ } finally {
5778
+ if (this.currentAbortController === abortController) {
5779
+ this.currentAbortController = undefined;
5780
+ }
5781
+ }
5782
+ const parsed = parseBunTestOutput(result.stdout, result.stderr);
5783
+ const record = await this.readRecord(recordFile, (text) => readDiscoveryRecord(text, ctx.eager));
5784
+ const verdict = acceptDiscovery({
5785
+ exitCode: result.exitCode,
5786
+ signal: result.signal ?? null,
5787
+ timedOut: result.timedOut,
5788
+ memoryLimitExceeded: result.memoryLimitExceeded === true,
5789
+ spawnError: result.spawnError,
5790
+ summaryPrinted: parsed.summaryPrinted,
5791
+ summaryPassed: parsed.summaryPassed,
5792
+ summaryFailed: parsed.summaryFailed,
5793
+ summaryErrors: parsed.summaryErrors,
5794
+ record,
5795
+ nonce
5796
+ });
5797
+ this.logger.debug("Dry run: the plain run of the tests ended with exit code %s (%d pass, %d fail): %s", String(result.exitCode), parsed.summaryPassed, parsed.summaryFailed, verdict.kind);
5798
+ return { result, verdict, command: spawned.command };
5799
+ }
5800
+ refuseDryRun(problems) {
5801
+ const errorMessage = refuseMessage(problems, this.incremental);
5802
+ this.logger.error("%s", errorMessage);
5803
+ return { status: DryRunStatus.Error, errorMessage };
5804
+ }
5805
+ async discoveryError(ctx, discovery, ordinal, reasons) {
5806
+ const { result } = discovery;
5807
+ const unhandled = describeUnhandledErrors(result.stderr, [], []);
5808
+ const tail = cleanDiagnosticText([result.stdout, result.stderr].join(`
5809
+ `)).trim().slice(-500) || "(empty)";
5810
+ const output = unhandled ?? `Last 500 chars of its output:
5811
+ ${tail}`;
5812
+ const outputLine = await this.saveFailedDryRunOutput(result, { command: discovery.command, cwd: ctx.cwd, syncToken: "" });
5813
+ const errorMessage = `${discoveryFailedMessage(ordinal, reasons)}
5814
+ ${output}
5815
+ ${outputLine}`;
5816
+ this.logger.error("%s", errorMessage);
5817
+ return { status: DryRunStatus.Error, errorMessage };
5818
+ }
5819
+ lateLoadError(ctx, launch, late, published, discovery) {
5820
+ const names = launch.publication?.testNames;
5821
+ const loads = late.map((observation) => ({
5822
+ file: shownPath(observation.file, ctx.cwd),
5823
+ test: observation.testKey === null ? null : names?.get(observation.testKey) ?? observation.testKey,
5824
+ sensor: observation.sensor
5825
+ }));
5826
+ const errorMessage = lateLoadMessage(loads, published, discovery, this.incremental);
5827
+ this.logListed("error", errorMessage, [["the files loaded late", lateLoadEntries(loads)]]);
5828
+ return { status: DryRunStatus.Error, errorMessage };
5829
+ }
5830
+ async lostError(ctx, ids, list, always, published) {
5831
+ const lost = new Set(ids);
5832
+ const holding = await Promise.all(ctx.eager.map(async (file) => {
5833
+ const read = fsPromises3.readFile(file, "utf8");
5834
+ const content = await read.catch(() => "");
5835
+ return [...mutantIdsInInstrumentedSource(content)].some((id) => lost.has(id));
5836
+ }));
5837
+ const kept = new Set(list);
5838
+ const report = {
5839
+ ids,
5840
+ files: this.projectPathsOf(ctx, ctx.eager.filter((_file, index) => holding[index])),
5841
+ imported: list.length,
5842
+ always,
5843
+ leftOut: this.projectPathsOf(ctx, ctx.eager.filter((file) => !kept.has(file))),
5844
+ published,
5845
+ incremental: this.incremental
5846
+ };
5847
+ const errorMessage = lostMessage(report);
5848
+ this.logListed("error", errorMessage, [["the lost mutant ids", ids], ["the files of the lost mutants", report.files], ["the files left out", report.leftOut]]);
5849
+ return { status: DryRunStatus.Error, errorMessage };
5850
+ }
5851
+ async publishDryRun(ctx, launch, seen = []) {
5852
+ const { publication } = launch;
5853
+ if (publication === undefined) {
5854
+ return launch.result;
5855
+ }
5856
+ const { tests, testNameIndex, testFileCoverage, processResult, parsed, totalElapsedMs } = publication;
5857
+ const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
5858
+ ctx.profile?.at("coverageChecked");
5859
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched: watchList(ctx.eager, launch.list, seen), eager: ctx.eager } : undefined;
5860
+ const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
5861
+ ctx.profile?.at("registryWritten");
5862
+ if (unpublished !== undefined) {
5863
+ this.logger.error("%s", unpublished);
5864
+ return { status: DryRunStatus.Error, errorMessage: unpublished };
5865
+ }
5866
+ this.warnOnUnidentifiedDryRunFailure(processResult, parsed, tests);
5867
+ this.warnOnTightDryRunTimeout(totalElapsedMs);
5868
+ return launch.result;
5869
+ }
5870
+ async runInspectedPass(ctx, list, planFile) {
3844
5871
  const abortController = new AbortController;
3845
5872
  this.currentAbortController = abortController;
5873
+ ctx.profile?.restartLaunch();
5874
+ const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path15.dirname(this.coverageFilePath), "coverage");
5875
+ const launched = {};
5876
+ try {
5877
+ return await this.runInspectedChild(ctx, list, planFile, coverageFile, abortController, launched);
5878
+ } catch (error) {
5879
+ await awaitChildExit(launched.child, CHILD_EXIT_WAIT_MS);
5880
+ throw error;
5881
+ } finally {
5882
+ if (coverageFile !== undefined) {
5883
+ await cleanupCoverageFile(coverageFile);
5884
+ }
5885
+ }
5886
+ }
5887
+ async runInspectedChild(ctx, list, planFile, coverageFile, abortController, launched) {
5888
+ const { coverageAnalysis, profile } = ctx;
3846
5889
  const syncServer = new SyncServer;
3847
5890
  let syncPort;
3848
5891
  try {
@@ -3853,8 +5896,10 @@ ${stack}` : baseFailureMessage;
3853
5896
  const errorMsg = error instanceof Error ? error.message : String(error);
3854
5897
  this.logger.error("Failed to start sync server: %s", errorMsg);
3855
5898
  return {
3856
- status: DryRunStatus.Error,
3857
- errorMessage: `Failed to start sync server: ${errorMsg}`
5899
+ result: {
5900
+ status: DryRunStatus.Error,
5901
+ errorMessage: `Failed to start sync server: ${errorMsg}`
5902
+ }
3858
5903
  };
3859
5904
  }
3860
5905
  const startTime = Date.now();
@@ -3866,6 +5911,7 @@ ${stack}` : baseFailureMessage;
3866
5911
  const listed = testFilesCached === null ? await this.getOrDiscoverTestFiles() : testFilesCached;
3867
5912
  this.logTestFilesSource(listed, cwd);
3868
5913
  const testFiles = this.fitTestFiles(listed, this.explicitTestFilesSource(cwd));
5914
+ const spawned = {};
3869
5915
  const testProcess = runBunTests({
3870
5916
  bunPath: this.bunPath,
3871
5917
  timeout: this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS,
@@ -3873,7 +5919,8 @@ ${stack}` : baseFailureMessage;
3873
5919
  bunArgs: this.bunArgs,
3874
5920
  bunfigPath,
3875
5921
  preloadScript: this.preloadScriptPath,
3876
- coverageFile: this.coverageFilePath,
5922
+ dryRunPlan: planFile,
5923
+ coverageFile,
3877
5924
  inspect: true,
3878
5925
  sequentialMode: true,
3879
5926
  syncPort,
@@ -3888,14 +5935,19 @@ ${stack}` : baseFailureMessage;
3888
5935
  this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during dryRun — killing and reporting as a timeout for this run", rssBytes);
3889
5936
  },
3890
5937
  onInspectorReady: inspectorUrlWaiter.onReady,
5938
+ onSpawn: (command) => {
5939
+ spawned.command = command;
5940
+ },
3891
5941
  profile
3892
5942
  });
5943
+ launched.child = testProcess;
3893
5944
  const inspectorUrl = await inspectorUrlWaiter.wait(testProcess, this.inspectorTimeout);
3894
5945
  if (!inspectorUrl) {
3895
5946
  await syncServer.close();
3896
5947
  const diagnosticResult = await testProcess;
3897
- const stdoutPreview = diagnosticResult.stdout.slice(0, 1000);
3898
- const stderrPreview = diagnosticResult.stderr.slice(0, 1000);
5948
+ const secrets = [syncServer.token];
5949
+ const stdoutPreview = cleanDiagnosticText(diagnosticResult.stdout, secrets).slice(0, 1000);
5950
+ const stderrPreview = cleanDiagnosticText(diagnosticResult.stderr, secrets).slice(0, 1000);
3899
5951
  this.logger.error(`Failed to get inspector URL within timeout (%dms).
3900
5952
  exit=%s timedOut=%s
3901
5953
  ` + `--- STDOUT (first 1000 chars) ---
@@ -3903,8 +5955,10 @@ exit=%s timedOut=%s
3903
5955
  ` + `--- STDERR (first 1000 chars) ---
3904
5956
  %s`, this.inspectorTimeout, String(diagnosticResult.exitCode), String(diagnosticResult.timedOut), stdoutPreview || "(empty)", stderrPreview || "(empty)");
3905
5957
  return {
3906
- status: DryRunStatus.Error,
3907
- errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult)
5958
+ result: {
5959
+ status: DryRunStatus.Error,
5960
+ errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult, secrets)
5961
+ }
3908
5962
  };
3909
5963
  }
3910
5964
  this.logger.debug("Inspector URL: %s", redactInspectorUrl(inspectorUrl));
@@ -3917,7 +5971,7 @@ exit=%s timedOut=%s
3917
5971
  this.logger.warn("Inspector error: %s", error.message);
3918
5972
  },
3919
5973
  onUnexpectedClose: (context) => {
3920
- this.logger.debug("Inspector WebSocket closed while the run was still thought to be in progress (wsClosed=%s closeExpected=%s isClosing=%s closeCode=%s closeReason=%s closeWasClean=%s msFromLastFrameToClose=%s) — often benign; see checkCompletenessGate", context.wsClosed, context.closeExpected, context.isClosing, String(context.closeCode), String(context.closeReason), String(context.closeWasClean), String(context.msFromLastFrameToClose));
5974
+ this.logger.debug("Inspector WebSocket closed while the run was still thought to be in progress (wsClosed=%s closeExpected=%s isClosing=%s closeCode=%s closeReason=%s closeWasClean=%s msFromLastFrameToClose=%s) — often benign; see findCompletenessProblems", context.wsClosed, context.closeExpected, context.isClosing, String(context.closeCode), String(context.closeReason), String(context.closeWasClean), String(context.msFromLastFrameToClose));
3921
5975
  },
3922
5976
  onRequestStall: (info) => {
3923
5977
  this.logger.warn("Inspector request unanswered after %dms even though other frames are still arriving (last frame %dms ago): %s (id=%d) — possible protocol-level stall distinct from total silence", info.msUnanswered, info.msSinceLastFrame, info.method, info.id);
@@ -3931,14 +5985,16 @@ exit=%s timedOut=%s
3931
5985
  profile?.mark("inspector");
3932
5986
  this.logger.debug("Inspector connected and TestReporter enabled");
3933
5987
  } catch (error) {
3934
- const errorMsg = error instanceof Error ? error.message : String(error);
5988
+ const errorMsg = cleanDiagnosticText(error instanceof Error ? error.message : String(error), [syncServer.token]);
3935
5989
  this.logger.error("Failed to connect inspector: %s", errorMsg);
3936
5990
  abortController.abort();
3937
5991
  await inspector.close();
3938
5992
  const child = await testProcess;
3939
5993
  return {
3940
- status: DryRunStatus.Error,
3941
- errorMessage: formatInspectorConnectMessage(errorMsg, child)
5994
+ result: {
5995
+ status: DryRunStatus.Error,
5996
+ errorMessage: formatInspectorConnectMessage(errorMsg, child, [syncServer.token])
5997
+ }
3942
5998
  };
3943
5999
  }
3944
6000
  let drainSettleReason;
@@ -4003,11 +6059,11 @@ exit=%s timedOut=%s
4003
6059
  });
4004
6060
  const parsed = parseBunTestOutput(result.stdout, result.stderr);
4005
6061
  markStep("outputParsed");
4006
- const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
6062
+ const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy, [syncServer.token]);
4007
6063
  if (earlyResult) {
4008
- return earlyResult;
6064
+ return { result: earlyResult };
4009
6065
  }
4010
- return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, coverageAnalysis, profile);
6066
+ return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, { coverageAnalysis, imported: list, coverageFile }, { command: spawned.command, cwd, syncToken: syncServer.token }, profile);
4011
6067
  } finally {
4012
6068
  abortController.abort();
4013
6069
  if (this.currentAbortController === abortController) {
@@ -4025,8 +6081,8 @@ exit=%s timedOut=%s
4025
6081
  this.logger.warn("Inspector data looks abnormal after the dry run: %s — test results may be incomplete; enable debug logging for the full drain/close/collision diagnostics", problems.join("; "));
4026
6082
  }
4027
6083
  }
4028
- async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, inspectorState, coverageAnalysis, profile) {
4029
- const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage } = await this.collectAndRemapCoverage(testHierarchy, executionOrder, profile);
6084
+ async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, inspectorState, run, spawnInfo, profile) {
6085
+ const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage, rawCoverage, counterKeyToTestName } = await this.collectAndRemapCoverage(run.coverageFile, testHierarchy, executionOrder, profile);
4030
6086
  profile?.at("coverageMapped");
4031
6087
  const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, [...new Set(executionOrder)], parsed, totalElapsedMs, inspectorIdToProjectFile);
4032
6088
  tests.sort((a, b) => a.name.localeCompare(b.name));
@@ -4040,27 +6096,35 @@ exit=%s timedOut=%s
4040
6096
  resultTestIds: tests.map((t) => t.id),
4041
6097
  duplicateFoundIdCount: inspectorState.duplicateFoundIdCount
4042
6098
  };
4043
- const gateResult = this.checkCompletenessGate(facts, parsed.summaryFailed, inspectorState.wasClosedUnexpectedly, tests, inspectorState.closeInfo, result.stderr);
6099
+ const gateReasons = this.findCompletenessProblems(facts, parsed.summaryFailed, tests, result.stderr, run.imported, [spawnInfo.syncToken]);
4044
6100
  profile?.at("gateChecked");
4045
- if (gateResult) {
4046
- return gateResult;
6101
+ if (gateReasons.length > 0) {
6102
+ const outputLine = await this.saveFailedDryRunOutput(result, spawnInfo);
6103
+ return { result: this.completenessError(gateReasons, inspectorState.wasClosedUnexpectedly, inspectorState.closeInfo, outputLine) };
4047
6104
  }
4048
- const coverageResult = this.checkCoverageData(mutantCoverage, tests, coverageAnalysis, result.stderr);
6105
+ const coverageResult = this.checkCoverageData(mutantCoverage, tests, run.coverageAnalysis, result.stderr, run.coverageFile);
4049
6106
  if (coverageResult) {
4050
- return coverageResult;
6107
+ return { result: coverageResult };
4051
6108
  }
4052
- profile?.at("coverageChecked");
4053
- await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage);
4054
- profile?.at("registryWritten");
4055
- this.warnOnUnidentifiedDryRunFailure(result, parsed, tests);
4056
- this.warnOnTightDryRunTimeout(totalElapsedMs);
4057
6109
  return {
4058
- status: DryRunStatus.Complete,
4059
- tests,
4060
- mutantCoverage
6110
+ result: {
6111
+ status: DryRunStatus.Complete,
6112
+ tests,
6113
+ mutantCoverage
6114
+ },
6115
+ publication: {
6116
+ tests,
6117
+ testNameIndex,
6118
+ testFileCoverage,
6119
+ rawCoverage,
6120
+ testNames: counterKeyToTestName,
6121
+ processResult: result,
6122
+ parsed,
6123
+ totalElapsedMs
6124
+ }
4061
6125
  };
4062
6126
  }
4063
- checkCoverageData(coverage, tests, coverageAnalysis, stderr) {
6127
+ checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
4064
6128
  const preloadLines = extractPreloadCoverageDiagnostics(stderr);
4065
6129
  const coverageMissing = coverage === undefined && coverageAnalysis !== "off";
4066
6130
  if (!coverageMissing || tests.some((t) => t.status === TestStatus.Failed)) {
@@ -4074,9 +6138,9 @@ exit=%s timedOut=%s
4074
6138
  }
4075
6139
  return null;
4076
6140
  }
4077
- const coverageDir = this.coverageFilePath === undefined ? tmpdir2() : path9.dirname(this.coverageFilePath);
6141
+ const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
4078
6142
  const parts = [
4079
- `stryker-bun-runner: the dry run produced no mutant coverage data — the coverage file ${this.coverageFilePath ?? "(none configured)"} was missing, unreadable or empty. ` + "Without it Stryker runs the full test suite for every mutant, which is far slower than running each mutant's covering tests. " + "Likely causes: the coverage preload never ran (check for a [test].preload in bunfig.toml or bun.bunArgs that replaces or bypasses it), " + `${coverageDir} is not writable, or the bun test child exited before its final afterAll hook wrote the file (e.g. a test calls process.exit).`
6143
+ `stryker-bun-runner: the dry run produced no mutant coverage data — the coverage file ${coverageFile ?? "(none configured)"} was missing, unreadable or empty. ` + "Without it Stryker runs the full test suite for every mutant, which is far slower than running each mutant's covering tests. " + "Likely causes: the coverage preload never ran (check for a [test].preload in bunfig.toml or bun.bunArgs that replaces or bypasses it), " + `${coverageDir} is not writable, or the bun test child exited before its final afterAll hook wrote the file (e.g. a test calls process.exit).`
4080
6144
  ];
4081
6145
  if (coverageAnalysis === "perTest") {
4082
6146
  parts.push("Failing the dry run because coverageAnalysis is 'perTest'; set coverageAnalysis to 'all' or 'off' to run without per-test coverage instead.");
@@ -4099,7 +6163,7 @@ ${preloadLines.join(`
4099
6163
  this.logger.warn("The dry run took %dms, more than 80%% of bun.timeout (%dms). bun.timeout bounds the dry run (mutant runs use Stryker's per-mutant timeout instead); a dry run that outgrows bun.timeout plus the drain-handshake allowance is killed — raise bun.timeout", elapsedMs, this.timeout);
4100
6164
  }
4101
6165
  }
4102
- async buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage) {
6166
+ async buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaignInput) {
4103
6167
  this.cachedTestNames = new Set(tests.map((t) => t.name));
4104
6168
  if (tests.length !== this.cachedTestNames.size) {
4105
6169
  const nameCount = new Map;
@@ -4125,27 +6189,75 @@ ${preloadLines.join(`
4125
6189
  this.testFileDurations = sumDurationsByFile(tests);
4126
6190
  this.logger.debug("Recorded dry-run durations for %d test file(s) to order mutant runs cheapest-first", this.testFileDurations.size);
4127
6191
  this.setTestFileCoverage(testFileCoverage);
6192
+ this.timeoutCorrectionMs = campaignInput?.timeoutCorrectionMs;
6193
+ if (campaignInput !== undefined) {
6194
+ this.logger.debug("Mutant runs take %d ms off Stryker's per-mutant timeout for the dry run's extra work", campaignInput.timeoutCorrectionMs);
6195
+ }
6196
+ this.campaign = undefined;
4128
6197
  try {
4129
- const registryPath = await this.resolveRegistryPath();
4130
- const tmpPath = `${registryPath}.tmp`;
4131
- const registryData = JSON.stringify({
4132
- version: 2,
4133
- writtenAt: Date.now(),
4134
- cachedTestNames: [...this.cachedTestNames],
4135
- baseNameIndex: [...this.baseNameIndex.entries()],
4136
- testNameIndex: [...testNameIndex.entries()],
4137
- testFiles: this.selectedTestFilesFor(process.cwd()),
4138
- testFileDurations: [...this.testFileDurations.entries()],
4139
- mutantTestFiles: testFileCoverage?.toJSON()
4140
- });
4141
- await writePrivateFile(tmpPath, registryData);
6198
+ const indexes = { cachedTestNames: this.cachedTestNames, baseNameIndex: this.baseNameIndex, testNameIndex, testFileDurations: this.testFileDurations };
6199
+ await this.writeRegistry(indexes, testFileCoverage, campaignInput);
6200
+ return;
6201
+ } catch (error) {
6202
+ return this.registryWriteFailed(error, campaignInput?.watched.length ?? 0);
6203
+ }
6204
+ }
6205
+ registryWriteFailed(error, watched) {
6206
+ if (watched > 0) {
6207
+ return error instanceof WriteFailure ? unpublishedCampaignMessage(error.file, error.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(error), watched);
6208
+ }
6209
+ this.warnRegistryWriteFailed(errorText(error));
6210
+ return;
6211
+ }
6212
+ async writeRegistry(indexes, testFileCoverage, campaignInput) {
6213
+ const registryPath = await this.resolveRegistryPath();
6214
+ const runDir = path15.dirname(registryPath);
6215
+ const campaign = campaignInput === undefined ? undefined : await this.writeCampaignFiles(runDir, campaignInput);
6216
+ const tmpPath = `${registryPath}.tmp`;
6217
+ const registryData = JSON.stringify({
6218
+ version: 2,
6219
+ writtenAt: Date.now(),
6220
+ cachedTestNames: [...indexes.cachedTestNames],
6221
+ baseNameIndex: [...indexes.baseNameIndex.entries()],
6222
+ testNameIndex: [...indexes.testNameIndex.entries()],
6223
+ testFiles: this.selectedTestFilesFor(process.cwd()),
6224
+ testFileDurations: [...indexes.testFileDurations.entries()],
6225
+ mutantTestFiles: testFileCoverage?.toJSON(),
6226
+ timeoutCorrectionMs: campaignInput?.timeoutCorrectionMs,
6227
+ campaign
6228
+ });
6229
+ try {
6230
+ await writingTo(tmpPath, async () => writePrivateFile(tmpPath, registryData));
4142
6231
  this.lastRegistryTmpPath = tmpPath;
4143
- await fsPromises2.rename(tmpPath, registryPath);
4144
- this.lastRegistryTmpPath = undefined;
4145
- this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, this.cachedTestNames.size);
6232
+ await writingTo(registryPath, async () => fsPromises3.rename(tmpPath, registryPath));
4146
6233
  } catch (error) {
4147
- this.warnRegistryWriteFailed(error instanceof Error ? error.message : String(error));
6234
+ if (campaign?.watchListFile) {
6235
+ await removeQuietly(path15.join(runDir, campaign.watchListFile));
6236
+ }
6237
+ throw error;
6238
+ }
6239
+ this.lastRegistryTmpPath = undefined;
6240
+ if (campaign !== undefined) {
6241
+ await removeQuietly(path15.join(runDir, ABORT_MARKER_FILE));
6242
+ this.campaign = { ...campaign, dir: runDir, watched: new Set(campaign.watchList) };
6243
+ }
6244
+ this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, indexes.cachedTestNames.size);
6245
+ }
6246
+ async writeCampaignFiles(runDir, campaignInput) {
6247
+ const { watched } = campaignInput;
6248
+ const generation = newGeneration();
6249
+ const watchListFile = watched.length === 0 ? null : watchListFileFor(generation);
6250
+ const campaign = {
6251
+ generation,
6252
+ watchList: [...watched],
6253
+ watchListFile,
6254
+ fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.eager)
6255
+ };
6256
+ if (watchListFile !== null) {
6257
+ const file = path15.join(runDir, watchListFile);
6258
+ await writingTo(file, async () => writeWatchList(file, watched));
4148
6259
  }
6260
+ return campaign;
4149
6261
  }
4150
6262
  warnRegistryWriteFailed(message) {
4151
6263
  if (this.selectedTestFilesFor(process.cwd()) === undefined) {
@@ -4191,7 +6303,7 @@ ${preloadLines.join(`
4191
6303
  this.logRandomizeOffOnce();
4192
6304
  this.effectiveTestFiles = await this.getOrDiscoverTestFiles();
4193
6305
  const strykerTimeoutMs = isUsableTimeout(options.timeout) ? options.timeout : undefined;
4194
- const limitMs = strykerTimeoutMs === undefined ? this.timeout : limitFromStrykerTimeout(strykerTimeoutMs);
6306
+ const limitMs = strykerTimeoutMs === undefined ? this.timeout : limitFromStrykerTimeout(this.correctedStrykerTimeout(strykerTimeoutMs));
4195
6307
  const sourceCoverage = this.ordersLikelyKillersFirst(options, filterIds.length) ? await this.sourceCoverageFor(options.sandboxFileName) : undefined;
4196
6308
  const result = await this.executeMutantRun({
4197
6309
  options,
@@ -4209,6 +6321,64 @@ ${preloadLines.join(`
4209
6321
  profile?.finish(result.status);
4210
6322
  return result;
4211
6323
  }
6324
+ correctedStrykerTimeout(strykerTimeoutMs) {
6325
+ const corrected = correctStrykerTimeout(strykerTimeoutMs, this.timeoutCorrectionMs);
6326
+ if (!corrected.applied && !this.loggedUnusableCorrection) {
6327
+ this.loggedUnusableCorrection = true;
6328
+ this.logger.debug("No usable dry-run timeout correction (%s); mutant runs use Stryker's per-mutant timeout unchanged", String(this.timeoutCorrectionMs));
6329
+ }
6330
+ return corrected.timeoutMs;
6331
+ }
6332
+ watchListForMutantRuns() {
6333
+ const { campaign } = this;
6334
+ return campaign?.watchListFile ? path15.join(campaign.dir, campaign.watchListFile) : undefined;
6335
+ }
6336
+ async enforceWitness(stderr, hitLimitToken, ctx, testNamePattern) {
6337
+ const { campaign } = this;
6338
+ if (campaign === undefined) {
6339
+ return;
6340
+ }
6341
+ const problem = readWatchListProblem(stderr, hitLimitToken);
6342
+ if (problem !== undefined && !this.warnedWatchListProblem) {
6343
+ this.warnedWatchListProblem = true;
6344
+ this.logger.warn("A mutant run could not use its watch list (%s), so it could not check for files the dry run missed; its result stands. This warning is shown once.", displayError(problem));
6345
+ }
6346
+ const loaded = readWitnessReport(stderr, hitLimitToken, campaign.watched);
6347
+ if (loaded === undefined) {
6348
+ return;
6349
+ }
6350
+ const cwd = process.cwd();
6351
+ const files = loaded.map((file) => shownPath(file, cwd));
6352
+ const scope = this.witnessScope(ctx, testNamePattern);
6353
+ const message = witnessMessage({
6354
+ files,
6355
+ mutantId: ctx.options.activeMutant.id,
6356
+ scope: scope.text,
6357
+ incremental: this.incremental
6358
+ });
6359
+ const lists = [["the watched files found loaded", files]];
6360
+ if (scope.tests !== undefined) {
6361
+ lists.push(["the covering tests", scope.tests]);
6362
+ }
6363
+ this.logListed("error", message, lists);
6364
+ try {
6365
+ await writeAbortMarker(campaign.dir, { generation: campaign.generation, message });
6366
+ } catch (error) {
6367
+ this.logger.error("Could not write the abort marker in %s (%s): a worker Stryker starts in this one's place will not know the campaign was stopped", campaign.dir, errorText(error));
6368
+ }
6369
+ throw new Error(message);
6370
+ }
6371
+ witnessScope(ctx, testNamePattern) {
6372
+ if (ctx.testFileScope !== undefined) {
6373
+ return { text: `the tests of ${ctx.testFileScope.length} file(s) Stryker's testFiles option selected` };
6374
+ }
6375
+ if (testNamePattern === undefined) {
6376
+ return { text: ctx.coveringTestCount === 0 ? "the whole suite" : `the whole suite, in place of its ${ctx.coveringTestCount} covering test(s)` };
6377
+ }
6378
+ const ids = ctx.options.testFilter ?? [];
6379
+ const tests = ids.map((id) => displayName(id));
6380
+ return { text: `${tests.length} covering test(s): ${listText(tests)}`, tests };
6381
+ }
4212
6382
  async resolveTestFileFilter(filter) {
4213
6383
  if (filter.length === 0) {
4214
6384
  return;
@@ -4221,7 +6391,7 @@ ${preloadLines.join(`
4221
6391
  const cwd = process.cwd();
4222
6392
  const exist = await Promise.all(entries.map(async (entry) => {
4223
6393
  try {
4224
- const stat = await fsPromises2.stat(path9.resolve(cwd, entry));
6394
+ const stat = await fsPromises3.stat(path15.resolve(cwd, entry));
4225
6395
  return stat.isFile();
4226
6396
  } catch {
4227
6397
  return false;
@@ -4249,6 +6419,7 @@ ${preloadLines.join(`
4249
6419
  activeMutant: options.activeMutant.id,
4250
6420
  hitLimit: options.hitLimit,
4251
6421
  hitLimitToken,
6422
+ watchList: this.watchListForMutantRuns(),
4252
6423
  bail: !options.disableBail,
4253
6424
  sequentialMode: true,
4254
6425
  preloadScript: this.preloadScriptPath,
@@ -4269,6 +6440,7 @@ ${preloadLines.join(`
4269
6440
  this.currentAbortController = undefined;
4270
6441
  }
4271
6442
  }
6443
+ await this.enforceWitness(result.stderr, hitLimitToken, ctx, testNamePattern);
4272
6444
  const runawayResult = this.classifyRunawayMutantRun(result, ctx, testNamePattern, hitLimitToken);
4273
6445
  if (runawayResult) {
4274
6446
  return runawayResult;
@@ -4404,7 +6576,7 @@ ${result.stderr}`).trim().slice(-500) || "(no output)";
4404
6576
  this.mutantWarnings.warn(MUTANT_WARN_KIND.earlyExit, mutantId, "Mutant %s: %s — scoring as Error rather than Survived", mutantId, errorMessage);
4405
6577
  return { status: MutantRunStatus.Error, errorMessage };
4406
6578
  }
4407
- checkDryRunProcessResult(result, parsed, testHierarchy) {
6579
+ checkDryRunProcessResult(result, parsed, testHierarchy, secrets) {
4408
6580
  if (result.timedOut) {
4409
6581
  if (result.memoryLimitExceeded !== true) {
4410
6582
  this.logger.warn("Dry run timed out: bun.timeout is %dms, and the dry-run child was killed at its %dms limit (bun.timeout plus the drain-handshake allowance) — raise bun.timeout above your full suite's run time", this.timeout, this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS);
@@ -4415,7 +6587,7 @@ ${result.stderr}`).trim().slice(-500) || "(no output)";
4415
6587
  return {
4416
6588
  status: DryRunStatus.Error,
4417
6589
  errorMessage: `${formatSpawnErrorMessage(result.spawnError)}
4418
- ${result.stderr}`
6590
+ ${cleanDiagnosticText(result.stderr, secrets)}`
4419
6591
  };
4420
6592
  }
4421
6593
  if (result.exitCode !== 0 && parsed.failed === 0) {
@@ -4424,7 +6596,7 @@ ${result.stderr}`
4424
6596
  if (failureDetails) {
4425
6597
  messageParts.push(failureDetails);
4426
6598
  }
4427
- messageParts.push(result.stderr);
6599
+ messageParts.push(cleanDiagnosticText(result.stderr, secrets));
4428
6600
  return {
4429
6601
  status: DryRunStatus.Error,
4430
6602
  errorMessage: messageParts.join(`
@@ -4465,42 +6637,90 @@ ${lines.join(`
4465
6637
  %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
4466
6638
  }
4467
6639
  }
4468
- checkCompletenessGate(facts, summaryFailed, wasClosedUnexpectedly, tests, closeInfo, stderr) {
6640
+ async saveFailedDryRunOutput(result, spawnInfo) {
6641
+ const secrets = [spawnInfo.syncToken];
6642
+ const couldNotSave = (reason) => `Full output of the bun test process could not be saved: ${escapeControlCharacters(redactSecrets(reason, secrets))}.`;
6643
+ let timer;
6644
+ try {
6645
+ if (this.dryRunOutputFile === undefined) {
6646
+ return OUTPUT_FILE_HINT;
6647
+ }
6648
+ const abandon = new AbortController;
6649
+ const expired = new Promise((resolve) => {
6650
+ timer = setTimeout(() => {
6651
+ abandon.abort();
6652
+ resolve("expired");
6653
+ }, SAVE_TIME_LIMIT_MS);
6654
+ });
6655
+ const saved = await Promise.race([
6656
+ saveDryRunOutput(resolveAgainstProject(this.dryRunOutputFile), {
6657
+ stdout: result.stdout,
6658
+ stderr: result.stderr,
6659
+ command: spawnInfo.command,
6660
+ cwd: spawnInfo.cwd,
6661
+ bunVersion: this.bunVersion,
6662
+ exitCode: result.exitCode,
6663
+ signal: result.signal,
6664
+ outputIncomplete: result.outputIncomplete === true,
6665
+ secrets
6666
+ }, { signal: abandon.signal }),
6667
+ expired
6668
+ ]);
6669
+ if (saved === "expired") {
6670
+ return couldNotSave(`saving took longer than ${SAVE_TIME_LIMIT_MS / 1000} seconds`);
6671
+ }
6672
+ return "path" in saved ? `Full output of the bun test process was saved to ${escapeControlCharacters(redactSecrets(saved.path, secrets))}.` : couldNotSave(saved.error);
6673
+ } catch (error) {
6674
+ return couldNotSave(errorText(error).replaceAll(/\s+/g, " ").trim());
6675
+ } finally {
6676
+ clearTimeout(timer);
6677
+ }
6678
+ }
6679
+ findCompletenessProblems(facts, summaryFailed, tests, stderr, eagerModules, secrets = []) {
4469
6680
  if (tests.some((t) => t.status === TestStatus.Failed)) {
4470
- return null;
6681
+ return [];
4471
6682
  }
4472
6683
  const reasons = findDryRunDataLoss(facts);
4473
6684
  if (summaryFailed > 0) {
4474
- reasons.push(`bun's console summary reported ${summaryFailed} failing test(s), but none of them could be ` + "attributed to an individual test — a whole spec file that fails to load (e.g. an unresolvable " + `import) produces exactly this shape. Last 500 chars of stderr:
4475
- ${stderr.slice(-500)}`);
4476
- }
4477
- if (reasons.length === 0) {
4478
- return null;
6685
+ const unattributed = `bun's console summary reported ${summaryFailed} failing test(s), but none of them could be attributed to an individual test`;
6686
+ const unhandled = describeUnhandledErrors(stderr, eagerModules, secrets);
6687
+ if (unhandled === undefined) {
6688
+ reasons.push(`${unattributed} — a whole spec file that fails to load (e.g. an unresolvable import) can produce this shape, ` + `but no "Unhandled error between tests" block was found in bun's stderr to say what happened. ` + `Last 500 chars of stderr:
6689
+ ${cleanDiagnosticText(stderr, secrets).slice(-500)}`);
6690
+ } else {
6691
+ reasons.push(`${unattributed}. ${unhandled}`);
6692
+ }
4479
6693
  }
6694
+ return reasons;
6695
+ }
6696
+ completenessError(problems, wasClosedUnexpectedly, closeInfo, outputLine) {
6697
+ const reasons = [...problems];
4480
6698
  if (wasClosedUnexpectedly) {
4481
6699
  const closeDetail = closeInfo.code === undefined ? "close code/reason not captured" : `close code=${closeInfo.code} reason=${JSON.stringify(closeInfo.reason ?? "")} wasClean=${String(closeInfo.wasClean)}, ${String(closeInfo.msFromLastFrameToClose)}ms after the last received frame`;
4482
6700
  reasons.push(`the inspector WebSocket also closed unexpectedly (${closeDetail}), which is routine on its own and listed only as context`);
4483
6701
  }
4484
- const errorMessage = "stryker-bun-runner: dry run data-completeness check failed — " + `${reasons.join("; ")}. Completing this dry run would hand Stryker test results or coverage that are silently ` + "missing or credited to the wrong tests, so it is reported as an error instead, and the test registry has NOT " + "been persisted. If a cause named above is in your test suite, fix it there; otherwise re-run the dry run, and " + "if this recurs, please report it at https://github.com/hughescr/stryker-bun-runner/issues with this message, " + "your bun version and a debug log (logLevel: 'debug').";
6702
+ const joined = reasons.map((reason, position) => position < reasons.length - 1 && reason.endsWith(".") ? reason.slice(0, -1) : reason).join("; ");
6703
+ const errorMessage = "stryker-bun-runner: dry run data-completeness check failed — " + `${joined}${joined.endsWith(".") ? "" : "."} Completing this dry run would hand Stryker test results or coverage that are silently ` + "missing or credited to the wrong tests, so it is reported as an error instead, and the test registry has NOT " + "been persisted. If a cause named above is in your test suite, fix it there; otherwise re-run the dry run, and " + "if this recurs, please report it at https://github.com/hughescr/stryker-bun-runner/issues with this message, " + `your bun version and a debug log (logLevel: 'debug').
6704
+ ${outputLine}`;
4485
6705
  this.logger.error("%s", errorMessage);
4486
6706
  return {
4487
6707
  status: DryRunStatus.Error,
4488
6708
  errorMessage
4489
6709
  };
4490
6710
  }
4491
- async collectAndRemapCoverage(testHierarchy, executionOrder, profile) {
6711
+ async collectAndRemapCoverage(coverageFile, testHierarchy, executionOrder, profile) {
4492
6712
  const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
4493
- if (!this.coverageFilePath) {
4494
- return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined };
6713
+ if (!coverageFile) {
6714
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
4495
6715
  }
4496
6716
  const [rawCoverage, lateHits] = await Promise.all([
4497
- collectCoverage(this.coverageFilePath, this.logger),
4498
- collectLateHits(this.coverageFilePath, this.logger)
6717
+ collectCoverage(coverageFile, this.logger),
6718
+ collectLateHits(coverageFile, this.logger)
4499
6719
  ]);
4500
6720
  profile?.at("coverageRead");
4501
- await cleanupCoverageFile(this.coverageFilePath);
6721
+ await cleanupCoverageFile(coverageFile);
4502
6722
  if (!rawCoverage) {
4503
- return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined };
6723
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
4504
6724
  }
4505
6725
  const testFileCoverage = TestFileCoverage.fromPerTest(rawCoverage.perTest);
4506
6726
  const { coverage, inspectorIdToProjectFile, counterKeyToTestName, rawKeyCount, orphanedKeyCount } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
@@ -4509,7 +6729,9 @@ ${stderr.slice(-500)}`);
4509
6729
  coverage,
4510
6730
  inspectorIdToProjectFile,
4511
6731
  coverageKeys: { keyCount: rawKeyCount, unmatchedKeyCount: orphanedKeyCount },
4512
- testFileCoverage
6732
+ testFileCoverage,
6733
+ rawCoverage,
6734
+ counterKeyToTestName
4513
6735
  };
4514
6736
  }
4515
6737
  emitCoverageBleedWarnings(lateHits, counterKeyToTestName) {
@@ -4622,7 +6844,7 @@ ${stderr.slice(-500)}`);
4622
6844
  }
4623
6845
  if (this.lastRegistryTmpPath) {
4624
6846
  try {
4625
- await fsPromises2.unlink(this.lastRegistryTmpPath);
6847
+ await fsPromises3.unlink(this.lastRegistryTmpPath);
4626
6848
  } catch (err) {
4627
6849
  if (err.code !== "ENOENT") {
4628
6850
  this.logger.debug("Failed to clean registry tmp file: %s", err instanceof Error ? err.message : String(err));
@@ -4632,9 +6854,9 @@ ${stderr.slice(-500)}`);
4632
6854
  }
4633
6855
  }
4634
6856
  // src/checker-tsconfig.ts
4635
- import { readFile as readFile6, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
6857
+ import { readFile as readFile7, rename as rename4, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
4636
6858
  import { createRequire as createRequire2 } from "node:module";
4637
- import path10 from "node:path";
6859
+ import path16 from "node:path";
4638
6860
  import { glob as glob2 } from "tinyglobby";
4639
6861
  var DEFAULT_MUTATE_PATTERNS = ["{src,lib}/**"];
4640
6862
  var MUTATION_RANGE_RE = /:\d+(?::\d+)?-\d+(?::\d+)?$/;
@@ -4644,7 +6866,7 @@ var LOG_PREFIX = "[Stryker] withTestFilesExcludedFromTypeCheck: ";
4644
6866
  var MAX_QUOTED_ERRORS = 3;
4645
6867
  function loadTypeScript(cwd) {
4646
6868
  try {
4647
- return createRequire2(path10.join(cwd, "package.json"))("typescript");
6869
+ return createRequire2(path16.join(cwd, "package.json"))("typescript");
4648
6870
  } catch {
4649
6871
  return;
4650
6872
  }
@@ -4671,7 +6893,7 @@ async function findTestFiles(config, cwd) {
4671
6893
  for (const relativeFiles of [await discoverTestFiles(cwd, undefined, sourceBunfig), bun.testFiles]) {
4672
6894
  if (relativeFiles) {
4673
6895
  for (const file of relativeFiles) {
4674
- testFiles.add(path10.resolve(cwd, file));
6896
+ testFiles.add(path16.resolve(cwd, file));
4675
6897
  }
4676
6898
  }
4677
6899
  }
@@ -4714,7 +6936,7 @@ function findNewErrors(derived, original, testFiles) {
4714
6936
  async function updateDerivedFile(derivedPath, shown, text) {
4715
6937
  const temp = `${derivedPath}.${process.pid}.tmp`;
4716
6938
  try {
4717
- const existing = await readFile6(derivedPath, "utf8").catch((error) => {
6939
+ const existing = await readFile7(derivedPath, "utf8").catch((error) => {
4718
6940
  if (error.code === "ENOENT") {
4719
6941
  return;
4720
6942
  }
@@ -4727,10 +6949,10 @@ async function updateDerivedFile(derivedPath, shown, text) {
4727
6949
  return `${shown} exists and was not generated by this helper (rename or delete it)`;
4728
6950
  }
4729
6951
  await writeFile2(temp, text);
4730
- await rename2(temp, derivedPath);
6952
+ await rename4(temp, derivedPath);
4731
6953
  return;
4732
6954
  } catch (error) {
4733
- await rm2(temp, { force: true });
6955
+ await rm5(temp, { force: true });
4734
6956
  return `cannot update ${shown}: ${error instanceof Error ? error.message : String(error)}`;
4735
6957
  }
4736
6958
  }
@@ -4749,12 +6971,12 @@ function derivedHeader(source) {
4749
6971
  `);
4750
6972
  }
4751
6973
  function renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints) {
4752
- const source = path10.basename(sourcePath);
6974
+ const source = path16.basename(sourcePath);
4753
6975
  const body = {
4754
6976
  extends: `./${source}`,
4755
6977
  ...project.options.declarationDir !== undefined && { compilerOptions: { declarationDir: null } },
4756
6978
  include: [],
4757
- files: entryPoints.map((file) => path10.relative(path10.dirname(derivedPath), file))
6979
+ files: entryPoints.map((file) => path16.relative(path16.dirname(derivedPath), file))
4758
6980
  };
4759
6981
  return `${derivedHeader(source)}${JSON.stringify(body, null, 2)}
4760
6982
  `;
@@ -4768,8 +6990,8 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
4768
6990
  if (!ts) {
4769
6991
  return leaveUnchanged(config, `typescript cannot be loaded from ${cwd}; install it there`);
4770
6992
  }
4771
- const sourcePath = path10.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
4772
- const shownSource = path10.relative(cwd, sourcePath);
6993
+ const sourcePath = path16.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
6994
+ const shownSource = path16.relative(cwd, sourcePath);
4773
6995
  const read = readProject(ts, sourcePath, shownSource);
4774
6996
  if ("problem" in read) {
4775
6997
  return leaveUnchanged(config, read.problem);
@@ -4786,10 +7008,10 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
4786
7008
  if (entryPoints.length === 0) {
4787
7009
  return leaveUnchanged(config, `${shownSource} would have no files left once test files are excluded`);
4788
7010
  }
4789
- const derivedPath = path10.join(path10.dirname(sourcePath), `${path10.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
4790
- const shownDerived = path10.relative(cwd, derivedPath);
7011
+ const derivedPath = path16.join(path16.dirname(sourcePath), `${path16.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7012
+ const shownDerived = path16.relative(cwd, derivedPath);
4791
7013
  const text = renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints);
4792
- const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path10.dirname(derivedPath), undefined, derivedPath);
7014
+ const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path16.dirname(derivedPath), undefined, derivedPath);
4793
7015
  const derived = createProgram(ts, derivedProject, original);
4794
7016
  const newErrors = findNewErrors(derived, original, testFiles);
4795
7017
  if (newErrors.length > 0) {
@@ -4883,6 +7105,31 @@ var strykerValidationSchema = {
4883
7105
  minimum: 1,
4884
7106
  description: "Maximum `bun test` spawn nesting depth before the runner refuses to spawn (default: 1). Guards against runaway recursion when a run spawned by this runner ends up spawning another one. Raise to 2 only if your own tests drive this runner.",
4885
7107
  default: 1
7108
+ },
7109
+ dryRunOutputFile: {
7110
+ type: "string",
7111
+ minLength: 1,
7112
+ description: "A file to write the dry run's complete `bun test` output (stdout and stderr) to when the dry run's data-completeness check fails; without it nothing is written. A relative path resolves against the directory Stryker was started in, not the sandbox. The file is replaced by each failure and created with mode 0600. Colour codes, inspector addresses and this run's tokens are removed from it; anything else the tests print is saved as printed, so check it before sharing it."
7113
+ },
7114
+ alwaysImport: {
7115
+ description: "Files matched by mutate that the dry run imports before the tests even when no test loads them, so that their module-level code runs before any test. 'all' imports every file mutate matches, in one run of the tests. A list holds glob patterns, matched against the project-relative paths of the files mutate matches (dot paths included); a file is kept when any pattern matches it. Negated patterns (!...) are not supported. A pattern that matches none of those files is reported at warn.",
7116
+ oneOf: [
7117
+ { type: "string", enum: ["all"] },
7118
+ {
7119
+ type: "array",
7120
+ items: {
7121
+ type: "string",
7122
+ minLength: 1,
7123
+ pattern: "^[^!]"
7124
+ }
7125
+ }
7126
+ ]
7127
+ },
7128
+ importDiscovery: {
7129
+ type: "string",
7130
+ enum: ["scan", "run"],
7131
+ description: "How the dry run establishes which mutated files the tests load. 'scan' (default): the runner reads the imports of the test files and preloads, and runs the tests once when that settles it; otherwise it first observes a plain run of the tests. 'run': a plain run of the tests is always observed first, unless the files the tests import, with alwaysImport, already cover every mutated file.",
7132
+ default: "scan"
4886
7133
  }
4887
7134
  },
4888
7135
  additionalProperties: false