@hughescr/stryker-bun-runner 1.7.2 → 1.8.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
@@ -5,12 +5,12 @@ import { PluginKind, declareClassPlugin } from "@stryker-mutator/api/plugin";
5
5
  import { randomBytes as randomBytes4 } from "node:crypto";
6
6
  import * as fsPromises3 from "node:fs/promises";
7
7
  import { tmpdir as tmpdir2 } from "node:os";
8
- import path15 from "node:path";
8
+ import path17 from "node:path";
9
9
  import { tokens, commonTokens } from "@stryker-mutator/api/plugin";
10
10
  import {
11
- DryRunStatus,
11
+ DryRunStatus as DryRunStatus2,
12
12
  MutantRunStatus,
13
- TestStatus,
13
+ TestStatus as TestStatus3,
14
14
  determineHitLimitReached,
15
15
  toMutantRunResult
16
16
  } from "@stryker-mutator/api/test-runner";
@@ -334,20 +334,23 @@ async function readAbortMarker(dir) {
334
334
  const { generation, message } = value;
335
335
  return typeof generation === "string" && generation !== "" && typeof message === "string" && message !== "" ? { generation, message } : undefined;
336
336
  }
337
+ function isPathSet(value) {
338
+ return Array.isArray(value) && value.every((file) => typeof file === "string" && path2.isAbsolute(file)) && new Set(value).size === value.length;
339
+ }
337
340
  function parseCampaignState(value) {
338
341
  if (typeof value !== "object" || value === null) {
339
342
  return;
340
343
  }
341
- const { generation, watchList, watchListFile, fingerprint } = value;
344
+ const { generation, watchList, watchListFile, fingerprint, handed } = value;
342
345
  const isList = Array.isArray(watchList) && watchList.every((file) => typeof file === "string" && file !== "");
343
346
  if (typeof generation !== "string" || generation === "" || !isList || fingerprint !== null && typeof fingerprint !== "string") {
344
347
  return;
345
348
  }
346
349
  const expectedFile = watchList.length === 0 ? null : watchListFileFor(generation);
347
- if (watchListFile !== expectedFile) {
350
+ if (watchListFile !== expectedFile || !isPathSet(handed)) {
348
351
  return;
349
352
  }
350
- return { generation, watchList, watchListFile: expectedFile, fingerprint };
353
+ return { generation, watchList, watchListFile: expectedFile, handed, fingerprint };
351
354
  }
352
355
  async function readRegistryCampaign(registryFile) {
353
356
  try {
@@ -422,10 +425,38 @@ var INCREMENTAL_ADVICE = " Results saved before the change are reused: run once
422
425
  function incrementalAdvice(incremental) {
423
426
  return incremental ? INCREMENTAL_ADVICE : "";
424
427
  }
428
+ var HANDED_INCREMENTAL_ADVICE = " Results for these files that an earlier run saved are reused: run once with --force after upgrading, and again whenever the tests that drive the worker or the child change.";
425
429
  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.";
430
+ var WORKER_CHILD_ADVICE = "A file that only a worker or a child process runs is not covered by that: it needs the call that starts it written in a form " + "the runner reads (the file's path written out in the call), or coverageAnalysis: 'off'.";
431
+ var UNSEEN_LOAD_ADVICE_OTHERS = `If the tests do load one of the others in a way the runner cannot see (through a package), add it to bun.alwaysImport. ${WORKER_CHILD_ADVICE}`;
432
+ var UNSEEN_LOAD_ADVICE_UNREAD = `If the tests do load one of those in a way the runner cannot see (through a package), add it to bun.alwaysImport. ${WORKER_CHILD_ADVICE}`;
433
+ var HAND_OFFS_UNREAD = "Files handed to a worker or a child process are not read.";
434
+ function startersText(testFiles, one) {
435
+ return `the tests in ${count(testFiles, "test file")} that start ${one ? "it" : "them"}`;
436
+ }
437
+ function handedText(handed, incremental) {
438
+ const { started, every, testFiles } = handed;
439
+ const total = started.length + every.length;
440
+ if (total === 0) {
441
+ return "";
442
+ }
443
+ const advice = incremental ? HANDED_INCREMENTAL_ADVICE : "";
444
+ const head = ` The tests hand ${total} of them to a worker or a child process`;
445
+ if (started.length > 0 && every.length > 0) {
446
+ return `${head}: the mutants of ${started.length} (${listText(started)}) are reported as covered by ${startersText(testFiles, started.length === 1)}, ` + `and those of ${every.length} (${listText(every)}) as covered by every test.${advice}`;
447
+ }
448
+ const one = total === 1;
449
+ const by = every.length === 0 ? startersText(testFiles, one) : "every test";
450
+ return `${head} (${listText(every.length === 0 ? started : every)}), so ${one ? "its" : "their"} mutants are reported as covered by ${by}.${advice}`;
451
+ }
426
452
  function leftOutText(summary, imported) {
427
453
  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)}`;
454
+ const handed = summary.handed ?? { started: [], testFiles: 0, every: [] };
455
+ const named = handed.started.length + handed.every.length;
456
+ const unseen = summary.handOffsUnread === true ? UNSEEN_LOAD_ADVICE_UNREAD : UNSEEN_LOAD_ADVICE;
457
+ const others = named === 0 ? ` ${unseen}` : ` ${UNSEEN_LOAD_ADVICE_OTHERS}`;
458
+ const advice = named === summary.left.length ? "" : others;
459
+ return `${verb}: ${listText(summary.left)}.${handedText(handed, summary.incremental)}${advice}${incrementalAdvice(summary.incremental)}`;
429
460
  }
430
461
  function importListOneRunMessage(summary, sources) {
431
462
  const imported = sources.statically + sources.named + sources.always;
@@ -457,15 +488,17 @@ var SCAN_NEXT = {
457
488
  static: "One run of the tests, with those files imported first and the rest watched.",
458
489
  dynamic: "A plain run of the tests is observed first, then the run that publishes results."
459
490
  };
491
+ var HAND_OFF_NOTE = "hand-offs ";
460
492
  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(", ")}]`;
493
+ const handed = scan.handed.length > 0 || scan.notes.some((note) => note.startsWith(HAND_OFF_NOTE)) ? `${scan.handed.length} handed to a worker or a child process [${scan.handed.join(", ")}], ` : "";
494
+ const sets = `${scan.statically.length} imported statically [${scan.statically.join(", ")}], ${scan.named.length} named in import() or require() [${scan.named.join(", ")}], ` + `${handed}${scan.always.length} kept by bun.alwaysImport [${scan.always.join(", ")}]`;
462
495
  const reasons = scan.reasons.length === 0 ? "" : `; reasons: ${escapeControlCharacters(scan.reasons.join("; "))}`;
463
496
  const notes = scan.notes.length === 0 ? "" : `; notes: ${escapeControlCharacters(scan.notes.join("; "))}`;
464
497
  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
498
  }
466
499
  function scanUnusableMessage(reason, started) {
467
500
  const what = started ? "The import scan gave no usable answer" : "The import scan was not started";
468
- return `${what}: ${escapeControlCharacters(reason)}. ${SCAN_NEXT.dynamic}`;
501
+ return `${what}: ${escapeControlCharacters(reason)}. ${SCAN_NEXT.dynamic} ${HAND_OFFS_UNREAD}`;
469
502
  }
470
503
  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
504
  function missMessage(files, testFiles, incremental) {
@@ -1069,45 +1102,179 @@ function budgetWarning(usedMs, budgetMs) {
1069
1102
  return { usedMs, remainingMs: Math.max(0, remainingMs), suggestedMinutes: Math.ceil(2 * usedMs / 60000) };
1070
1103
  }
1071
1104
 
1105
+ // src/coverage/handed-coverage.ts
1106
+ import path5 from "node:path";
1107
+ import { DryRunStatus, TestStatus } from "@stryker-mutator/api/test-runner";
1108
+ function holdsAnyId(files) {
1109
+ return files.some((entry) => entry.ids.length > 0);
1110
+ }
1111
+ function testsByFile(tests, cwd, scanned) {
1112
+ const byFile = new Map;
1113
+ let complete = true;
1114
+ for (const test of tests) {
1115
+ if (test.status !== TestStatus.Skipped) {
1116
+ const file = test.fileName === undefined ? undefined : path5.resolve(cwd, test.fileName);
1117
+ if (file === undefined || !scanned.has(file)) {
1118
+ complete = false;
1119
+ continue;
1120
+ }
1121
+ const ids = byFile.get(file) ?? [];
1122
+ ids.push(test.id);
1123
+ byFile.set(file, ids);
1124
+ }
1125
+ }
1126
+ return { byFile, complete };
1127
+ }
1128
+ function handedCredits(handed, tests) {
1129
+ return handed.map(({ file, ids, launchers, every }) => {
1130
+ const started = tests === undefined || launchers === undefined ? undefined : testsOf(launchers, tests.byFile);
1131
+ if (started === undefined || started.tests.length === 0) {
1132
+ return { file, ids };
1133
+ }
1134
+ const startedBy = { testFiles: launchers, tests: started.tests };
1135
+ return every === true || !started.all || !tests.complete ? { file, ids, startedBy, every: true } : { file, ids, startedBy };
1136
+ });
1137
+ }
1138
+ function testsOf(launchers, byFile) {
1139
+ const tests = [];
1140
+ let all = true;
1141
+ for (const launcher of launchers) {
1142
+ const own = byFile.get(launcher);
1143
+ all &&= own !== undefined;
1144
+ for (const id of own ?? []) {
1145
+ tests.push(id);
1146
+ }
1147
+ }
1148
+ return { tests, all };
1149
+ }
1150
+
1151
+ class CreditedCoverage {
1152
+ coverage;
1153
+ constructor(measured) {
1154
+ this.coverage = { static: { ...measured.static }, perTest: { ...measured.perTest } };
1155
+ }
1156
+ addStatic(ids) {
1157
+ for (const id of ids) {
1158
+ this.coverage.static[id] = 1;
1159
+ }
1160
+ }
1161
+ addToTests(ids, tests) {
1162
+ if (ids.length === 0) {
1163
+ return;
1164
+ }
1165
+ for (const test of tests) {
1166
+ const entry = { ...this.coverage.perTest[test] };
1167
+ for (const id of ids) {
1168
+ entry[id] = Math.max(entry[id] ?? 0, 1);
1169
+ }
1170
+ this.coverage.perTest[test] = entry;
1171
+ }
1172
+ }
1173
+ }
1174
+ var EVERY_TEST_ENTRY_LIMIT = 5000000;
1175
+ var n = (value) => value.toLocaleString("en-US");
1176
+ function overLimitWarning(ids, tests, limit) {
1177
+ return `Dry run: ${n(ids)} mutants of files the tests hand to a worker or a child process are covered by every test, ` + `but crediting each of the ${n(tests)} tests that ran with them would take ${n(ids * tests)} per-test entries, more than the runner adds (${n(limit)}), ` + "so they are reported as static only. With ignoreStatic, Stryker ignores them, or runs only the tests known to start their file or seen to reach them. " + "To test them, run without ignoreStatic, or write the path of the worker's or the child's file literally in the test file that starts it, " + "so that the runner can tell which tests start it.";
1178
+ }
1179
+ function creditHandedCoverage(result, credits, display, perTestForEvery, entryLimit = EVERY_TEST_ENTRY_LIMIT) {
1180
+ if (result.status !== DryRunStatus.Complete || result.mutantCoverage === undefined || credits.length === 0) {
1181
+ return { result, files: [], debug: [] };
1182
+ }
1183
+ const measured = result.mutantCoverage;
1184
+ const counts = new CreditedCoverage(measured);
1185
+ const debug = [];
1186
+ const files = [];
1187
+ const toEvery = [];
1188
+ let toTests = 0;
1189
+ let toStatic = 0;
1190
+ for (const { file, ids, startedBy, every } of credits) {
1191
+ if (ids.length === 0) {
1192
+ debug.push(`Dry run: ${display(file)}, which the tests hand to a worker or a child process, holds no mutant id; none of its mutants is credited`);
1193
+ } else {
1194
+ files.push(file);
1195
+ }
1196
+ if (startedBy !== undefined) {
1197
+ counts.addToTests(ids, startedBy.tests);
1198
+ toTests += ids.length;
1199
+ }
1200
+ if (startedBy === undefined || every === true) {
1201
+ const notStatic = ids.filter((id) => (measured.static[id] ?? 0) <= 0);
1202
+ counts.addStatic(notStatic);
1203
+ toStatic += notStatic.length;
1204
+ for (const id of ids) {
1205
+ toEvery.push(id);
1206
+ }
1207
+ }
1208
+ }
1209
+ const { text, warning } = perTestForEvery ? creditEachTest(counts, result.tests, toEvery, entryLimit) : { text: "" };
1210
+ debug.push(`Dry run: of the mutants of ${credits.length} files the tests hand to a worker or a child process, ${toTests} credited to the tests of the test files that start them and ${toStatic} reported as static (run against every test)${text}`);
1211
+ return { result: { ...result, mutantCoverage: counts.coverage }, files, debug, ...warning === undefined ? {} : { warning } };
1212
+ }
1213
+ function creditEachTest(counts, tests, ids, entryLimit) {
1214
+ const ran = tests.filter((test) => test.status !== TestStatus.Skipped).map((test) => test.id);
1215
+ if (ids.length * ran.length > entryLimit) {
1216
+ return {
1217
+ text: `, and none credited to each of the ${ran.length} tests that ran (${ids.length} would take more than ${entryLimit} per-test entries)`,
1218
+ warning: overLimitWarning(ids.length, ran.length, entryLimit)
1219
+ };
1220
+ }
1221
+ counts.addToTests(ids, ran);
1222
+ return { text: `, and ${ids.length} credited to each of the ${ran.length} tests that ran` };
1223
+ }
1224
+
1072
1225
  // src/coverage/import-scan-runner.ts
1073
1226
  import { spawn } from "node:child_process";
1074
1227
  import { randomBytes as randomBytes2 } from "node:crypto";
1075
1228
  import { rm as rm3 } from "node:fs/promises";
1076
- import path5 from "node:path";
1229
+ import path6 from "node:path";
1077
1230
  import { fileURLToPath } from "node:url";
1078
1231
  var IMPORT_SCAN_TIMEOUT_MS = 5000;
1232
+ var HAND_OFF_BUDGET = { wallMs: 250, files: 1000, ids: 1e5 };
1233
+ var HAND_OFF_GRACE_MS = 250;
1234
+ var MAX_MUTANT_ID_LENGTH = 32;
1235
+ var MAX_LAUNCHERS = 1e5;
1236
+ var LAUNCHERS_KEY_BYTES = 32;
1079
1237
  var STDERR_EXCERPT_CHARS = 2000;
1080
1238
  var IMPORT_SCAN_STDERR_LIMIT_BYTES = 64 * 1024;
1081
1239
  var STDOUT_BASE_BYTES = 1024 * 1024;
1082
1240
  function scanOutputLimits(input) {
1083
1241
  const eagerBytes = input.eager.reduce((sum, file) => sum + Buffer.byteLength(file) + 3, 0);
1084
- return { stdout: STDOUT_BASE_BYTES + 6 * eagerBytes, stderr: IMPORT_SCAN_STDERR_LIMIT_BYTES };
1242
+ const idBytes = (input.handOffBudget ?? HAND_OFF_BUDGET).ids * (6 * MAX_MUTANT_ID_LENGTH + 3);
1243
+ const launcherBytes = MAX_LAUNCHERS * (String(input.tests.length).length + 1) + LAUNCHERS_KEY_BYTES * input.eager.length;
1244
+ return { stdout: 2 * STDOUT_BASE_BYTES + 12 * eagerBytes + idBytes + launcherBytes, stderr: IMPORT_SCAN_STDERR_LIMIT_BYTES };
1085
1245
  }
1086
1246
  function resolveBunExecutable(bunPath, cwd) {
1087
- const hasDirectory = bunPath.includes("/") || path5.sep === "\\" && bunPath.includes("\\");
1088
- return hasDirectory && !path5.isAbsolute(bunPath) ? path5.resolve(cwd, bunPath) : bunPath;
1247
+ const hasDirectory = bunPath.includes("/") || path6.sep === "\\" && bunPath.includes("\\");
1248
+ return hasDirectory && !path6.isAbsolute(bunPath) ? path6.resolve(cwd, bunPath) : bunPath;
1089
1249
  }
1090
1250
  var PRELOADING_ENV = ["BUN_OPTIONS", "NODE_OPTIONS"];
1091
1251
  function resolveImportScanScript(moduleDir) {
1092
1252
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1093
- return isBundled ? path5.join(moduleDir, "templates/import-scan.js") : path5.join(moduleDir, "import-scan.ts");
1253
+ return isBundled ? path6.join(moduleDir, "templates/import-scan.js") : path6.join(moduleDir, "import-scan.ts");
1094
1254
  }
1095
1255
  function failedScanResult(reason) {
1096
- return { answer: "dynamic", mandatory: [], named: [], reasons: [reason], notes: [], scannedFiles: 0, elapsedMs: 0 };
1256
+ return { answer: "dynamic", mandatory: [], named: [], handed: [], reasons: [reason], notes: [], scannedFiles: 0, elapsedMs: 0 };
1097
1257
  }
1098
1258
  var isStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
1099
- function parseImportScanOutput(stdout, eagerList) {
1259
+ function jsonObject(line, what) {
1100
1260
  let value;
1101
1261
  try {
1102
- value = JSON.parse(stdout);
1262
+ value = JSON.parse(line);
1103
1263
  } catch (error) {
1104
- return { problem: `its output is not JSON (${error.message})` };
1264
+ return { problem: `its ${what} is not JSON (${error.message})` };
1105
1265
  }
1106
1266
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
1107
- return { problem: "its output is not a JSON object" };
1267
+ return { problem: `its ${what} is not a JSON object` };
1108
1268
  }
1109
- const output = value;
1110
- const problem = outputProblem(output, new Set(eagerList));
1269
+ return { value };
1270
+ }
1271
+ function parseScanAnswer(line, eagerList) {
1272
+ const parsed = jsonObject(line, "output");
1273
+ if ("problem" in parsed) {
1274
+ return parsed;
1275
+ }
1276
+ const output = parsed.value;
1277
+ const problem = answerProblem(output, new Set(eagerList));
1111
1278
  if (problem !== undefined) {
1112
1279
  return { problem };
1113
1280
  }
@@ -1115,7 +1282,7 @@ function parseImportScanOutput(stdout, eagerList) {
1115
1282
  const mandatorySet = new Set(mandatory);
1116
1283
  const namedSet = new Set(named);
1117
1284
  return {
1118
- result: {
1285
+ answer: {
1119
1286
  answer,
1120
1287
  mandatory: eagerList.filter((file) => mandatorySet.has(file)),
1121
1288
  named: eagerList.filter((file) => namedSet.has(file)),
@@ -1126,7 +1293,7 @@ function parseImportScanOutput(stdout, eagerList) {
1126
1293
  }
1127
1294
  };
1128
1295
  }
1129
- function outputProblem(output, eager) {
1296
+ function answerProblem(output, eager) {
1130
1297
  if (output.answer !== "full" && output.answer !== "static" && output.answer !== "dynamic") {
1131
1298
  return `its answer ${JSON.stringify(output.answer)} is not full, static or dynamic`;
1132
1299
  }
@@ -1136,12 +1303,18 @@ function outputProblem(output, eager) {
1136
1303
  return `its ${name} list is not a list of files of the eager list`;
1137
1304
  }
1138
1305
  }
1139
- for (const name of ["reasons", "notes"]) {
1306
+ return notesProblem(output, ["reasons", "notes"]) ?? countsProblem(output, ["scannedFiles", "elapsedMs"]);
1307
+ }
1308
+ function notesProblem(output, names) {
1309
+ for (const name of names) {
1140
1310
  if (!isStringArray(output[name])) {
1141
1311
  return `its ${name} are not a list of strings`;
1142
1312
  }
1143
1313
  }
1144
- for (const name of ["scannedFiles", "elapsedMs"]) {
1314
+ return;
1315
+ }
1316
+ function countsProblem(output, names) {
1317
+ for (const name of names) {
1145
1318
  const value = output[name];
1146
1319
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
1147
1320
  return `its ${name} is not a non-negative number`;
@@ -1149,6 +1322,98 @@ function outputProblem(output, eager) {
1149
1322
  }
1150
1323
  return;
1151
1324
  }
1325
+ function isIdList(ids) {
1326
+ return isStringArray(ids) && ids.every((id) => id !== "" && id.length <= MAX_MUTANT_ID_LENGTH) && new Set(ids).size === ids.length;
1327
+ }
1328
+ function launcherFiles(launchers, tests) {
1329
+ if (launchers === undefined) {
1330
+ return {};
1331
+ }
1332
+ if (!Array.isArray(launchers) || launchers.length === 0) {
1333
+ return;
1334
+ }
1335
+ const files = [];
1336
+ let last = -1;
1337
+ for (const index of launchers) {
1338
+ if (!Number.isSafeInteger(index) || index <= last || index >= tests.length) {
1339
+ return;
1340
+ }
1341
+ last = index;
1342
+ files.push(tests[last]);
1343
+ }
1344
+ return { files };
1345
+ }
1346
+ function handedEntry(entry, eager, tests) {
1347
+ const { file, ids, launchers, every } = entry ?? {};
1348
+ const starters = launcherFiles(launchers, tests);
1349
+ if (typeof file !== "string" || !eager.has(file) || !isIdList(ids) || starters === undefined) {
1350
+ return;
1351
+ }
1352
+ if (starters.files === undefined) {
1353
+ return every === undefined ? { file, ids } : undefined;
1354
+ }
1355
+ if (every === undefined) {
1356
+ return { file, ids, launchers: starters.files };
1357
+ }
1358
+ return every === true ? { file, ids, launchers: starters.files, every: true } : undefined;
1359
+ }
1360
+ function parseScanHandOffs(line, eagerList, testList) {
1361
+ const parsed = jsonObject(line, "hand-off line");
1362
+ if ("problem" in parsed) {
1363
+ return parsed;
1364
+ }
1365
+ const output = parsed.value;
1366
+ const eager = new Set(eagerList);
1367
+ const { handed } = output;
1368
+ const notHanded = { problem: "its handed list is not a list of files of the eager list, each once with its mutant ids and the test files that start it" };
1369
+ if (!Array.isArray(handed)) {
1370
+ return notHanded;
1371
+ }
1372
+ const byFile = new Map;
1373
+ for (const entry of handed) {
1374
+ const read = handedEntry(entry, eager, testList);
1375
+ if (read === undefined || byFile.has(read.file)) {
1376
+ return notHanded;
1377
+ }
1378
+ byFile.set(read.file, read);
1379
+ }
1380
+ const problem = notesProblem(output, ["notes"]) ?? countsProblem(output, ["elapsedMs"]);
1381
+ if (problem !== undefined) {
1382
+ return { problem };
1383
+ }
1384
+ return { handOffs: { handed: eagerList.filter((file) => byFile.has(file)).map((file) => byFile.get(file)), notes: output.notes } };
1385
+ }
1386
+ function handOffsNotRead(why) {
1387
+ return `hand-offs not read: ${why}`;
1388
+ }
1389
+ function parseImportScanOutput(stdout, input, handOffFailure) {
1390
+ const lines = stdout.split(`
1391
+ `);
1392
+ const parsed = parseScanAnswer(lines[0], input.eager);
1393
+ if ("problem" in parsed) {
1394
+ return parsed;
1395
+ }
1396
+ const { answer } = parsed;
1397
+ const withoutHandOffs = (why) => ({ result: { ...answer, handed: [], notes: [...answer.notes, handOffsNotRead(why)] } });
1398
+ if (handOffFailure !== undefined) {
1399
+ return withoutHandOffs(handOffFailure);
1400
+ }
1401
+ if (lines.length !== 3 || lines[2] !== "") {
1402
+ return withoutHandOffs("the scan helper did not print them on a line of their own");
1403
+ }
1404
+ const handOffs = parseScanHandOffs(lines[1], input.eager, input.tests);
1405
+ if ("problem" in handOffs) {
1406
+ return withoutHandOffs(`the scan helper's hand-off line cannot be used: ${handOffs.problem}`);
1407
+ }
1408
+ return { result: { ...answer, handed: handOffs.handOffs.handed, notes: [...answer.notes, ...handOffs.handOffs.notes] } };
1409
+ }
1410
+ function lineEnds(chunk) {
1411
+ let count = 0;
1412
+ for (let at = chunk.indexOf(10);at !== -1; at = chunk.indexOf(10, at + 1)) {
1413
+ count++;
1414
+ }
1415
+ return count;
1416
+ }
1152
1417
 
1153
1418
  class BoundedStream {
1154
1419
  limit;
@@ -1158,8 +1423,10 @@ class BoundedStream {
1158
1423
  this.limit = limit;
1159
1424
  }
1160
1425
  add(chunk) {
1426
+ const room = this.limit - this.bytes;
1161
1427
  this.bytes += chunk.length;
1162
1428
  if (this.bytes > this.limit) {
1429
+ this.chunks.push(chunk.subarray(0, room));
1163
1430
  return false;
1164
1431
  }
1165
1432
  this.chunks.push(chunk);
@@ -1169,18 +1436,27 @@ class BoundedStream {
1169
1436
  return Buffer.concat(this.chunks).toString("utf8");
1170
1437
  }
1171
1438
  }
1172
- function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
1439
+ function runHelper(bunPath, args, cwd, limits) {
1173
1440
  const env = { ...process.env };
1174
1441
  for (const name of PRELOADING_ENV) {
1175
1442
  delete env[name];
1176
1443
  }
1444
+ const { timeoutMs, handOffMs, maxBytes } = limits;
1177
1445
  return new Promise((resolve) => {
1178
1446
  const streams = { stdout: new BoundedStream(maxBytes.stdout), stderr: new BoundedStream(maxBytes.stderr) };
1179
1447
  let timedOut = false;
1448
+ let cut = false;
1180
1449
  let overflow;
1181
1450
  let error;
1451
+ let answeredAt;
1452
+ let complete = false;
1453
+ let newlines = 0;
1454
+ let handOffTimer;
1455
+ let answered = false;
1182
1456
  const ended = (exitCode, signal) => {
1183
- resolve({ stdout: streams.stdout.text(), stderr: streams.stderr.text(), exitCode, signal, timedOut, overflow, error });
1457
+ answered = true;
1458
+ clearTimeout(handOffTimer);
1459
+ resolve({ stdout: streams.stdout.text(), stderr: streams.stderr.text(), exitCode, signal, timedOut, cut, overflow, error, answeredAt, complete });
1184
1460
  };
1185
1461
  let child;
1186
1462
  try {
@@ -1196,15 +1472,42 @@ function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
1196
1472
  child.stderr?.destroy();
1197
1473
  ended(null, null);
1198
1474
  };
1475
+ const release = () => {
1476
+ child.unref();
1477
+ for (const stream of [child.stdout, child.stderr]) {
1478
+ stream?.unref();
1479
+ }
1480
+ ended(null, null);
1481
+ };
1199
1482
  const timer = setTimeout(() => {
1200
1483
  timedOut = true;
1201
1484
  abandon();
1202
1485
  }, timeoutMs);
1486
+ const cutHandOffs = () => {
1487
+ cut = true;
1488
+ clearTimeout(timer);
1489
+ abandon();
1490
+ };
1203
1491
  const collect = (name) => (chunk) => {
1204
- if (!streams[name].add(chunk) && overflow === undefined) {
1492
+ if (answered) {
1493
+ return;
1494
+ }
1495
+ const kept = streams[name].add(chunk);
1496
+ if (name === "stdout") {
1497
+ newlines += lineEnds(chunk);
1498
+ }
1499
+ if (newlines > 0 && answeredAt === undefined) {
1500
+ answeredAt = performance.now();
1501
+ handOffTimer = setTimeout(cutHandOffs, handOffMs);
1502
+ }
1503
+ if (!kept) {
1205
1504
  overflow = name;
1206
1505
  clearTimeout(timer);
1207
1506
  abandon();
1507
+ } else if (newlines >= 2) {
1508
+ complete = true;
1509
+ clearTimeout(timer);
1510
+ release();
1208
1511
  }
1209
1512
  };
1210
1513
  child.stdout?.on("data", collect("stdout"));
@@ -1218,17 +1521,20 @@ function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
1218
1521
  });
1219
1522
  });
1220
1523
  }
1221
- function helperFailure(exit, timeoutMs, maxBytes) {
1524
+ function helperFailure(exit, limits) {
1222
1525
  if (exit.error !== undefined) {
1223
1526
  return `the scan helper could not be started (${exit.error.message})`;
1224
1527
  }
1225
1528
  if (exit.overflow !== undefined) {
1226
- return `the scan helper printed more than ${maxBytes[exit.overflow]} bytes on ${exit.overflow}`;
1529
+ return `the scan helper printed more than ${limits.maxBytes[exit.overflow]} bytes on ${exit.overflow}`;
1227
1530
  }
1228
1531
  if (exit.timedOut) {
1229
- return `the scan helper did not finish within ${timeoutMs} ms`;
1532
+ return `the scan helper did not finish within ${limits.timeoutMs} ms`;
1230
1533
  }
1231
- if (exit.exitCode !== 0) {
1534
+ if (exit.cut) {
1535
+ return `the scan helper did not finish them within ${limits.handOffMs} ms of its answer`;
1536
+ }
1537
+ if (!exit.complete && exit.exitCode !== 0) {
1232
1538
  const how = exit.exitCode === null ? `was ended by ${exit.signal}` : `exited with code ${exit.exitCode}`;
1233
1539
  const said = exit.stderr.trim().slice(0, STDERR_EXCERPT_CHARS);
1234
1540
  return said === "" ? `the scan helper ${how}` : `the scan helper ${how}: ${said}`;
@@ -1237,30 +1543,39 @@ function helperFailure(exit, timeoutMs, maxBytes) {
1237
1543
  }
1238
1544
  async function runImportScan(input, launch) {
1239
1545
  const started = performance.now();
1240
- const timeoutMs = launch.timeoutMs ?? IMPORT_SCAN_TIMEOUT_MS;
1241
- const maxBytes = launch.maxBytes ?? scanOutputLimits(input);
1242
- const scriptPath = launch.scriptPath ?? resolveImportScanScript(path5.dirname(fileURLToPath(import.meta.url)));
1243
- const stem = path5.join(launch.workDir, `import-scan-${process.pid}-${randomBytes2(8).toString("hex")}`);
1546
+ const scanInput = { ...input, handOffBudget: input.handOffBudget ?? HAND_OFF_BUDGET };
1547
+ const limits = {
1548
+ timeoutMs: launch.timeoutMs ?? IMPORT_SCAN_TIMEOUT_MS,
1549
+ handOffMs: scanInput.handOffBudget.wallMs + HAND_OFF_GRACE_MS,
1550
+ maxBytes: launch.maxBytes ?? scanOutputLimits(scanInput)
1551
+ };
1552
+ const scriptPath = launch.scriptPath ?? resolveImportScanScript(path6.dirname(fileURLToPath(import.meta.url)));
1553
+ const stem = path6.join(launch.workDir, `import-scan-${process.pid}-${randomBytes2(8).toString("hex")}`);
1244
1554
  const inputFile = `${stem}.json`;
1245
1555
  const configFile = `${stem}.bunfig.toml`;
1246
- const report = (result, failure) => ({ result, failure, wallMs: performance.now() - started });
1556
+ const report = (result, failure, answeredAt) => {
1557
+ const ended = performance.now();
1558
+ return { result, failure, wallMs: ended - started, answerMs: (answeredAt ?? ended) - started };
1559
+ };
1247
1560
  const fail = (failure) => report(failedScanResult(failure), failure);
1248
1561
  try {
1249
1562
  try {
1250
1563
  await ensurePrivateDir(launch.workDir);
1251
- await writePrivateFile(inputFile, JSON.stringify(input));
1564
+ await writePrivateFile(inputFile, JSON.stringify(scanInput));
1252
1565
  await writePrivateFile(configFile, "");
1253
1566
  } catch (error) {
1254
1567
  return fail(`the scan's input could not be written (${error.message})`);
1255
1568
  }
1256
1569
  const bunPath = resolveBunExecutable(launch.bunPath, process.cwd());
1257
- const exit = await runHelper(bunPath, ["--no-macros", "--no-install", `--config=${configFile}`, scriptPath, inputFile], launch.workDir, timeoutMs, maxBytes);
1258
- const failure = helperFailure(exit, timeoutMs, maxBytes);
1259
- if (failure !== undefined) {
1570
+ const exit = await runHelper(bunPath, ["--no-macros", "--no-install", `--config=${configFile}`, scriptPath, inputFile], launch.workDir, limits);
1571
+ const failure = helperFailure(exit, limits);
1572
+ const answered = exit.stdout.includes(`
1573
+ `);
1574
+ if (failure !== undefined && !answered) {
1260
1575
  return fail(failure);
1261
1576
  }
1262
- const parsed = parseImportScanOutput(exit.stdout, input.eager);
1263
- return "problem" in parsed ? fail(`the scan helper's answer cannot be used: ${parsed.problem}`) : report(parsed.result, null);
1577
+ const parsed = parseImportScanOutput(exit.stdout, input, failure);
1578
+ return "problem" in parsed ? fail(`the scan helper's answer cannot be used: ${parsed.problem}`) : report(parsed.result, null, exit.answeredAt);
1264
1579
  } finally {
1265
1580
  await Promise.all([inputFile, configFile].map((file) => rm3(file).catch(() => {
1266
1581
  return;
@@ -1270,7 +1585,7 @@ async function runImportScan(input, launch) {
1270
1585
 
1271
1586
  // src/coverage/preload-generator.ts
1272
1587
  import { unlink, readFile as readFile2, realpath as realpath2 } from "node:fs/promises";
1273
- import path6 from "node:path";
1588
+ import path7 from "node:path";
1274
1589
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1275
1590
  import { glob } from "tinyglobby";
1276
1591
 
@@ -1342,7 +1657,7 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
1342
1657
  expandDirectories: false
1343
1658
  });
1344
1659
  const filtered = paths.filter((p) => CODE_FILE_RE.test(p) && !DECLARATION_FILE_RE.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1345
- const resolved = filtered.map((p) => path6.resolve(p));
1660
+ const resolved = filtered.map((p) => path7.resolve(p));
1346
1661
  resolved.sort((a, b) => a.localeCompare(b));
1347
1662
  return resolved;
1348
1663
  }
@@ -1363,21 +1678,21 @@ function resolvePreloadTemplate(moduleDir) {
1363
1678
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1364
1679
  if (isBundled) {
1365
1680
  return {
1366
- templatePath: path6.join(moduleDir, "templates/coverage-preload.js"),
1681
+ templatePath: path7.join(moduleDir, "templates/coverage-preload.js"),
1367
1682
  preloadLogicPath: undefined,
1368
1683
  extension: "js"
1369
1684
  };
1370
1685
  }
1371
1686
  return {
1372
- templatePath: path6.join(moduleDir, "../templates/coverage-preload.ts"),
1373
- preloadLogicPath: path6.join(moduleDir, "preload-logic.ts"),
1687
+ templatePath: path7.join(moduleDir, "../templates/coverage-preload.ts"),
1688
+ preloadLogicPath: path7.join(moduleDir, "preload-logic.ts"),
1374
1689
  extension: "ts"
1375
1690
  };
1376
1691
  }
1377
- async function generatePreloadScript(options, moduleDir = path6.dirname(fileURLToPath2(import.meta.url))) {
1692
+ async function generatePreloadScript(options, moduleDir = path7.dirname(fileURLToPath2(import.meta.url))) {
1378
1693
  await ensurePrivateDir(options.tempDir);
1379
1694
  const { templatePath, preloadLogicPath, extension } = resolvePreloadTemplate(moduleDir);
1380
- const preloadPath = path6.join(options.tempDir, `stryker-coverage-preload-${process.pid}.${extension}`);
1695
+ const preloadPath = path7.join(options.tempDir, `stryker-coverage-preload-${process.pid}.${extension}`);
1381
1696
  const template = await readFile2(templatePath, "utf8");
1382
1697
  const content = preloadLogicPath === undefined ? template : template.replace("__PRELOAD_LOGIC_PATH__", () => preloadLogicPath);
1383
1698
  await writePrivateFile(preloadPath, content);
@@ -2577,8 +2892,12 @@ class InspectorClient {
2577
2892
  }
2578
2893
  }
2579
2894
  }
2895
+ // src/load-failure-killers.ts
2896
+ import path9 from "node:path";
2897
+ import { TestStatus as TestStatus2 } from "@stryker-mutator/api/test-runner";
2898
+
2580
2899
  // src/parsers/console-parser.ts
2581
- import path7 from "node:path";
2900
+ import path8 from "node:path";
2582
2901
 
2583
2902
  // src/utils/strip-ansi.ts
2584
2903
  function stripAnsi(text) {
@@ -2596,11 +2915,11 @@ function headerFilter(lines, testFiles) {
2596
2915
  if (testFiles === undefined) {
2597
2916
  return () => true;
2598
2917
  }
2599
- const roots = new Set(testFiles.map((file) => path7.resolve(file)));
2918
+ const roots = new Set(testFiles.map((file) => path8.resolve(file)));
2600
2919
  const isRunFile = (file) => {
2601
- let candidate = path7.resolve(file);
2920
+ let candidate = path8.resolve(file);
2602
2921
  while (!roots.has(candidate)) {
2603
- const parent = path7.dirname(candidate);
2922
+ const parent = path8.dirname(candidate);
2604
2923
  if (parent === candidate) {
2605
2924
  return false;
2606
2925
  }
@@ -2891,22 +3210,41 @@ function buildBlock(printed, headerFile) {
2891
3210
  lateCall: errorLine === undefined ? undefined : LATE_CALL_RE.exec(errorLine)?.[1]
2892
3211
  };
2893
3212
  }
2894
- function parseUnhandledErrorBlocks(stderr, secrets = []) {
3213
+ function blockSpans(stderr, secrets) {
2895
3214
  const lines = cleanDiagnosticText(stderr, secrets).split(/\r?\n/).map((line) => line.trimEnd());
2896
3215
  const starts = lines.flatMap((line, i) => line === BLOCK_MARKER && lines[i + 1] === BLOCK_RULE ? [i] : []);
2897
- const blocks = [];
2898
- let headerFile;
3216
+ const spans = [];
2899
3217
  let scanned = 0;
2900
3218
  for (const [n, start] of starts.entries()) {
2901
- for (const line of lines.slice(scanned, start)) {
2902
- headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
2903
- }
2904
3219
  const following = lines.slice(start + 2, starts[n + 1] ?? lines.length);
2905
3220
  const closingRule = following.indexOf(BLOCK_RULE);
2906
- blocks.push(buildBlock(closingRule === -1 ? following : following.slice(0, closingRule), headerFile));
3221
+ spans.push({ before: lines.slice(scanned, start), body: closingRule === -1 ? following : following.slice(0, closingRule) });
2907
3222
  scanned = closingRule === -1 ? start + 2 + following.length : start + 2 + closingRule + 1;
2908
3223
  }
2909
- return blocks;
3224
+ return spans;
3225
+ }
3226
+ function parseUnhandledErrorBlocks(stderr, secrets = []) {
3227
+ let headerFile;
3228
+ return blockSpans(stderr, secrets).map(({ before, body }) => {
3229
+ for (const line of before) {
3230
+ headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
3231
+ }
3232
+ return buildBlock(body, headerFile);
3233
+ });
3234
+ }
3235
+ function blockHeaderFiles(stderr, runFileOf, secrets = []) {
3236
+ return blockSpans(stderr, secrets).map(({ before }) => {
3237
+ const printed = before.filter((line) => line !== "");
3238
+ const last = printed.at(-1);
3239
+ const file = last === undefined ? undefined : runFileOf(last);
3240
+ if (typeof file !== "string") {
3241
+ return;
3242
+ }
3243
+ return printed.every((line) => {
3244
+ const named = runFileOf(line);
3245
+ return named === file || named === undefined && !FILE_HEADER_RE.test(line);
3246
+ }) ? file : undefined;
3247
+ });
2910
3248
  }
2911
3249
  var isSnippetLine = (line) => SNIPPET_LINE_RE.test(line) || SNIPPET_CARET_RE.test(line);
2912
3250
  function renderBlock(block, index, total) {
@@ -3128,6 +3466,114 @@ function layOut(blocks, claims) {
3128
3466
  };
3129
3467
  }
3130
3468
 
3469
+ // src/load-failure-killers.ts
3470
+ var TEST_ID_FILE_SEPARATOR = " > ";
3471
+ var GROUP_PREFIX = "::group::";
3472
+ function indexTestIdsByFile(tests) {
3473
+ const byFile = new Map;
3474
+ const uncertain = new Set;
3475
+ for (const test of tests) {
3476
+ const file = test.fileName;
3477
+ if (file === undefined) {
3478
+ continue;
3479
+ }
3480
+ if (!test.id.startsWith(`${file}${TEST_ID_FILE_SEPARATOR}`)) {
3481
+ uncertain.add(file);
3482
+ } else if (test.status !== TestStatus2.Skipped) {
3483
+ const ids = byFile.get(file) ?? [];
3484
+ ids.push(test.id);
3485
+ byFile.set(file, ids);
3486
+ }
3487
+ }
3488
+ for (const file of uncertain) {
3489
+ byFile.delete(file);
3490
+ }
3491
+ return byFile;
3492
+ }
3493
+ function isTestIdsEntry(entry) {
3494
+ return Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && Array.isArray(entry[1]) && entry[1].every((id) => typeof id === "string");
3495
+ }
3496
+ function parseTestIdsByFile(value, known) {
3497
+ if (!Array.isArray(value)) {
3498
+ return;
3499
+ }
3500
+ const byFile = new Map;
3501
+ for (const entry of value) {
3502
+ if (!isTestIdsEntry(entry) || byFile.has(entry[0])) {
3503
+ return;
3504
+ }
3505
+ const [file, ids] = entry;
3506
+ if (!ids.every((id) => known.has(id) && id.startsWith(`${file}${TEST_ID_FILE_SEPARATOR}`))) {
3507
+ return;
3508
+ }
3509
+ byFile.set(file, ids);
3510
+ }
3511
+ return byFile;
3512
+ }
3513
+ function runFileResolver(testFiles, cwd) {
3514
+ const files = new Set(testFiles.map((file) => path9.resolve(cwd, file)));
3515
+ const keyCounts = new Map;
3516
+ for (const file of files) {
3517
+ const key = dryRunKey(file, cwd);
3518
+ keyCounts.set(key, (keyCounts.get(key) ?? 0) + 1);
3519
+ }
3520
+ return (line) => {
3521
+ if (!line.endsWith(":")) {
3522
+ return;
3523
+ }
3524
+ const printed = line.slice(0, -1);
3525
+ const candidates = printed.startsWith(GROUP_PREFIX) ? [printed, printed.slice(GROUP_PREFIX.length)] : [printed];
3526
+ const matches = new Set(candidates.filter((candidate) => candidate !== "").map((candidate) => path9.resolve(cwd, candidate)).filter((file) => files.has(file)));
3527
+ if (matches.size === 0) {
3528
+ return;
3529
+ }
3530
+ const [file] = matches;
3531
+ const key = dryRunKey(file, cwd);
3532
+ return matches.size === 1 && keyCounts.get(key) === 1 && path9.resolve(cwd, key) === file ? file : null;
3533
+ };
3534
+ }
3535
+ function dryRunKey(file, cwd) {
3536
+ return normalizeTestFilePath(file, cwd) ?? file;
3537
+ }
3538
+ function noTestRan(output, blockCount) {
3539
+ const summary = readBunSummary(output);
3540
+ if (summary.ran === undefined) {
3541
+ return false;
3542
+ }
3543
+ if (summary.bailed !== undefined) {
3544
+ return summary.ran === summary.bailed;
3545
+ }
3546
+ return summary.pass === 0 && summary.ran === summary.skip + summary.todo + summary.fail && summary.fail <= blockCount;
3547
+ }
3548
+ var NO_CREDIT = { killedBy: [], files: [] };
3549
+ function creditLoadFailures(run) {
3550
+ const { byFile, testFiles, cwd, covering } = run;
3551
+ if (byFile === undefined || testFiles === undefined || testFiles.length === 0) {
3552
+ return NO_CREDIT;
3553
+ }
3554
+ const headers = blockHeaderFiles(run.stderr, runFileResolver(testFiles, cwd));
3555
+ if (headers.length === 0 || !noTestRan(`${run.stdout}
3556
+ ${run.stderr}`, headers.length)) {
3557
+ return NO_CREDIT;
3558
+ }
3559
+ const killedBy = new Set;
3560
+ const files = new Set;
3561
+ for (const header of headers) {
3562
+ if (header === undefined) {
3563
+ continue;
3564
+ }
3565
+ const file = dryRunKey(header, cwd);
3566
+ const selected = (byFile.get(file) ?? []).filter((id) => covering.size === 0 || covering.has(id));
3567
+ if (selected.length > 0) {
3568
+ files.add(file);
3569
+ }
3570
+ for (const id of selected) {
3571
+ killedBy.add(id);
3572
+ }
3573
+ }
3574
+ return { killedBy: [...killedBy], files: [...files] };
3575
+ }
3576
+
3131
3577
  // src/process-runner.ts
3132
3578
  import { spawn as spawn3 } from "node:child_process";
3133
3579
 
@@ -3190,13 +3636,13 @@ async function getPsRss(pid) {
3190
3636
  }
3191
3637
 
3192
3638
  // src/utils/project-dir.ts
3193
- import path8 from "node:path";
3639
+ import path10 from "node:path";
3194
3640
  var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
3195
3641
  var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
3196
3642
  function recordProjectDirectory() {
3197
3643
  const inherited = process.env[PROJECT_DIR_ENV];
3198
3644
  const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
3199
- if (isWorker && inherited !== undefined && path8.isAbsolute(inherited)) {
3645
+ if (isWorker && inherited !== undefined && path10.isAbsolute(inherited)) {
3200
3646
  return inherited;
3201
3647
  }
3202
3648
  const here = process.cwd();
@@ -3205,24 +3651,24 @@ function recordProjectDirectory() {
3205
3651
  }
3206
3652
  var projectDirectory = recordProjectDirectory();
3207
3653
  function resolveAgainstProject(file) {
3208
- return path8.resolve(projectDirectory, file);
3654
+ return path10.resolve(projectDirectory, file);
3209
3655
  }
3210
3656
 
3211
3657
  // src/utils/test-file-args.ts
3212
- import path9 from "node:path";
3658
+ import path11 from "node:path";
3213
3659
  var MAX_TEST_FILE_ARGS_BYTES = 131072;
3214
3660
  var ENTRY_OVERHEAD_BYTES = 1 + 8;
3215
3661
  var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
3216
3662
  function shortestSpelling(absolute, cwd) {
3217
- const relative = path9.relative(cwd, absolute);
3663
+ const relative = path11.relative(cwd, absolute);
3218
3664
  if (relative === "" || relative === "..") {
3219
3665
  return absolute;
3220
3666
  }
3221
- const spelled = relative.startsWith(`..${path9.sep}`) ? relative : `.${path9.sep}${relative}`;
3667
+ const spelled = relative.startsWith(`..${path11.sep}`) ? relative : `.${path11.sep}${relative}`;
3222
3668
  return spelled.length < absolute.length ? spelled : absolute;
3223
3669
  }
3224
3670
  function computeTestFileArgs(files, cwd, budget) {
3225
- const absolute = files.map((file) => path9.resolve(cwd, file));
3671
+ const absolute = files.map((file) => path11.resolve(cwd, file));
3226
3672
  const absoluteBytes = bytesOf(absolute);
3227
3673
  if (absoluteBytes <= budget) {
3228
3674
  return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
@@ -3236,7 +3682,7 @@ function sameEntries(a, b) {
3236
3682
  }
3237
3683
  var lastBuild;
3238
3684
  function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
3239
- if (!path9.isAbsolute(cwd)) {
3685
+ if (!path11.isAbsolute(cwd)) {
3240
3686
  return computeTestFileArgs(files, cwd, budget);
3241
3687
  }
3242
3688
  const cached = lastBuild;
@@ -3578,7 +4024,7 @@ Process error: ${error.message}`,
3578
4024
 
3579
4025
  // src/run-profile.ts
3580
4026
  import { appendFileSync as appendFileSync2 } from "node:fs";
3581
- import path10 from "node:path";
4027
+ import path12 from "node:path";
3582
4028
  import { StringDecoder } from "node:string_decoder";
3583
4029
  var PROFILE_FORMAT_VERSION = 1;
3584
4030
  var SPAWN_MARKS = ["spawnStart", "spawned", "firstStderr", "inspector", "firstFile", "decisive", "exit", "close"];
@@ -3936,7 +4382,7 @@ function createWorkerProfiler(logger, env = process.env) {
3936
4382
  if (value === undefined || value === "" || value === "0" || value === "false") {
3937
4383
  return;
3938
4384
  }
3939
- if (!path10.isAbsolute(value)) {
4385
+ if (!path12.isAbsolute(value)) {
3940
4386
  logger.warn("%s must be the absolute path of a JSONL file to append to (got %s); profiling is off", PROFILE_ENV, value);
3941
4387
  return;
3942
4388
  }
@@ -4309,7 +4755,7 @@ class SyncServer {
4309
4755
  }
4310
4756
  // src/utils/bunfig-sanitizer.ts
4311
4757
  import { readFile as readFile5, unlink as unlink3 } from "node:fs/promises";
4312
- import path11 from "node:path";
4758
+ import path13 from "node:path";
4313
4759
  import { parse, stringify } from "smol-toml";
4314
4760
  var SAFE_TEST_KEYS = new Set([
4315
4761
  "preload",
@@ -4343,7 +4789,7 @@ function absolutizePath(value, projectCwd) {
4343
4789
  if (typeof value !== "string") {
4344
4790
  return value;
4345
4791
  }
4346
- return path11.isAbsolute(value) ? value : path11.resolve(projectCwd, value);
4792
+ return path13.isAbsolute(value) ? value : path13.resolve(projectCwd, value);
4347
4793
  }
4348
4794
  function absolutizePathValue(value, projectCwd) {
4349
4795
  if (Array.isArray(value)) {
@@ -4352,7 +4798,7 @@ function absolutizePathValue(value, projectCwd) {
4352
4798
  return absolutizePath(value, projectCwd);
4353
4799
  }
4354
4800
  async function readSourceBunfig(projectCwd, sourceBunfig) {
4355
- const bunfigPath = sourceBunfig === undefined ? path11.join(projectCwd, "bunfig.toml") : path11.resolve(projectCwd, sourceBunfig);
4801
+ const bunfigPath = sourceBunfig === undefined ? path13.join(projectCwd, "bunfig.toml") : path13.resolve(projectCwd, sourceBunfig);
4356
4802
  try {
4357
4803
  const content = await readFile5(bunfigPath, "utf8");
4358
4804
  return parse(content);
@@ -4367,14 +4813,14 @@ async function readSourceBunfig(projectCwd, sourceBunfig) {
4367
4813
  async function readBunfigTestRoot(projectCwd, sourceBunfig) {
4368
4814
  const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
4369
4815
  const root = rawConfig.test?.root;
4370
- return typeof root === "string" ? path11.resolve(projectCwd, root) : undefined;
4816
+ return typeof root === "string" ? path13.resolve(projectCwd, root) : undefined;
4371
4817
  }
4372
4818
  async function readBunfigTestPreloads(projectCwd, sourceBunfig) {
4373
4819
  return testPreloadsOf(await readSourceBunfig(projectCwd, sourceBunfig), projectCwd);
4374
4820
  }
4375
4821
  function testPreloadsOf(rawConfig, projectCwd) {
4376
4822
  const preload = rawConfig.test?.preload;
4377
- return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path11.resolve(projectCwd, entry));
4823
+ return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path13.resolve(projectCwd, entry));
4378
4824
  }
4379
4825
  var SCAN_NEUTRAL_BUNFIG_KEYS = new Set(["preload", "smol", "logLevel", "telemetry", "env", "console", "serve", "install", "run", "conditions", "test"]);
4380
4826
  var JSX_BUNFIG_KEYS = new Set(["jsx", "jsxImportSource", "jsxFactory", "jsxFragment"]);
@@ -4456,7 +4902,7 @@ async function generateSanitizedBunfig(projectCwd, tmpDir, sourceBunfig, onDropp
4456
4902
  dropped.push({ key: `test.${key}`, reason: RANDOM_ORDER_REASON, warn: false, mutantRunsOnly: true });
4457
4903
  }
4458
4904
  onDropped?.(dropped);
4459
- const outPath = path11.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
4905
+ const outPath = path13.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
4460
4906
  await writePrivateFile(outPath, stringify(sanitized));
4461
4907
  const mutantRunTest = { ...sanitizedTest, onlyFailures: true };
4462
4908
  if (randomOrderKeys.length > 0) {
@@ -4481,7 +4927,7 @@ async function cleanupSanitizedBunfig(filePath) {
4481
4927
  }
4482
4928
  // src/utils/test-file-discovery.ts
4483
4929
  import * as fsPromises2 from "node:fs/promises";
4484
- import path12 from "node:path";
4930
+ import path14 from "node:path";
4485
4931
  function isExcludedDirName(name) {
4486
4932
  return name.startsWith(".") || name.toLowerCase() === "node_modules";
4487
4933
  }
@@ -4527,7 +4973,7 @@ async function handleSymlinkFile(fullPath, entryName, ctx) {
4527
4973
  }
4528
4974
  const resolvedTarget = await tryRealpath(fullPath);
4529
4975
  if (resolvedTarget && !hasExcludedAncestor(resolvedTarget)) {
4530
- ctx.results.push(path12.relative(ctx.cwd, fullPath));
4976
+ ctx.results.push(path14.relative(ctx.cwd, fullPath));
4531
4977
  }
4532
4978
  }
4533
4979
  async function handleSymlink(fullPath, entryName, ctx) {
@@ -4543,7 +4989,7 @@ async function handleSymlink(fullPath, entryName, ctx) {
4543
4989
  }
4544
4990
  }
4545
4991
  async function processEntry(entry, dir, ctx) {
4546
- const fullPath = path12.join(dir, entry.name);
4992
+ const fullPath = path14.join(dir, entry.name);
4547
4993
  if (entry.isDirectory()) {
4548
4994
  if (!isExcludedDirName(entry.name)) {
4549
4995
  await ctx.walk(fullPath);
@@ -4551,7 +4997,7 @@ async function processEntry(entry, dir, ctx) {
4551
4997
  } else if (entry.isSymbolicLink()) {
4552
4998
  await handleSymlink(fullPath, entry.name, ctx);
4553
4999
  } else if (entry.isFile() && TEST_FILE_SUFFIX_RE.test(entry.name)) {
4554
- ctx.results.push(path12.relative(ctx.cwd, fullPath));
5000
+ ctx.results.push(path14.relative(ctx.cwd, fullPath));
4555
5001
  }
4556
5002
  }
4557
5003
  async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
@@ -4595,14 +5041,14 @@ async function walkTestFiles(walkRoot, cwd, logger) {
4595
5041
  }
4596
5042
  async function expandTestFileEntries(entries, cwd, logger) {
4597
5043
  const expanded = await Promise.all(entries.map(async (entry) => {
4598
- const absolute = path12.resolve(cwd, entry);
5044
+ const absolute = path14.resolve(cwd, entry);
4599
5045
  const stat = await tryStat(absolute);
4600
5046
  if (stat?.isFile()) {
4601
5047
  return [absolute];
4602
5048
  }
4603
5049
  if (stat?.isDirectory()) {
4604
5050
  const found = await walkTestFiles(absolute, cwd, logger);
4605
- return found.map((file) => path12.resolve(cwd, file));
5051
+ return found.map((file) => path14.resolve(cwd, file));
4606
5052
  }
4607
5053
  return entry;
4608
5054
  }));
@@ -4641,10 +5087,25 @@ class MutantWarnAggregator {
4641
5087
  }
4642
5088
  }
4643
5089
  // src/utils/likely-killer-order.ts
4644
- import path13 from "node:path";
4645
- var MUTANT_SWITCH_RE = /stryMutAct_9fa48\("([^"\\]+)"\)/g;
5090
+ import path15 from "node:path";
5091
+ var SWITCH_DECLARATION_RE = /function stryMutAct_([\w$]+)\(/;
5092
+ var HELPER_CALL_RE = /(?<![\w$])(?:stryMutAct|stryCov)_([\w$]+)\(([^()]*)\)/g;
5093
+ var ID_ARGUMENT_RE = /"([^"\\]+)"/g;
5094
+ function instrumenterSuffix(code) {
5095
+ const suffix = SWITCH_DECLARATION_RE.exec(code)?.[1];
5096
+ return code.includes(`function stryCov_${suffix}(`) ? suffix : undefined;
5097
+ }
4646
5098
  function mutantIdsInInstrumentedSource(code) {
4647
- return new Set(Array.from(code.matchAll(MUTANT_SWITCH_RE), (match) => match[1]));
5099
+ const ids = new Set;
5100
+ const suffix = instrumenterSuffix(code);
5101
+ for (const [, callSuffix, args] of code.matchAll(HELPER_CALL_RE)) {
5102
+ if (callSuffix === suffix) {
5103
+ for (const [, id] of args.matchAll(ID_ARGUMENT_RE)) {
5104
+ ids.add(id);
5105
+ }
5106
+ }
5107
+ }
5108
+ return ids;
4648
5109
  }
4649
5110
 
4650
5111
  class TestFileCoverage {
@@ -4716,8 +5177,8 @@ function namedAfter(sourceFile) {
4716
5177
  if (sourceFile === undefined) {
4717
5178
  return () => false;
4718
5179
  }
4719
- const sourceStem = path13.parse(sourceFile).name.toLowerCase();
4720
- return (testFile) => path13.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
5180
+ const sourceStem = path15.parse(sourceFile).name.toLowerCase();
5181
+ return (testFile) => path15.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
4721
5182
  }
4722
5183
  function compareKillerRanks(a, b) {
4723
5184
  return a.coverage - b.coverage || b.sourceMutants - a.sourceMutants || Number(b.namedAfter) - Number(a.namedAfter);
@@ -4729,7 +5190,7 @@ function orderLikelyKillersFirst(files, rankOf) {
4729
5190
  // src/utils/dry-run-output-log.ts
4730
5191
  import { randomUUID } from "node:crypto";
4731
5192
  import { lstat as lstat2, mkdir as mkdir2, open, rename as rename2, rm as rm4 } from "node:fs/promises";
4732
- import path14 from "node:path";
5193
+ import path16 from "node:path";
4733
5194
  var MAX_LOG_STREAM_CHARS = 16 * 1024 * 1024;
4734
5195
  var MAX_LOG_COMMAND_CHARS = 4000;
4735
5196
  function capStream(text, max) {
@@ -4824,11 +5285,11 @@ function oneLine(error) {
4824
5285
  async function saveDryRunOutput(file, output, options = {}) {
4825
5286
  try {
4826
5287
  const text = formatDryRunOutputLog(output, new Date(options.now ?? Date.now()), options.maxStreamChars);
4827
- const directory = path14.dirname(file);
5288
+ const directory = path16.dirname(file);
4828
5289
  await mkdir2(directory, { recursive: true });
4829
5290
  throwIfAbandoned(options.signal);
4830
5291
  await checkTarget(file);
4831
- const temporary = path14.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
5292
+ const temporary = path16.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
4832
5293
  const handle = await open(temporary, "wx", 384);
4833
5294
  try {
4834
5295
  try {
@@ -4948,7 +5409,7 @@ async function writingTo(file, write) {
4948
5409
  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";
4949
5410
  var RUN_ORDINALS = ["first", "second", "third"];
4950
5411
  function isGreen(result) {
4951
- return result.status === DryRunStatus.Complete && !result.tests.some((test) => test.status === TestStatus.Failed);
5412
+ return result.status === DryRunStatus2.Complete && !result.tests.some((test) => test.status === TestStatus3.Failed);
4952
5413
  }
4953
5414
  function buildTestNameIndex(tests, bunNames) {
4954
5415
  const testNameIndex = new Map;
@@ -4977,7 +5438,6 @@ function defaultFailureMessage(testInfo) {
4977
5438
  }
4978
5439
  var MAX_DRY_RUN_FAILURE_TESTS_LISTED = 20;
4979
5440
  var MAX_COVERAGE_BLEED_WARNINGS = 25;
4980
- var TEST_ID_FILE_SEPARATOR = " > ";
4981
5441
  function sumDurationsByFile(tests) {
4982
5442
  const durations = new Map;
4983
5443
  for (const test of tests) {
@@ -5020,6 +5480,9 @@ function coversAnyMutant(coverage) {
5020
5480
  const buckets = [coverage.static, ...Object.values(coverage.perTest)];
5021
5481
  return buckets.some((bucket) => Object.values(bucket).some((count) => count > 0));
5022
5482
  }
5483
+ function campaignOf(campaign, dir) {
5484
+ return { ...campaign, dir, watched: new Set(campaign.watchList), handedFiles: new Set(campaign.handed) };
5485
+ }
5023
5486
  var MUTANT_WARN_KIND = {
5024
5487
  unresolvedKilledBy: "failed test names could not be resolved to dry-run test ids",
5025
5488
  noRegistry: "no exact-name registry available (lossy covering-test patterns)",
@@ -5077,6 +5540,7 @@ class BunTestRunner {
5077
5540
  loggedRandomizeOff = false;
5078
5541
  loggedFileArgNotes = new Set;
5079
5542
  testFileDurations;
5543
+ testIdsByFile;
5080
5544
  testFileCoverage;
5081
5545
  sourceCoverageCounts = new Map;
5082
5546
  sourceBunfig;
@@ -5088,6 +5552,7 @@ class BunTestRunner {
5088
5552
  maxSpawnDepth;
5089
5553
  dryRunOutputFile;
5090
5554
  coverageAnalysis;
5555
+ ignoreStatic;
5091
5556
  preloadScriptPath;
5092
5557
  coverageFilePath;
5093
5558
  sanitizedBunfigPath;
@@ -5126,6 +5591,7 @@ class BunTestRunner {
5126
5591
  warnedWatchListProblem = false;
5127
5592
  currentAbortController;
5128
5593
  drainSilenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS;
5594
+ handOffBudget = HAND_OFF_BUDGET;
5129
5595
  constructor(logger, options) {
5130
5596
  this.logger = logger;
5131
5597
  const bunOptions = options.bun ?? {};
@@ -5152,6 +5618,7 @@ class BunTestRunner {
5152
5618
  this.mutateGlobs = options.mutate ?? [];
5153
5619
  this.coverageAnalysis = options.coverageAnalysis;
5154
5620
  this.disableBail = options.disableBail;
5621
+ this.ignoreStatic = options.ignoreStatic === true;
5155
5622
  this.incremental = options.incremental === true;
5156
5623
  this.inPlace = options.inPlace === true;
5157
5624
  this.alwaysImport = bunOptions.alwaysImport;
@@ -5170,7 +5637,7 @@ class BunTestRunner {
5170
5637
  maxSpawnDepth: this.maxSpawnDepth,
5171
5638
  dryRunOutputFile: this.dryRunOutputFile
5172
5639
  });
5173
- if (this.testFilesOverride?.some((p) => path15.isAbsolute(p))) {
5640
+ if (this.testFilesOverride?.some((p) => path17.isAbsolute(p))) {
5174
5641
  const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
5175
5642
  if (isSandbox) {
5176
5643
  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());
@@ -5179,7 +5646,7 @@ class BunTestRunner {
5179
5646
  }
5180
5647
  async resolveRegistryPath() {
5181
5648
  this.assertRunOwnerIsParent();
5182
- return path15.join(await resolveRunTempDir(), REGISTRY_FILE);
5649
+ return path17.join(await resolveRunTempDir(), REGISTRY_FILE);
5183
5650
  }
5184
5651
  assertRunOwnerIsParent() {
5185
5652
  if (this.runOwnerPid !== undefined && process.ppid !== this.runOwnerPid) {
@@ -5310,7 +5777,7 @@ class BunTestRunner {
5310
5777
  this.logger.debug("Stryker passed an empty testFiles array; ignoring it");
5311
5778
  }
5312
5779
  } else {
5313
- const files = [...new Set(requested.map((file) => path15.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
5780
+ const files = [...new Set(requested.map((file) => path17.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
5314
5781
  this.strykerTestFiles = { cwd, files };
5315
5782
  this.warnIfTestFilesOverridden(files, cwd);
5316
5783
  }
@@ -5372,7 +5839,7 @@ class BunTestRunner {
5372
5839
  if (this.warnedTestFilesConflict || this.testFilesOverride === undefined) {
5373
5840
  return;
5374
5841
  }
5375
- const configured = [...new Set(this.testFilesOverride.map((file) => path15.resolve(cwd, file)))];
5842
+ const configured = [...new Set(this.testFilesOverride.map((file) => path17.resolve(cwd, file)))];
5376
5843
  const selectedSet = new Set(selected);
5377
5844
  if (configured.length === selectedSet.size && configured.every((file) => selectedSet.has(file))) {
5378
5845
  return;
@@ -5445,7 +5912,7 @@ class BunTestRunner {
5445
5912
  this.runOwnerPid ??= process.ppid;
5446
5913
  const tempDir = await this.ensureRunTempDir();
5447
5914
  this.tempDirTouchedAt = Date.now();
5448
- this.coverageFilePath = path15.join(tempDir, `coverage-${Date.now()}.json`);
5915
+ this.coverageFilePath = path17.join(tempDir, `coverage-${Date.now()}.json`);
5449
5916
  this.logger.debug("Generating coverage preload script...");
5450
5917
  const eagerCwd = process.cwd();
5451
5918
  const testFilesPending = this.getOrDiscoverTestFiles();
@@ -5474,7 +5941,7 @@ class BunTestRunner {
5474
5941
  if (marker === undefined) {
5475
5942
  return;
5476
5943
  }
5477
- const campaign = await readRegistryCampaign(path15.join(runDir, REGISTRY_FILE));
5944
+ const campaign = await readRegistryCampaign(path17.join(runDir, REGISTRY_FILE));
5478
5945
  if (campaign?.generation !== marker.generation) {
5479
5946
  this.logger.debug("Ignoring the abort marker in %s: it belongs to an earlier campaign", runDir);
5480
5947
  return;
@@ -5549,11 +6016,12 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
5549
6016
  this.strykerTestFiles = { cwd: process.cwd(), files: selectedFiles };
5550
6017
  }
5551
6018
  this.testFileDurations = parseTestFileDurations(parsed.testFileDurations);
6019
+ this.testIdsByFile = parseTestIdsByFile(parsed.testIdsByFile, this.cachedTestNames);
5552
6020
  this.setTestFileCoverage(TestFileCoverage.fromJson(parsed.mutantTestFiles));
5553
6021
  if (this.coverageAnalysis !== "off") {
5554
6022
  this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5555
6023
  const campaign = parseCampaignState(parsed.campaign);
5556
- this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
6024
+ this.campaign = campaign === undefined ? undefined : campaignOf(campaign, path17.dirname(registryPath));
5557
6025
  }
5558
6026
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
5559
6027
  } catch (err) {
@@ -5580,7 +6048,7 @@ ${stack}` : baseFailureMessage;
5580
6048
  return {
5581
6049
  id: normalizedName,
5582
6050
  name: normalizedName,
5583
- status: TestStatus.Failed,
6051
+ status: TestStatus3.Failed,
5584
6052
  failureMessage: t.failureMessage ?? "Test failed",
5585
6053
  timeSpentMs: Math.round(t.duration ?? 1)
5586
6054
  };
@@ -5589,14 +6057,14 @@ ${stack}` : baseFailureMessage;
5589
6057
  return {
5590
6058
  id: normalizedName,
5591
6059
  name: normalizedName,
5592
- status: TestStatus.Skipped,
6060
+ status: TestStatus3.Skipped,
5593
6061
  timeSpentMs: Math.round(t.duration ?? 1)
5594
6062
  };
5595
6063
  }
5596
6064
  return {
5597
6065
  id: normalizedName,
5598
6066
  name: normalizedName,
5599
- status: TestStatus.Success,
6067
+ status: TestStatus3.Success,
5600
6068
  timeSpentMs: Math.round(t.duration ?? 1)
5601
6069
  };
5602
6070
  });
@@ -5614,7 +6082,7 @@ ${stack}` : baseFailureMessage;
5614
6082
  return {
5615
6083
  id: `unknown-${inspectorId}`,
5616
6084
  name: `unknown-${inspectorId}`,
5617
- status: TestStatus.Success,
6085
+ status: TestStatus3.Success,
5618
6086
  timeSpentMs: timePerTest
5619
6087
  };
5620
6088
  }
@@ -5630,7 +6098,7 @@ ${stack}` : baseFailureMessage;
5630
6098
  name: uniqueName,
5631
6099
  fileName,
5632
6100
  startPosition,
5633
- status: TestStatus.Failed,
6101
+ status: TestStatus3.Failed,
5634
6102
  failureMessage: this.buildFailureMessage(testInfo, parsed),
5635
6103
  timeSpentMs: elapsed
5636
6104
  };
@@ -5641,7 +6109,7 @@ ${stack}` : baseFailureMessage;
5641
6109
  name: uniqueName,
5642
6110
  fileName,
5643
6111
  startPosition,
5644
- status: TestStatus.Skipped,
6112
+ status: TestStatus3.Skipped,
5645
6113
  timeSpentMs: elapsed
5646
6114
  };
5647
6115
  }
@@ -5650,7 +6118,7 @@ ${stack}` : baseFailureMessage;
5650
6118
  name: uniqueName,
5651
6119
  fileName,
5652
6120
  startPosition,
5653
- status: TestStatus.Success,
6121
+ status: TestStatus3.Success,
5654
6122
  timeSpentMs: elapsed
5655
6123
  };
5656
6124
  });
@@ -5704,10 +6172,11 @@ ${stack}` : baseFailureMessage;
5704
6172
  startedAt,
5705
6173
  profile,
5706
6174
  extraMs: 0,
5707
- launches: 0
6175
+ launches: 0,
6176
+ handed: []
5708
6177
  };
5709
6178
  if (this.inPlace && this.tempDir !== undefined) {
5710
- await removeQuietly(path15.join(this.tempDir, ABORT_MARKER_FILE));
6179
+ await removeQuietly(path17.join(this.tempDir, ABORT_MARKER_FILE));
5711
6180
  }
5712
6181
  if (coverageAnalysis === "off") {
5713
6182
  return this.runWithoutCoverage(launchContext);
@@ -5757,7 +6226,7 @@ ${stack}` : baseFailureMessage;
5757
6226
  const { expanded } = tests;
5758
6227
  let selected = [];
5759
6228
  if (expanded !== undefined) {
5760
- selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path15.resolve(ctx.cwd, entry));
6229
+ selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path17.resolve(ctx.cwd, entry));
5761
6230
  }
5762
6231
  const split = await withoutSelectedTestFiles(ctx.matched, selected);
5763
6232
  if (split.removed.length > 0) {
@@ -5780,6 +6249,22 @@ ${stack}` : baseFailureMessage;
5780
6249
  projectPathsOf(ctx, files) {
5781
6250
  return files.map((file) => shownPath(file, ctx.cwd));
5782
6251
  }
6252
+ handedCreditsOf(ctx, tests) {
6253
+ const started = ctx.handed.some((entry) => entry.launchers !== undefined);
6254
+ const byFile = started && ctx.coverageAnalysis !== "all" ? testsByFile(tests, ctx.cwd, new Set(ctx.handOffTests)) : undefined;
6255
+ return handedCredits(ctx.handed, byFile);
6256
+ }
6257
+ handedSummary(ctx, credits, notLoaded) {
6258
+ const left = new Set(notLoaded);
6259
+ const named = credits.filter((credit) => credit.ids.length > 0 && left.has(credit.file));
6260
+ const started = named.filter((credit) => credit.startedBy !== undefined && credit.every === undefined);
6261
+ const every = named.filter((credit) => credit.startedBy === undefined || credit.every === true);
6262
+ return {
6263
+ started: this.projectPathsOf(ctx, started.map((credit) => credit.file)),
6264
+ testFiles: new Set(started.flatMap((credit) => credit.startedBy.testFiles)).size,
6265
+ every: this.projectPathsOf(ctx, every.map((credit) => credit.file))
6266
+ };
6267
+ }
5783
6268
  logListed(level, message, lists) {
5784
6269
  this.logger[level]("%s", message);
5785
6270
  for (const [what, entries] of lists) {
@@ -5791,6 +6276,7 @@ ${stack}` : baseFailureMessage;
5791
6276
  }
5792
6277
  async decideShape(ctx) {
5793
6278
  const started = performance.now();
6279
+ ctx.handOffsUnread = true;
5794
6280
  try {
5795
6281
  const input = await this.importScanInput(ctx);
5796
6282
  if ("problem" in input) {
@@ -5799,14 +6285,18 @@ ${stack}` : baseFailureMessage;
5799
6285
  }
5800
6286
  const report = await runImportScan(input.input, { bunPath: this.bunPath, workDir: ctx.runDir });
5801
6287
  const decision = decideFromScan(report.result, ctx.eager, ctx.always, this.importDiscovery);
6288
+ ctx.handed = report.result.handed;
6289
+ ctx.handOffTests = input.input.tests;
6290
+ ctx.handOffsUnread = report.failure !== null;
5802
6291
  if (report.failure === null) {
5803
6292
  this.logger.debug("%s", scanMessage({
5804
6293
  answer: report.result.answer,
5805
- wallMs: report.wallMs,
6294
+ wallMs: report.answerMs,
5806
6295
  scannedFiles: report.result.scannedFiles,
5807
6296
  matched: ctx.eager.length,
5808
6297
  statically: this.projectPathsOf(ctx, decision.sources.statically),
5809
6298
  named: this.projectPathsOf(ctx, decision.sources.named),
6299
+ handed: this.projectPathsOf(ctx, report.result.handed.map((entry) => entry.file)),
5810
6300
  always: this.projectPathsOf(ctx, decision.sources.always),
5811
6301
  reasons: decision.kind === "dynamic" ? decision.reasons : report.result.reasons,
5812
6302
  notes: report.result.notes,
@@ -5842,19 +6332,22 @@ ${stack}` : baseFailureMessage;
5842
6332
  return { problem: bunfig.problem };
5843
6333
  }
5844
6334
  const { preloads } = bunfig;
6335
+ const preloaded = new Set([...preloads, ...launch.preloads]);
5845
6336
  return {
5846
6337
  input: {
5847
6338
  eager: ctx.eager,
5848
- roots: [...new Set([...expanded.files, ...preloads, ...launch.preloads])],
6339
+ roots: [...new Set([...expanded.files, ...preloaded])],
6340
+ tests: expanded.files.filter((file) => !preloaded.has(file)),
5849
6341
  always: ctx.always,
5850
6342
  tsconfig: await this.applicableTsconfig(ctx.cwd),
5851
- projectDir: ctx.cwd
6343
+ projectDir: ctx.cwd,
6344
+ handOffBudget: this.handOffBudget
5852
6345
  }
5853
6346
  };
5854
6347
  }
5855
6348
  async applicableTsconfig(cwd) {
5856
6349
  for (const name of ["tsconfig.json", "jsconfig.json"]) {
5857
- const file = path15.join(cwd, name);
6350
+ const file = path17.join(cwd, name);
5858
6351
  const stat = await fsPromises3.stat(file).catch(() => {
5859
6352
  return;
5860
6353
  });
@@ -5898,7 +6391,7 @@ ${stack}` : baseFailureMessage;
5898
6391
  }
5899
6392
  launchFiles(ctx) {
5900
6393
  return {
5901
- planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path15.dirname(this.preloadScriptPath), "dry-run-plan"),
6394
+ planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path17.dirname(this.preloadScriptPath), "dry-run-plan"),
5902
6395
  recordFile: newRecordFile(ctx.runDir)
5903
6396
  };
5904
6397
  }
@@ -5916,7 +6409,7 @@ ${stack}` : baseFailureMessage;
5916
6409
  } catch (error) {
5917
6410
  const errorMessage = `stryker-bun-runner: cannot write the dry-run plan ${planFile} (${errorText(error)})`;
5918
6411
  this.logger.error("%s", errorMessage);
5919
- return { result: { status: DryRunStatus.Error, errorMessage } };
6412
+ return { result: { status: DryRunStatus2.Error, errorMessage } };
5920
6413
  }
5921
6414
  }
5922
6415
  async readRecord(file, parse) {
@@ -5949,7 +6442,7 @@ ${stack}` : baseFailureMessage;
5949
6442
  }
5950
6443
  async runStaticShape(ctx, decision, roots) {
5951
6444
  const launch = await this.runPublished(ctx, decision.list);
5952
- const testFiles = launch.result.status === DryRunStatus.Complete ? launch.result.tests.map((test) => test.fileName) : [];
6445
+ const testFiles = launch.result.status === DryRunStatus2.Complete ? launch.result.tests.map((test) => test.fileName) : [];
5953
6446
  const outcome = oneRunOutcome(this.launchFacts(ctx, launch), unscannedTestFiles(testFiles, roots, ctx.cwd), decision.sources.named);
5954
6447
  if (outcome.kind === "refuse") {
5955
6448
  return this.refuseDryRun(outcome.problems);
@@ -5967,8 +6460,10 @@ ${stack}` : baseFailureMessage;
5967
6460
  }
5968
6461
  this.warnEagerFailures(ctx, launch.record);
5969
6462
  if (outcome.kind === "publish") {
5970
- const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !decision.list.includes(file)));
5971
- 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]]);
6463
+ const notImported = ctx.eager.filter((file) => !decision.list.includes(file));
6464
+ const left = this.projectPathsOf(ctx, notImported);
6465
+ const handed = this.handedSummary(ctx, this.handedCreditsOf(ctx, launch.publication.tests), notImported);
6466
+ this.logListed("info", importListOneRunMessage({ matched: ctx.eager.length, left, handed, 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]]);
5972
6467
  }
5973
6468
  return this.publishDryRun(ctx, launch);
5974
6469
  }
@@ -6032,7 +6527,8 @@ ${stack}` : baseFailureMessage;
6032
6527
  return this.refuseDryRun([MISSING_COVERAGE_FOR_RULE_3_3]);
6033
6528
  }
6034
6529
  const early = outcome.early.map((observation) => observation.file);
6035
- this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched }, publishedOrdinal, discoveryOrdinal);
6530
+ const credits = this.handedCreditsOf(ctx, launch.publication.tests);
6531
+ this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched, credits }, publishedOrdinal, discoveryOrdinal);
6036
6532
  this.warnEagerFailures(ctx, launch.record);
6037
6533
  return this.publishDryRun(ctx, launch, early);
6038
6534
  }
@@ -6043,9 +6539,11 @@ ${stack}` : baseFailureMessage;
6043
6539
  }
6044
6540
  const kept = new Set(run.list);
6045
6541
  if (run.watched) {
6046
- const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !kept.has(file)));
6542
+ const notImported = ctx.eager.filter((file) => !kept.has(file));
6543
+ const left = this.projectPathsOf(ctx, notImported);
6544
+ const handed = this.handedSummary(ctx, run.credits, notImported);
6047
6545
  const fromObservation = run.list.filter((file) => run.observed.has(file)).length;
6048
- 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]]);
6546
+ this.logListed("info", importListTwoRunMessage({ matched: ctx.eager.length, left, handed, handOffsUnread: ctx.handOffsUnread, incremental: this.incremental }, { observed: fromObservation, always: run.list.length - fromObservation }, publishedOrdinal, discoveryOrdinal), [["the files the runner does not import", left]]);
6049
6547
  }
6050
6548
  if (run.cause.kind === "failed") {
6051
6549
  const unloaded = run.cause.named.filter((file) => !run.observed.has(file));
@@ -6112,7 +6610,7 @@ ${stack}` : baseFailureMessage;
6112
6610
  refuseDryRun(problems) {
6113
6611
  const errorMessage = refuseMessage(problems, this.incremental);
6114
6612
  this.logger.error("%s", errorMessage);
6115
- return { status: DryRunStatus.Error, errorMessage };
6613
+ return { status: DryRunStatus2.Error, errorMessage };
6116
6614
  }
6117
6615
  async discoveryError(ctx, discovery, ordinal, reasons) {
6118
6616
  const { result } = discovery;
@@ -6126,7 +6624,7 @@ ${tail}`;
6126
6624
  ${output}
6127
6625
  ${outputLine}`;
6128
6626
  this.logger.error("%s", errorMessage);
6129
- return { status: DryRunStatus.Error, errorMessage };
6627
+ return { status: DryRunStatus2.Error, errorMessage };
6130
6628
  }
6131
6629
  lateLoadError(ctx, launch, late, published, discovery) {
6132
6630
  const names = launch.publication?.testNames;
@@ -6137,7 +6635,7 @@ ${outputLine}`;
6137
6635
  }));
6138
6636
  const errorMessage = lateLoadMessage(loads, published, discovery, this.incremental);
6139
6637
  this.logListed("error", errorMessage, [["the files loaded late", lateLoadEntries(loads)]]);
6140
- return { status: DryRunStatus.Error, errorMessage };
6638
+ return { status: DryRunStatus2.Error, errorMessage };
6141
6639
  }
6142
6640
  async lostError(ctx, ids, list, always, published) {
6143
6641
  const lost = new Set(ids);
@@ -6158,7 +6656,7 @@ ${outputLine}`;
6158
6656
  };
6159
6657
  const errorMessage = lostMessage(report);
6160
6658
  this.logListed("error", errorMessage, [["the lost mutant ids", ids], ["the files of the lost mutants", report.files], ["the files left out", report.leftOut]]);
6161
- return { status: DryRunStatus.Error, errorMessage };
6659
+ return { status: DryRunStatus2.Error, errorMessage };
6162
6660
  }
6163
6661
  async publishDryRun(ctx, launch, seen = []) {
6164
6662
  const { publication } = launch;
@@ -6169,22 +6667,34 @@ ${outputLine}`;
6169
6667
  const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
6170
6668
  ctx.profile?.at("coverageChecked");
6171
6669
  const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
6172
- const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched } : undefined;
6670
+ const handed = creditHandedCoverage(launch.result, this.handedCreditsOf(ctx, tests), (file) => shownPath(file, ctx.cwd), this.ignoreStatic && ctx.coverageAnalysis !== "all");
6671
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched, handed: handed.files } : undefined;
6173
6672
  const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
6174
6673
  ctx.profile?.at("registryWritten");
6175
6674
  if (unpublished !== undefined) {
6176
6675
  this.logger.error("%s", unpublished);
6177
- return { status: DryRunStatus.Error, errorMessage: unpublished };
6676
+ return { status: DryRunStatus2.Error, errorMessage: unpublished };
6178
6677
  }
6179
6678
  this.warnOnUnidentifiedDryRunFailure(processResult, parsed, tests);
6180
6679
  this.warnOnTightDryRunTimeout(totalElapsedMs);
6181
- return launch.result;
6680
+ for (const line of handed.debug) {
6681
+ this.logger.debug("%s", line);
6682
+ }
6683
+ if (handed.warning !== undefined) {
6684
+ this.logger.warn("%s", handed.warning);
6685
+ }
6686
+ return handed.result;
6687
+ }
6688
+ warnIfNoMutantCovered(result, coverageAnalysis) {
6689
+ if (result.mutantCoverage !== undefined && coverageAnalysis !== "off" && !coversAnyMutant(result.mutantCoverage)) {
6690
+ this.logger.warn("The dry run's coverage data shows no mutant covered by any test, per test or statically, so Stryker will report every mutant as NoCoverage. " + "Check that the mutate globs (%s) match the source files your tests import, and that the tests import those files rather than a built copy (e.g. dist/).", this.mutateGlobs.join(", ") || "(none)");
6691
+ }
6182
6692
  }
6183
6693
  async runInspectedPass(ctx, list, planFile) {
6184
6694
  const abortController = new AbortController;
6185
6695
  this.currentAbortController = abortController;
6186
6696
  ctx.profile?.restartLaunch();
6187
- const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path15.dirname(this.coverageFilePath), "coverage");
6697
+ const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path17.dirname(this.coverageFilePath), "coverage");
6188
6698
  const launched = {};
6189
6699
  try {
6190
6700
  return await this.runInspectedChild(ctx, list, planFile, coverageFile, abortController, launched);
@@ -6210,7 +6720,7 @@ ${outputLine}`;
6210
6720
  this.logger.error("Failed to start sync server: %s", errorMsg);
6211
6721
  return {
6212
6722
  result: {
6213
- status: DryRunStatus.Error,
6723
+ status: DryRunStatus2.Error,
6214
6724
  errorMessage: `Failed to start sync server: ${errorMsg}`
6215
6725
  }
6216
6726
  };
@@ -6270,7 +6780,7 @@ exit=%s timedOut=%s
6270
6780
  %s`, this.inspectorTimeout, String(diagnosticResult.exitCode), String(diagnosticResult.timedOut), stdoutPreview || "(empty)", stderrPreview || "(empty)");
6271
6781
  return {
6272
6782
  result: {
6273
- status: DryRunStatus.Error,
6783
+ status: DryRunStatus2.Error,
6274
6784
  errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult, secrets)
6275
6785
  }
6276
6786
  };
@@ -6306,7 +6816,7 @@ exit=%s timedOut=%s
6306
6816
  const child = await testProcess;
6307
6817
  return {
6308
6818
  result: {
6309
- status: DryRunStatus.Error,
6819
+ status: DryRunStatus2.Error,
6310
6820
  errorMessage: formatInspectorConnectMessage(errorMsg, child, [syncServer.token])
6311
6821
  }
6312
6822
  };
@@ -6349,7 +6859,7 @@ exit=%s timedOut=%s
6349
6859
  if (earlyResult) {
6350
6860
  return { result: earlyResult };
6351
6861
  }
6352
- 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);
6862
+ return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, { coverageAnalysis, imported: list, coverageFile, handedIdsHeld: holdsAnyId(ctx.handed) }, { command: spawned.command, cwd, syncToken: syncServer.token }, profile);
6353
6863
  } finally {
6354
6864
  abortController.abort();
6355
6865
  if (this.currentAbortController === abortController) {
@@ -6388,12 +6898,12 @@ exit=%s timedOut=%s
6388
6898
  const outputLine = await this.saveFailedDryRunOutput(result, spawnInfo);
6389
6899
  return { result: this.completenessError(gateReasons, inspectorState.wasClosedUnexpectedly, inspectorState.closeInfo, outputLine) };
6390
6900
  }
6391
- const coverageResult = this.checkCoverageData(mutantCoverage, tests, run.coverageAnalysis, result.stderr, run.coverageFile);
6901
+ const coverageResult = this.checkCoverageData(mutantCoverage, tests, run, result.stderr);
6392
6902
  if (coverageResult) {
6393
6903
  return { result: coverageResult };
6394
6904
  }
6395
6905
  const off = run.coverageAnalysis === "off";
6396
- const complete = { status: DryRunStatus.Complete, tests };
6906
+ const complete = { status: DryRunStatus2.Complete, tests };
6397
6907
  if (mutantCoverage !== undefined && !off) {
6398
6908
  complete.mutantCoverage = run.coverageAnalysis === "all" ? reachedOnly(mutantCoverage) : mutantCoverage;
6399
6909
  }
@@ -6411,24 +6921,25 @@ exit=%s timedOut=%s
6411
6921
  }
6412
6922
  };
6413
6923
  }
6414
- checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
6924
+ checkCoverageData(coverage, tests, run, stderr) {
6415
6925
  const preloadLines = extractPreloadCoverageDiagnostics(stderr);
6416
- if (coverage !== undefined || tests.some((t) => t.status === TestStatus.Failed)) {
6926
+ if (coverage !== undefined || tests.some((t) => t.status === TestStatus3.Failed)) {
6417
6927
  if (preloadLines.length > 0) {
6418
6928
  this.logger.warn(`The coverage preload reported problems on the dry-run child's stderr:
6419
6929
  %s`, preloadLines.join(`
6420
6930
  `));
6421
6931
  }
6422
- if (coverage !== undefined && coverageAnalysis !== "off" && !coversAnyMutant(coverage)) {
6423
- this.logger.warn("The dry run's coverage data shows no mutant covered by any test, per test or statically, so Stryker will report every mutant as NoCoverage. " + "Check that the mutate globs (%s) match the source files your tests import, and that the tests import those files rather than a built copy (e.g. dist/).", this.mutateGlobs.join(", ") || "(none)");
6932
+ if (!run.handedIdsHeld) {
6933
+ this.warnIfNoMutantCovered({ mutantCoverage: coverage }, run.coverageAnalysis);
6424
6934
  }
6425
6935
  return null;
6426
6936
  }
6937
+ const { coverageAnalysis, coverageFile } = run;
6427
6938
  return this.missingCoverageResult(coverageAnalysis, preloadLines, coverageFile);
6428
6939
  }
6429
6940
  missingCoverageResult(coverageAnalysis, preloadLines, coverageFile) {
6430
6941
  const file = coverageFile ?? "(none configured)";
6431
- const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
6942
+ const coverageDir = coverageFile === undefined ? tmpdir2() : path17.dirname(coverageFile);
6432
6943
  const causes = "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).`;
6433
6944
  const diagnostics = preloadLines.length > 0 ? [`Coverage preload diagnostics from the child's stderr:
6434
6945
  ${preloadLines.join(`
@@ -6448,7 +6959,7 @@ ${preloadLines.join(`
6448
6959
  ].join(" ");
6449
6960
  if (fails) {
6450
6961
  this.logger.error("%s", message);
6451
- return { status: DryRunStatus.Error, errorMessage: message };
6962
+ return { status: DryRunStatus2.Error, errorMessage: message };
6452
6963
  }
6453
6964
  this.logger.warn("%s", message);
6454
6965
  return null;
@@ -6483,6 +6994,7 @@ ${preloadLines.join(`
6483
6994
  this.testNameIndex = testNameIndex;
6484
6995
  this.testFileDurations = sumDurationsByFile(tests);
6485
6996
  this.logger.debug("Recorded dry-run durations for %d test file(s) to order mutant runs cheapest-first", this.testFileDurations.size);
6997
+ this.testIdsByFile = indexTestIdsByFile(tests);
6486
6998
  this.setTestFileCoverage(testFileCoverage);
6487
6999
  this.timeoutCorrectionMs = campaignInput?.timeoutCorrectionMs;
6488
7000
  if (campaignInput !== undefined) {
@@ -6490,7 +7002,7 @@ ${preloadLines.join(`
6490
7002
  }
6491
7003
  this.campaign = undefined;
6492
7004
  try {
6493
- const indexes = { cachedTestNames: this.cachedTestNames, baseNameIndex: this.baseNameIndex, testNameIndex, testFileDurations: this.testFileDurations };
7005
+ const indexes = { cachedTestNames: this.cachedTestNames, baseNameIndex: this.baseNameIndex, testNameIndex, testFileDurations: this.testFileDurations, testIdsByFile: this.testIdsByFile };
6494
7006
  await this.writeRegistry(indexes, testFileCoverage, campaignInput);
6495
7007
  return;
6496
7008
  } catch (error) {
@@ -6503,7 +7015,7 @@ ${preloadLines.join(`
6503
7015
  return failure instanceof WriteFailure ? unpublishedCampaignMessage(failure.file, failure.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(failure), watched);
6504
7016
  }
6505
7017
  if (campaignInput !== undefined && failure instanceof WriteFailure) {
6506
- const registryPath = path15.join(path15.dirname(failure.file), REGISTRY_FILE);
7018
+ const registryPath = path17.join(path17.dirname(failure.file), REGISTRY_FILE);
6507
7019
  const earlier = await fsPromises3.lstat(registryPath).catch(() => {
6508
7020
  return;
6509
7021
  });
@@ -6516,7 +7028,7 @@ ${preloadLines.join(`
6516
7028
  }
6517
7029
  async writeRegistry(indexes, testFileCoverage, campaignInput) {
6518
7030
  const registryPath = await this.resolveRegistryPath();
6519
- const runDir = path15.dirname(registryPath);
7031
+ const runDir = path17.dirname(registryPath);
6520
7032
  const campaign = campaignInput === undefined ? undefined : await this.writeCampaignFiles(runDir, campaignInput);
6521
7033
  const tmpPath = `${registryPath}.tmp`;
6522
7034
  const registryData = JSON.stringify({
@@ -6527,6 +7039,7 @@ ${preloadLines.join(`
6527
7039
  testNameIndex: [...indexes.testNameIndex.entries()],
6528
7040
  testFiles: this.selectedTestFilesFor(process.cwd()),
6529
7041
  testFileDurations: [...indexes.testFileDurations.entries()],
7042
+ testIdsByFile: [...indexes.testIdsByFile.entries()],
6530
7043
  mutantTestFiles: testFileCoverage?.toJSON(),
6531
7044
  timeoutCorrectionMs: campaignInput?.timeoutCorrectionMs,
6532
7045
  campaign
@@ -6537,14 +7050,14 @@ ${preloadLines.join(`
6537
7050
  await writingTo(registryPath, async () => fsPromises3.rename(tmpPath, registryPath));
6538
7051
  } catch (error) {
6539
7052
  if (campaign?.watchListFile) {
6540
- await removeQuietly(path15.join(runDir, campaign.watchListFile));
7053
+ await removeQuietly(path17.join(runDir, campaign.watchListFile));
6541
7054
  }
6542
7055
  throw error;
6543
7056
  }
6544
7057
  this.lastRegistryTmpPath = undefined;
6545
7058
  if (campaign !== undefined) {
6546
- await removeQuietly(path15.join(runDir, ABORT_MARKER_FILE));
6547
- this.campaign = { ...campaign, dir: runDir, watched: new Set(campaign.watchList) };
7059
+ await removeQuietly(path17.join(runDir, ABORT_MARKER_FILE));
7060
+ this.campaign = campaignOf(campaign, runDir);
6548
7061
  }
6549
7062
  this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, indexes.cachedTestNames.size);
6550
7063
  }
@@ -6556,10 +7069,11 @@ ${preloadLines.join(`
6556
7069
  generation,
6557
7070
  watchList: [...watched],
6558
7071
  watchListFile,
7072
+ handed: [...campaignInput.handed],
6559
7073
  fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.matched)
6560
7074
  };
6561
7075
  if (watchListFile !== null) {
6562
- const file = path15.join(runDir, watchListFile);
7076
+ const file = path17.join(runDir, watchListFile);
6563
7077
  await writingTo(file, async () => writeWatchList(file, watched));
6564
7078
  }
6565
7079
  return campaign;
@@ -6634,9 +7148,22 @@ ${preloadLines.join(`
6634
7148
  }
6635
7149
  return corrected.timeoutMs;
6636
7150
  }
7151
+ handedFileOf(options) {
7152
+ if (typeof options.sandboxFileName !== "string") {
7153
+ return;
7154
+ }
7155
+ const file = path17.resolve(options.sandboxFileName);
7156
+ return this.campaign?.handedFiles.has(file) === true ? file : undefined;
7157
+ }
7158
+ mutantRunGuards(options) {
7159
+ if (this.handedFileOf(options) !== undefined) {
7160
+ return { hitLimit: undefined, watchList: undefined };
7161
+ }
7162
+ return { hitLimit: options.hitLimit, watchList: this.watchListForMutantRuns() };
7163
+ }
6637
7164
  watchListForMutantRuns() {
6638
7165
  const { campaign } = this;
6639
- return campaign?.watchListFile ? path15.join(campaign.dir, campaign.watchListFile) : undefined;
7166
+ return campaign?.watchListFile ? path17.join(campaign.dir, campaign.watchListFile) : undefined;
6640
7167
  }
6641
7168
  async enforceWitness(stderr, hitLimitToken, ctx, testNamePattern) {
6642
7169
  const { campaign } = this;
@@ -6696,7 +7223,7 @@ ${preloadLines.join(`
6696
7223
  const cwd = process.cwd();
6697
7224
  const exist = await Promise.all(entries.map(async (entry) => {
6698
7225
  try {
6699
- const stat = await fsPromises3.stat(path15.resolve(cwd, entry));
7226
+ const stat = await fsPromises3.stat(path17.resolve(cwd, entry));
6700
7227
  return stat.isFile();
6701
7228
  } catch {
6702
7229
  return false;
@@ -6710,6 +7237,7 @@ ${preloadLines.join(`
6710
7237
  const abortController = new AbortController;
6711
7238
  this.currentAbortController = abortController;
6712
7239
  const hitLimitToken = newHitLimitToken();
7240
+ const guards = this.mutantRunGuards(options);
6713
7241
  const ordered = this.orderForMutantRun(ctx.testFileScope ?? (testNamePattern === undefined ? this.effectiveTestFiles : coveringTestFiles ?? this.effectiveTestFiles), ctx);
6714
7242
  const testFiles = this.fitTestFiles(ordered, ctx.testFileScope === undefined ? this.explicitTestFilesSource(process.cwd()) : "Stryker's testFiles option");
6715
7243
  ctx.profile?.setScope(mutantRunScope(ctx.testFileScope !== undefined, testNamePattern, ctx.coveringTestCount));
@@ -6722,9 +7250,9 @@ ${preloadLines.join(`
6722
7250
  bunArgs: this.mutantBunArgs,
6723
7251
  bunfigPath,
6724
7252
  activeMutant: options.activeMutant.id,
6725
- hitLimit: options.hitLimit,
7253
+ hitLimit: guards.hitLimit,
6726
7254
  hitLimitToken,
6727
- watchList: this.watchListForMutantRuns(),
7255
+ watchList: guards.watchList,
6728
7256
  bail: !options.disableBail,
6729
7257
  sequentialMode: true,
6730
7258
  preloadScript: this.preloadScriptPath,
@@ -6767,10 +7295,10 @@ ${preloadLines.join(`
6767
7295
  this.mutantWarnings.warn(MUTANT_WARN_KIND.zeroMatchRetry, options.activeMutant.id, "Mutant %s: --test-name-pattern matched 0 tests — usually a runner pattern gap or a mutant that changed an interpolated test title (it.each); retrying once with the full suite", options.activeMutant.id);
6768
7296
  return this.executeMutantRun(ctx, undefined);
6769
7297
  }
6770
- return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, options.activeMutant.id);
7298
+ return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, options.activeMutant.id);
6771
7299
  }
6772
7300
  if (!parsed.summaryPrinted) {
6773
- return this.classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, options.activeMutant.id);
7301
+ return this.classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, testFiles, options.activeMutant.id);
6774
7302
  }
6775
7303
  return {
6776
7304
  status: MutantRunStatus.Survived,
@@ -6804,7 +7332,7 @@ ${preloadLines.join(`
6804
7332
  this.mutantWarnings.warn(MUTANT_WARN_KIND.inconclusiveTimeout, mutantId, "Mutant %s: inconclusive timeout, scoring as Error rather than Timeout: %s", mutantId, errorMessage);
6805
7333
  return { status: MutantRunStatus.Error, errorMessage };
6806
7334
  }
6807
- buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, mutantId, earlyExit = false) {
7335
+ buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId, earlyExit = false) {
6808
7336
  const rawFailedNames = parsed.tests.filter((test) => test.status === "failed").map((test) => normalizeTestName(test.name));
6809
7337
  if (result.signal && rawFailedNames.length === 0) {
6810
7338
  return this.buildSignalErrorResult(result, mutantId, `bun test terminated by ${result.signal} before any test reported a failure`);
@@ -6815,7 +7343,7 @@ ${preloadLines.join(`
6815
7343
  return noEvidenceResult;
6816
7344
  }
6817
7345
  }
6818
- const killedBy = this.resolveKilledBy(rawFailedNames, localRegistry, localBaseIndex, mutantId);
7346
+ const killedBy = this.killersOf(rawFailedNames, result, testFiles, localRegistry, localBaseIndex, mutantId);
6819
7347
  if (result.signal && killedBy.length === 0) {
6820
7348
  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`);
6821
7349
  }
@@ -6867,9 +7395,9 @@ ${preloadLines.join(`
6867
7395
  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}`
6868
7396
  };
6869
7397
  }
6870
- classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, mutantId) {
7398
+ classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId) {
6871
7399
  if (parsed.tests.some((test) => test.status === "failed")) {
6872
- return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, mutantId, true);
7400
+ return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId, true);
6873
7401
  }
6874
7402
  return this.buildEarlyExitErrorResult(result, mutantId, "no test reported a failure");
6875
7403
  }
@@ -6886,11 +7414,11 @@ ${result.stderr}`).trim().slice(-500) || "(no output)";
6886
7414
  if (result.memoryLimitExceeded !== true) {
6887
7415
  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);
6888
7416
  }
6889
- return { status: DryRunStatus.Timeout };
7417
+ return { status: DryRunStatus2.Timeout };
6890
7418
  }
6891
7419
  if (result.spawnError !== undefined) {
6892
7420
  return {
6893
- status: DryRunStatus.Error,
7421
+ status: DryRunStatus2.Error,
6894
7422
  errorMessage: `${formatSpawnErrorMessage(result.spawnError)}
6895
7423
  ${cleanDiagnosticText(result.stderr, secrets)}`
6896
7424
  };
@@ -6903,7 +7431,7 @@ ${cleanDiagnosticText(result.stderr, secrets)}`
6903
7431
  }
6904
7432
  messageParts.push(cleanDiagnosticText(result.stderr, secrets));
6905
7433
  return {
6906
- status: DryRunStatus.Error,
7434
+ status: DryRunStatus2.Error,
6907
7435
  errorMessage: messageParts.join(`
6908
7436
  `)
6909
7437
  };
@@ -6937,7 +7465,7 @@ ${lines.join(`
6937
7465
  `)}`;
6938
7466
  }
6939
7467
  warnOnUnidentifiedDryRunFailure(result, parsed, tests) {
6940
- if (parsed.failed > 0 && !tests.some((t) => t.status === TestStatus.Failed)) {
7468
+ if (parsed.failed > 0 && !tests.some((t) => t.status === TestStatus3.Failed)) {
6941
7469
  this.logger.warn("Bun exited with code %s and its console output reported %d failed test(s), " + "but no failing test could be identified from inspector or console data. " + "An unhandled error firing between tests (e.g. a rejected fire-and-forget " + `promise) is a likely cause. Last 500 chars of stderr:
6942
7470
  %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
6943
7471
  }
@@ -6982,7 +7510,7 @@ ${lines.join(`
6982
7510
  }
6983
7511
  }
6984
7512
  findCompletenessProblems(facts, summaryFailed, tests, stderr, eagerModules, secrets = []) {
6985
- if (tests.some((t) => t.status === TestStatus.Failed)) {
7513
+ if (tests.some((t) => t.status === TestStatus3.Failed)) {
6986
7514
  return [];
6987
7515
  }
6988
7516
  const reasons = findDryRunDataLoss(facts);
@@ -7009,7 +7537,7 @@ ${cleanDiagnosticText(stderr, secrets).slice(-500)}`);
7009
7537
  ${outputLine}`;
7010
7538
  this.logger.error("%s", errorMessage);
7011
7539
  return {
7012
- status: DryRunStatus.Error,
7540
+ status: DryRunStatus2.Error,
7013
7541
  errorMessage
7014
7542
  };
7015
7543
  }
@@ -7103,6 +7631,23 @@ ${outputLine}`;
7103
7631
  this.warnUnresolvedKilledBy(unresolved, mutantId);
7104
7632
  return [...killedBySet];
7105
7633
  }
7634
+ killersOf(rawFailedNames, result, testFiles, localRegistry, localBaseIndex, mutantId) {
7635
+ return rawFailedNames.length === 0 ? this.creditFilesThatFailedToLoad(result, testFiles, localRegistry, mutantId) : this.resolveKilledBy(rawFailedNames, localRegistry, localBaseIndex, mutantId);
7636
+ }
7637
+ creditFilesThatFailedToLoad(result, testFiles, localRegistry, mutantId) {
7638
+ const credit = creditLoadFailures({
7639
+ stdout: result.stdout,
7640
+ stderr: result.stderr,
7641
+ testFiles,
7642
+ cwd: process.cwd(),
7643
+ byFile: this.testIdsByFile,
7644
+ covering: localRegistry
7645
+ });
7646
+ if (credit.killedBy.length > 0) {
7647
+ this.logger.debug("Mutant %s: no test ran, and %d test file(s) failed to load (%s); killedBy holds their %d selected test(s)", mutantId, credit.files.length, credit.files.join(", "), credit.killedBy.length);
7648
+ }
7649
+ return credit.killedBy;
7650
+ }
7106
7651
  warnUnresolvedKilledBy(unresolved, mutantId) {
7107
7652
  if (unresolved.size === 0) {
7108
7653
  return;
@@ -7163,7 +7708,7 @@ ${outputLine}`;
7163
7708
  // src/checker-tsconfig.ts
7164
7709
  import { readFile as readFile7, rename as rename4, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
7165
7710
  import { createRequire as createRequire2 } from "node:module";
7166
- import path16 from "node:path";
7711
+ import path18 from "node:path";
7167
7712
  import { glob as glob2 } from "tinyglobby";
7168
7713
  var DEFAULT_MUTATE_PATTERNS = ["{src,lib}/**"];
7169
7714
  var MUTATION_RANGE_RE = /:\d+(?::\d+)?-\d+(?::\d+)?$/;
@@ -7171,11 +7716,37 @@ var DERIVED_SUFFIX = ".stryker-checker.json";
7171
7716
  var GENERATED_MARKER = "// Generated by withTestFilesExcludedFromTypeCheck()";
7172
7717
  var LOG_PREFIX = "[Stryker] withTestFilesExcludedFromTypeCheck: ";
7173
7718
  var MAX_QUOTED_ERRORS = 3;
7719
+ var COMPILER_API = [
7720
+ "createProgram",
7721
+ "formatDiagnostic",
7722
+ "getParsedCommandLineOfConfigFile",
7723
+ "isExternalModule",
7724
+ "isModuleDeclaration",
7725
+ "isStringLiteral",
7726
+ "parseJsonSourceFileConfigFileContent",
7727
+ "parseJsonText",
7728
+ "preProcessFile",
7729
+ "resolveModuleName"
7730
+ ];
7731
+ function cannotLoad(cwd) {
7732
+ return { problem: `typescript cannot be loaded from ${cwd}; install it there` };
7733
+ }
7734
+ function checkTypeScript(exported, cwd) {
7735
+ const candidate = exported;
7736
+ if (COMPILER_API.every((name) => typeof candidate?.[name] === "function")) {
7737
+ return { ts: exported };
7738
+ }
7739
+ const version = String(candidate?.version);
7740
+ if (Number.parseInt(version, 10) >= 7) {
7741
+ return { problem: `typescript ${version} in ${cwd} is TypeScript 7 or later, which has no compiler API to read the tsconfig with, so the config is left as it is; install typescript 6 or earlier, which Stryker needs too (TypeScript 7 can go beside it as @typescript/native)` };
7742
+ }
7743
+ return cannotLoad(cwd);
7744
+ }
7174
7745
  function loadTypeScript(cwd) {
7175
7746
  try {
7176
- return createRequire2(path16.join(cwd, "package.json"))("typescript");
7747
+ return checkTypeScript(createRequire2(path18.join(cwd, "package.json"))("typescript"), cwd);
7177
7748
  } catch {
7178
- return;
7749
+ return cannotLoad(cwd);
7179
7750
  }
7180
7751
  }
7181
7752
  function readProject(ts, tsconfigPath, shown) {
@@ -7200,7 +7771,7 @@ async function findTestFiles(config, cwd) {
7200
7771
  for (const relativeFiles of [await discoverTestFiles(cwd, undefined, sourceBunfig), bun.testFiles]) {
7201
7772
  if (relativeFiles) {
7202
7773
  for (const file of relativeFiles) {
7203
- testFiles.add(path16.resolve(cwd, file));
7774
+ testFiles.add(path18.resolve(cwd, file));
7204
7775
  }
7205
7776
  }
7206
7777
  }
@@ -7278,12 +7849,12 @@ function derivedHeader(source) {
7278
7849
  `);
7279
7850
  }
7280
7851
  function renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints) {
7281
- const source = path16.basename(sourcePath);
7852
+ const source = path18.basename(sourcePath);
7282
7853
  const body = {
7283
7854
  extends: `./${source}`,
7284
7855
  ...project.options.declarationDir !== undefined && { compilerOptions: { declarationDir: null } },
7285
7856
  include: [],
7286
- files: entryPoints.map((file) => path16.relative(path16.dirname(derivedPath), file))
7857
+ files: entryPoints.map((file) => path18.relative(path18.dirname(derivedPath), file))
7287
7858
  };
7288
7859
  return `${derivedHeader(source)}${JSON.stringify(body, null, 2)}
7289
7860
  `;
@@ -7293,12 +7864,13 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
7293
7864
  console.info(`${LOG_PREFIX}not applied: the config's checkers do not include 'typescript'`);
7294
7865
  return config;
7295
7866
  }
7296
- const ts = loadTypeScript(cwd);
7297
- if (!ts) {
7298
- return leaveUnchanged(config, `typescript cannot be loaded from ${cwd}; install it there`);
7867
+ const loaded = loadTypeScript(cwd);
7868
+ if ("problem" in loaded) {
7869
+ return leaveUnchanged(config, loaded.problem);
7299
7870
  }
7300
- const sourcePath = path16.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
7301
- const shownSource = path16.relative(cwd, sourcePath);
7871
+ const { ts } = loaded;
7872
+ const sourcePath = path18.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
7873
+ const shownSource = path18.relative(cwd, sourcePath);
7302
7874
  const read = readProject(ts, sourcePath, shownSource);
7303
7875
  if ("problem" in read) {
7304
7876
  return leaveUnchanged(config, read.problem);
@@ -7315,10 +7887,10 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
7315
7887
  if (entryPoints.length === 0) {
7316
7888
  return leaveUnchanged(config, `${shownSource} would have no files left once test files are excluded`);
7317
7889
  }
7318
- const derivedPath = path16.join(path16.dirname(sourcePath), `${path16.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7319
- const shownDerived = path16.relative(cwd, derivedPath);
7890
+ const derivedPath = path18.join(path18.dirname(sourcePath), `${path18.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7891
+ const shownDerived = path18.relative(cwd, derivedPath);
7320
7892
  const text = renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints);
7321
- const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path16.dirname(derivedPath), undefined, derivedPath);
7893
+ const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path18.dirname(derivedPath), undefined, derivedPath);
7322
7894
  const derived = createProgram(ts, derivedProject, original);
7323
7895
  const newErrors = findNewErrors(derived, original, testFiles);
7324
7896
  if (newErrors.length > 0) {