@hughescr/stryker-bun-runner 1.5.2 → 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 path7 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,14 +15,19 @@ 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";
30
+ import { lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, utimesSync } from "node:fs";
26
31
  import { lstat, mkdir, realpath, rm, writeFile } from "node:fs/promises";
27
32
  import { tmpdir } from "node:os";
28
33
  import path from "node:path";
@@ -33,6 +38,28 @@ class UnsafeTempDirError extends Error {
33
38
  this.name = "UnsafeTempDirError";
34
39
  }
35
40
  }
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")}`;
44
+ }
45
+ function computePidSpace(platform = process.platform, readIds = readLinuxPidSpaceIds) {
46
+ if (platform !== "linux") {
47
+ return { tag: tagOf(""), known: true };
48
+ }
49
+ try {
50
+ return { tag: tagOf(readIds()), known: true };
51
+ } catch {
52
+ return { tag: tagOf("stryker-bun-runner: unknown Linux pid space"), known: false };
53
+ }
54
+ }
55
+ function tagOf(ids) {
56
+ return createHash("sha256").update(ids).digest("hex").slice(0, 8);
57
+ }
58
+ var currentPidSpace;
59
+ function pidSpace() {
60
+ currentPidSpace ??= computePidSpace();
61
+ return currentPidSpace;
62
+ }
36
63
  var RUN_TEMP_DIR_SLOTS = 16;
37
64
  function currentUid() {
38
65
  const uid = process.getuid?.();
@@ -45,7 +72,8 @@ function runTempDirPrefix(key = {}) {
45
72
  const cwd = key.cwd ?? process.cwd();
46
73
  const ppid = key.ppid ?? process.ppid;
47
74
  const hash = createHash("sha256").update(`${cwd}:${ppid}`).digest("hex").slice(0, 16);
48
- return path.join(key.baseDir ?? tmpdir(), `stryker-bun-runner-${key.uid ?? currentUid()}-${hash}`);
75
+ const space = key.pidSpace ?? pidSpace().tag;
76
+ return path.join(key.baseDir ?? tmpdir(), `stryker-bun-runner-${key.uid ?? currentUid()}-${space}-${ppid}-${hash}`);
49
77
  }
50
78
  function octal(mode) {
51
79
  return (mode & 4095).toString(8).padStart(4, "0");
@@ -143,6 +171,1104 @@ async function writePrivateFile(file, data) {
143
171
  await rm(file, { force: true });
144
172
  await writeFile(file, data, { encoding: "utf8", flag: "wx", mode: 384 });
145
173
  }
174
+ var RUN_DIR_NAME_RE = /^stryker-bun-runner-(0|[1-9]\d*)-([0-9a-f]{8})-([1-9]\d*)-[0-9a-f]{16}-(?:0|[1-9]\d*)$/;
175
+ var STALE_RUN_DIR_AGE_MS = 60 * 60 * 1000;
176
+ var RUN_DIR_TOUCH_INTERVAL_MS = 10 * 60 * 1000;
177
+ var MAX_RUN_DIRS_EXAMINED = 1000;
178
+ function touchRunTempDir(dir, now = Date.now()) {
179
+ try {
180
+ utimesSync(dir, now / 1000, now / 1000);
181
+ } catch {}
182
+ }
183
+ function processExists(pid) {
184
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
185
+ return true;
186
+ }
187
+ try {
188
+ process.kill(pid, 0);
189
+ return true;
190
+ } catch (err) {
191
+ return err.code !== "ESRCH";
192
+ }
193
+ }
194
+ function ancestorsSafe(top, uid, lstatFn) {
195
+ for (let component = top;; component = path.dirname(component)) {
196
+ if (ancestorProblem(lstatFn(component), uid) !== undefined) {
197
+ return false;
198
+ }
199
+ if (component === path.dirname(component)) {
200
+ return true;
201
+ }
202
+ }
203
+ }
204
+ function listSafeBaseDir(baseDir, uid, lstatFn, readdirFn = listDir) {
205
+ try {
206
+ const base = realpathSync(baseDir ?? tmpdir());
207
+ return ancestorsSafe(base, uid, lstatFn) ? { base, names: readdirFn(base) } : undefined;
208
+ } catch {
209
+ return;
210
+ }
211
+ }
212
+ function runDirOwner(name, uid, space) {
213
+ const match = RUN_DIR_NAME_RE.exec(name);
214
+ return match !== null && Number(match[1]) === uid && match[2] === space ? Number(match[3]) : undefined;
215
+ }
216
+ function listDir(dir) {
217
+ return readdirSync(dir);
218
+ }
219
+ function removeTree(dir) {
220
+ rmSync(dir, { recursive: true });
221
+ }
222
+ function runIsOver({ dir, owner }, judge) {
223
+ const st = judge.lstatFn(dir);
224
+ if (dirProblem(st, judge.uid) !== undefined) {
225
+ return false;
226
+ }
227
+ if (owner === judge.exitingPid) {
228
+ return true;
229
+ }
230
+ return judge.now - st.mtimeMs >= judge.minAgeMs && !judge.isAlive(owner);
231
+ }
232
+ function removeFinishedRunTempDirs(options = {}) {
233
+ const uid = options.uid ?? process.getuid?.();
234
+ const space = options.pidSpace ?? pidSpace();
235
+ const lstatFn = options.lstat ?? lstatSync;
236
+ const listing = uid === undefined || !space.known ? undefined : listSafeBaseDir(options.baseDir, uid, lstatFn, options.readdir);
237
+ if (uid === undefined || listing === undefined) {
238
+ return [];
239
+ }
240
+ const { exitingPid } = options;
241
+ const candidates = listing.names.map((name) => ({ dir: path.join(listing.base, name), owner: runDirOwner(name, uid, space.tag) })).filter((candidate) => candidate.owner !== undefined).toSorted((a, b) => Number(b.owner === exitingPid) - Number(a.owner === exitingPid)).slice(0, options.maxExamined ?? MAX_RUN_DIRS_EXAMINED);
242
+ const judge = {
243
+ uid,
244
+ lstatFn,
245
+ exitingPid,
246
+ isAlive: options.isAlive ?? processExists,
247
+ minAgeMs: options.minAgeMs ?? STALE_RUN_DIR_AGE_MS,
248
+ now: options.now ?? Date.now()
249
+ };
250
+ const remove = options.remove ?? removeTree;
251
+ return candidates.filter((candidate) => {
252
+ try {
253
+ if (!runIsOver(candidate, judge)) {
254
+ return false;
255
+ }
256
+ remove(candidate.dir);
257
+ return true;
258
+ } catch {
259
+ return false;
260
+ }
261
+ }).map((candidate) => candidate.dir);
262
+ }
263
+ var exitCleanupRegistered = new WeakSet;
264
+ function removeRunTempDirsOnExit(proc = process) {
265
+ if (exitCleanupRegistered.has(proc)) {
266
+ return;
267
+ }
268
+ exitCleanupRegistered.add(proc);
269
+ proc.once("exit", () => {
270
+ try {
271
+ removeFinishedRunTempDirs({ exitingPid: process.pid });
272
+ } catch {}
273
+ });
274
+ }
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";
146
1272
 
147
1273
  // src/utils/test-name-pattern.ts
148
1274
  var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
@@ -209,36 +1335,79 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
209
1335
  const sourceFileRe = /\.(?:tsx?|[cm]?js)$/;
210
1336
  const dtsRe = /\.d\.[cm]?ts$/;
211
1337
  const filtered = paths.filter((p) => sourceFileRe.test(p) && !dtsRe.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
212
- const resolved = filtered.map((p) => path2.resolve(p));
1338
+ const resolved = filtered.map((p) => path6.resolve(p));
213
1339
  resolved.sort((a, b) => a.localeCompare(b));
214
1340
  return resolved;
215
1341
  }
216
- async function generatePreloadScript(options) {
217
- const preloadPath = path2.join(options.tempDir, `stryker-coverage-preload-${process.pid}.ts`);
1342
+ function resolvePreloadTemplate(moduleDir) {
1343
+ const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1344
+ if (isBundled) {
1345
+ return {
1346
+ templatePath: path6.join(moduleDir, "templates/coverage-preload.js"),
1347
+ preloadLogicPath: undefined,
1348
+ extension: "js"
1349
+ };
1350
+ }
1351
+ return {
1352
+ templatePath: path6.join(moduleDir, "../templates/coverage-preload.ts"),
1353
+ preloadLogicPath: path6.join(moduleDir, "preload-logic.ts"),
1354
+ extension: "ts"
1355
+ };
1356
+ }
1357
+ async function generatePreloadScript(options, moduleDir = path6.dirname(fileURLToPath2(import.meta.url))) {
218
1358
  await ensurePrivateDir(options.tempDir);
219
- const __dirname2 = path2.dirname(fileURLToPath(import.meta.url));
220
- const isBundled = __dirname2.endsWith("dist") || __dirname2.includes("dist/");
221
- const templatePath = isBundled ? path2.join(__dirname2, "templates/coverage-preload.ts") : path2.join(__dirname2, "../templates/coverage-preload.ts");
222
- const template = await readFile(templatePath, "utf8");
223
- const preloadLogicPath = isBundled ? path2.join(__dirname2, "coverage/preload-logic.js") : path2.join(__dirname2, "preload-logic.ts");
224
- const eagerModules = options.eagerModules ?? [];
225
- const content = template.replace("__PRELOAD_LOGIC_PATH__", preloadLogicPath).replace("__EAGER_MODULES__", JSON.stringify(eagerModules));
1359
+ const { templatePath, preloadLogicPath, extension } = resolvePreloadTemplate(moduleDir);
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);
226
1363
  await writePrivateFile(preloadPath, content);
1364
+ if (options.dryRunPlan !== undefined) {
1365
+ await writeDryRunPlan(dryRunPlanFileFor(preloadPath), options.dryRunPlan);
1366
+ }
227
1367
  return preloadPath;
228
1368
  }
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`;
1378
+ }
229
1379
  async function cleanupPreloadScript(preloadPath) {
230
- try {
231
- await unlink(preloadPath);
232
- } catch {}
1380
+ for (const file of [preloadPath, dryRunPlanFileFor(preloadPath)]) {
1381
+ try {
1382
+ await unlink(file);
1383
+ } catch {}
1384
+ }
233
1385
  }
234
1386
  // src/coverage/collector.ts
235
- import { readFile as readFile2, unlink as unlink2 } from "node:fs/promises";
1387
+ import { readFile as readFile3, unlink as unlink2 } from "node:fs/promises";
236
1388
  function addHitCounts(into, from) {
237
1389
  for (const [mutantId, count] of Object.entries(from)) {
238
1390
  into[mutantId] = (into[mutantId] ?? 0) + count;
239
1391
  }
240
1392
  }
1393
+ function isRecordObject(value) {
1394
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1395
+ }
1396
+ function isWellFormedLine(data) {
1397
+ if (!isRecordObject(data.perTest) || !isRecordObject(data.static)) {
1398
+ return false;
1399
+ }
1400
+ for (const counts of Object.values(data.perTest)) {
1401
+ if (!isRecordObject(counts)) {
1402
+ return false;
1403
+ }
1404
+ }
1405
+ return true;
1406
+ }
241
1407
  function mergeCoverageData(dataList) {
1408
+ if (dataList.length === 1 && isWellFormedLine(dataList[0])) {
1409
+ return { perTest: dataList[0].perTest, static: dataList[0].static };
1410
+ }
242
1411
  const merged = { perTest: {}, static: {} };
243
1412
  for (const data of dataList) {
244
1413
  for (const [testId, counts] of Object.entries(data.perTest)) {
@@ -249,9 +1418,23 @@ function mergeCoverageData(dataList) {
249
1418
  }
250
1419
  return merged;
251
1420
  }
1421
+ var readsInFlight = new Map;
1422
+ async function readCoverageFileDataShared(coverageFile, logger) {
1423
+ const inFlight = readsInFlight.get(coverageFile);
1424
+ if (inFlight) {
1425
+ return inFlight;
1426
+ }
1427
+ const read = readCoverageFileData(coverageFile, logger);
1428
+ readsInFlight.set(coverageFile, read);
1429
+ try {
1430
+ return await read;
1431
+ } finally {
1432
+ readsInFlight.delete(coverageFile);
1433
+ }
1434
+ }
252
1435
  async function readCoverageFileData(coverageFile, logger) {
253
1436
  try {
254
- const content = await readFile2(coverageFile, "utf8");
1437
+ const content = await readFile3(coverageFile, "utf8");
255
1438
  const trimmed = content.trim();
256
1439
  const lines = trimmed.split(`
257
1440
  `).filter((line) => line.length > 0);
@@ -272,7 +1455,7 @@ async function readCoverageFileData(coverageFile, logger) {
272
1455
  }
273
1456
  async function collectCoverage(coverageFile, logger) {
274
1457
  try {
275
- const dataList = await readCoverageFileData(coverageFile, logger);
1458
+ const dataList = await readCoverageFileDataShared(coverageFile, logger);
276
1459
  if (dataList.length === 0) {
277
1460
  return;
278
1461
  }
@@ -282,7 +1465,7 @@ async function collectCoverage(coverageFile, logger) {
282
1465
  }
283
1466
  }
284
1467
  async function collectLateHits(coverageFile, logger) {
285
- const dataList = await readCoverageFileData(coverageFile, logger);
1468
+ const dataList = await readCoverageFileDataShared(coverageFile, logger);
286
1469
  return dataList.flatMap((data) => data.lateHits ?? []);
287
1470
  }
288
1471
  async function cleanupCoverageFile(coverageFile) {
@@ -503,27 +1686,83 @@ function resolveEachTestName(baseName, inspectorId, nameInspectorIds, duplicateN
503
1686
  const index = duplicateNameIndex.get(key_) ?? 0;
504
1687
  return `${baseName} [${index}]`;
505
1688
  }
506
- function buildRemappedPerTest(counterIds, resolved, rawPerTest, testHierarchy) {
1689
+ function buildMappedCoverage(counterIds, resolved, rawCoverage, testHierarchy) {
507
1690
  const nameInspectorIds = buildNameInspectorIds(resolved);
508
1691
  const duplicateNameIndex = buildDuplicateNameIndex(nameInspectorIds, testHierarchy);
509
- const remappedPerTest = {};
1692
+ const staticCounts = { ...rawCoverage.static };
1693
+ const staticIds = new Set(Object.keys(staticCounts));
1694
+ const creditedByName = new Map;
1695
+ const orphaned = [];
510
1696
  for (const [i, key] of counterIds.entries()) {
1697
+ const incoming = rawCoverage.perTest[key] ?? {};
511
1698
  const { name: baseName, testInfo, inspectorId } = resolved[i];
512
1699
  if (!testInfo) {
1700
+ orphaned.push(incoming);
513
1701
  continue;
514
1702
  }
515
1703
  const finalName = resolveEachTestName(baseName, inspectorId, nameInspectorIds, duplicateNameIndex);
516
- const incoming = rawPerTest[key];
517
- const existing = remappedPerTest[finalName];
518
- if (existing) {
519
- for (const [mutantId, count_] of Object.entries(incoming)) {
520
- existing[mutantId] = (existing[mutantId] ?? 0) + count_;
521
- }
1704
+ const credited = creditedByName.get(finalName);
1705
+ if (!credited && !holdsAny(incoming, staticIds)) {
1706
+ creditedByName.set(finalName, incoming);
1707
+ continue;
1708
+ }
1709
+ const writable = { ...credited };
1710
+ creditedByName.set(finalName, writable);
1711
+ creditHits(incoming, writable, staticIds, staticCounts);
1712
+ }
1713
+ const perTest = nonEmptyTests(creditedByName, orphaned.length > 0);
1714
+ creditOrphanedHits(orphaned, staticCounts, perTest);
1715
+ return { static: staticCounts, perTest };
1716
+ }
1717
+ function creditHits(incoming, credited, staticIds, staticCounts) {
1718
+ for (const mutantId of Object.keys(incoming)) {
1719
+ const hits = incoming[mutantId];
1720
+ if (staticIds.has(mutantId)) {
1721
+ staticCounts[mutantId] += hits;
522
1722
  } else {
523
- remappedPerTest[finalName] = { ...incoming };
1723
+ credited[mutantId] = (credited[mutantId] ?? 0) + hits;
1724
+ }
1725
+ }
1726
+ }
1727
+ function nonEmptyTests(creditedByName, copy) {
1728
+ const perTest = {};
1729
+ for (const [name, counts] of creditedByName) {
1730
+ if (Object.keys(counts).length > 0) {
1731
+ perTest[name] = copy ? { ...counts } : counts;
1732
+ }
1733
+ }
1734
+ return perTest;
1735
+ }
1736
+ function holdsAny(counts, mutantIds) {
1737
+ for (const mutantId of Object.keys(counts)) {
1738
+ if (mutantIds.has(mutantId)) {
1739
+ return true;
1740
+ }
1741
+ }
1742
+ return false;
1743
+ }
1744
+ function firstHolders(staticCounts, perTest) {
1745
+ const firstHolder = new Map;
1746
+ for (const counts of [staticCounts, ...Object.values(perTest)]) {
1747
+ for (const mutantId of Object.keys(counts)) {
1748
+ if (!firstHolder.has(mutantId)) {
1749
+ firstHolder.set(mutantId, counts);
1750
+ }
1751
+ }
1752
+ }
1753
+ return firstHolder;
1754
+ }
1755
+ function creditOrphanedHits(orphaned, staticCounts, perTest) {
1756
+ let firstHolder;
1757
+ for (const counts of orphaned) {
1758
+ firstHolder ??= firstHolders(staticCounts, perTest);
1759
+ for (const mutantId of Object.keys(counts)) {
1760
+ const holder = firstHolder.get(mutantId);
1761
+ if (holder) {
1762
+ holder[mutantId] += counts[mutantId];
1763
+ }
524
1764
  }
525
1765
  }
526
- return remappedPerTest;
527
1766
  }
528
1767
  function warnInteriorGapIfPresent(pairs, testHierarchy, logger) {
529
1768
  const warnedFiles = new Set;
@@ -578,7 +1817,6 @@ function mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy,
578
1817
  }
579
1818
  const counterIds = globallyOrderedKeys.toSorted((a, b) => splitCounterKey(a).position - splitCounterKey(b).position);
580
1819
  const resolved = resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logger);
581
- const remappedPerTest = buildRemappedPerTest(counterIds, resolved, rawCoverage.perTest, testHierarchy);
582
1820
  const counterKeyToTestName = new Map;
583
1821
  for (const [i, key] of counterIds.entries()) {
584
1822
  if (resolved[i].testInfo) {
@@ -586,10 +1824,7 @@ function mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy,
586
1824
  }
587
1825
  }
588
1826
  const orphanedKeyCount = reportOrphanedKeys(resolved, counterIds, logger);
589
- const coverage = restoreHitTotals(rawCoverage, stabilizeCoverage({
590
- static: rawCoverage.static,
591
- perTest: remappedPerTest
592
- }));
1827
+ const coverage = buildMappedCoverage(counterIds, resolved, rawCoverage, testHierarchy);
593
1828
  return {
594
1829
  coverage,
595
1830
  inspectorIdToProjectFile,
@@ -646,13 +1881,6 @@ function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger
646
1881
  orphanedKeyCount: counterIds.length - creditedKeyCount
647
1882
  };
648
1883
  }
649
- // src/coverage/preload-logic.ts
650
- import { appendFileSync, closeSync, constants, createReadStream, openSync, writeSync } from "node:fs";
651
- var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
652
- var HIT_LIMIT_SENTINEL = "__STRYKER_HIT_LIMIT_REACHED__";
653
- var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
654
- var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
655
-
656
1884
  // src/inspector/types.ts
657
1885
  var TEST_STATUSES = ["pass", "fail", "timeout", "skip", "todo", "skipped_because_label"];
658
1886
  function isTestReporterFoundEvent(message) {
@@ -1102,10 +2330,10 @@ class InspectorClient {
1102
2330
  }
1103
2331
  }
1104
2332
  // src/parsers/console-parser.ts
1105
- import path4 from "node:path";
2333
+ import path9 from "node:path";
1106
2334
 
1107
2335
  // src/process-runner.ts
1108
- import { spawn as spawn2 } from "node:child_process";
2336
+ import { spawn as spawn3 } from "node:child_process";
1109
2337
 
1110
2338
  // src/utils/process-group.ts
1111
2339
  function killProcessGroup(pid, signal) {
@@ -1118,8 +2346,8 @@ function killProcessGroup(pid, signal) {
1118
2346
  }
1119
2347
 
1120
2348
  // src/utils/process-rss.ts
1121
- import { spawn } from "node:child_process";
1122
- 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";
1123
2351
  async function getProcessRssBytes(pid) {
1124
2352
  return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
1125
2353
  }
@@ -1129,7 +2357,7 @@ function parseVmRss(statusContent) {
1129
2357
  }
1130
2358
  async function getLinuxRss(pid) {
1131
2359
  try {
1132
- const status = await readFile3(`/proc/${pid}/status`, "utf8");
2360
+ const status = await readFile4(`/proc/${pid}/status`, "utf8");
1133
2361
  return parseVmRss(status);
1134
2362
  } catch {
1135
2363
  return null;
@@ -1147,7 +2375,7 @@ async function getPsRss(pid) {
1147
2375
  return new Promise((resolve) => {
1148
2376
  let child;
1149
2377
  try {
1150
- 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"] });
1151
2379
  } catch {
1152
2380
  resolve(null);
1153
2381
  return;
@@ -1165,21 +2393,40 @@ async function getPsRss(pid) {
1165
2393
  });
1166
2394
  }
1167
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
+
1168
2415
  // src/utils/test-file-args.ts
1169
- import path3 from "node:path";
2416
+ import path8 from "node:path";
1170
2417
  var MAX_TEST_FILE_ARGS_BYTES = 131072;
1171
2418
  var ENTRY_OVERHEAD_BYTES = 1 + 8;
1172
2419
  var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
1173
2420
  function shortestSpelling(absolute, cwd) {
1174
- const relative = path3.relative(cwd, absolute);
2421
+ const relative = path8.relative(cwd, absolute);
1175
2422
  if (relative === "" || relative === "..") {
1176
2423
  return absolute;
1177
2424
  }
1178
- const spelled = relative.startsWith(`..${path3.sep}`) ? relative : `.${path3.sep}${relative}`;
2425
+ const spelled = relative.startsWith(`..${path8.sep}`) ? relative : `.${path8.sep}${relative}`;
1179
2426
  return spelled.length < absolute.length ? spelled : absolute;
1180
2427
  }
1181
- function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
1182
- const absolute = files.map((file) => path3.resolve(cwd, file));
2428
+ function computeTestFileArgs(files, cwd, budget) {
2429
+ const absolute = files.map((file) => path8.resolve(cwd, file));
1183
2430
  const absoluteBytes = bytesOf(absolute);
1184
2431
  if (absoluteBytes <= budget) {
1185
2432
  return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
@@ -1188,6 +2435,22 @@ function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_AR
1188
2435
  const relativeBytes = bytesOf(relative);
1189
2436
  return { args: relative, form: "relative", bytes: relativeBytes, fits: relativeBytes <= budget };
1190
2437
  }
2438
+ function sameEntries(a, b) {
2439
+ return a.length === b.length && a.every((entry, index) => entry === b[index]);
2440
+ }
2441
+ var lastBuild;
2442
+ function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
2443
+ if (!path8.isAbsolute(cwd)) {
2444
+ return computeTestFileArgs(files, cwd, budget);
2445
+ }
2446
+ const cached = lastBuild;
2447
+ if (cached?.cwd === cwd && cached.budget === budget && sameEntries(cached.files, files)) {
2448
+ return { ...cached.result, args: [...cached.result.args] };
2449
+ }
2450
+ const result = computeTestFileArgs(files, cwd, budget);
2451
+ lastBuild = { files: [...files], cwd, budget, result: { ...result, args: [...result.args] } };
2452
+ return result;
2453
+ }
1191
2454
 
1192
2455
  // src/process-runner.ts
1193
2456
  var KILL_GRACE_PERIOD_MS = 500;
@@ -1195,6 +2458,7 @@ var STDIO_CLOSE_GRACE_MS = 4 * KILL_GRACE_PERIOD_MS;
1195
2458
  var LIFELINE_FD = 3;
1196
2459
  var SPAWN_DEPTH_ENV = "__STRYKER_BUN_RUNNER_DEPTH__";
1197
2460
  var DEFAULT_MAX_SPAWN_DEPTH = 1;
2461
+ var PROFILE_ENV = "STRYKER_BUN_PROFILE";
1198
2462
  function stripAnsi(text) {
1199
2463
  return text.replaceAll(/\u001B\[[0-9;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "");
1200
2464
  }
@@ -1306,6 +2570,8 @@ function buildChildEnv(options, spawnDepth) {
1306
2570
  __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
1307
2571
  __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
1308
2572
  [SYNC_TOKEN_ENV]: options.syncToken,
2573
+ [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
2574
+ [WATCH_LIST_ENV]: options.watchList,
1309
2575
  [LIFELINE_FD_ENV]: String(LIFELINE_FD)
1310
2576
  };
1311
2577
  for (const [name, value] of Object.entries(preloadVars)) {
@@ -1316,9 +2582,20 @@ function buildChildEnv(options, spawnDepth) {
1316
2582
  }
1317
2583
  }
1318
2584
  env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
2585
+ delete env[PROJECT_DIR_ENV];
2586
+ if (options.profile) {
2587
+ delete env[PROFILE_ENV];
2588
+ }
2589
+ if (options.profile && options.syncPort) {
2590
+ env[PRELOAD_TIMINGS_ENV] = "1";
2591
+ } else {
2592
+ delete env[PRELOAD_TIMINGS_ENV];
2593
+ }
1319
2594
  return env;
1320
2595
  }
1321
2596
  async function spawnBunTests(options, spawnDepth) {
2597
+ const profile = options.profile;
2598
+ profile?.beginSpawn(options.bail === true, options.testFiles, options.testNamePattern);
1322
2599
  const args = ["test"];
1323
2600
  if (options.inspect) {
1324
2601
  args.push("--inspect=127.0.0.1:0");
@@ -1369,7 +2646,11 @@ async function spawnBunTests(options, spawnDepth) {
1369
2646
  cwd: process.cwd(),
1370
2647
  detached: true
1371
2648
  };
1372
- 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);
2653
+ profile?.mark("spawned");
1373
2654
  liveChildren.add(childProcess);
1374
2655
  ensureSignalCleanup();
1375
2656
  const beginTermination = () => {
@@ -1429,6 +2710,7 @@ async function spawnBunTests(options, spawnDepth) {
1429
2710
  if (childProcess.stderr) {
1430
2711
  childProcess.stderr.on("data", (data) => {
1431
2712
  stderrChunks.push(data);
2713
+ profile?.onStderr(data);
1432
2714
  if (options.inspect && !inspectorUrlExtracted && options.onInspectorReady) {
1433
2715
  const text = Buffer.concat(stderrChunks).toString();
1434
2716
  const match = /Listening:[\t\v\f\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*(ws:\/\/\S+)/.exec(stripAnsi(text));
@@ -1451,6 +2733,7 @@ async function spawnBunTests(options, spawnDepth) {
1451
2733
  }
1452
2734
  };
1453
2735
  childProcess.on("exit", (code, signal) => {
2736
+ profile?.mark("exit");
1454
2737
  onLeaderExitDuringTermination?.();
1455
2738
  stdioCloseHandle = setTimeout(() => {
1456
2739
  release();
@@ -1466,6 +2749,7 @@ async function spawnBunTests(options, spawnDepth) {
1466
2749
  }, STDIO_CLOSE_GRACE_MS);
1467
2750
  });
1468
2751
  childProcess.on("close", (code, signal) => {
2752
+ profile?.mark("close");
1469
2753
  hasClosed = true;
1470
2754
  onLeaderExitDuringTermination?.();
1471
2755
  release();
@@ -1479,6 +2763,7 @@ async function spawnBunTests(options, spawnDepth) {
1479
2763
  });
1480
2764
  });
1481
2765
  childProcess.on("error", (error) => {
2766
+ profile?.mark("close");
1482
2767
  hasClosed = true;
1483
2768
  onLeaderExitDuringTermination?.();
1484
2769
  release();
@@ -1508,13 +2793,17 @@ function headerFilter(lines, testFiles) {
1508
2793
  if (testFiles === undefined) {
1509
2794
  return () => true;
1510
2795
  }
1511
- const roots = testFiles.map((file) => path4.resolve(file));
2796
+ const roots = new Set(testFiles.map((file) => path9.resolve(file)));
1512
2797
  const isRunFile = (file) => {
1513
- const resolved = path4.resolve(file);
1514
- return roots.some((root) => {
1515
- const relative = path4.relative(root, resolved);
1516
- return relative !== ".." && !relative.startsWith(`..${path4.sep}`);
1517
- });
2798
+ let candidate = path9.resolve(file);
2799
+ while (!roots.has(candidate)) {
2800
+ const parent = path9.dirname(candidate);
2801
+ if (parent === candidate) {
2802
+ return false;
2803
+ }
2804
+ candidate = parent;
2805
+ }
2806
+ return true;
1518
2807
  };
1519
2808
  const namesRunFile = lines.some((line) => {
1520
2809
  const file = parseFilePath(line);
@@ -1525,6 +2814,7 @@ function headerFilter(lines, testFiles) {
1525
2814
  function isWorkflowCommandLine(line) {
1526
2815
  return workflowCommandRe.test(line);
1527
2816
  }
2817
+ var MAX_FAILURE_MESSAGE_LENGTH = 4000;
1528
2818
  function buildTestName(testName, currentFile) {
1529
2819
  return currentFile ? `${currentFile} > ${testName}` : testName;
1530
2820
  }
@@ -1548,8 +2838,7 @@ function parseTestLine(line, currentFile) {
1548
2838
  file: currentFile,
1549
2839
  status: "failed",
1550
2840
  duration: failMatch[2] ? Number.parseFloat(failMatch[2]) : undefined
1551
- },
1552
- startedCollectingError: true
2841
+ }
1553
2842
  };
1554
2843
  }
1555
2844
  const bailFailMatch = /^\(fail\) +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
@@ -1560,8 +2849,7 @@ function parseTestLine(line, currentFile) {
1560
2849
  file: currentFile,
1561
2850
  status: "failed",
1562
2851
  duration: bailFailMatch[2] ? Number.parseFloat(bailFailMatch[2]) : undefined
1563
- },
1564
- startedCollectingError: true
2852
+ }
1565
2853
  };
1566
2854
  }
1567
2855
  const skipMatch = /^⏭ +(\S.*)$/.exec(line);
@@ -1574,152 +2862,837 @@ function parseTestLine(line, currentFile) {
1574
2862
  }
1575
2863
  };
1576
2864
  }
1577
- return {};
2865
+ return {};
2866
+ }
2867
+ var NON_FAILING_RESULT_LINE = /^(?:\((?:pass|skip|todo)\)|[✓»✎⏭]) +\S/;
2868
+ var CODE_FRAME_LINE = /^\s*\d+ \|(?: |$)/;
2869
+ var ERROR_HEADING_LINE = /^(?:error|\w*Error)(?: \[[^\]]*\])?: /;
2870
+ var AFTER_FAIL_NOTE_LINE = /^\s+\^ \S/;
2871
+ function capFailureMessage(message) {
2872
+ return message.length > MAX_FAILURE_MESSAGE_LENGTH ? `${message.slice(0, MAX_FAILURE_MESSAGE_LENGTH)}
2873
+ … (${message.length - MAX_FAILURE_MESSAGE_LENGTH} more characters)` : message;
2874
+ }
2875
+ function readFailureBlock(block) {
2876
+ const lines = block.filter((line) => !isWorkflowCommandLine(line));
2877
+ const frameStart = lines.findIndex((line) => CODE_FRAME_LINE.test(line));
2878
+ const start = frameStart === -1 ? lines.findIndex((line) => ERROR_HEADING_LINE.test(line)) : frameStart;
2879
+ const text = lines.slice(Math.max(start, 0)).join(`
2880
+ `).trim();
2881
+ return { text: text === "" ? undefined : text, reported: start !== -1 };
2882
+ }
2883
+ function failureMessageFrom(block, notes) {
2884
+ const report = block.text !== undefined && (block.reported || notes.length === 0) ? capFailureMessage(block.text) : undefined;
2885
+ const parts = report === undefined ? notes : [report, ...notes];
2886
+ return parts.length === 0 ? undefined : parts.join(`
2887
+ `);
2888
+ }
2889
+ function setFailureMessage(test, block, notes) {
2890
+ const failureMessage = failureMessageFrom(block, notes);
2891
+ if (failureMessage !== undefined) {
2892
+ test.failureMessage = failureMessage;
2893
+ }
2894
+ }
2895
+ function recordTest(reader, test, index) {
2896
+ if (test.status === "failed") {
2897
+ const block = readFailureBlock(reader.lines.slice(reader.blockStart, index));
2898
+ setFailureMessage(test, block, []);
2899
+ reader.lastFailed = { test, block, notes: [] };
2900
+ }
2901
+ reader.tests.push(test);
2902
+ reader.counters[test.status]++;
2903
+ reader.blockStart = index + 1;
2904
+ }
2905
+ function readLine(reader, index) {
2906
+ const line = reader.lines[index];
2907
+ const filePath = parseFilePath(line);
2908
+ if (filePath && reader.isHeaderFile(filePath)) {
2909
+ reader.currentFile = filePath;
2910
+ reader.blockStart = index + 1;
2911
+ reader.lastFailed = undefined;
2912
+ return;
2913
+ }
2914
+ if (isWorkflowCommandLine(line)) {
2915
+ return;
2916
+ }
2917
+ if (reader.lastFailed && AFTER_FAIL_NOTE_LINE.test(line)) {
2918
+ const { test, block, notes } = reader.lastFailed;
2919
+ notes.push(line.trim());
2920
+ setFailureMessage(test, block, notes);
2921
+ reader.blockStart = index + 1;
2922
+ return;
2923
+ }
2924
+ reader.lastFailed = undefined;
2925
+ const { test } = parseTestLine(line, reader.currentFile);
2926
+ if (test) {
2927
+ recordTest(reader, test, index);
2928
+ } else if (NON_FAILING_RESULT_LINE.test(line)) {
2929
+ reader.blockStart = index + 1;
2930
+ }
2931
+ }
2932
+ var RAN_LINE = /^\s*Ran\s+(\d+)\s+tests?\b/;
2933
+ var PASS_LINE = /^\s*\d+\s+pass\s*$/;
2934
+ var COUNT_LINE = /^\s*(\d+)\s+(pass|skip|todo|fail|errors?)\s*$/;
2935
+ var BAIL_LINE = /^\s*Bailed out after (\d+) failures?\s*$/;
2936
+ function lastLineMatching(lines, from, pattern, stopAtBlank) {
2937
+ for (let index = from;index >= 0; index--) {
2938
+ const match = pattern.exec(lines[index]);
2939
+ if (match) {
2940
+ return { index, match };
2941
+ }
2942
+ if (stopAtBlank && !lines[index].trim()) {
2943
+ return;
2944
+ }
2945
+ }
2946
+ return;
2947
+ }
2948
+ function readBunSummary(output) {
2949
+ const lines = stripAnsi(output).split(`
2950
+ `);
2951
+ const lastIndex = lines.length - 1;
2952
+ const ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
2953
+ const pass = ran ? lastLineMatching(lines, ran.index - 1, PASS_LINE, true) : lastLineMatching(lines, lastIndex, PASS_LINE, false);
2954
+ const summary = {
2955
+ pass: 0,
2956
+ skip: 0,
2957
+ todo: 0,
2958
+ fail: 0,
2959
+ error: 0,
2960
+ ran: ran && Number.parseInt(ran.match[1], 10),
2961
+ bailed: undefined,
2962
+ printed: ran !== undefined || pass !== undefined
2963
+ };
2964
+ if (pass) {
2965
+ for (const line of lines.slice(pass.index, ran?.index ?? lines.length)) {
2966
+ const match = COUNT_LINE.exec(line);
2967
+ if (match) {
2968
+ summary[match[2] === "errors" ? "error" : match[2]] = Number.parseInt(match[1], 10);
2969
+ }
2970
+ }
2971
+ }
2972
+ for (const line of lines.slice(ran?.index ?? 0)) {
2973
+ const match = BAIL_LINE.exec(line);
2974
+ if (match) {
2975
+ summary.bailed = Number.parseInt(match[1], 10);
2976
+ }
2977
+ }
2978
+ return summary;
2979
+ }
2980
+ function parseSummaryLines(output) {
2981
+ const bun = readBunSummary(output);
2982
+ const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
2983
+ if (bun.bailed !== undefined) {
2984
+ counts.failed = Math.max(counts.failed, bun.bailed);
2985
+ }
2986
+ const genuinePassed = counts.passed;
2987
+ const genuineFailed = counts.failed;
2988
+ if (bun.ran !== undefined) {
2989
+ const totalParsed = counts.passed + counts.failed + counts.skipped;
2990
+ if (totalParsed !== bun.ran && counts.passed === 0 && counts.failed === 0) {
2991
+ counts.passed = bun.ran;
2992
+ }
2993
+ }
2994
+ return { ...counts, todo: bun.todo, errors: bun.error, printed: bun.printed, genuinePassed, genuineFailed };
2995
+ }
2996
+ function parseBunTestOutput(stdout, stderr, testFiles) {
2997
+ const tests = [];
2998
+ const counters = { passed: 0, failed: 0, skipped: 0 };
2999
+ const output = `${stdout}
3000
+ ${stderr}`;
3001
+ const lines = output.split(`
3002
+ `).map((line) => stripAnsi(line));
3003
+ const reader = {
3004
+ lines,
3005
+ isHeaderFile: headerFilter(lines, testFiles),
3006
+ tests,
3007
+ counters,
3008
+ currentFile: undefined,
3009
+ blockStart: 0,
3010
+ lastFailed: undefined
3011
+ };
3012
+ for (const index of lines.keys()) {
3013
+ readLine(reader, index);
3014
+ }
3015
+ const summaryCounts = parseSummaryLines(output);
3016
+ counters.passed = Math.max(counters.passed, summaryCounts.passed);
3017
+ counters.failed = Math.max(counters.failed, summaryCounts.failed);
3018
+ counters.skipped = Math.max(counters.skipped, summaryCounts.skipped);
3019
+ return {
3020
+ tests,
3021
+ totalTests: counters.passed + counters.failed + counters.skipped,
3022
+ passed: counters.passed,
3023
+ failed: counters.failed,
3024
+ skipped: counters.skipped,
3025
+ summaryPassed: summaryCounts.genuinePassed,
3026
+ summaryFailed: summaryCounts.genuineFailed,
3027
+ summarySkipped: summaryCounts.skipped,
3028
+ summaryTodo: summaryCounts.todo,
3029
+ summaryErrors: summaryCounts.errors,
3030
+ summaryPrinted: summaryCounts.printed
3031
+ };
3032
+ }
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
+ };
1578
3326
  }
1579
- function finalizeErrorMessage(currentTest, errorLines) {
1580
- if (currentTest && errorLines.length > 0) {
1581
- currentTest.failureMessage = errorLines.join(`
1582
- `).trim();
3327
+
3328
+ // src/run-profile.ts
3329
+ import { appendFileSync as appendFileSync2 } from "node:fs";
3330
+ import path10 from "node:path";
3331
+ import { StringDecoder } from "node:string_decoder";
3332
+ var PROFILE_FORMAT_VERSION = 1;
3333
+ var SPAWN_MARKS = ["spawnStart", "spawned", "firstStderr", "inspector", "firstFile", "decisive", "exit", "close"];
3334
+ var PHASES = ["prep", "spawn", "startup", "inspector", "load", "tests", "teardown", "stdio", "finish"];
3335
+ var PHASE_FROM = {
3336
+ requested: "prep",
3337
+ spawnStart: "spawn",
3338
+ spawned: "startup",
3339
+ firstStderr: "load",
3340
+ inspector: "load",
3341
+ firstFile: "tests",
3342
+ decisive: "teardown",
3343
+ exit: "stdio",
3344
+ close: "finish"
3345
+ };
3346
+ function mutantRunScope(fileScoped, testNamePattern, coveringTestCount) {
3347
+ if (fileScoped) {
3348
+ return "files";
3349
+ }
3350
+ if (testNamePattern !== undefined) {
3351
+ return "targeted";
1583
3352
  }
3353
+ return coveringTestCount > 0 ? "fallback" : "static";
1584
3354
  }
1585
- function shouldCollectErrorLine(line) {
1586
- if (!line.trim()) {
1587
- return false;
3355
+ var systemClock = { now: () => performance.now(), origin: performance.timeOrigin };
3356
+ function round3(value) {
3357
+ return Math.round(value * 1000) / 1000;
3358
+ }
3359
+ function share(part, whole) {
3360
+ return whole > 0 ? Math.round(part / whole * 1e4) / 1e4 : 0;
3361
+ }
3362
+ function computePhases(sequence) {
3363
+ const phases = {};
3364
+ if (sequence.length === 0) {
3365
+ return phases;
3366
+ }
3367
+ const end = sequence.at(-1)[1];
3368
+ let [previousMark, previousAt] = sequence[0];
3369
+ for (const [mark, at] of sequence.slice(1)) {
3370
+ if (at < previousAt || at > end) {
3371
+ continue;
3372
+ }
3373
+ const phase = mark === "inspector" ? "inspector" : PHASE_FROM[previousMark];
3374
+ phases[phase] = (phases[phase] ?? 0) + (at - previousAt);
3375
+ previousMark = mark;
3376
+ previousAt = at;
1588
3377
  }
1589
- return !/^\s*\d+\s+(?:pass|fail|skip)/.test(line);
3378
+ return phases;
1590
3379
  }
1591
- function updateCounters(test, counters, parseResult) {
1592
- if (test.status === "passed") {
1593
- counters.passed++;
1594
- return false;
1595
- } else if (test.status === "failed") {
1596
- counters.failed++;
1597
- return parseResult.startedCollectingError ?? false;
1598
- } else {
1599
- counters.skipped++;
1600
- return false;
3380
+ function percentile(sorted, q) {
3381
+ return sorted[Math.max(0, Math.ceil(q * sorted.length) - 1)];
3382
+ }
3383
+ function summarize(values) {
3384
+ const sorted = values.toSorted((a, b) => a - b);
3385
+ const sum = sorted.reduce((total, value) => total + value, 0);
3386
+ return {
3387
+ count: sorted.length,
3388
+ sum: round3(sum),
3389
+ mean: round3(sum / sorted.length),
3390
+ p50: round3(percentile(sorted, 0.5)),
3391
+ p95: round3(percentile(sorted, 0.95))
3392
+ };
3393
+ }
3394
+ function groupKeys(record) {
3395
+ if (record.kind === "dry") {
3396
+ return ["all", "dry", `dry/${record.status}`];
1601
3397
  }
3398
+ const scope = record.scope ?? "unknown";
3399
+ return ["all", "mutant", `mutant/${record.status}`, `mutant/*/${scope}`, `mutant/${record.status}/${scope}`];
1602
3400
  }
1603
- var RAN_LINE = /^\s*Ran\s+(\d+)\s+tests?\b/;
1604
- var PASS_LINE = /^\s*\d+\s+pass\s*$/;
1605
- var COUNT_LINE = /^\s*(\d+)\s+(pass|skip|todo|fail|errors?)\s*$/;
1606
- var BAIL_LINE = /^\s*Bailed out after (\d+) failures?\s*$/;
1607
- function lastLineMatching(lines, from, pattern, stopAtBlank) {
1608
- for (let index = from;index >= 0; index--) {
1609
- const match = pattern.exec(lines[index]);
1610
- if (match) {
1611
- return { index, match };
1612
- }
1613
- if (stopAtBlank && !lines[index].trim()) {
1614
- return;
3401
+ function optionalStats(values) {
3402
+ return values.length > 0 ? summarize(values) : undefined;
3403
+ }
3404
+ function groupStats(records) {
3405
+ const totalMs = summarize(records.map((record) => record.totalMs));
3406
+ const phases = {};
3407
+ const phaseShare = {};
3408
+ for (const phase of PHASES) {
3409
+ const stats = optionalStats(records.flatMap((record) => record.phases[phase] ?? []));
3410
+ if (stats) {
3411
+ phases[phase] = stats;
3412
+ phaseShare[phase] = share(stats.sum, totalMs.sum);
1615
3413
  }
1616
3414
  }
1617
- return;
1618
- }
1619
- function readBunSummary(output) {
1620
- const lines = stripAnsi(output).split(`
1621
- `);
1622
- const lastIndex = lines.length - 1;
1623
- const ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
1624
- const pass = ran ? lastLineMatching(lines, ran.index - 1, PASS_LINE, true) : lastLineMatching(lines, lastIndex, PASS_LINE, false);
1625
- const summary = {
1626
- pass: 0,
1627
- skip: 0,
1628
- todo: 0,
1629
- fail: 0,
1630
- error: 0,
1631
- ran: ran && Number.parseInt(ran.match[1], 10),
1632
- bailed: undefined,
1633
- printed: ran !== undefined || pass !== undefined
3415
+ return {
3416
+ runs: records.length,
3417
+ totalMs,
3418
+ files: optionalStats(records.flatMap((record) => record.files ?? [])),
3419
+ fileHeaders: optionalStats(records.flatMap((record) => record.fileHeaders ?? [])),
3420
+ phases,
3421
+ phaseShare
1634
3422
  };
1635
- if (pass) {
1636
- for (const line of lines.slice(pass.index, ran?.index ?? lines.length)) {
1637
- const match = COUNT_LINE.exec(line);
1638
- if (match) {
1639
- summary[match[2] === "errors" ? "error" : match[2]] = Number.parseInt(match[1], 10);
3423
+ }
3424
+ function aggregateRuns(records) {
3425
+ const groups = new Map;
3426
+ for (const record of records) {
3427
+ for (const key of groupKeys(record)) {
3428
+ const members = groups.get(key);
3429
+ if (members) {
3430
+ members.push(record);
3431
+ } else {
3432
+ groups.set(key, [record]);
1640
3433
  }
1641
3434
  }
1642
3435
  }
1643
- for (const line of lines.slice(ran?.index ?? 0)) {
1644
- const match = BAIL_LINE.exec(line);
1645
- if (match) {
1646
- summary.bailed = Number.parseInt(match[1], 10);
1647
- }
3436
+ return Object.fromEntries([...groups.keys()].toSorted((a, b) => a.localeCompare(b)).map((key) => [key, groupStats(groups.get(key))]));
3437
+ }
3438
+ var FAIL_LINE_RE = /^(?:\(fail\)|✗) /;
3439
+ var MAX_PENDING_LINE = 4096;
3440
+ function classifyStderrLine(line, bail) {
3441
+ if (fileHeaderRe.test(line)) {
3442
+ return "file";
1648
3443
  }
1649
- return summary;
3444
+ if (line.startsWith(HIT_LIMIT_SENTINEL)) {
3445
+ return "hitLimit";
3446
+ }
3447
+ if (bail && FAIL_LINE_RE.test(line)) {
3448
+ return "fail";
3449
+ }
3450
+ return RAN_LINE.test(line) ? "summary" : undefined;
1650
3451
  }
1651
- function parseSummaryLines(output) {
1652
- const bun = readBunSummary(output);
1653
- const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
1654
- if (bun.bailed !== undefined) {
1655
- counts.failed = Math.max(counts.failed, bun.bailed);
3452
+
3453
+ class RunProfile {
3454
+ owner;
3455
+ kind;
3456
+ mutantId;
3457
+ clock;
3458
+ requestedAt;
3459
+ spawnStates = [];
3460
+ details = {};
3461
+ scope;
3462
+ files;
3463
+ patternBytes;
3464
+ launches = 0;
3465
+ constructor(owner, kind, mutantId, clock) {
3466
+ this.owner = owner;
3467
+ this.kind = kind;
3468
+ this.mutantId = mutantId;
3469
+ this.clock = clock;
3470
+ this.requestedAt = clock.now();
3471
+ this.scope = kind === "dry" ? "dry" : undefined;
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
+ }
3482
+ setScope(scope) {
3483
+ this.scope = scope;
3484
+ }
3485
+ beginSpawn(bail, testFiles, testNamePattern) {
3486
+ this.files = testFiles?.length;
3487
+ this.patternBytes = testNamePattern === undefined ? undefined : Buffer.byteLength(testNamePattern);
3488
+ this.spawnStates.push({
3489
+ bail,
3490
+ marks: { spawnStart: this.clock.now() },
3491
+ fileHeaders: 0,
3492
+ scanning: true,
3493
+ decoder: new StringDecoder("utf8"),
3494
+ pending: "",
3495
+ skippingLine: false
3496
+ });
1656
3497
  }
1657
- const genuinePassed = counts.passed;
1658
- const genuineFailed = counts.failed;
1659
- if (bun.ran !== undefined) {
1660
- const totalParsed = counts.passed + counts.failed + counts.skipped;
1661
- if (totalParsed !== bun.ran && counts.passed === 0 && counts.failed === 0) {
1662
- counts.passed = bun.ran;
3498
+ mark(name) {
3499
+ const state = this.spawnStates.at(-1);
3500
+ if (state && state.marks[name] === undefined) {
3501
+ state.marks[name] = this.clock.now();
1663
3502
  }
1664
3503
  }
1665
- return { ...counts, todo: bun.todo, errors: bun.error, printed: bun.printed, genuinePassed, genuineFailed };
1666
- }
1667
- function parseBunTestOutput(stdout, stderr, testFiles) {
1668
- const tests = [];
1669
- const counters = { passed: 0, failed: 0, skipped: 0 };
1670
- const output = `${stdout}
1671
- ${stderr}`;
1672
- const lines = output.split(`
3504
+ onStderr(chunk) {
3505
+ const state = this.spawnStates.at(-1);
3506
+ if (!state) {
3507
+ return;
3508
+ }
3509
+ const at = this.clock.now();
3510
+ state.marks.firstStderr ??= at;
3511
+ if (!state.scanning) {
3512
+ return;
3513
+ }
3514
+ let text = state.decoder.write(chunk);
3515
+ if (state.skippingLine) {
3516
+ const newline = text.indexOf(`
1673
3517
  `);
1674
- const isHeaderFile = headerFilter(lines, testFiles);
1675
- let currentTest = null;
1676
- let collectingError = false;
1677
- let errorLines = [];
1678
- let currentFile;
1679
- for (const line of lines) {
1680
- const filePath = parseFilePath(line);
1681
- if (filePath && isHeaderFile(filePath)) {
1682
- currentFile = filePath;
1683
- continue;
3518
+ if (newline === -1) {
3519
+ return;
3520
+ }
3521
+ text = text.slice(newline + 1);
3522
+ state.skippingLine = false;
1684
3523
  }
1685
- if (isWorkflowCommandLine(line)) {
1686
- continue;
3524
+ const lines = (state.pending + text).split(`
3525
+ `);
3526
+ state.pending = lines.pop();
3527
+ for (const line of lines) {
3528
+ if (!this.readLine(state, stripAnsi(line).replace(/\r$/, ""), at)) {
3529
+ return;
3530
+ }
3531
+ }
3532
+ if (state.pending.length > MAX_PENDING_LINE) {
3533
+ state.pending = "";
3534
+ state.skippingLine = true;
3535
+ }
3536
+ }
3537
+ readLine(state, line, at) {
3538
+ const kind = classifyStderrLine(line, state.bail);
3539
+ if (kind === "file") {
3540
+ state.fileHeaders++;
3541
+ state.marks.firstFile ??= at;
3542
+ } else if (kind !== undefined) {
3543
+ state.decisive = kind;
3544
+ state.marks.decisive = at;
3545
+ state.scanning = false;
1687
3546
  }
1688
- const parseResult = parseTestLine(line, currentFile);
1689
- if (parseResult.test) {
1690
- if (currentTest && collectingError) {
1691
- finalizeErrorMessage(currentTest, errorLines);
1692
- errorLines = [];
3547
+ return state.scanning;
3548
+ }
3549
+ at(name) {
3550
+ this.details[`at.${name}`] ??= round3(this.clock.now() - this.requestedAt);
3551
+ }
3552
+ atEpoch(name, epochMs) {
3553
+ this.details[`at.${name}`] ??= round3(epochMs - (this.clock.origin + this.requestedAt));
3554
+ }
3555
+ preloadTimings(timings) {
3556
+ for (const [name, value] of Object.entries(timings ?? {})) {
3557
+ if (name.startsWith("at.")) {
3558
+ this.atEpoch(`preload.${name.slice(3)}`, value);
3559
+ } else {
3560
+ this.detail(`preload.${name}`, value);
1693
3561
  }
1694
- currentTest = parseResult.test;
1695
- tests.push(currentTest);
1696
- collectingError = updateCounters(currentTest, counters, parseResult);
1697
- continue;
1698
3562
  }
1699
- if (collectingError && currentTest && shouldCollectErrorLine(line)) {
1700
- errorLines.push(line);
3563
+ }
3564
+ detail(name, value) {
3565
+ this.details[name] = round3(value);
3566
+ }
3567
+ finish(status) {
3568
+ this.owner.record(this.toRecord(status, this.clock.now()));
3569
+ }
3570
+ toRecord(status, returnedAt) {
3571
+ const sequence = [["requested", this.requestedAt]];
3572
+ for (const state of this.spawnStates) {
3573
+ for (const mark of SPAWN_MARKS) {
3574
+ const at = state.marks[mark];
3575
+ if (at !== undefined) {
3576
+ sequence.push([mark, at]);
3577
+ }
3578
+ }
1701
3579
  }
3580
+ sequence.push(["returned", returnedAt]);
3581
+ const phases = computePhases(sequence);
3582
+ const last = this.spawnStates.at(-1);
3583
+ return {
3584
+ type: "run",
3585
+ v: PROFILE_FORMAT_VERSION,
3586
+ pid: this.owner.pid,
3587
+ kind: this.kind,
3588
+ mutant: this.mutantId,
3589
+ status,
3590
+ scope: this.scope,
3591
+ files: this.files,
3592
+ patternBytes: this.patternBytes,
3593
+ spawns: this.spawnStates.length,
3594
+ launches: this.kind === "dry" ? this.launches : undefined,
3595
+ bail: last?.bail,
3596
+ decisive: last?.decisive,
3597
+ fileHeaders: last?.fileHeaders,
3598
+ startEpochMs: round3(this.clock.origin + this.requestedAt),
3599
+ totalMs: round3(returnedAt - this.requestedAt),
3600
+ detail: Object.keys(this.details).length > 0 ? { ...this.details } : undefined,
3601
+ marks: this.spawnStates.map((state) => Object.fromEntries(SPAWN_MARKS.flatMap((mark) => state.marks[mark] === undefined ? [] : [[mark, round3(state.marks[mark] - this.requestedAt)]]))),
3602
+ phases: Object.fromEntries(Object.entries(phases).map(([phase, ms]) => [phase, round3(ms)]))
3603
+ };
3604
+ }
3605
+ }
3606
+ var NO_HANDLERS = Object.freeze({});
3607
+ function profileInspectorHandlers(profile) {
3608
+ if (profile === undefined) {
3609
+ return NO_HANDLERS;
1702
3610
  }
1703
- finalizeErrorMessage(currentTest, errorLines);
1704
- const summaryCounts = parseSummaryLines(output);
1705
- counters.passed = Math.max(counters.passed, summaryCounts.passed);
1706
- counters.failed = Math.max(counters.failed, summaryCounts.failed);
1707
- counters.skipped = Math.max(counters.skipped, summaryCounts.skipped);
1708
3611
  return {
1709
- tests,
1710
- totalTests: counters.passed + counters.failed + counters.skipped,
1711
- passed: counters.passed,
1712
- failed: counters.failed,
1713
- skipped: counters.skipped,
1714
- summaryPassed: summaryCounts.genuinePassed,
1715
- summaryFailed: summaryCounts.genuineFailed,
1716
- summarySkipped: summaryCounts.skipped,
1717
- summaryTodo: summaryCounts.todo,
1718
- summaryErrors: summaryCounts.errors,
1719
- summaryPrinted: summaryCounts.printed
3612
+ onTestFound: () => {
3613
+ profile.mark("firstFile");
3614
+ }
1720
3615
  };
1721
3616
  }
1722
3617
 
3618
+ class WorkerProfiler {
3619
+ file;
3620
+ logger;
3621
+ clock;
3622
+ pid;
3623
+ records = [];
3624
+ createdAt;
3625
+ failed = false;
3626
+ constructor(file, logger, clock = systemClock, pid = process.pid) {
3627
+ this.file = file;
3628
+ this.logger = logger;
3629
+ this.clock = clock;
3630
+ this.pid = pid;
3631
+ this.createdAt = clock.now();
3632
+ }
3633
+ startRun(kind, mutantId) {
3634
+ return new RunProfile(this, kind, mutantId, this.clock);
3635
+ }
3636
+ record(record) {
3637
+ this.records.push(record);
3638
+ this.append(record);
3639
+ }
3640
+ writeSummary() {
3641
+ if (this.records.length === 0) {
3642
+ return;
3643
+ }
3644
+ const end = round3(this.clock.origin + this.clock.now());
3645
+ let firstRun = Number.POSITIVE_INFINITY;
3646
+ for (const record of this.records) {
3647
+ firstRun = Math.min(firstRun, record.startEpochMs);
3648
+ }
3649
+ const busyMs = this.records.reduce((total, record) => total + record.totalMs, 0);
3650
+ const dryRunMs = this.records.reduce((total, record) => total + (record.kind === "dry" ? record.totalMs : 0), 0);
3651
+ const wallMs = end - firstRun;
3652
+ const summary = {
3653
+ type: "summary",
3654
+ v: PROFILE_FORMAT_VERSION,
3655
+ pid: this.pid,
3656
+ runs: this.records.length,
3657
+ createdEpochMs: round3(this.clock.origin + this.createdAt),
3658
+ firstRunEpochMs: firstRun,
3659
+ endEpochMs: end,
3660
+ wallMs: round3(wallMs),
3661
+ busyMs: round3(busyMs),
3662
+ dryRunMs: round3(dryRunMs),
3663
+ dryRunShareOfBusy: share(dryRunMs, busyMs),
3664
+ dryRunShareOfWall: share(dryRunMs, wallMs),
3665
+ groups: aggregateRuns(this.records)
3666
+ };
3667
+ this.records.length = 0;
3668
+ this.append(summary);
3669
+ }
3670
+ append(line) {
3671
+ if (this.failed) {
3672
+ return;
3673
+ }
3674
+ try {
3675
+ appendFileSync2(this.file, `${JSON.stringify(line)}
3676
+ `);
3677
+ } catch (error) {
3678
+ this.failed = true;
3679
+ this.logger.warn("%s: cannot append to %s (%s); profiling is off for this worker", PROFILE_ENV, this.file, error instanceof Error ? error.message : String(error));
3680
+ }
3681
+ }
3682
+ }
3683
+ function createWorkerProfiler(logger, env = process.env) {
3684
+ const value = env[PROFILE_ENV];
3685
+ if (value === undefined || value === "" || value === "0" || value === "false") {
3686
+ return;
3687
+ }
3688
+ if (!path10.isAbsolute(value)) {
3689
+ logger.warn("%s must be the absolute path of a JSONL file to append to (got %s); profiling is off", PROFILE_ENV, value);
3690
+ return;
3691
+ }
3692
+ logger.debug("Profiling every run to %s", value);
3693
+ return new WorkerProfiler(value, logger);
3694
+ }
3695
+
1723
3696
  // src/utils/bun-args.ts
1724
3697
  var BREAKS_ATTRIBUTION = "breaks per-test coverage attribution";
1725
3698
  var RETRY_REASON = "re-runs failing tests, which repeats test names (so a killedBy test cannot be resolved to one test, and incremental mode re-runs them) and cannot improve mutation scores";
@@ -1811,7 +3784,7 @@ function assertSupportedBunArgs(bunArgs) {
1811
3784
  throw new Error(`stryker-bun-runner: bun.bunArgs contains unsupported flags: ${list}. Remove them.`);
1812
3785
  }
1813
3786
  // src/utils/bun-version.ts
1814
- import { spawn as spawn3 } from "node:child_process";
3787
+ import { spawn as spawn4 } from "node:child_process";
1815
3788
  var MIN_BUN_VERSION = "1.4.0";
1816
3789
  var VERSION_CHECK_TIMEOUT_MS = 1e4;
1817
3790
  function parseBunVersion(output) {
@@ -1830,7 +3803,7 @@ function compareVersions(a, b) {
1830
3803
  function probeBunVersion(bunPath, env, timeoutMs) {
1831
3804
  return new Promise((resolve) => {
1832
3805
  try {
1833
- const child = spawn3(bunPath, ["--version"], {
3806
+ const child = spawn4(bunPath, ["--version"], {
1834
3807
  env: { ...process.env, ...env },
1835
3808
  stdio: ["ignore", "pipe", "pipe"]
1836
3809
  });
@@ -1877,9 +3850,10 @@ async function checkBunVersion(bunPath, env, timeoutMs = VERSION_CHECK_TIMEOUT_M
1877
3850
  return version;
1878
3851
  }
1879
3852
  // src/utils/sync-server.ts
1880
- import { randomBytes, timingSafeEqual } from "node:crypto";
1881
- import { createServer } from "node:http";
3853
+ import { randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
3854
+ import { createRequire } from "node:module";
1882
3855
  import { WebSocketServer, WebSocket as WebSocket3 } from "ws";
3856
+ var { createServer } = createRequire(import.meta.url)("node:http");
1883
3857
  function isExpectedPath(url, expected) {
1884
3858
  if (url === undefined) {
1885
3859
  return false;
@@ -1895,7 +3869,7 @@ function rawDataToString(data) {
1895
3869
  }
1896
3870
 
1897
3871
  class SyncServer {
1898
- token = randomBytes(16).toString("hex");
3872
+ token = randomBytes3(16).toString("hex");
1899
3873
  httpServer = null;
1900
3874
  wss = null;
1901
3875
  clients = new Set;
@@ -2032,8 +4006,8 @@ class SyncServer {
2032
4006
  }
2033
4007
  }
2034
4008
  // src/utils/bunfig-sanitizer.ts
2035
- import { readFile as readFile4, unlink as unlink3 } from "node:fs/promises";
2036
- import path5 from "node:path";
4009
+ import { readFile as readFile5, unlink as unlink3 } from "node:fs/promises";
4010
+ import path11 from "node:path";
2037
4011
  import { parse, stringify } from "smol-toml";
2038
4012
  var SAFE_TEST_KEYS = new Set([
2039
4013
  "preload",
@@ -2050,7 +4024,7 @@ var IGNORED_TEST_KEY_REASONS = new Map([
2050
4024
  ]);
2051
4025
  var FORCED_FALSE_TEST_KEY_REASONS = new Map([
2052
4026
  ["coverage", "forced to false for mutation runs: a coverageThreshold miss makes bun exit 1 even when no test fails, which would be mistaken for a mutant kill"],
2053
- ["onlyFailures", "forced to false for mutation runs: hiding passing tests would hide the results the runner needs"]
4027
+ ["onlyFailures", "forced to false for the dry run, which reads every test's result; mutant runs hide passing tests themselves"]
2054
4028
  ]);
2055
4029
  var COVERAGE_DROP_REASON = "dropped: coverage is disabled for mutation runs (the runner collects its own per-test coverage)";
2056
4030
  var GENERIC_DROP_REASON = "dropped: not on the runner's allowlist of [test] settings that are safe for mutation runs";
@@ -2067,7 +4041,7 @@ function absolutizePath(value, projectCwd) {
2067
4041
  if (typeof value !== "string") {
2068
4042
  return value;
2069
4043
  }
2070
- return path5.isAbsolute(value) ? value : path5.resolve(projectCwd, value);
4044
+ return path11.isAbsolute(value) ? value : path11.resolve(projectCwd, value);
2071
4045
  }
2072
4046
  function absolutizePathValue(value, projectCwd) {
2073
4047
  if (Array.isArray(value)) {
@@ -2076,9 +4050,9 @@ function absolutizePathValue(value, projectCwd) {
2076
4050
  return absolutizePath(value, projectCwd);
2077
4051
  }
2078
4052
  async function readSourceBunfig(projectCwd, sourceBunfig) {
2079
- const bunfigPath = sourceBunfig === undefined ? path5.join(projectCwd, "bunfig.toml") : path5.resolve(projectCwd, sourceBunfig);
4053
+ const bunfigPath = sourceBunfig === undefined ? path11.join(projectCwd, "bunfig.toml") : path11.resolve(projectCwd, sourceBunfig);
2080
4054
  try {
2081
- const content = await readFile4(bunfigPath, "utf8");
4055
+ const content = await readFile5(bunfigPath, "utf8");
2082
4056
  return parse(content);
2083
4057
  } catch (err) {
2084
4058
  if (sourceBunfig === undefined && err.code === "ENOENT") {
@@ -2091,12 +4065,60 @@ async function readSourceBunfig(projectCwd, sourceBunfig) {
2091
4065
  async function readBunfigTestRoot(projectCwd, sourceBunfig) {
2092
4066
  const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
2093
4067
  const root = rawConfig.test?.root;
2094
- return typeof root === "string" ? path5.resolve(projectCwd, root) : undefined;
4068
+ return typeof root === "string" ? path11.resolve(projectCwd, root) : undefined;
2095
4069
  }
2096
4070
  async function readBunfigTestPreloads(projectCwd, sourceBunfig) {
2097
- const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
4071
+ return testPreloadsOf(await readSourceBunfig(projectCwd, sourceBunfig), projectCwd);
4072
+ }
4073
+ function testPreloadsOf(rawConfig, projectCwd) {
2098
4074
  const preload = rawConfig.test?.preload;
2099
- return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path5.resolve(projectCwd, entry));
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;
4118
+ }
4119
+ async function readBunfigForScan(projectCwd, sourceBunfig) {
4120
+ const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
4121
+ return { preloads: testPreloadsOf(rawConfig, projectCwd), problem: bunfigScanProblem(rawConfig) };
2100
4122
  }
2101
4123
  function sanitizeTestSection(sourceTest, projectCwd, dropped) {
2102
4124
  const sanitizedTest = {};
@@ -2132,13 +4154,14 @@ async function generateSanitizedBunfig(projectCwd, tmpDir, sourceBunfig, onDropp
2132
4154
  dropped.push({ key: `test.${key}`, reason: RANDOM_ORDER_REASON, warn: false, mutantRunsOnly: true });
2133
4155
  }
2134
4156
  onDropped?.(dropped);
2135
- const outPath = path5.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`);
2136
4158
  await writePrivateFile(outPath, stringify(sanitized));
4159
+ const mutantRunTest = { ...sanitizedTest, onlyFailures: true };
2137
4160
  if (randomOrderKeys.length > 0) {
2138
- const mutantRunTest = Object.fromEntries(Object.entries(sanitizedTest).filter(([key]) => key !== "seed"));
4161
+ delete mutantRunTest.seed;
2139
4162
  mutantRunTest.randomize = false;
2140
- await writePrivateFile(mutantRunBunfigPath(outPath), stringify({ ...sanitized, test: mutantRunTest }));
2141
4163
  }
4164
+ await writePrivateFile(mutantRunBunfigPath(outPath), stringify({ ...sanitized, test: mutantRunTest }));
2142
4165
  return outPath;
2143
4166
  }
2144
4167
  async function unlinkIfPresent(filePath) {
@@ -2155,8 +4178,8 @@ async function cleanupSanitizedBunfig(filePath) {
2155
4178
  await unlinkIfPresent(mutantRunBunfigPath(filePath));
2156
4179
  }
2157
4180
  // src/utils/test-file-discovery.ts
2158
- import * as fsPromises from "node:fs/promises";
2159
- import path6 from "node:path";
4181
+ import * as fsPromises2 from "node:fs/promises";
4182
+ import path12 from "node:path";
2160
4183
  function isExcludedDirName(name) {
2161
4184
  return name.startsWith(".") || name.toLowerCase() === "node_modules";
2162
4185
  }
@@ -2166,14 +4189,14 @@ function hasExcludedAncestor(absolutePath) {
2166
4189
  }
2167
4190
  async function tryRealpath(p) {
2168
4191
  try {
2169
- return await fsPromises.realpath(p);
4192
+ return await fsPromises2.realpath(p);
2170
4193
  } catch {
2171
4194
  return;
2172
4195
  }
2173
4196
  }
2174
4197
  async function tryStat(p) {
2175
4198
  try {
2176
- return await fsPromises.stat(p);
4199
+ return await fsPromises2.stat(p);
2177
4200
  } catch {
2178
4201
  return;
2179
4202
  }
@@ -2202,7 +4225,7 @@ async function handleSymlinkFile(fullPath, entryName, ctx) {
2202
4225
  }
2203
4226
  const resolvedTarget = await tryRealpath(fullPath);
2204
4227
  if (resolvedTarget && !hasExcludedAncestor(resolvedTarget)) {
2205
- ctx.results.push(path6.relative(ctx.cwd, fullPath));
4228
+ ctx.results.push(path12.relative(ctx.cwd, fullPath));
2206
4229
  }
2207
4230
  }
2208
4231
  async function handleSymlink(fullPath, entryName, ctx) {
@@ -2218,7 +4241,7 @@ async function handleSymlink(fullPath, entryName, ctx) {
2218
4241
  }
2219
4242
  }
2220
4243
  async function processEntry(entry, dir, ctx) {
2221
- const fullPath = path6.join(dir, entry.name);
4244
+ const fullPath = path12.join(dir, entry.name);
2222
4245
  if (entry.isDirectory()) {
2223
4246
  if (!isExcludedDirName(entry.name)) {
2224
4247
  await ctx.walk(fullPath);
@@ -2226,10 +4249,20 @@ async function processEntry(entry, dir, ctx) {
2226
4249
  } else if (entry.isSymbolicLink()) {
2227
4250
  await handleSymlink(fullPath, entry.name, ctx);
2228
4251
  } else if (entry.isFile() && TEST_FILE_SUFFIX_RE.test(entry.name)) {
2229
- ctx.results.push(path6.relative(ctx.cwd, fullPath));
4252
+ ctx.results.push(path12.relative(ctx.cwd, fullPath));
2230
4253
  }
2231
4254
  }
2232
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) {
2233
4266
  const results = [];
2234
4267
  const visitedRealPaths = new Set;
2235
4268
  const ctx = { cwd, results, visitedRealPaths, logger, walk };
@@ -2245,7 +4278,7 @@ async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
2245
4278
  visitedRealPaths.add(realDir);
2246
4279
  let entries;
2247
4280
  try {
2248
- entries = await fsPromises.readdir(dir, { withFileTypes: true });
4281
+ entries = await fsPromises2.readdir(dir, { withFileTypes: true });
2249
4282
  } catch {
2250
4283
  return;
2251
4284
  }
@@ -2254,16 +4287,29 @@ async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
2254
4287
  await processEntry(entry, dir, ctx);
2255
4288
  }
2256
4289
  }
2257
- const walkRoot = await readBunfigTestRoot(cwd, sourceBunfig) ?? cwd;
2258
4290
  await walk(walkRoot);
2259
- if (results.length === 0) {
2260
- logger?.warn("discoverTestFiles: no test files found in %s; falling back to Bun discovery", walkRoot);
2261
- return;
2262
- }
2263
4291
  results.sort((a, b) => a.localeCompare(b));
2264
- logger?.debug("discoverTestFiles: found %d test files in %s", results.length, cwd);
2265
4292
  return results;
2266
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
+ }
2267
4313
  // src/utils/mutant-warn-aggregator.ts
2268
4314
  var MAX_LISTED_MUTANT_IDS = 5;
2269
4315
 
@@ -2283,13 +4329,227 @@ class MutantWarnAggregator {
2283
4329
  this.logger.debug(format, ...args);
2284
4330
  }
2285
4331
  }
2286
- flush() {
2287
- for (const [kind, ids] of this.affected) {
2288
- if (ids.size > 1) {
2289
- this.logger.warn("%s: %d mutants affected (first: %s%s); see debug log for details", kind, ids.size, [...ids].slice(0, MAX_LISTED_MUTANT_IDS).join(", "), ids.size > MAX_LISTED_MUTANT_IDS ? ", …" : "");
4332
+ flush() {
4333
+ for (const [kind, ids] of this.affected) {
4334
+ if (ids.size > 1) {
4335
+ this.logger.warn("%s: %d mutants affected (first: %s%s); see debug log for details", kind, ids.size, [...ids].slice(0, MAX_LISTED_MUTANT_IDS).join(", "), ids.size > MAX_LISTED_MUTANT_IDS ? ", …" : "");
4336
+ }
4337
+ }
4338
+ this.affected.clear();
4339
+ }
4340
+ }
4341
+ // src/utils/likely-killer-order.ts
4342
+ import path13 from "node:path";
4343
+ var MUTANT_SWITCH_RE = /stryMutAct_9fa48\("([^"\\]+)"\)/g;
4344
+ function mutantIdsInInstrumentedSource(code) {
4345
+ return new Set(Array.from(code.matchAll(MUTANT_SWITCH_RE), (match) => match[1]));
4346
+ }
4347
+
4348
+ class TestFileCoverage {
4349
+ files;
4350
+ byMutant;
4351
+ constructor(files, byMutant) {
4352
+ this.files = files;
4353
+ this.byMutant = byMutant;
4354
+ }
4355
+ static fromPerTest(perTest) {
4356
+ const files = [];
4357
+ const fileIndex = new Map;
4358
+ const byMutant = new Map;
4359
+ for (const [key, counts] of Object.entries(perTest)) {
4360
+ const sepIdx = key.lastIndexOf("@@");
4361
+ if (sepIdx === -1) {
4362
+ continue;
4363
+ }
4364
+ const file = key.slice(0, sepIdx);
4365
+ let index = fileIndex.get(file);
4366
+ if (index === undefined) {
4367
+ index = files.push(file) - 1;
4368
+ fileIndex.set(file, index);
4369
+ }
4370
+ for (const mutantId of Object.keys(counts)) {
4371
+ let indices = byMutant.get(mutantId);
4372
+ if (indices === undefined) {
4373
+ indices = new Set;
4374
+ byMutant.set(mutantId, indices);
4375
+ }
4376
+ indices.add(index);
4377
+ }
4378
+ }
4379
+ return files.length === 0 ? undefined : new TestFileCoverage(files, new Map([...byMutant].map(([mutantId, indices]) => [mutantId, [...indices]])));
4380
+ }
4381
+ static fromJson(value) {
4382
+ if (typeof value !== "object" || value === null) {
4383
+ return;
4384
+ }
4385
+ const { files, mutants } = value;
4386
+ if (!Array.isArray(files) || !files.every((file) => typeof file === "string") || typeof mutants !== "object" || mutants === null || Array.isArray(mutants)) {
4387
+ return;
4388
+ }
4389
+ const isFileIndex = (index) => Number.isInteger(index) && index >= 0 && index < files.length;
4390
+ const entries = Object.entries(mutants);
4391
+ if (!entries.every(([, indices]) => Array.isArray(indices) && indices.every((index) => isFileIndex(index)))) {
4392
+ return;
4393
+ }
4394
+ return new TestFileCoverage(files, new Map(entries));
4395
+ }
4396
+ toJSON() {
4397
+ return { files: [...this.files], mutants: Object.fromEntries([...this.byMutant].map(([mutantId, indices]) => [mutantId, [...indices]])) };
4398
+ }
4399
+ filesCovering(mutantId) {
4400
+ return new Set((this.byMutant.get(mutantId) ?? []).map((index) => this.files[index]));
4401
+ }
4402
+ coverageCounts(mutantIds) {
4403
+ const counts = new Map;
4404
+ for (const mutantId of mutantIds) {
4405
+ for (const index of this.byMutant.get(mutantId) ?? []) {
4406
+ const file = this.files[index];
4407
+ counts.set(file, (counts.get(file) ?? 0) + 1);
4408
+ }
4409
+ }
4410
+ return counts;
4411
+ }
4412
+ }
4413
+ function namedAfter(sourceFile) {
4414
+ if (sourceFile === undefined) {
4415
+ return () => false;
4416
+ }
4417
+ const sourceStem = path13.parse(sourceFile).name.toLowerCase();
4418
+ return (testFile) => path13.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
4419
+ }
4420
+ function compareKillerRanks(a, b) {
4421
+ return a.coverage - b.coverage || b.sourceMutants - a.sourceMutants || Number(b.namedAfter) - Number(a.namedAfter);
4422
+ }
4423
+ function orderLikelyKillersFirst(files, rankOf) {
4424
+ const ranks = new Map(files.map((file) => [file, rankOf(file)]));
4425
+ return files.toSorted((a, b) => compareKillerRanks(ranks.get(a), ranks.get(b)));
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
+ });
2290
4541
  }
4542
+ throwIfAbandoned(options.signal);
4543
+ await rename2(temporary, file);
4544
+ } catch (error) {
4545
+ await rm4(temporary).catch(() => {
4546
+ return;
4547
+ });
4548
+ throw error;
2291
4549
  }
2292
- this.affected.clear();
4550
+ return { path: file };
4551
+ } catch (error) {
4552
+ return { error: redactSecrets(oneLine(error), output.secrets) };
2293
4553
  }
2294
4554
  }
2295
4555
  // src/bun-test-runner.ts
@@ -2361,7 +4621,7 @@ function formatDrainSettleReason(reason) {
2361
4621
  function formatSpawnErrorMessage(spawnError) {
2362
4622
  return `could not start bun test: ${spawnError}`;
2363
4623
  }
2364
- function formatInspectorTimeoutMessage(inspectorTimeoutMs, child) {
4624
+ function formatInspectorTimeoutMessage(inspectorTimeoutMs, child, secrets) {
2365
4625
  if (child.spawnError !== undefined) {
2366
4626
  return formatSpawnErrorMessage(child.spawnError);
2367
4627
  }
@@ -2370,10 +4630,10 @@ function formatInspectorTimeoutMessage(inspectorTimeoutMs, child) {
2370
4630
  ended = "killed by the runner after the run timeout (bun.timeout)";
2371
4631
  }
2372
4632
  const prefix = `Timeout waiting for inspector URL after ${inspectorTimeoutMs}ms (raise bun.inspectorTimeout if bun is slow to start)`;
2373
- return `${prefix}; bun test ${ended}; last stderr: ${formatStderrTail(child)}`;
4633
+ return `${prefix}; bun test ${ended}; last stderr: ${formatStderrTail(child, secrets)}`;
2374
4634
  }
2375
- function formatStderrTail(child) {
2376
- const tail = child.stderr.trim().slice(-1000) || "(empty)";
4635
+ function formatStderrTail(child, secrets) {
4636
+ const tail = cleanDiagnosticText(child.stderr, secrets).trim().slice(-1000) || "(empty)";
2377
4637
  return child.outputIncomplete ? `${tail} (possibly cut short: ${formatOutputIncomplete()})` : tail;
2378
4638
  }
2379
4639
  function redactInspectorUrl(url) {
@@ -2383,8 +4643,8 @@ function redactInspectorUrl(url) {
2383
4643
  function formatOutputIncomplete() {
2384
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`;
2385
4645
  }
2386
- function formatInspectorConnectMessage(error, child) {
2387
- 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)}`;
2388
4648
  }
2389
4649
  function collectAbnormalDrainProblems(data) {
2390
4650
  const problems = [];
@@ -2400,6 +4660,32 @@ function collectAbnormalDrainProblems(data) {
2400
4660
  }
2401
4661
  return problems;
2402
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
+ }
2403
4689
  function buildTestNameIndex(tests, bunNames) {
2404
4690
  const testNameIndex = new Map;
2405
4691
  for (const [i, test] of tests.entries()) {
@@ -2411,6 +4697,17 @@ function buildTestNameIndex(tests, bunNames) {
2411
4697
  return testNameIndex;
2412
4698
  }
2413
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
+ }
2414
4711
  function defaultFailureMessage(testInfo) {
2415
4712
  return testInfo.status === "timeout" ? "Test timed out" : "Test failed";
2416
4713
  }
@@ -2468,6 +4765,7 @@ var MUTANT_WARN_KIND = {
2468
4765
  spawnError: "could not start bun test, scoring as Error rather than Killed",
2469
4766
  signalError: "bun test terminated by a signal, scoring as Error rather than Killed",
2470
4767
  noEvidence: "bun test exited non-zero with no failing test and no fail/error count, scoring as Error rather than Killed",
4768
+ earlyExit: "bun test exited 0 before printing its summary, scoring as Error rather than Survived",
2471
4769
  inconclusiveTimeout: "inconclusive timeout, scoring as Error rather than Timeout",
2472
4770
  registryVersion: "dryRun registry file has an unexpected version (skipped)",
2473
4771
  registryMalformed: "dryRun registry file is malformed (treated as absent)",
@@ -2484,12 +4782,22 @@ function emptyMutantRunCounts() {
2484
4782
  };
2485
4783
  }
2486
4784
  function newHitLimitToken() {
2487
- return randomBytes2(16).toString("hex");
4785
+ return randomBytes4(16).toString("hex");
2488
4786
  }
2489
4787
  function readReportedHitCount(stderr, token) {
2490
4788
  const match = new RegExp(String.raw`^${HIT_LIMIT_SENTINEL} ${token} (\d+)$`, "m").exec(stderr);
2491
4789
  return match ? Number(match[1]) : undefined;
2492
4790
  }
4791
+ function ignoreStep() {}
4792
+ function dryRunStepMarker(profile, stderr) {
4793
+ if (profile === undefined) {
4794
+ return ignoreStep;
4795
+ }
4796
+ profile.preloadTimings(readPreloadTimings(stderr));
4797
+ return (step) => {
4798
+ profile.at(step);
4799
+ };
4800
+ }
2493
4801
 
2494
4802
  class BunTestRunner {
2495
4803
  logger;
@@ -2505,6 +4813,8 @@ class BunTestRunner {
2505
4813
  loggedRandomizeOff = false;
2506
4814
  loggedFileArgNotes = new Set;
2507
4815
  testFileDurations;
4816
+ testFileCoverage;
4817
+ sourceCoverageCounts = new Map;
2508
4818
  sourceBunfig;
2509
4819
  testFilesOverride;
2510
4820
  mutateGlobs;
@@ -2512,12 +4822,15 @@ class BunTestRunner {
2512
4822
  maxChildRss;
2513
4823
  rssCheckIntervalMs;
2514
4824
  maxSpawnDepth;
4825
+ dryRunOutputFile;
2515
4826
  coverageAnalysis;
2516
4827
  preloadScriptPath;
2517
4828
  coverageFilePath;
2518
4829
  sanitizedBunfigPath;
2519
4830
  sanitizedBunfigCwd;
2520
4831
  tempDir;
4832
+ tempDirTouchedAt = 0;
4833
+ runOwnerPid;
2521
4834
  cachedTestNames;
2522
4835
  baseNameIndex;
2523
4836
  testNameIndex;
@@ -2538,6 +4851,15 @@ class BunTestRunner {
2538
4851
  mutantWarnings;
2539
4852
  mutantRunsByStatus = emptyMutantRunCounts();
2540
4853
  fullSuiteFallbacks = 0;
4854
+ profiler;
4855
+ alwaysImport;
4856
+ importDiscovery;
4857
+ incremental;
4858
+ inPlace;
4859
+ timeoutCorrectionMs;
4860
+ loggedUnusableCorrection = false;
4861
+ campaign;
4862
+ warnedWatchListProblem = false;
2541
4863
  currentAbortController;
2542
4864
  constructor(logger, options) {
2543
4865
  this.logger = logger;
@@ -2555,6 +4877,7 @@ class BunTestRunner {
2555
4877
  this.maxChildRss = bunOptions.maxChildRss;
2556
4878
  this.rssCheckIntervalMs = bunOptions.rssCheckIntervalMs;
2557
4879
  this.maxSpawnDepth = bunOptions.maxSpawnDepth;
4880
+ this.dryRunOutputFile = nonEmptyString(bunOptions.dryRunOutputFile);
2558
4881
  if (bunOptions.testFiles?.length === 0) {
2559
4882
  this.logger.warn("bun.testFiles was set to an empty array — treating as undefined and falling back to auto-discovery");
2560
4883
  this.testFilesOverride = undefined;
@@ -2564,7 +4887,12 @@ class BunTestRunner {
2564
4887
  this.mutateGlobs = options.mutate ?? [];
2565
4888
  this.coverageAnalysis = options.coverageAnalysis;
2566
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;
2567
4894
  this.mutantWarnings = new MutantWarnAggregator(logger);
4895
+ this.profiler = createWorkerProfiler(logger);
2568
4896
  this.logger.debug("BunTestRunner initialized with options: %o", {
2569
4897
  bunPath: this.bunPath,
2570
4898
  timeout: this.timeout,
@@ -2574,9 +4902,10 @@ class BunTestRunner {
2574
4902
  smol: this.smol,
2575
4903
  maxChildRss: this.maxChildRss,
2576
4904
  rssCheckIntervalMs: this.rssCheckIntervalMs,
2577
- maxSpawnDepth: this.maxSpawnDepth
4905
+ maxSpawnDepth: this.maxSpawnDepth,
4906
+ dryRunOutputFile: this.dryRunOutputFile
2578
4907
  });
2579
- if (this.testFilesOverride?.some((p) => path7.isAbsolute(p))) {
4908
+ if (this.testFilesOverride?.some((p) => path15.isAbsolute(p))) {
2580
4909
  const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
2581
4910
  if (isSandbox) {
2582
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());
@@ -2584,7 +4913,20 @@ class BunTestRunner {
2584
4913
  }
2585
4914
  }
2586
4915
  async resolveRegistryPath() {
2587
- return path7.join(await resolveRunTempDir(), "registry.json");
4916
+ this.assertRunOwnerIsParent();
4917
+ return path15.join(await resolveRunTempDir(), REGISTRY_FILE);
4918
+ }
4919
+ assertRunOwnerIsParent() {
4920
+ if (this.runOwnerPid !== undefined && process.ppid !== this.runOwnerPid) {
4921
+ throw new Error(`stryker-bun-runner: the Stryker main process (pid ${this.runOwnerPid}) that owns this run has exited ` + `(this worker's parent is now pid ${process.ppid}); not recreating the run's temporary directory`);
4922
+ }
4923
+ }
4924
+ keepRunTempDirFresh(now) {
4925
+ if (this.tempDir === undefined || now - this.tempDirTouchedAt < RUN_DIR_TOUCH_INTERVAL_MS || process.ppid !== this.runOwnerPid) {
4926
+ return;
4927
+ }
4928
+ this.tempDirTouchedAt = now;
4929
+ touchRunTempDir(this.tempDir, now);
2588
4930
  }
2589
4931
  resolveCoveringTestFiles(filterIds) {
2590
4932
  if (filterIds.length === 0) {
@@ -2613,9 +4955,64 @@ class BunTestRunner {
2613
4955
  }
2614
4956
  return [...files].toSorted((a, b) => a.localeCompare(b));
2615
4957
  }
2616
- orderCheapestFirst(files) {
2617
- const cost = (file) => this.testFileDurations?.get(normalizeTestFilePath(file) ?? file) ?? Number.POSITIVE_INFINITY;
2618
- return files?.toSorted((a, b) => cost(a) - cost(b));
4958
+ orderCheapestFirst(files, projectFiles) {
4959
+ const costed = files.map((file) => ({ file, cost: this.testFileDurations?.get(projectFiles.get(file)) ?? Number.POSITIVE_INFINITY }));
4960
+ return costed.toSorted((a, b) => a.cost - b.cost).map((entry) => entry.file);
4961
+ }
4962
+ projectFilesOf(files) {
4963
+ return new Map(files.map((file) => [file, normalizeTestFilePath(file) ?? file]));
4964
+ }
4965
+ ordersLikelyKillersFirst(options, coveringTestCount) {
4966
+ return coveringTestCount === 0 && !options.disableBail;
4967
+ }
4968
+ orderForMutantRun(files, ctx) {
4969
+ if (files === undefined) {
4970
+ return;
4971
+ }
4972
+ const projectFiles = this.projectFilesOf(files);
4973
+ const cheapest = this.orderCheapestFirst(files, projectFiles);
4974
+ if (!this.ordersLikelyKillersFirst(ctx.options, ctx.coveringTestCount)) {
4975
+ return cheapest;
4976
+ }
4977
+ const { id: mutantId, fileName } = ctx.options.activeMutant;
4978
+ const mutantFiles = this.testFileCoverage?.filesCovering(mutantId);
4979
+ const isNamedAfterSource = namedAfter(fileName);
4980
+ const rankOf = (file) => {
4981
+ const projectFile = projectFiles.get(file);
4982
+ return {
4983
+ coverage: mutantFiles?.has(projectFile) ? 0 : 1,
4984
+ sourceMutants: ctx.sourceCoverage?.get(projectFile) ?? 0,
4985
+ namedAfter: isNamedAfterSource(file)
4986
+ };
4987
+ };
4988
+ const ordered = orderLikelyKillersFirst(cheapest, rankOf);
4989
+ if (ordered[0] !== cheapest[0]) {
4990
+ this.logger.debug("Mutant %s: running %s first as its likeliest killer (cheapest first would start with %s)", mutantId, ordered[0], cheapest[0]);
4991
+ }
4992
+ return ordered;
4993
+ }
4994
+ setTestFileCoverage(testFileCoverage) {
4995
+ this.testFileCoverage = testFileCoverage;
4996
+ this.sourceCoverageCounts.clear();
4997
+ }
4998
+ async sourceCoverageFor(sandboxFileName) {
4999
+ const coverage = this.testFileCoverage;
5000
+ if (coverage === undefined) {
5001
+ return;
5002
+ }
5003
+ const cached = this.sourceCoverageCounts.get(sandboxFileName);
5004
+ if (cached !== undefined) {
5005
+ return cached;
5006
+ }
5007
+ let mutantIds = new Set;
5008
+ try {
5009
+ mutantIds = mutantIdsInInstrumentedSource(await fsPromises3.readFile(sandboxFileName, "utf8"));
5010
+ } catch (error) {
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));
5012
+ }
5013
+ const counts = coverage.coverageCounts(mutantIds);
5014
+ this.sourceCoverageCounts.set(sandboxFileName, counts);
5015
+ return counts;
2619
5016
  }
2620
5017
  logRandomizeOffOnce() {
2621
5018
  const sources = [];
@@ -2648,7 +5045,7 @@ class BunTestRunner {
2648
5045
  this.logger.debug("Stryker passed an empty testFiles array; ignoring it");
2649
5046
  }
2650
5047
  } else {
2651
- const files = [...new Set(requested.map((file) => path7.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));
2652
5049
  this.strykerTestFiles = { cwd, files };
2653
5050
  this.warnIfTestFilesOverridden(files, cwd);
2654
5051
  }
@@ -2710,7 +5107,7 @@ class BunTestRunner {
2710
5107
  if (this.warnedTestFilesConflict || this.testFilesOverride === undefined) {
2711
5108
  return;
2712
5109
  }
2713
- const configured = [...new Set(this.testFilesOverride.map((file) => path7.resolve(cwd, file)))];
5110
+ const configured = [...new Set(this.testFilesOverride.map((file) => path15.resolve(cwd, file)))];
2714
5111
  const selectedSet = new Set(selected);
2715
5112
  if (configured.length === selectedSet.size && configured.every((file) => selectedSet.has(file))) {
2716
5113
  return;
@@ -2780,26 +5177,50 @@ class BunTestRunner {
2780
5177
  }
2781
5178
  this.coverageFilePath = undefined;
2782
5179
  }
5180
+ this.runOwnerPid ??= process.ppid;
2783
5181
  const tempDir = await this.ensureRunTempDir();
2784
- this.coverageFilePath = path7.join(tempDir, `coverage-${Date.now()}.json`);
5182
+ this.tempDirTouchedAt = Date.now();
5183
+ this.coverageFilePath = path15.join(tempDir, `coverage-${Date.now()}.json`);
2785
5184
  this.logger.debug("Generating coverage preload script...");
2786
5185
  const eagerCwd = process.cwd();
5186
+ const testFilesPending = this.getOrDiscoverTestFiles();
5187
+ testFilesPending.catch(() => {
5188
+ return;
5189
+ });
2787
5190
  if (this.cachedEagerModules === undefined || this.cachedEagerModulesCwd !== eagerCwd) {
2788
5191
  this.cachedEagerModules = await resolveEagerModulesFromGlobs(this.mutateGlobs);
2789
5192
  this.cachedEagerModulesCwd = eagerCwd;
2790
5193
  this.logger.debug("Resolved %d eager modules from mutate globs", this.cachedEagerModules.length);
2791
5194
  }
5195
+ await this.rejectIfCampaignStopped(tempDir, this.cachedEagerModules);
2792
5196
  this.preloadScriptPath = await generatePreloadScript({
2793
5197
  tempDir,
2794
- coverageFile: this.coverageFilePath,
2795
- eagerModules: this.cachedEagerModules
5198
+ coverageFile: this.coverageFilePath
2796
5199
  });
2797
5200
  this.logger.debug("Preload script generated at: %s", this.preloadScriptPath);
2798
5201
  await this.ensureSanitizedBunfig();
2799
- const testFiles = await this.getOrDiscoverTestFiles();
5202
+ const testFiles = await testFilesPending;
2800
5203
  this.logStartSummary(testFiles);
2801
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
+ }
2802
5222
  async ensureRunTempDir() {
5223
+ this.assertRunOwnerIsParent();
2803
5224
  this.tempDir = await resolveRunTempDir();
2804
5225
  return this.tempDir;
2805
5226
  }
@@ -2839,7 +5260,7 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
2839
5260
  async loadRegistryFile(mutantId) {
2840
5261
  const registryPath = await this.resolveRegistryPath();
2841
5262
  try {
2842
- const raw = await fsPromises2.readFile(registryPath, "utf8");
5263
+ const raw = await fsPromises3.readFile(registryPath, "utf8");
2843
5264
  const parsed = JSON.parse(raw);
2844
5265
  if (parsed.version !== 2) {
2845
5266
  this.mutantWarnings.warn(MUTANT_WARN_KIND.registryVersion, mutantId, "dryRun registry file has unexpected version %s; skipping", String(parsed.version));
@@ -2861,6 +5282,10 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
2861
5282
  this.strykerTestFiles = { cwd: process.cwd(), files: selectedFiles };
2862
5283
  }
2863
5284
  this.testFileDurations = parseTestFileDurations(parsed.testFileDurations);
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) };
2864
5289
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
2865
5290
  } catch (err) {
2866
5291
  const code = err.code;
@@ -2872,7 +5297,7 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
2872
5297
  }
2873
5298
  }
2874
5299
  buildFailureMessage(testInfo, parsed) {
2875
- const parsedTest = parsed.tests.find((t) => t.name.includes(testInfo.name));
5300
+ const parsedTest = parsed.tests.find((t) => t.status === "failed" && t.name.includes(testInfo.name));
2876
5301
  const baseFailureMessage = parsedTest?.failureMessage ?? testInfo.error?.message ?? defaultFailureMessage(testInfo);
2877
5302
  const stack = testInfo.error?.stack;
2878
5303
  return stack && !baseFailureMessage.includes(stack) ? `${baseFailureMessage}
@@ -2988,11 +5413,479 @@ ${stack}` : baseFailureMessage;
2988
5413
  return { tests, testNameIndex: buildTestNameIndex(tests, bunNames) };
2989
5414
  }
2990
5415
  async dryRun(options) {
5416
+ const profile = this.profiler?.startRun("dry");
5417
+ const result = await this.executeDryRun(options, profile);
5418
+ profile?.finish(result.status);
5419
+ return result;
5420
+ }
5421
+ async executeDryRun(options, profile) {
5422
+ const startedAt = performance.now();
2991
5423
  const coverageAnalysis = this.resolveCoverageAnalysis(options);
2992
5424
  this.applyDryRunTestFiles(options);
2993
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);
2994
5750
  const abortController = new AbortController;
2995
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) {
5871
+ const abortController = new AbortController;
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;
2996
5889
  const syncServer = new SyncServer;
2997
5890
  let syncPort;
2998
5891
  try {
@@ -3003,8 +5896,10 @@ ${stack}` : baseFailureMessage;
3003
5896
  const errorMsg = error instanceof Error ? error.message : String(error);
3004
5897
  this.logger.error("Failed to start sync server: %s", errorMsg);
3005
5898
  return {
3006
- status: DryRunStatus.Error,
3007
- errorMessage: `Failed to start sync server: ${errorMsg}`
5899
+ result: {
5900
+ status: DryRunStatus.Error,
5901
+ errorMessage: `Failed to start sync server: ${errorMsg}`
5902
+ }
3008
5903
  };
3009
5904
  }
3010
5905
  const startTime = Date.now();
@@ -3016,6 +5911,7 @@ ${stack}` : baseFailureMessage;
3016
5911
  const listed = testFilesCached === null ? await this.getOrDiscoverTestFiles() : testFilesCached;
3017
5912
  this.logTestFilesSource(listed, cwd);
3018
5913
  const testFiles = this.fitTestFiles(listed, this.explicitTestFilesSource(cwd));
5914
+ const spawned = {};
3019
5915
  const testProcess = runBunTests({
3020
5916
  bunPath: this.bunPath,
3021
5917
  timeout: this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS,
@@ -3023,7 +5919,8 @@ ${stack}` : baseFailureMessage;
3023
5919
  bunArgs: this.bunArgs,
3024
5920
  bunfigPath,
3025
5921
  preloadScript: this.preloadScriptPath,
3026
- coverageFile: this.coverageFilePath,
5922
+ dryRunPlan: planFile,
5923
+ coverageFile,
3027
5924
  inspect: true,
3028
5925
  sequentialMode: true,
3029
5926
  syncPort,
@@ -3037,14 +5934,20 @@ ${stack}` : baseFailureMessage;
3037
5934
  onMemoryLimitExceeded: (rssBytes) => {
3038
5935
  this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during dryRun — killing and reporting as a timeout for this run", rssBytes);
3039
5936
  },
3040
- onInspectorReady: inspectorUrlWaiter.onReady
5937
+ onInspectorReady: inspectorUrlWaiter.onReady,
5938
+ onSpawn: (command) => {
5939
+ spawned.command = command;
5940
+ },
5941
+ profile
3041
5942
  });
5943
+ launched.child = testProcess;
3042
5944
  const inspectorUrl = await inspectorUrlWaiter.wait(testProcess, this.inspectorTimeout);
3043
5945
  if (!inspectorUrl) {
3044
5946
  await syncServer.close();
3045
5947
  const diagnosticResult = await testProcess;
3046
- const stdoutPreview = diagnosticResult.stdout.slice(0, 1000);
3047
- 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);
3048
5951
  this.logger.error(`Failed to get inspector URL within timeout (%dms).
3049
5952
  exit=%s timedOut=%s
3050
5953
  ` + `--- STDOUT (first 1000 chars) ---
@@ -3052,8 +5955,10 @@ exit=%s timedOut=%s
3052
5955
  ` + `--- STDERR (first 1000 chars) ---
3053
5956
  %s`, this.inspectorTimeout, String(diagnosticResult.exitCode), String(diagnosticResult.timedOut), stdoutPreview || "(empty)", stderrPreview || "(empty)");
3054
5957
  return {
3055
- status: DryRunStatus.Error,
3056
- errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult)
5958
+ result: {
5959
+ status: DryRunStatus.Error,
5960
+ errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult, secrets)
5961
+ }
3057
5962
  };
3058
5963
  }
3059
5964
  this.logger.debug("Inspector URL: %s", redactInspectorUrl(inspectorUrl));
@@ -3066,32 +5971,37 @@ exit=%s timedOut=%s
3066
5971
  this.logger.warn("Inspector error: %s", error.message);
3067
5972
  },
3068
5973
  onUnexpectedClose: (context) => {
3069
- 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));
3070
5975
  },
3071
5976
  onRequestStall: (info) => {
3072
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);
3073
- }
5978
+ },
5979
+ ...profileInspectorHandlers(profile)
3074
5980
  }
3075
5981
  });
3076
5982
  try {
3077
5983
  await inspector.connect();
3078
5984
  await inspector.send("TestReporter.enable", {});
5985
+ profile?.mark("inspector");
3079
5986
  this.logger.debug("Inspector connected and TestReporter enabled");
3080
5987
  } catch (error) {
3081
- const errorMsg = error instanceof Error ? error.message : String(error);
5988
+ const errorMsg = cleanDiagnosticText(error instanceof Error ? error.message : String(error), [syncServer.token]);
3082
5989
  this.logger.error("Failed to connect inspector: %s", errorMsg);
3083
5990
  abortController.abort();
3084
5991
  await inspector.close();
3085
5992
  const child = await testProcess;
3086
5993
  return {
3087
- status: DryRunStatus.Error,
3088
- errorMessage: formatInspectorConnectMessage(errorMsg, child)
5994
+ result: {
5995
+ status: DryRunStatus.Error,
5996
+ errorMessage: formatInspectorConnectMessage(errorMsg, child, [syncServer.token])
5997
+ }
3089
5998
  };
3090
5999
  }
3091
6000
  let drainSettleReason;
3092
6001
  let drainRejection;
3093
6002
  syncServer.setDrainHandler(async () => {
3094
6003
  const drainRequestReceivedAt = Date.now();
6004
+ profile?.at("drainRequest");
3095
6005
  const countsAtRequest = inspector.getEventCounts();
3096
6006
  const gapsAtRequest = inspector.getFoundIdGaps();
3097
6007
  this.logger.debug("Drain-request received: %d/%d/%d found/start/end events received so far; %d found-id gap(s)%s", countsAtRequest.found, countsAtRequest.start, countsAtRequest.end, gapsAtRequest.length, formatGapIdList(gapsAtRequest));
@@ -3112,6 +6022,7 @@ exit=%s timedOut=%s
3112
6022
  this.logger.debug("Inspector drain round-trip rejected before any wait bound was hit: %s", drainRejection);
3113
6023
  }
3114
6024
  } finally {
6025
+ profile?.at("drainSettled");
3115
6026
  cancelSilence();
3116
6027
  const elapsedMs = Date.now() - drainRequestReceivedAt;
3117
6028
  const countsAtSettle = inspector.getEventCounts();
@@ -3123,11 +6034,13 @@ exit=%s timedOut=%s
3123
6034
  this.logger.debug("Signaled preload script to proceed");
3124
6035
  const result = await testProcess;
3125
6036
  const totalElapsedMs = Date.now() - startTime;
6037
+ const markStep = dryRunStepMarker(profile, result.stderr);
3126
6038
  if (result.outputIncomplete) {
3127
6039
  this.logger.warn("%s; the dry run may report fewer tests than ran", formatOutputIncomplete());
3128
6040
  }
3129
6041
  inspector.expectClose();
3130
6042
  await inspector.waitForClose(INSPECTOR_DRAIN_TIMEOUT_MS);
6043
+ markStep("inspectorClosed");
3131
6044
  const testHierarchy = inspector.getTests();
3132
6045
  const executionOrder = inspector.getExecutionOrder();
3133
6046
  const wasClosedUnexpectedly = inspector.wasClosedUnexpectedly;
@@ -3145,11 +6058,12 @@ exit=%s timedOut=%s
3145
6058
  duplicateFoundIdCount: collisionStats.duplicateFoundIdCount
3146
6059
  });
3147
6060
  const parsed = parseBunTestOutput(result.stdout, result.stderr);
3148
- const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
6061
+ markStep("outputParsed");
6062
+ const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy, [syncServer.token]);
3149
6063
  if (earlyResult) {
3150
- return earlyResult;
6064
+ return { result: earlyResult };
3151
6065
  }
3152
- return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, coverageAnalysis);
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);
3153
6067
  } finally {
3154
6068
  abortController.abort();
3155
6069
  if (this.currentAbortController === abortController) {
@@ -3167,10 +6081,12 @@ exit=%s timedOut=%s
3167
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("; "));
3168
6082
  }
3169
6083
  }
3170
- async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, inspectorState, coverageAnalysis) {
3171
- const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
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);
6086
+ profile?.at("coverageMapped");
3172
6087
  const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, [...new Set(executionOrder)], parsed, totalElapsedMs, inspectorIdToProjectFile);
3173
6088
  tests.sort((a, b) => a.name.localeCompare(b.name));
6089
+ profile?.at("testsBuilt");
3174
6090
  const facts = {
3175
6091
  executionOrder,
3176
6092
  testHierarchy,
@@ -3180,24 +6096,35 @@ exit=%s timedOut=%s
3180
6096
  resultTestIds: tests.map((t) => t.id),
3181
6097
  duplicateFoundIdCount: inspectorState.duplicateFoundIdCount
3182
6098
  };
3183
- const gateResult = this.checkCompletenessGate(facts, parsed.summaryFailed, inspectorState.wasClosedUnexpectedly, tests, inspectorState.closeInfo, result.stderr);
3184
- if (gateResult) {
3185
- return gateResult;
6099
+ const gateReasons = this.findCompletenessProblems(facts, parsed.summaryFailed, tests, result.stderr, run.imported, [spawnInfo.syncToken]);
6100
+ profile?.at("gateChecked");
6101
+ if (gateReasons.length > 0) {
6102
+ const outputLine = await this.saveFailedDryRunOutput(result, spawnInfo);
6103
+ return { result: this.completenessError(gateReasons, inspectorState.wasClosedUnexpectedly, inspectorState.closeInfo, outputLine) };
3186
6104
  }
3187
- const coverageResult = this.checkCoverageData(mutantCoverage, tests, coverageAnalysis, result.stderr);
6105
+ const coverageResult = this.checkCoverageData(mutantCoverage, tests, run.coverageAnalysis, result.stderr, run.coverageFile);
3188
6106
  if (coverageResult) {
3189
- return coverageResult;
6107
+ return { result: coverageResult };
3190
6108
  }
3191
- await this.buildAndPersistTestRegistry(tests, testNameIndex);
3192
- this.warnOnUnidentifiedDryRunFailure(result, parsed, tests);
3193
- this.warnOnTightDryRunTimeout(totalElapsedMs);
3194
6109
  return {
3195
- status: DryRunStatus.Complete,
3196
- tests,
3197
- 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
+ }
3198
6125
  };
3199
6126
  }
3200
- checkCoverageData(coverage, tests, coverageAnalysis, stderr) {
6127
+ checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
3201
6128
  const preloadLines = extractPreloadCoverageDiagnostics(stderr);
3202
6129
  const coverageMissing = coverage === undefined && coverageAnalysis !== "off";
3203
6130
  if (!coverageMissing || tests.some((t) => t.status === TestStatus.Failed)) {
@@ -3211,9 +6138,9 @@ exit=%s timedOut=%s
3211
6138
  }
3212
6139
  return null;
3213
6140
  }
3214
- const coverageDir = this.coverageFilePath === undefined ? tmpdir2() : path7.dirname(this.coverageFilePath);
6141
+ const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
3215
6142
  const parts = [
3216
- `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).`
3217
6144
  ];
3218
6145
  if (coverageAnalysis === "perTest") {
3219
6146
  parts.push("Failing the dry run because coverageAnalysis is 'perTest'; set coverageAnalysis to 'all' or 'off' to run without per-test coverage instead.");
@@ -3236,7 +6163,7 @@ ${preloadLines.join(`
3236
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);
3237
6164
  }
3238
6165
  }
3239
- async buildAndPersistTestRegistry(tests, testNameIndex) {
6166
+ async buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaignInput) {
3240
6167
  this.cachedTestNames = new Set(tests.map((t) => t.name));
3241
6168
  if (tests.length !== this.cachedTestNames.size) {
3242
6169
  const nameCount = new Map;
@@ -3261,26 +6188,76 @@ ${preloadLines.join(`
3261
6188
  this.testNameIndex = testNameIndex;
3262
6189
  this.testFileDurations = sumDurationsByFile(tests);
3263
6190
  this.logger.debug("Recorded dry-run durations for %d test file(s) to order mutant runs cheapest-first", this.testFileDurations.size);
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;
3264
6197
  try {
3265
- const registryPath = await this.resolveRegistryPath();
3266
- const tmpPath = `${registryPath}.tmp`;
3267
- const registryData = JSON.stringify({
3268
- version: 2,
3269
- writtenAt: Date.now(),
3270
- cachedTestNames: [...this.cachedTestNames],
3271
- baseNameIndex: [...this.baseNameIndex.entries()],
3272
- testNameIndex: [...testNameIndex.entries()],
3273
- testFiles: this.selectedTestFilesFor(process.cwd()),
3274
- testFileDurations: [...this.testFileDurations.entries()]
3275
- });
3276
- 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));
3277
6231
  this.lastRegistryTmpPath = tmpPath;
3278
- await fsPromises2.rename(tmpPath, registryPath);
3279
- this.lastRegistryTmpPath = undefined;
3280
- this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, this.cachedTestNames.size);
6232
+ await writingTo(registryPath, async () => fsPromises3.rename(tmpPath, registryPath));
3281
6233
  } catch (error) {
3282
- 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));
3283
6259
  }
6260
+ return campaign;
3284
6261
  }
3285
6262
  warnRegistryWriteFailed(message) {
3286
6263
  if (this.selectedTestFilesFor(process.cwd()) === undefined) {
@@ -3305,7 +6282,9 @@ ${preloadLines.join(`
3305
6282
  }
3306
6283
  async mutantRun(options) {
3307
6284
  const startedAt = Date.now();
6285
+ const profile = this.profiler?.startRun("mutant", options.activeMutant.id);
3308
6286
  this.logger.debug("Running mutant run for mutant %s", options.activeMutant.id);
6287
+ this.keepRunTempDirFresh(startedAt);
3309
6288
  const requestedFilter = options.testFilter ?? [];
3310
6289
  if (!this.cachedTestNames) {
3311
6290
  await this.loadRegistryFile(options.activeMutant.id);
@@ -3320,11 +6299,12 @@ ${preloadLines.join(`
3320
6299
  const { localRegistry, localBaseIndex } = this.buildLocalTestFilterIndex(filterIds);
3321
6300
  const mutantCwd = process.cwd();
3322
6301
  const sanitizedBunfig = this.sanitizedBunfigPath && this.sanitizedBunfigCwd === mutantCwd ? this.sanitizedBunfigPath : await this.ensureSanitizedBunfig();
3323
- const bunfigPath = this.sanitizedBunfigRandomizes ? mutantRunBunfigPath(sanitizedBunfig) : sanitizedBunfig;
6302
+ const bunfigPath = mutantRunBunfigPath(sanitizedBunfig);
3324
6303
  this.logRandomizeOffOnce();
3325
6304
  this.effectiveTestFiles = await this.getOrDiscoverTestFiles();
3326
6305
  const strykerTimeoutMs = isUsableTimeout(options.timeout) ? options.timeout : undefined;
3327
- const limitMs = strykerTimeoutMs === undefined ? this.timeout : limitFromStrykerTimeout(strykerTimeoutMs);
6306
+ const limitMs = strykerTimeoutMs === undefined ? this.timeout : limitFromStrykerTimeout(this.correctedStrykerTimeout(strykerTimeoutMs));
6307
+ const sourceCoverage = this.ordersLikelyKillersFirst(options, filterIds.length) ? await this.sourceCoverageFor(options.sandboxFileName) : undefined;
3328
6308
  const result = await this.executeMutantRun({
3329
6309
  options,
3330
6310
  bunfigPath,
@@ -3333,11 +6313,72 @@ ${preloadLines.join(`
3333
6313
  coveringTestCount: filterIds.length,
3334
6314
  deadline: startedAt + limitMs,
3335
6315
  strykerTimeoutMs,
3336
- testFileScope
6316
+ testFileScope,
6317
+ sourceCoverage,
6318
+ profile
3337
6319
  }, testNamePattern, this.resolveCoveringTestFiles(filterIds));
3338
6320
  this.mutantRunsByStatus[result.status]++;
6321
+ profile?.finish(result.status);
3339
6322
  return result;
3340
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
+ }
3341
6382
  async resolveTestFileFilter(filter) {
3342
6383
  if (filter.length === 0) {
3343
6384
  return;
@@ -3350,7 +6391,7 @@ ${preloadLines.join(`
3350
6391
  const cwd = process.cwd();
3351
6392
  const exist = await Promise.all(entries.map(async (entry) => {
3352
6393
  try {
3353
- const stat = await fsPromises2.stat(path7.resolve(cwd, entry));
6394
+ const stat = await fsPromises3.stat(path15.resolve(cwd, entry));
3354
6395
  return stat.isFile();
3355
6396
  } catch {
3356
6397
  return false;
@@ -3364,8 +6405,9 @@ ${preloadLines.join(`
3364
6405
  const abortController = new AbortController;
3365
6406
  this.currentAbortController = abortController;
3366
6407
  const hitLimitToken = newHitLimitToken();
3367
- const ordered = this.orderCheapestFirst(ctx.testFileScope ?? (testNamePattern === undefined ? this.effectiveTestFiles : coveringTestFiles ?? this.effectiveTestFiles));
6408
+ const ordered = this.orderForMutantRun(ctx.testFileScope ?? (testNamePattern === undefined ? this.effectiveTestFiles : coveringTestFiles ?? this.effectiveTestFiles), ctx);
3368
6409
  const testFiles = this.fitTestFiles(ordered, ctx.testFileScope === undefined ? this.explicitTestFilesSource(process.cwd()) : "Stryker's testFiles option");
6410
+ ctx.profile?.setScope(mutantRunScope(ctx.testFileScope !== undefined, testNamePattern, ctx.coveringTestCount));
3369
6411
  let result;
3370
6412
  try {
3371
6413
  result = await runBunTests({
@@ -3377,6 +6419,7 @@ ${preloadLines.join(`
3377
6419
  activeMutant: options.activeMutant.id,
3378
6420
  hitLimit: options.hitLimit,
3379
6421
  hitLimitToken,
6422
+ watchList: this.watchListForMutantRuns(),
3380
6423
  bail: !options.disableBail,
3381
6424
  sequentialMode: true,
3382
6425
  preloadScript: this.preloadScriptPath,
@@ -3389,13 +6432,15 @@ ${preloadLines.join(`
3389
6432
  maxSpawnDepth: this.maxSpawnDepth,
3390
6433
  onMemoryLimitExceeded: (rssBytes) => {
3391
6434
  this.mutantWarnings.warn(MUTANT_WARN_KIND.memoryLimit, options.activeMutant.id, "bun test child exceeded maxChildRss (%d bytes observed) during mutant run %s — killing and reporting as a timeout for this mutant", rssBytes, options.activeMutant.id);
3392
- }
6435
+ },
6436
+ profile: ctx.profile
3393
6437
  });
3394
6438
  } finally {
3395
6439
  if (this.currentAbortController === abortController) {
3396
6440
  this.currentAbortController = undefined;
3397
6441
  }
3398
6442
  }
6443
+ await this.enforceWitness(result.stderr, hitLimitToken, ctx, testNamePattern);
3399
6444
  const runawayResult = this.classifyRunawayMutantRun(result, ctx, testNamePattern, hitLimitToken);
3400
6445
  if (runawayResult) {
3401
6446
  return runawayResult;
@@ -3419,6 +6464,9 @@ ${preloadLines.join(`
3419
6464
  }
3420
6465
  return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, options.activeMutant.id);
3421
6466
  }
6467
+ if (!parsed.summaryPrinted) {
6468
+ return this.classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, options.activeMutant.id);
6469
+ }
3422
6470
  return {
3423
6471
  status: MutantRunStatus.Survived,
3424
6472
  nrOfTests: parsed.totalTests
@@ -3451,7 +6499,7 @@ ${preloadLines.join(`
3451
6499
  this.mutantWarnings.warn(MUTANT_WARN_KIND.inconclusiveTimeout, mutantId, "Mutant %s: inconclusive timeout, scoring as Error rather than Timeout: %s", mutantId, errorMessage);
3452
6500
  return { status: MutantRunStatus.Error, errorMessage };
3453
6501
  }
3454
- buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, mutantId) {
6502
+ buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, mutantId, earlyExit = false) {
3455
6503
  const rawFailedNames = parsed.tests.filter((test) => test.status === "failed").map((test) => normalizeTestName(test.name));
3456
6504
  if (result.signal && rawFailedNames.length === 0) {
3457
6505
  return this.buildSignalErrorResult(result, mutantId, `bun test terminated by ${result.signal} before any test reported a failure`);
@@ -3466,6 +6514,9 @@ ${preloadLines.join(`
3466
6514
  if (result.signal && killedBy.length === 0) {
3467
6515
  return this.buildSignalErrorResult(result, mutantId, `bun test terminated by ${result.signal}; the ${rawFailedNames.length} failing test(s) reported could not be attributed to a known test`);
3468
6516
  }
6517
+ if (earlyExit && killedBy.length === 0) {
6518
+ return this.buildEarlyExitErrorResult(result, mutantId, `the ${rawFailedNames.length} failing test(s) it reported could not be attributed to a known test`);
6519
+ }
3469
6520
  if (killedBy.length === 0) {
3470
6521
  this.mutantWarnings.warn(MUTANT_WARN_KIND.noKillerIdentified, mutantId, "Mutant %s: no killing test identifiable — emitting empty killedBy; " + `this mutant will re-run on every incremental run
3471
6522
  ` + `exit=%s
@@ -3511,7 +6562,21 @@ ${preloadLines.join(`
3511
6562
  errorMessage: `bun test exited with code ${result.exitCode} but reported no failing test and no fail/error count, so there is no evidence a test detected this mutant: ${output}`
3512
6563
  };
3513
6564
  }
3514
- checkDryRunProcessResult(result, parsed, testHierarchy) {
6565
+ classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, mutantId) {
6566
+ if (parsed.tests.some((test) => test.status === "failed")) {
6567
+ return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, mutantId, true);
6568
+ }
6569
+ return this.buildEarlyExitErrorResult(result, mutantId, "no test reported a failure");
6570
+ }
6571
+ buildEarlyExitErrorResult(result, mutantId, evidence) {
6572
+ const output = stripAnsi(`${result.stdout}
6573
+ ${result.stderr}`).trim().slice(-500) || "(no output)";
6574
+ const incomplete = result.outputIncomplete ? " (its output was still held open by a process it started, so the summary may also have been cut off)" : "";
6575
+ const errorMessage = `bun exited 0 before running every selected test: it printed no test summary${incomplete}, so a test, hook or module most likely called process.exit(0) and the tests after it never ran; the mutant changed what the suite does, but ${evidence}: ${output}`;
6576
+ this.mutantWarnings.warn(MUTANT_WARN_KIND.earlyExit, mutantId, "Mutant %s: %s — scoring as Error rather than Survived", mutantId, errorMessage);
6577
+ return { status: MutantRunStatus.Error, errorMessage };
6578
+ }
6579
+ checkDryRunProcessResult(result, parsed, testHierarchy, secrets) {
3515
6580
  if (result.timedOut) {
3516
6581
  if (result.memoryLimitExceeded !== true) {
3517
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);
@@ -3522,7 +6587,7 @@ ${preloadLines.join(`
3522
6587
  return {
3523
6588
  status: DryRunStatus.Error,
3524
6589
  errorMessage: `${formatSpawnErrorMessage(result.spawnError)}
3525
- ${result.stderr}`
6590
+ ${cleanDiagnosticText(result.stderr, secrets)}`
3526
6591
  };
3527
6592
  }
3528
6593
  if (result.exitCode !== 0 && parsed.failed === 0) {
@@ -3531,7 +6596,7 @@ ${result.stderr}`
3531
6596
  if (failureDetails) {
3532
6597
  messageParts.push(failureDetails);
3533
6598
  }
3534
- messageParts.push(result.stderr);
6599
+ messageParts.push(cleanDiagnosticText(result.stderr, secrets));
3535
6600
  return {
3536
6601
  status: DryRunStatus.Error,
3537
6602
  errorMessage: messageParts.join(`
@@ -3572,45 +6637,102 @@ ${lines.join(`
3572
6637
  %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
3573
6638
  }
3574
6639
  }
3575
- 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 = []) {
3576
6680
  if (tests.some((t) => t.status === TestStatus.Failed)) {
3577
- return null;
6681
+ return [];
3578
6682
  }
3579
6683
  const reasons = findDryRunDataLoss(facts);
3580
6684
  if (summaryFailed > 0) {
3581
- 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:
3582
- ${stderr.slice(-500)}`);
3583
- }
3584
- if (reasons.length === 0) {
3585
- 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
+ }
3586
6693
  }
6694
+ return reasons;
6695
+ }
6696
+ completenessError(problems, wasClosedUnexpectedly, closeInfo, outputLine) {
6697
+ const reasons = [...problems];
3587
6698
  if (wasClosedUnexpectedly) {
3588
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`;
3589
6700
  reasons.push(`the inspector WebSocket also closed unexpectedly (${closeDetail}), which is routine on its own and listed only as context`);
3590
6701
  }
3591
- 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}`;
3592
6705
  this.logger.error("%s", errorMessage);
3593
6706
  return {
3594
6707
  status: DryRunStatus.Error,
3595
6708
  errorMessage
3596
6709
  };
3597
6710
  }
3598
- async collectAndRemapCoverage(testHierarchy, executionOrder) {
6711
+ async collectAndRemapCoverage(coverageFile, testHierarchy, executionOrder, profile) {
3599
6712
  const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
3600
- if (!this.coverageFilePath) {
3601
- return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined };
6713
+ if (!coverageFile) {
6714
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
3602
6715
  }
3603
6716
  const [rawCoverage, lateHits] = await Promise.all([
3604
- collectCoverage(this.coverageFilePath, this.logger),
3605
- collectLateHits(this.coverageFilePath, this.logger)
6717
+ collectCoverage(coverageFile, this.logger),
6718
+ collectLateHits(coverageFile, this.logger)
3606
6719
  ]);
3607
- await cleanupCoverageFile(this.coverageFilePath);
6720
+ profile?.at("coverageRead");
6721
+ await cleanupCoverageFile(coverageFile);
3608
6722
  if (!rawCoverage) {
3609
- return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined };
6723
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
3610
6724
  }
6725
+ const testFileCoverage = TestFileCoverage.fromPerTest(rawCoverage.perTest);
3611
6726
  const { coverage, inspectorIdToProjectFile, counterKeyToTestName, rawKeyCount, orphanedKeyCount } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
3612
6727
  this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
3613
- return { coverage, inspectorIdToProjectFile, coverageKeys: { keyCount: rawKeyCount, unmatchedKeyCount: orphanedKeyCount } };
6728
+ return {
6729
+ coverage,
6730
+ inspectorIdToProjectFile,
6731
+ coverageKeys: { keyCount: rawKeyCount, unmatchedKeyCount: orphanedKeyCount },
6732
+ testFileCoverage,
6733
+ rawCoverage,
6734
+ counterKeyToTestName
6735
+ };
3614
6736
  }
3615
6737
  emitCoverageBleedWarnings(lateHits, counterKeyToTestName) {
3616
6738
  const listed = lateHits.slice(0, MAX_COVERAGE_BLEED_WARNINGS);
@@ -3691,10 +6813,18 @@ ${stderr.slice(-500)}`);
3691
6813
  this.mutantRunsByStatus = emptyMutantRunCounts();
3692
6814
  this.fullSuiteFallbacks = 0;
3693
6815
  }
6816
+ writeProfileSummary() {
6817
+ try {
6818
+ this.profiler?.writeSummary();
6819
+ } catch (error) {
6820
+ this.logger.warn("Could not write the run profile's summary: %s", error instanceof Error ? error.message : String(error));
6821
+ }
6822
+ }
3694
6823
  async dispose() {
3695
6824
  this.logger.debug("Disposing BunTestRunner");
3696
6825
  this.logMutantRunSummary();
3697
6826
  this.mutantWarnings.flush();
6827
+ this.writeProfileSummary();
3698
6828
  if (this.currentAbortController) {
3699
6829
  this.logger.debug("Aborting in-flight bun test child during dispose");
3700
6830
  this.currentAbortController.abort();
@@ -3714,7 +6844,7 @@ ${stderr.slice(-500)}`);
3714
6844
  }
3715
6845
  if (this.lastRegistryTmpPath) {
3716
6846
  try {
3717
- await fsPromises2.unlink(this.lastRegistryTmpPath);
6847
+ await fsPromises3.unlink(this.lastRegistryTmpPath);
3718
6848
  } catch (err) {
3719
6849
  if (err.code !== "ENOENT") {
3720
6850
  this.logger.debug("Failed to clean registry tmp file: %s", err instanceof Error ? err.message : String(err));
@@ -3724,9 +6854,9 @@ ${stderr.slice(-500)}`);
3724
6854
  }
3725
6855
  }
3726
6856
  // src/checker-tsconfig.ts
3727
- import { readFile as readFile6, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
3728
- import { createRequire } from "node:module";
3729
- import path8 from "node:path";
6857
+ import { readFile as readFile7, rename as rename4, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
6858
+ import { createRequire as createRequire2 } from "node:module";
6859
+ import path16 from "node:path";
3730
6860
  import { glob as glob2 } from "tinyglobby";
3731
6861
  var DEFAULT_MUTATE_PATTERNS = ["{src,lib}/**"];
3732
6862
  var MUTATION_RANGE_RE = /:\d+(?::\d+)?-\d+(?::\d+)?$/;
@@ -3736,7 +6866,7 @@ var LOG_PREFIX = "[Stryker] withTestFilesExcludedFromTypeCheck: ";
3736
6866
  var MAX_QUOTED_ERRORS = 3;
3737
6867
  function loadTypeScript(cwd) {
3738
6868
  try {
3739
- return createRequire(path8.join(cwd, "package.json"))("typescript");
6869
+ return createRequire2(path16.join(cwd, "package.json"))("typescript");
3740
6870
  } catch {
3741
6871
  return;
3742
6872
  }
@@ -3763,7 +6893,7 @@ async function findTestFiles(config, cwd) {
3763
6893
  for (const relativeFiles of [await discoverTestFiles(cwd, undefined, sourceBunfig), bun.testFiles]) {
3764
6894
  if (relativeFiles) {
3765
6895
  for (const file of relativeFiles) {
3766
- testFiles.add(path8.resolve(cwd, file));
6896
+ testFiles.add(path16.resolve(cwd, file));
3767
6897
  }
3768
6898
  }
3769
6899
  }
@@ -3806,7 +6936,7 @@ function findNewErrors(derived, original, testFiles) {
3806
6936
  async function updateDerivedFile(derivedPath, shown, text) {
3807
6937
  const temp = `${derivedPath}.${process.pid}.tmp`;
3808
6938
  try {
3809
- const existing = await readFile6(derivedPath, "utf8").catch((error) => {
6939
+ const existing = await readFile7(derivedPath, "utf8").catch((error) => {
3810
6940
  if (error.code === "ENOENT") {
3811
6941
  return;
3812
6942
  }
@@ -3819,10 +6949,10 @@ async function updateDerivedFile(derivedPath, shown, text) {
3819
6949
  return `${shown} exists and was not generated by this helper (rename or delete it)`;
3820
6950
  }
3821
6951
  await writeFile2(temp, text);
3822
- await rename2(temp, derivedPath);
6952
+ await rename4(temp, derivedPath);
3823
6953
  return;
3824
6954
  } catch (error) {
3825
- await rm2(temp, { force: true });
6955
+ await rm5(temp, { force: true });
3826
6956
  return `cannot update ${shown}: ${error instanceof Error ? error.message : String(error)}`;
3827
6957
  }
3828
6958
  }
@@ -3841,12 +6971,12 @@ function derivedHeader(source) {
3841
6971
  `);
3842
6972
  }
3843
6973
  function renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints) {
3844
- const source = path8.basename(sourcePath);
6974
+ const source = path16.basename(sourcePath);
3845
6975
  const body = {
3846
6976
  extends: `./${source}`,
3847
6977
  ...project.options.declarationDir !== undefined && { compilerOptions: { declarationDir: null } },
3848
6978
  include: [],
3849
- files: entryPoints.map((file) => path8.relative(path8.dirname(derivedPath), file))
6979
+ files: entryPoints.map((file) => path16.relative(path16.dirname(derivedPath), file))
3850
6980
  };
3851
6981
  return `${derivedHeader(source)}${JSON.stringify(body, null, 2)}
3852
6982
  `;
@@ -3860,8 +6990,8 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
3860
6990
  if (!ts) {
3861
6991
  return leaveUnchanged(config, `typescript cannot be loaded from ${cwd}; install it there`);
3862
6992
  }
3863
- const sourcePath = path8.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
3864
- const shownSource = path8.relative(cwd, sourcePath);
6993
+ const sourcePath = path16.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
6994
+ const shownSource = path16.relative(cwd, sourcePath);
3865
6995
  const read = readProject(ts, sourcePath, shownSource);
3866
6996
  if ("problem" in read) {
3867
6997
  return leaveUnchanged(config, read.problem);
@@ -3878,10 +7008,10 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
3878
7008
  if (entryPoints.length === 0) {
3879
7009
  return leaveUnchanged(config, `${shownSource} would have no files left once test files are excluded`);
3880
7010
  }
3881
- const derivedPath = path8.join(path8.dirname(sourcePath), `${path8.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
3882
- const shownDerived = path8.relative(cwd, derivedPath);
7011
+ const derivedPath = path16.join(path16.dirname(sourcePath), `${path16.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7012
+ const shownDerived = path16.relative(cwd, derivedPath);
3883
7013
  const text = renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints);
3884
- const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path8.dirname(derivedPath), undefined, derivedPath);
7014
+ const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path16.dirname(derivedPath), undefined, derivedPath);
3885
7015
  const derived = createProgram(ts, derivedProject, original);
3886
7016
  const newErrors = findNewErrors(derived, original, testFiles);
3887
7017
  if (newErrors.length > 0) {
@@ -3903,6 +7033,7 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
3903
7033
  }
3904
7034
 
3905
7035
  // src/index.ts
7036
+ removeRunTempDirsOnExit();
3906
7037
  var strykerPlugins = [
3907
7038
  declareClassPlugin(PluginKind.TestRunner, "bun", BunTestRunner)
3908
7039
  ];
@@ -3974,6 +7105,31 @@ var strykerValidationSchema = {
3974
7105
  minimum: 1,
3975
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.",
3976
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"
3977
7133
  }
3978
7134
  },
3979
7135
  additionalProperties: false