@hughescr/stryker-bun-runner 1.7.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 path16 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 TestStatus2,
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`;
1533
+ }
1534
+ if (exit.cut) {
1535
+ return `the scan helper did not finish them within ${limits.handOffMs} ms of its answer`;
1230
1536
  }
1231
- if (exit.exitCode !== 0) {
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);
@@ -2578,7 +2893,7 @@ class InspectorClient {
2578
2893
  }
2579
2894
  }
2580
2895
  // src/parsers/console-parser.ts
2581
- import path7 from "node:path";
2896
+ import path8 from "node:path";
2582
2897
 
2583
2898
  // src/utils/strip-ansi.ts
2584
2899
  function stripAnsi(text) {
@@ -2596,11 +2911,11 @@ function headerFilter(lines, testFiles) {
2596
2911
  if (testFiles === undefined) {
2597
2912
  return () => true;
2598
2913
  }
2599
- const roots = new Set(testFiles.map((file) => path7.resolve(file)));
2914
+ const roots = new Set(testFiles.map((file) => path8.resolve(file)));
2600
2915
  const isRunFile = (file) => {
2601
- let candidate = path7.resolve(file);
2916
+ let candidate = path8.resolve(file);
2602
2917
  while (!roots.has(candidate)) {
2603
- const parent = path7.dirname(candidate);
2918
+ const parent = path8.dirname(candidate);
2604
2919
  if (parent === candidate) {
2605
2920
  return false;
2606
2921
  }
@@ -3190,13 +3505,13 @@ async function getPsRss(pid) {
3190
3505
  }
3191
3506
 
3192
3507
  // src/utils/project-dir.ts
3193
- import path8 from "node:path";
3508
+ import path9 from "node:path";
3194
3509
  var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
3195
3510
  var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
3196
3511
  function recordProjectDirectory() {
3197
3512
  const inherited = process.env[PROJECT_DIR_ENV];
3198
3513
  const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
3199
- if (isWorker && inherited !== undefined && path8.isAbsolute(inherited)) {
3514
+ if (isWorker && inherited !== undefined && path9.isAbsolute(inherited)) {
3200
3515
  return inherited;
3201
3516
  }
3202
3517
  const here = process.cwd();
@@ -3205,24 +3520,24 @@ function recordProjectDirectory() {
3205
3520
  }
3206
3521
  var projectDirectory = recordProjectDirectory();
3207
3522
  function resolveAgainstProject(file) {
3208
- return path8.resolve(projectDirectory, file);
3523
+ return path9.resolve(projectDirectory, file);
3209
3524
  }
3210
3525
 
3211
3526
  // src/utils/test-file-args.ts
3212
- import path9 from "node:path";
3527
+ import path10 from "node:path";
3213
3528
  var MAX_TEST_FILE_ARGS_BYTES = 131072;
3214
3529
  var ENTRY_OVERHEAD_BYTES = 1 + 8;
3215
3530
  var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
3216
3531
  function shortestSpelling(absolute, cwd) {
3217
- const relative = path9.relative(cwd, absolute);
3532
+ const relative = path10.relative(cwd, absolute);
3218
3533
  if (relative === "" || relative === "..") {
3219
3534
  return absolute;
3220
3535
  }
3221
- const spelled = relative.startsWith(`..${path9.sep}`) ? relative : `.${path9.sep}${relative}`;
3536
+ const spelled = relative.startsWith(`..${path10.sep}`) ? relative : `.${path10.sep}${relative}`;
3222
3537
  return spelled.length < absolute.length ? spelled : absolute;
3223
3538
  }
3224
3539
  function computeTestFileArgs(files, cwd, budget) {
3225
- const absolute = files.map((file) => path9.resolve(cwd, file));
3540
+ const absolute = files.map((file) => path10.resolve(cwd, file));
3226
3541
  const absoluteBytes = bytesOf(absolute);
3227
3542
  if (absoluteBytes <= budget) {
3228
3543
  return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
@@ -3236,7 +3551,7 @@ function sameEntries(a, b) {
3236
3551
  }
3237
3552
  var lastBuild;
3238
3553
  function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
3239
- if (!path9.isAbsolute(cwd)) {
3554
+ if (!path10.isAbsolute(cwd)) {
3240
3555
  return computeTestFileArgs(files, cwd, budget);
3241
3556
  }
3242
3557
  const cached = lastBuild;
@@ -3578,7 +3893,7 @@ Process error: ${error.message}`,
3578
3893
 
3579
3894
  // src/run-profile.ts
3580
3895
  import { appendFileSync as appendFileSync2 } from "node:fs";
3581
- import path10 from "node:path";
3896
+ import path11 from "node:path";
3582
3897
  import { StringDecoder } from "node:string_decoder";
3583
3898
  var PROFILE_FORMAT_VERSION = 1;
3584
3899
  var SPAWN_MARKS = ["spawnStart", "spawned", "firstStderr", "inspector", "firstFile", "decisive", "exit", "close"];
@@ -3936,7 +4251,7 @@ function createWorkerProfiler(logger, env = process.env) {
3936
4251
  if (value === undefined || value === "" || value === "0" || value === "false") {
3937
4252
  return;
3938
4253
  }
3939
- if (!path10.isAbsolute(value)) {
4254
+ if (!path11.isAbsolute(value)) {
3940
4255
  logger.warn("%s must be the absolute path of a JSONL file to append to (got %s); profiling is off", PROFILE_ENV, value);
3941
4256
  return;
3942
4257
  }
@@ -4309,7 +4624,7 @@ class SyncServer {
4309
4624
  }
4310
4625
  // src/utils/bunfig-sanitizer.ts
4311
4626
  import { readFile as readFile5, unlink as unlink3 } from "node:fs/promises";
4312
- import path11 from "node:path";
4627
+ import path12 from "node:path";
4313
4628
  import { parse, stringify } from "smol-toml";
4314
4629
  var SAFE_TEST_KEYS = new Set([
4315
4630
  "preload",
@@ -4343,7 +4658,7 @@ function absolutizePath(value, projectCwd) {
4343
4658
  if (typeof value !== "string") {
4344
4659
  return value;
4345
4660
  }
4346
- return path11.isAbsolute(value) ? value : path11.resolve(projectCwd, value);
4661
+ return path12.isAbsolute(value) ? value : path12.resolve(projectCwd, value);
4347
4662
  }
4348
4663
  function absolutizePathValue(value, projectCwd) {
4349
4664
  if (Array.isArray(value)) {
@@ -4352,7 +4667,7 @@ function absolutizePathValue(value, projectCwd) {
4352
4667
  return absolutizePath(value, projectCwd);
4353
4668
  }
4354
4669
  async function readSourceBunfig(projectCwd, sourceBunfig) {
4355
- const bunfigPath = sourceBunfig === undefined ? path11.join(projectCwd, "bunfig.toml") : path11.resolve(projectCwd, sourceBunfig);
4670
+ const bunfigPath = sourceBunfig === undefined ? path12.join(projectCwd, "bunfig.toml") : path12.resolve(projectCwd, sourceBunfig);
4356
4671
  try {
4357
4672
  const content = await readFile5(bunfigPath, "utf8");
4358
4673
  return parse(content);
@@ -4367,14 +4682,14 @@ async function readSourceBunfig(projectCwd, sourceBunfig) {
4367
4682
  async function readBunfigTestRoot(projectCwd, sourceBunfig) {
4368
4683
  const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
4369
4684
  const root = rawConfig.test?.root;
4370
- return typeof root === "string" ? path11.resolve(projectCwd, root) : undefined;
4685
+ return typeof root === "string" ? path12.resolve(projectCwd, root) : undefined;
4371
4686
  }
4372
4687
  async function readBunfigTestPreloads(projectCwd, sourceBunfig) {
4373
4688
  return testPreloadsOf(await readSourceBunfig(projectCwd, sourceBunfig), projectCwd);
4374
4689
  }
4375
4690
  function testPreloadsOf(rawConfig, projectCwd) {
4376
4691
  const preload = rawConfig.test?.preload;
4377
- return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path11.resolve(projectCwd, entry));
4692
+ return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path12.resolve(projectCwd, entry));
4378
4693
  }
4379
4694
  var SCAN_NEUTRAL_BUNFIG_KEYS = new Set(["preload", "smol", "logLevel", "telemetry", "env", "console", "serve", "install", "run", "conditions", "test"]);
4380
4695
  var JSX_BUNFIG_KEYS = new Set(["jsx", "jsxImportSource", "jsxFactory", "jsxFragment"]);
@@ -4456,7 +4771,7 @@ async function generateSanitizedBunfig(projectCwd, tmpDir, sourceBunfig, onDropp
4456
4771
  dropped.push({ key: `test.${key}`, reason: RANDOM_ORDER_REASON, warn: false, mutantRunsOnly: true });
4457
4772
  }
4458
4773
  onDropped?.(dropped);
4459
- const outPath = path11.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
4774
+ const outPath = path12.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
4460
4775
  await writePrivateFile(outPath, stringify(sanitized));
4461
4776
  const mutantRunTest = { ...sanitizedTest, onlyFailures: true };
4462
4777
  if (randomOrderKeys.length > 0) {
@@ -4481,7 +4796,7 @@ async function cleanupSanitizedBunfig(filePath) {
4481
4796
  }
4482
4797
  // src/utils/test-file-discovery.ts
4483
4798
  import * as fsPromises2 from "node:fs/promises";
4484
- import path12 from "node:path";
4799
+ import path13 from "node:path";
4485
4800
  function isExcludedDirName(name) {
4486
4801
  return name.startsWith(".") || name.toLowerCase() === "node_modules";
4487
4802
  }
@@ -4527,7 +4842,7 @@ async function handleSymlinkFile(fullPath, entryName, ctx) {
4527
4842
  }
4528
4843
  const resolvedTarget = await tryRealpath(fullPath);
4529
4844
  if (resolvedTarget && !hasExcludedAncestor(resolvedTarget)) {
4530
- ctx.results.push(path12.relative(ctx.cwd, fullPath));
4845
+ ctx.results.push(path13.relative(ctx.cwd, fullPath));
4531
4846
  }
4532
4847
  }
4533
4848
  async function handleSymlink(fullPath, entryName, ctx) {
@@ -4543,7 +4858,7 @@ async function handleSymlink(fullPath, entryName, ctx) {
4543
4858
  }
4544
4859
  }
4545
4860
  async function processEntry(entry, dir, ctx) {
4546
- const fullPath = path12.join(dir, entry.name);
4861
+ const fullPath = path13.join(dir, entry.name);
4547
4862
  if (entry.isDirectory()) {
4548
4863
  if (!isExcludedDirName(entry.name)) {
4549
4864
  await ctx.walk(fullPath);
@@ -4551,7 +4866,7 @@ async function processEntry(entry, dir, ctx) {
4551
4866
  } else if (entry.isSymbolicLink()) {
4552
4867
  await handleSymlink(fullPath, entry.name, ctx);
4553
4868
  } else if (entry.isFile() && TEST_FILE_SUFFIX_RE.test(entry.name)) {
4554
- ctx.results.push(path12.relative(ctx.cwd, fullPath));
4869
+ ctx.results.push(path13.relative(ctx.cwd, fullPath));
4555
4870
  }
4556
4871
  }
4557
4872
  async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
@@ -4595,14 +4910,14 @@ async function walkTestFiles(walkRoot, cwd, logger) {
4595
4910
  }
4596
4911
  async function expandTestFileEntries(entries, cwd, logger) {
4597
4912
  const expanded = await Promise.all(entries.map(async (entry) => {
4598
- const absolute = path12.resolve(cwd, entry);
4913
+ const absolute = path13.resolve(cwd, entry);
4599
4914
  const stat = await tryStat(absolute);
4600
4915
  if (stat?.isFile()) {
4601
4916
  return [absolute];
4602
4917
  }
4603
4918
  if (stat?.isDirectory()) {
4604
4919
  const found = await walkTestFiles(absolute, cwd, logger);
4605
- return found.map((file) => path12.resolve(cwd, file));
4920
+ return found.map((file) => path13.resolve(cwd, file));
4606
4921
  }
4607
4922
  return entry;
4608
4923
  }));
@@ -4641,10 +4956,25 @@ class MutantWarnAggregator {
4641
4956
  }
4642
4957
  }
4643
4958
  // src/utils/likely-killer-order.ts
4644
- import path13 from "node:path";
4645
- var MUTANT_SWITCH_RE = /stryMutAct_9fa48\("([^"\\]+)"\)/g;
4959
+ import path14 from "node:path";
4960
+ var SWITCH_DECLARATION_RE = /function stryMutAct_([\w$]+)\(/;
4961
+ var HELPER_CALL_RE = /(?<![\w$])(?:stryMutAct|stryCov)_([\w$]+)\(([^()]*)\)/g;
4962
+ var ID_ARGUMENT_RE = /"([^"\\]+)"/g;
4963
+ function instrumenterSuffix(code) {
4964
+ const suffix = SWITCH_DECLARATION_RE.exec(code)?.[1];
4965
+ return code.includes(`function stryCov_${suffix}(`) ? suffix : undefined;
4966
+ }
4646
4967
  function mutantIdsInInstrumentedSource(code) {
4647
- return new Set(Array.from(code.matchAll(MUTANT_SWITCH_RE), (match) => match[1]));
4968
+ const ids = new Set;
4969
+ const suffix = instrumenterSuffix(code);
4970
+ for (const [, callSuffix, args] of code.matchAll(HELPER_CALL_RE)) {
4971
+ if (callSuffix === suffix) {
4972
+ for (const [, id] of args.matchAll(ID_ARGUMENT_RE)) {
4973
+ ids.add(id);
4974
+ }
4975
+ }
4976
+ }
4977
+ return ids;
4648
4978
  }
4649
4979
 
4650
4980
  class TestFileCoverage {
@@ -4716,8 +5046,8 @@ function namedAfter(sourceFile) {
4716
5046
  if (sourceFile === undefined) {
4717
5047
  return () => false;
4718
5048
  }
4719
- const sourceStem = path13.parse(sourceFile).name.toLowerCase();
4720
- return (testFile) => path13.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
5049
+ const sourceStem = path14.parse(sourceFile).name.toLowerCase();
5050
+ return (testFile) => path14.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
4721
5051
  }
4722
5052
  function compareKillerRanks(a, b) {
4723
5053
  return a.coverage - b.coverage || b.sourceMutants - a.sourceMutants || Number(b.namedAfter) - Number(a.namedAfter);
@@ -4729,7 +5059,7 @@ function orderLikelyKillersFirst(files, rankOf) {
4729
5059
  // src/utils/dry-run-output-log.ts
4730
5060
  import { randomUUID } from "node:crypto";
4731
5061
  import { lstat as lstat2, mkdir as mkdir2, open, rename as rename2, rm as rm4 } from "node:fs/promises";
4732
- import path14 from "node:path";
5062
+ import path15 from "node:path";
4733
5063
  var MAX_LOG_STREAM_CHARS = 16 * 1024 * 1024;
4734
5064
  var MAX_LOG_COMMAND_CHARS = 4000;
4735
5065
  function capStream(text, max) {
@@ -4824,11 +5154,11 @@ function oneLine(error) {
4824
5154
  async function saveDryRunOutput(file, output, options = {}) {
4825
5155
  try {
4826
5156
  const text = formatDryRunOutputLog(output, new Date(options.now ?? Date.now()), options.maxStreamChars);
4827
- const directory = path14.dirname(file);
5157
+ const directory = path15.dirname(file);
4828
5158
  await mkdir2(directory, { recursive: true });
4829
5159
  throwIfAbandoned(options.signal);
4830
5160
  await checkTarget(file);
4831
- const temporary = path14.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
5161
+ const temporary = path15.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
4832
5162
  const handle = await open(temporary, "wx", 384);
4833
5163
  try {
4834
5164
  try {
@@ -4948,7 +5278,7 @@ async function writingTo(file, write) {
4948
5278
  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
5279
  var RUN_ORDINALS = ["first", "second", "third"];
4950
5280
  function isGreen(result) {
4951
- return result.status === DryRunStatus.Complete && !result.tests.some((test) => test.status === TestStatus.Failed);
5281
+ return result.status === DryRunStatus2.Complete && !result.tests.some((test) => test.status === TestStatus2.Failed);
4952
5282
  }
4953
5283
  function buildTestNameIndex(tests, bunNames) {
4954
5284
  const testNameIndex = new Map;
@@ -5020,6 +5350,9 @@ function coversAnyMutant(coverage) {
5020
5350
  const buckets = [coverage.static, ...Object.values(coverage.perTest)];
5021
5351
  return buckets.some((bucket) => Object.values(bucket).some((count) => count > 0));
5022
5352
  }
5353
+ function campaignOf(campaign, dir) {
5354
+ return { ...campaign, dir, watched: new Set(campaign.watchList), handedFiles: new Set(campaign.handed) };
5355
+ }
5023
5356
  var MUTANT_WARN_KIND = {
5024
5357
  unresolvedKilledBy: "failed test names could not be resolved to dry-run test ids",
5025
5358
  noRegistry: "no exact-name registry available (lossy covering-test patterns)",
@@ -5088,6 +5421,7 @@ class BunTestRunner {
5088
5421
  maxSpawnDepth;
5089
5422
  dryRunOutputFile;
5090
5423
  coverageAnalysis;
5424
+ ignoreStatic;
5091
5425
  preloadScriptPath;
5092
5426
  coverageFilePath;
5093
5427
  sanitizedBunfigPath;
@@ -5126,6 +5460,7 @@ class BunTestRunner {
5126
5460
  warnedWatchListProblem = false;
5127
5461
  currentAbortController;
5128
5462
  drainSilenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS;
5463
+ handOffBudget = HAND_OFF_BUDGET;
5129
5464
  constructor(logger, options) {
5130
5465
  this.logger = logger;
5131
5466
  const bunOptions = options.bun ?? {};
@@ -5152,6 +5487,7 @@ class BunTestRunner {
5152
5487
  this.mutateGlobs = options.mutate ?? [];
5153
5488
  this.coverageAnalysis = options.coverageAnalysis;
5154
5489
  this.disableBail = options.disableBail;
5490
+ this.ignoreStatic = options.ignoreStatic === true;
5155
5491
  this.incremental = options.incremental === true;
5156
5492
  this.inPlace = options.inPlace === true;
5157
5493
  this.alwaysImport = bunOptions.alwaysImport;
@@ -5170,7 +5506,7 @@ class BunTestRunner {
5170
5506
  maxSpawnDepth: this.maxSpawnDepth,
5171
5507
  dryRunOutputFile: this.dryRunOutputFile
5172
5508
  });
5173
- if (this.testFilesOverride?.some((p) => path15.isAbsolute(p))) {
5509
+ if (this.testFilesOverride?.some((p) => path16.isAbsolute(p))) {
5174
5510
  const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
5175
5511
  if (isSandbox) {
5176
5512
  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 +5515,7 @@ class BunTestRunner {
5179
5515
  }
5180
5516
  async resolveRegistryPath() {
5181
5517
  this.assertRunOwnerIsParent();
5182
- return path15.join(await resolveRunTempDir(), REGISTRY_FILE);
5518
+ return path16.join(await resolveRunTempDir(), REGISTRY_FILE);
5183
5519
  }
5184
5520
  assertRunOwnerIsParent() {
5185
5521
  if (this.runOwnerPid !== undefined && process.ppid !== this.runOwnerPid) {
@@ -5310,7 +5646,7 @@ class BunTestRunner {
5310
5646
  this.logger.debug("Stryker passed an empty testFiles array; ignoring it");
5311
5647
  }
5312
5648
  } else {
5313
- const files = [...new Set(requested.map((file) => path15.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
5649
+ const files = [...new Set(requested.map((file) => path16.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
5314
5650
  this.strykerTestFiles = { cwd, files };
5315
5651
  this.warnIfTestFilesOverridden(files, cwd);
5316
5652
  }
@@ -5372,7 +5708,7 @@ class BunTestRunner {
5372
5708
  if (this.warnedTestFilesConflict || this.testFilesOverride === undefined) {
5373
5709
  return;
5374
5710
  }
5375
- const configured = [...new Set(this.testFilesOverride.map((file) => path15.resolve(cwd, file)))];
5711
+ const configured = [...new Set(this.testFilesOverride.map((file) => path16.resolve(cwd, file)))];
5376
5712
  const selectedSet = new Set(selected);
5377
5713
  if (configured.length === selectedSet.size && configured.every((file) => selectedSet.has(file))) {
5378
5714
  return;
@@ -5445,7 +5781,7 @@ class BunTestRunner {
5445
5781
  this.runOwnerPid ??= process.ppid;
5446
5782
  const tempDir = await this.ensureRunTempDir();
5447
5783
  this.tempDirTouchedAt = Date.now();
5448
- this.coverageFilePath = path15.join(tempDir, `coverage-${Date.now()}.json`);
5784
+ this.coverageFilePath = path16.join(tempDir, `coverage-${Date.now()}.json`);
5449
5785
  this.logger.debug("Generating coverage preload script...");
5450
5786
  const eagerCwd = process.cwd();
5451
5787
  const testFilesPending = this.getOrDiscoverTestFiles();
@@ -5474,7 +5810,7 @@ class BunTestRunner {
5474
5810
  if (marker === undefined) {
5475
5811
  return;
5476
5812
  }
5477
- const campaign = await readRegistryCampaign(path15.join(runDir, REGISTRY_FILE));
5813
+ const campaign = await readRegistryCampaign(path16.join(runDir, REGISTRY_FILE));
5478
5814
  if (campaign?.generation !== marker.generation) {
5479
5815
  this.logger.debug("Ignoring the abort marker in %s: it belongs to an earlier campaign", runDir);
5480
5816
  return;
@@ -5553,7 +5889,7 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
5553
5889
  if (this.coverageAnalysis !== "off") {
5554
5890
  this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5555
5891
  const campaign = parseCampaignState(parsed.campaign);
5556
- this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
5892
+ this.campaign = campaign === undefined ? undefined : campaignOf(campaign, path16.dirname(registryPath));
5557
5893
  }
5558
5894
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
5559
5895
  } catch (err) {
@@ -5580,7 +5916,7 @@ ${stack}` : baseFailureMessage;
5580
5916
  return {
5581
5917
  id: normalizedName,
5582
5918
  name: normalizedName,
5583
- status: TestStatus.Failed,
5919
+ status: TestStatus2.Failed,
5584
5920
  failureMessage: t.failureMessage ?? "Test failed",
5585
5921
  timeSpentMs: Math.round(t.duration ?? 1)
5586
5922
  };
@@ -5589,14 +5925,14 @@ ${stack}` : baseFailureMessage;
5589
5925
  return {
5590
5926
  id: normalizedName,
5591
5927
  name: normalizedName,
5592
- status: TestStatus.Skipped,
5928
+ status: TestStatus2.Skipped,
5593
5929
  timeSpentMs: Math.round(t.duration ?? 1)
5594
5930
  };
5595
5931
  }
5596
5932
  return {
5597
5933
  id: normalizedName,
5598
5934
  name: normalizedName,
5599
- status: TestStatus.Success,
5935
+ status: TestStatus2.Success,
5600
5936
  timeSpentMs: Math.round(t.duration ?? 1)
5601
5937
  };
5602
5938
  });
@@ -5614,7 +5950,7 @@ ${stack}` : baseFailureMessage;
5614
5950
  return {
5615
5951
  id: `unknown-${inspectorId}`,
5616
5952
  name: `unknown-${inspectorId}`,
5617
- status: TestStatus.Success,
5953
+ status: TestStatus2.Success,
5618
5954
  timeSpentMs: timePerTest
5619
5955
  };
5620
5956
  }
@@ -5630,7 +5966,7 @@ ${stack}` : baseFailureMessage;
5630
5966
  name: uniqueName,
5631
5967
  fileName,
5632
5968
  startPosition,
5633
- status: TestStatus.Failed,
5969
+ status: TestStatus2.Failed,
5634
5970
  failureMessage: this.buildFailureMessage(testInfo, parsed),
5635
5971
  timeSpentMs: elapsed
5636
5972
  };
@@ -5641,7 +5977,7 @@ ${stack}` : baseFailureMessage;
5641
5977
  name: uniqueName,
5642
5978
  fileName,
5643
5979
  startPosition,
5644
- status: TestStatus.Skipped,
5980
+ status: TestStatus2.Skipped,
5645
5981
  timeSpentMs: elapsed
5646
5982
  };
5647
5983
  }
@@ -5650,7 +5986,7 @@ ${stack}` : baseFailureMessage;
5650
5986
  name: uniqueName,
5651
5987
  fileName,
5652
5988
  startPosition,
5653
- status: TestStatus.Success,
5989
+ status: TestStatus2.Success,
5654
5990
  timeSpentMs: elapsed
5655
5991
  };
5656
5992
  });
@@ -5704,10 +6040,11 @@ ${stack}` : baseFailureMessage;
5704
6040
  startedAt,
5705
6041
  profile,
5706
6042
  extraMs: 0,
5707
- launches: 0
6043
+ launches: 0,
6044
+ handed: []
5708
6045
  };
5709
6046
  if (this.inPlace && this.tempDir !== undefined) {
5710
- await removeQuietly(path15.join(this.tempDir, ABORT_MARKER_FILE));
6047
+ await removeQuietly(path16.join(this.tempDir, ABORT_MARKER_FILE));
5711
6048
  }
5712
6049
  if (coverageAnalysis === "off") {
5713
6050
  return this.runWithoutCoverage(launchContext);
@@ -5757,7 +6094,7 @@ ${stack}` : baseFailureMessage;
5757
6094
  const { expanded } = tests;
5758
6095
  let selected = [];
5759
6096
  if (expanded !== undefined) {
5760
- selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path15.resolve(ctx.cwd, entry));
6097
+ selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path16.resolve(ctx.cwd, entry));
5761
6098
  }
5762
6099
  const split = await withoutSelectedTestFiles(ctx.matched, selected);
5763
6100
  if (split.removed.length > 0) {
@@ -5780,6 +6117,22 @@ ${stack}` : baseFailureMessage;
5780
6117
  projectPathsOf(ctx, files) {
5781
6118
  return files.map((file) => shownPath(file, ctx.cwd));
5782
6119
  }
6120
+ handedCreditsOf(ctx, tests) {
6121
+ const started = ctx.handed.some((entry) => entry.launchers !== undefined);
6122
+ const byFile = started && ctx.coverageAnalysis !== "all" ? testsByFile(tests, ctx.cwd, new Set(ctx.handOffTests)) : undefined;
6123
+ return handedCredits(ctx.handed, byFile);
6124
+ }
6125
+ handedSummary(ctx, credits, notLoaded) {
6126
+ const left = new Set(notLoaded);
6127
+ const named = credits.filter((credit) => credit.ids.length > 0 && left.has(credit.file));
6128
+ const started = named.filter((credit) => credit.startedBy !== undefined && credit.every === undefined);
6129
+ const every = named.filter((credit) => credit.startedBy === undefined || credit.every === true);
6130
+ return {
6131
+ started: this.projectPathsOf(ctx, started.map((credit) => credit.file)),
6132
+ testFiles: new Set(started.flatMap((credit) => credit.startedBy.testFiles)).size,
6133
+ every: this.projectPathsOf(ctx, every.map((credit) => credit.file))
6134
+ };
6135
+ }
5783
6136
  logListed(level, message, lists) {
5784
6137
  this.logger[level]("%s", message);
5785
6138
  for (const [what, entries] of lists) {
@@ -5791,6 +6144,7 @@ ${stack}` : baseFailureMessage;
5791
6144
  }
5792
6145
  async decideShape(ctx) {
5793
6146
  const started = performance.now();
6147
+ ctx.handOffsUnread = true;
5794
6148
  try {
5795
6149
  const input = await this.importScanInput(ctx);
5796
6150
  if ("problem" in input) {
@@ -5799,14 +6153,18 @@ ${stack}` : baseFailureMessage;
5799
6153
  }
5800
6154
  const report = await runImportScan(input.input, { bunPath: this.bunPath, workDir: ctx.runDir });
5801
6155
  const decision = decideFromScan(report.result, ctx.eager, ctx.always, this.importDiscovery);
6156
+ ctx.handed = report.result.handed;
6157
+ ctx.handOffTests = input.input.tests;
6158
+ ctx.handOffsUnread = report.failure !== null;
5802
6159
  if (report.failure === null) {
5803
6160
  this.logger.debug("%s", scanMessage({
5804
6161
  answer: report.result.answer,
5805
- wallMs: report.wallMs,
6162
+ wallMs: report.answerMs,
5806
6163
  scannedFiles: report.result.scannedFiles,
5807
6164
  matched: ctx.eager.length,
5808
6165
  statically: this.projectPathsOf(ctx, decision.sources.statically),
5809
6166
  named: this.projectPathsOf(ctx, decision.sources.named),
6167
+ handed: this.projectPathsOf(ctx, report.result.handed.map((entry) => entry.file)),
5810
6168
  always: this.projectPathsOf(ctx, decision.sources.always),
5811
6169
  reasons: decision.kind === "dynamic" ? decision.reasons : report.result.reasons,
5812
6170
  notes: report.result.notes,
@@ -5842,19 +6200,22 @@ ${stack}` : baseFailureMessage;
5842
6200
  return { problem: bunfig.problem };
5843
6201
  }
5844
6202
  const { preloads } = bunfig;
6203
+ const preloaded = new Set([...preloads, ...launch.preloads]);
5845
6204
  return {
5846
6205
  input: {
5847
6206
  eager: ctx.eager,
5848
- roots: [...new Set([...expanded.files, ...preloads, ...launch.preloads])],
6207
+ roots: [...new Set([...expanded.files, ...preloaded])],
6208
+ tests: expanded.files.filter((file) => !preloaded.has(file)),
5849
6209
  always: ctx.always,
5850
6210
  tsconfig: await this.applicableTsconfig(ctx.cwd),
5851
- projectDir: ctx.cwd
6211
+ projectDir: ctx.cwd,
6212
+ handOffBudget: this.handOffBudget
5852
6213
  }
5853
6214
  };
5854
6215
  }
5855
6216
  async applicableTsconfig(cwd) {
5856
6217
  for (const name of ["tsconfig.json", "jsconfig.json"]) {
5857
- const file = path15.join(cwd, name);
6218
+ const file = path16.join(cwd, name);
5858
6219
  const stat = await fsPromises3.stat(file).catch(() => {
5859
6220
  return;
5860
6221
  });
@@ -5898,7 +6259,7 @@ ${stack}` : baseFailureMessage;
5898
6259
  }
5899
6260
  launchFiles(ctx) {
5900
6261
  return {
5901
- planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path15.dirname(this.preloadScriptPath), "dry-run-plan"),
6262
+ planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path16.dirname(this.preloadScriptPath), "dry-run-plan"),
5902
6263
  recordFile: newRecordFile(ctx.runDir)
5903
6264
  };
5904
6265
  }
@@ -5916,7 +6277,7 @@ ${stack}` : baseFailureMessage;
5916
6277
  } catch (error) {
5917
6278
  const errorMessage = `stryker-bun-runner: cannot write the dry-run plan ${planFile} (${errorText(error)})`;
5918
6279
  this.logger.error("%s", errorMessage);
5919
- return { result: { status: DryRunStatus.Error, errorMessage } };
6280
+ return { result: { status: DryRunStatus2.Error, errorMessage } };
5920
6281
  }
5921
6282
  }
5922
6283
  async readRecord(file, parse) {
@@ -5949,7 +6310,7 @@ ${stack}` : baseFailureMessage;
5949
6310
  }
5950
6311
  async runStaticShape(ctx, decision, roots) {
5951
6312
  const launch = await this.runPublished(ctx, decision.list);
5952
- const testFiles = launch.result.status === DryRunStatus.Complete ? launch.result.tests.map((test) => test.fileName) : [];
6313
+ const testFiles = launch.result.status === DryRunStatus2.Complete ? launch.result.tests.map((test) => test.fileName) : [];
5953
6314
  const outcome = oneRunOutcome(this.launchFacts(ctx, launch), unscannedTestFiles(testFiles, roots, ctx.cwd), decision.sources.named);
5954
6315
  if (outcome.kind === "refuse") {
5955
6316
  return this.refuseDryRun(outcome.problems);
@@ -5967,8 +6328,10 @@ ${stack}` : baseFailureMessage;
5967
6328
  }
5968
6329
  this.warnEagerFailures(ctx, launch.record);
5969
6330
  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]]);
6331
+ const notImported = ctx.eager.filter((file) => !decision.list.includes(file));
6332
+ const left = this.projectPathsOf(ctx, notImported);
6333
+ const handed = this.handedSummary(ctx, this.handedCreditsOf(ctx, launch.publication.tests), notImported);
6334
+ 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
6335
  }
5973
6336
  return this.publishDryRun(ctx, launch);
5974
6337
  }
@@ -6032,7 +6395,8 @@ ${stack}` : baseFailureMessage;
6032
6395
  return this.refuseDryRun([MISSING_COVERAGE_FOR_RULE_3_3]);
6033
6396
  }
6034
6397
  const early = outcome.early.map((observation) => observation.file);
6035
- this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched }, publishedOrdinal, discoveryOrdinal);
6398
+ const credits = this.handedCreditsOf(ctx, launch.publication.tests);
6399
+ this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched, credits }, publishedOrdinal, discoveryOrdinal);
6036
6400
  this.warnEagerFailures(ctx, launch.record);
6037
6401
  return this.publishDryRun(ctx, launch, early);
6038
6402
  }
@@ -6043,9 +6407,11 @@ ${stack}` : baseFailureMessage;
6043
6407
  }
6044
6408
  const kept = new Set(run.list);
6045
6409
  if (run.watched) {
6046
- const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !kept.has(file)));
6410
+ const notImported = ctx.eager.filter((file) => !kept.has(file));
6411
+ const left = this.projectPathsOf(ctx, notImported);
6412
+ const handed = this.handedSummary(ctx, run.credits, notImported);
6047
6413
  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]]);
6414
+ 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
6415
  }
6050
6416
  if (run.cause.kind === "failed") {
6051
6417
  const unloaded = run.cause.named.filter((file) => !run.observed.has(file));
@@ -6112,7 +6478,7 @@ ${stack}` : baseFailureMessage;
6112
6478
  refuseDryRun(problems) {
6113
6479
  const errorMessage = refuseMessage(problems, this.incremental);
6114
6480
  this.logger.error("%s", errorMessage);
6115
- return { status: DryRunStatus.Error, errorMessage };
6481
+ return { status: DryRunStatus2.Error, errorMessage };
6116
6482
  }
6117
6483
  async discoveryError(ctx, discovery, ordinal, reasons) {
6118
6484
  const { result } = discovery;
@@ -6126,7 +6492,7 @@ ${tail}`;
6126
6492
  ${output}
6127
6493
  ${outputLine}`;
6128
6494
  this.logger.error("%s", errorMessage);
6129
- return { status: DryRunStatus.Error, errorMessage };
6495
+ return { status: DryRunStatus2.Error, errorMessage };
6130
6496
  }
6131
6497
  lateLoadError(ctx, launch, late, published, discovery) {
6132
6498
  const names = launch.publication?.testNames;
@@ -6137,7 +6503,7 @@ ${outputLine}`;
6137
6503
  }));
6138
6504
  const errorMessage = lateLoadMessage(loads, published, discovery, this.incremental);
6139
6505
  this.logListed("error", errorMessage, [["the files loaded late", lateLoadEntries(loads)]]);
6140
- return { status: DryRunStatus.Error, errorMessage };
6506
+ return { status: DryRunStatus2.Error, errorMessage };
6141
6507
  }
6142
6508
  async lostError(ctx, ids, list, always, published) {
6143
6509
  const lost = new Set(ids);
@@ -6158,7 +6524,7 @@ ${outputLine}`;
6158
6524
  };
6159
6525
  const errorMessage = lostMessage(report);
6160
6526
  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 };
6527
+ return { status: DryRunStatus2.Error, errorMessage };
6162
6528
  }
6163
6529
  async publishDryRun(ctx, launch, seen = []) {
6164
6530
  const { publication } = launch;
@@ -6169,22 +6535,34 @@ ${outputLine}`;
6169
6535
  const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
6170
6536
  ctx.profile?.at("coverageChecked");
6171
6537
  const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
6172
- const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched } : undefined;
6538
+ const handed = creditHandedCoverage(launch.result, this.handedCreditsOf(ctx, tests), (file) => shownPath(file, ctx.cwd), this.ignoreStatic && ctx.coverageAnalysis !== "all");
6539
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched, handed: handed.files } : undefined;
6173
6540
  const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
6174
6541
  ctx.profile?.at("registryWritten");
6175
6542
  if (unpublished !== undefined) {
6176
6543
  this.logger.error("%s", unpublished);
6177
- return { status: DryRunStatus.Error, errorMessage: unpublished };
6544
+ return { status: DryRunStatus2.Error, errorMessage: unpublished };
6178
6545
  }
6179
6546
  this.warnOnUnidentifiedDryRunFailure(processResult, parsed, tests);
6180
6547
  this.warnOnTightDryRunTimeout(totalElapsedMs);
6181
- return launch.result;
6548
+ for (const line of handed.debug) {
6549
+ this.logger.debug("%s", line);
6550
+ }
6551
+ if (handed.warning !== undefined) {
6552
+ this.logger.warn("%s", handed.warning);
6553
+ }
6554
+ return handed.result;
6555
+ }
6556
+ warnIfNoMutantCovered(result, coverageAnalysis) {
6557
+ if (result.mutantCoverage !== undefined && coverageAnalysis !== "off" && !coversAnyMutant(result.mutantCoverage)) {
6558
+ 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)");
6559
+ }
6182
6560
  }
6183
6561
  async runInspectedPass(ctx, list, planFile) {
6184
6562
  const abortController = new AbortController;
6185
6563
  this.currentAbortController = abortController;
6186
6564
  ctx.profile?.restartLaunch();
6187
- const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path15.dirname(this.coverageFilePath), "coverage");
6565
+ const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path16.dirname(this.coverageFilePath), "coverage");
6188
6566
  const launched = {};
6189
6567
  try {
6190
6568
  return await this.runInspectedChild(ctx, list, planFile, coverageFile, abortController, launched);
@@ -6210,7 +6588,7 @@ ${outputLine}`;
6210
6588
  this.logger.error("Failed to start sync server: %s", errorMsg);
6211
6589
  return {
6212
6590
  result: {
6213
- status: DryRunStatus.Error,
6591
+ status: DryRunStatus2.Error,
6214
6592
  errorMessage: `Failed to start sync server: ${errorMsg}`
6215
6593
  }
6216
6594
  };
@@ -6270,7 +6648,7 @@ exit=%s timedOut=%s
6270
6648
  %s`, this.inspectorTimeout, String(diagnosticResult.exitCode), String(diagnosticResult.timedOut), stdoutPreview || "(empty)", stderrPreview || "(empty)");
6271
6649
  return {
6272
6650
  result: {
6273
- status: DryRunStatus.Error,
6651
+ status: DryRunStatus2.Error,
6274
6652
  errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult, secrets)
6275
6653
  }
6276
6654
  };
@@ -6306,7 +6684,7 @@ exit=%s timedOut=%s
6306
6684
  const child = await testProcess;
6307
6685
  return {
6308
6686
  result: {
6309
- status: DryRunStatus.Error,
6687
+ status: DryRunStatus2.Error,
6310
6688
  errorMessage: formatInspectorConnectMessage(errorMsg, child, [syncServer.token])
6311
6689
  }
6312
6690
  };
@@ -6349,7 +6727,7 @@ exit=%s timedOut=%s
6349
6727
  if (earlyResult) {
6350
6728
  return { result: earlyResult };
6351
6729
  }
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);
6730
+ 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
6731
  } finally {
6354
6732
  abortController.abort();
6355
6733
  if (this.currentAbortController === abortController) {
@@ -6388,12 +6766,12 @@ exit=%s timedOut=%s
6388
6766
  const outputLine = await this.saveFailedDryRunOutput(result, spawnInfo);
6389
6767
  return { result: this.completenessError(gateReasons, inspectorState.wasClosedUnexpectedly, inspectorState.closeInfo, outputLine) };
6390
6768
  }
6391
- const coverageResult = this.checkCoverageData(mutantCoverage, tests, run.coverageAnalysis, result.stderr, run.coverageFile);
6769
+ const coverageResult = this.checkCoverageData(mutantCoverage, tests, run, result.stderr);
6392
6770
  if (coverageResult) {
6393
6771
  return { result: coverageResult };
6394
6772
  }
6395
6773
  const off = run.coverageAnalysis === "off";
6396
- const complete = { status: DryRunStatus.Complete, tests };
6774
+ const complete = { status: DryRunStatus2.Complete, tests };
6397
6775
  if (mutantCoverage !== undefined && !off) {
6398
6776
  complete.mutantCoverage = run.coverageAnalysis === "all" ? reachedOnly(mutantCoverage) : mutantCoverage;
6399
6777
  }
@@ -6411,24 +6789,25 @@ exit=%s timedOut=%s
6411
6789
  }
6412
6790
  };
6413
6791
  }
6414
- checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
6792
+ checkCoverageData(coverage, tests, run, stderr) {
6415
6793
  const preloadLines = extractPreloadCoverageDiagnostics(stderr);
6416
- if (coverage !== undefined || tests.some((t) => t.status === TestStatus.Failed)) {
6794
+ if (coverage !== undefined || tests.some((t) => t.status === TestStatus2.Failed)) {
6417
6795
  if (preloadLines.length > 0) {
6418
6796
  this.logger.warn(`The coverage preload reported problems on the dry-run child's stderr:
6419
6797
  %s`, preloadLines.join(`
6420
6798
  `));
6421
6799
  }
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)");
6800
+ if (!run.handedIdsHeld) {
6801
+ this.warnIfNoMutantCovered({ mutantCoverage: coverage }, run.coverageAnalysis);
6424
6802
  }
6425
6803
  return null;
6426
6804
  }
6805
+ const { coverageAnalysis, coverageFile } = run;
6427
6806
  return this.missingCoverageResult(coverageAnalysis, preloadLines, coverageFile);
6428
6807
  }
6429
6808
  missingCoverageResult(coverageAnalysis, preloadLines, coverageFile) {
6430
6809
  const file = coverageFile ?? "(none configured)";
6431
- const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
6810
+ const coverageDir = coverageFile === undefined ? tmpdir2() : path16.dirname(coverageFile);
6432
6811
  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
6812
  const diagnostics = preloadLines.length > 0 ? [`Coverage preload diagnostics from the child's stderr:
6434
6813
  ${preloadLines.join(`
@@ -6448,7 +6827,7 @@ ${preloadLines.join(`
6448
6827
  ].join(" ");
6449
6828
  if (fails) {
6450
6829
  this.logger.error("%s", message);
6451
- return { status: DryRunStatus.Error, errorMessage: message };
6830
+ return { status: DryRunStatus2.Error, errorMessage: message };
6452
6831
  }
6453
6832
  this.logger.warn("%s", message);
6454
6833
  return null;
@@ -6503,7 +6882,7 @@ ${preloadLines.join(`
6503
6882
  return failure instanceof WriteFailure ? unpublishedCampaignMessage(failure.file, failure.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(failure), watched);
6504
6883
  }
6505
6884
  if (campaignInput !== undefined && failure instanceof WriteFailure) {
6506
- const registryPath = path15.join(path15.dirname(failure.file), REGISTRY_FILE);
6885
+ const registryPath = path16.join(path16.dirname(failure.file), REGISTRY_FILE);
6507
6886
  const earlier = await fsPromises3.lstat(registryPath).catch(() => {
6508
6887
  return;
6509
6888
  });
@@ -6516,7 +6895,7 @@ ${preloadLines.join(`
6516
6895
  }
6517
6896
  async writeRegistry(indexes, testFileCoverage, campaignInput) {
6518
6897
  const registryPath = await this.resolveRegistryPath();
6519
- const runDir = path15.dirname(registryPath);
6898
+ const runDir = path16.dirname(registryPath);
6520
6899
  const campaign = campaignInput === undefined ? undefined : await this.writeCampaignFiles(runDir, campaignInput);
6521
6900
  const tmpPath = `${registryPath}.tmp`;
6522
6901
  const registryData = JSON.stringify({
@@ -6537,14 +6916,14 @@ ${preloadLines.join(`
6537
6916
  await writingTo(registryPath, async () => fsPromises3.rename(tmpPath, registryPath));
6538
6917
  } catch (error) {
6539
6918
  if (campaign?.watchListFile) {
6540
- await removeQuietly(path15.join(runDir, campaign.watchListFile));
6919
+ await removeQuietly(path16.join(runDir, campaign.watchListFile));
6541
6920
  }
6542
6921
  throw error;
6543
6922
  }
6544
6923
  this.lastRegistryTmpPath = undefined;
6545
6924
  if (campaign !== undefined) {
6546
- await removeQuietly(path15.join(runDir, ABORT_MARKER_FILE));
6547
- this.campaign = { ...campaign, dir: runDir, watched: new Set(campaign.watchList) };
6925
+ await removeQuietly(path16.join(runDir, ABORT_MARKER_FILE));
6926
+ this.campaign = campaignOf(campaign, runDir);
6548
6927
  }
6549
6928
  this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, indexes.cachedTestNames.size);
6550
6929
  }
@@ -6556,10 +6935,11 @@ ${preloadLines.join(`
6556
6935
  generation,
6557
6936
  watchList: [...watched],
6558
6937
  watchListFile,
6938
+ handed: [...campaignInput.handed],
6559
6939
  fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.matched)
6560
6940
  };
6561
6941
  if (watchListFile !== null) {
6562
- const file = path15.join(runDir, watchListFile);
6942
+ const file = path16.join(runDir, watchListFile);
6563
6943
  await writingTo(file, async () => writeWatchList(file, watched));
6564
6944
  }
6565
6945
  return campaign;
@@ -6634,9 +7014,22 @@ ${preloadLines.join(`
6634
7014
  }
6635
7015
  return corrected.timeoutMs;
6636
7016
  }
7017
+ handedFileOf(options) {
7018
+ if (typeof options.sandboxFileName !== "string") {
7019
+ return;
7020
+ }
7021
+ const file = path16.resolve(options.sandboxFileName);
7022
+ return this.campaign?.handedFiles.has(file) === true ? file : undefined;
7023
+ }
7024
+ mutantRunGuards(options) {
7025
+ if (this.handedFileOf(options) !== undefined) {
7026
+ return { hitLimit: undefined, watchList: undefined };
7027
+ }
7028
+ return { hitLimit: options.hitLimit, watchList: this.watchListForMutantRuns() };
7029
+ }
6637
7030
  watchListForMutantRuns() {
6638
7031
  const { campaign } = this;
6639
- return campaign?.watchListFile ? path15.join(campaign.dir, campaign.watchListFile) : undefined;
7032
+ return campaign?.watchListFile ? path16.join(campaign.dir, campaign.watchListFile) : undefined;
6640
7033
  }
6641
7034
  async enforceWitness(stderr, hitLimitToken, ctx, testNamePattern) {
6642
7035
  const { campaign } = this;
@@ -6696,7 +7089,7 @@ ${preloadLines.join(`
6696
7089
  const cwd = process.cwd();
6697
7090
  const exist = await Promise.all(entries.map(async (entry) => {
6698
7091
  try {
6699
- const stat = await fsPromises3.stat(path15.resolve(cwd, entry));
7092
+ const stat = await fsPromises3.stat(path16.resolve(cwd, entry));
6700
7093
  return stat.isFile();
6701
7094
  } catch {
6702
7095
  return false;
@@ -6710,6 +7103,7 @@ ${preloadLines.join(`
6710
7103
  const abortController = new AbortController;
6711
7104
  this.currentAbortController = abortController;
6712
7105
  const hitLimitToken = newHitLimitToken();
7106
+ const guards = this.mutantRunGuards(options);
6713
7107
  const ordered = this.orderForMutantRun(ctx.testFileScope ?? (testNamePattern === undefined ? this.effectiveTestFiles : coveringTestFiles ?? this.effectiveTestFiles), ctx);
6714
7108
  const testFiles = this.fitTestFiles(ordered, ctx.testFileScope === undefined ? this.explicitTestFilesSource(process.cwd()) : "Stryker's testFiles option");
6715
7109
  ctx.profile?.setScope(mutantRunScope(ctx.testFileScope !== undefined, testNamePattern, ctx.coveringTestCount));
@@ -6722,9 +7116,9 @@ ${preloadLines.join(`
6722
7116
  bunArgs: this.mutantBunArgs,
6723
7117
  bunfigPath,
6724
7118
  activeMutant: options.activeMutant.id,
6725
- hitLimit: options.hitLimit,
7119
+ hitLimit: guards.hitLimit,
6726
7120
  hitLimitToken,
6727
- watchList: this.watchListForMutantRuns(),
7121
+ watchList: guards.watchList,
6728
7122
  bail: !options.disableBail,
6729
7123
  sequentialMode: true,
6730
7124
  preloadScript: this.preloadScriptPath,
@@ -6886,11 +7280,11 @@ ${result.stderr}`).trim().slice(-500) || "(no output)";
6886
7280
  if (result.memoryLimitExceeded !== true) {
6887
7281
  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
7282
  }
6889
- return { status: DryRunStatus.Timeout };
7283
+ return { status: DryRunStatus2.Timeout };
6890
7284
  }
6891
7285
  if (result.spawnError !== undefined) {
6892
7286
  return {
6893
- status: DryRunStatus.Error,
7287
+ status: DryRunStatus2.Error,
6894
7288
  errorMessage: `${formatSpawnErrorMessage(result.spawnError)}
6895
7289
  ${cleanDiagnosticText(result.stderr, secrets)}`
6896
7290
  };
@@ -6903,7 +7297,7 @@ ${cleanDiagnosticText(result.stderr, secrets)}`
6903
7297
  }
6904
7298
  messageParts.push(cleanDiagnosticText(result.stderr, secrets));
6905
7299
  return {
6906
- status: DryRunStatus.Error,
7300
+ status: DryRunStatus2.Error,
6907
7301
  errorMessage: messageParts.join(`
6908
7302
  `)
6909
7303
  };
@@ -6937,7 +7331,7 @@ ${lines.join(`
6937
7331
  `)}`;
6938
7332
  }
6939
7333
  warnOnUnidentifiedDryRunFailure(result, parsed, tests) {
6940
- if (parsed.failed > 0 && !tests.some((t) => t.status === TestStatus.Failed)) {
7334
+ if (parsed.failed > 0 && !tests.some((t) => t.status === TestStatus2.Failed)) {
6941
7335
  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
7336
  %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
6943
7337
  }
@@ -6982,7 +7376,7 @@ ${lines.join(`
6982
7376
  }
6983
7377
  }
6984
7378
  findCompletenessProblems(facts, summaryFailed, tests, stderr, eagerModules, secrets = []) {
6985
- if (tests.some((t) => t.status === TestStatus.Failed)) {
7379
+ if (tests.some((t) => t.status === TestStatus2.Failed)) {
6986
7380
  return [];
6987
7381
  }
6988
7382
  const reasons = findDryRunDataLoss(facts);
@@ -7009,7 +7403,7 @@ ${cleanDiagnosticText(stderr, secrets).slice(-500)}`);
7009
7403
  ${outputLine}`;
7010
7404
  this.logger.error("%s", errorMessage);
7011
7405
  return {
7012
- status: DryRunStatus.Error,
7406
+ status: DryRunStatus2.Error,
7013
7407
  errorMessage
7014
7408
  };
7015
7409
  }
@@ -7163,7 +7557,7 @@ ${outputLine}`;
7163
7557
  // src/checker-tsconfig.ts
7164
7558
  import { readFile as readFile7, rename as rename4, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
7165
7559
  import { createRequire as createRequire2 } from "node:module";
7166
- import path16 from "node:path";
7560
+ import path17 from "node:path";
7167
7561
  import { glob as glob2 } from "tinyglobby";
7168
7562
  var DEFAULT_MUTATE_PATTERNS = ["{src,lib}/**"];
7169
7563
  var MUTATION_RANGE_RE = /:\d+(?::\d+)?-\d+(?::\d+)?$/;
@@ -7171,11 +7565,37 @@ var DERIVED_SUFFIX = ".stryker-checker.json";
7171
7565
  var GENERATED_MARKER = "// Generated by withTestFilesExcludedFromTypeCheck()";
7172
7566
  var LOG_PREFIX = "[Stryker] withTestFilesExcludedFromTypeCheck: ";
7173
7567
  var MAX_QUOTED_ERRORS = 3;
7568
+ var COMPILER_API = [
7569
+ "createProgram",
7570
+ "formatDiagnostic",
7571
+ "getParsedCommandLineOfConfigFile",
7572
+ "isExternalModule",
7573
+ "isModuleDeclaration",
7574
+ "isStringLiteral",
7575
+ "parseJsonSourceFileConfigFileContent",
7576
+ "parseJsonText",
7577
+ "preProcessFile",
7578
+ "resolveModuleName"
7579
+ ];
7580
+ function cannotLoad(cwd) {
7581
+ return { problem: `typescript cannot be loaded from ${cwd}; install it there` };
7582
+ }
7583
+ function checkTypeScript(exported, cwd) {
7584
+ const candidate = exported;
7585
+ if (COMPILER_API.every((name) => typeof candidate?.[name] === "function")) {
7586
+ return { ts: exported };
7587
+ }
7588
+ const version = String(candidate?.version);
7589
+ if (Number.parseInt(version, 10) >= 7) {
7590
+ 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)` };
7591
+ }
7592
+ return cannotLoad(cwd);
7593
+ }
7174
7594
  function loadTypeScript(cwd) {
7175
7595
  try {
7176
- return createRequire2(path16.join(cwd, "package.json"))("typescript");
7596
+ return checkTypeScript(createRequire2(path17.join(cwd, "package.json"))("typescript"), cwd);
7177
7597
  } catch {
7178
- return;
7598
+ return cannotLoad(cwd);
7179
7599
  }
7180
7600
  }
7181
7601
  function readProject(ts, tsconfigPath, shown) {
@@ -7200,7 +7620,7 @@ async function findTestFiles(config, cwd) {
7200
7620
  for (const relativeFiles of [await discoverTestFiles(cwd, undefined, sourceBunfig), bun.testFiles]) {
7201
7621
  if (relativeFiles) {
7202
7622
  for (const file of relativeFiles) {
7203
- testFiles.add(path16.resolve(cwd, file));
7623
+ testFiles.add(path17.resolve(cwd, file));
7204
7624
  }
7205
7625
  }
7206
7626
  }
@@ -7278,12 +7698,12 @@ function derivedHeader(source) {
7278
7698
  `);
7279
7699
  }
7280
7700
  function renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints) {
7281
- const source = path16.basename(sourcePath);
7701
+ const source = path17.basename(sourcePath);
7282
7702
  const body = {
7283
7703
  extends: `./${source}`,
7284
7704
  ...project.options.declarationDir !== undefined && { compilerOptions: { declarationDir: null } },
7285
7705
  include: [],
7286
- files: entryPoints.map((file) => path16.relative(path16.dirname(derivedPath), file))
7706
+ files: entryPoints.map((file) => path17.relative(path17.dirname(derivedPath), file))
7287
7707
  };
7288
7708
  return `${derivedHeader(source)}${JSON.stringify(body, null, 2)}
7289
7709
  `;
@@ -7293,12 +7713,13 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
7293
7713
  console.info(`${LOG_PREFIX}not applied: the config's checkers do not include 'typescript'`);
7294
7714
  return config;
7295
7715
  }
7296
- const ts = loadTypeScript(cwd);
7297
- if (!ts) {
7298
- return leaveUnchanged(config, `typescript cannot be loaded from ${cwd}; install it there`);
7716
+ const loaded = loadTypeScript(cwd);
7717
+ if ("problem" in loaded) {
7718
+ return leaveUnchanged(config, loaded.problem);
7299
7719
  }
7300
- const sourcePath = path16.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
7301
- const shownSource = path16.relative(cwd, sourcePath);
7720
+ const { ts } = loaded;
7721
+ const sourcePath = path17.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
7722
+ const shownSource = path17.relative(cwd, sourcePath);
7302
7723
  const read = readProject(ts, sourcePath, shownSource);
7303
7724
  if ("problem" in read) {
7304
7725
  return leaveUnchanged(config, read.problem);
@@ -7315,10 +7736,10 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
7315
7736
  if (entryPoints.length === 0) {
7316
7737
  return leaveUnchanged(config, `${shownSource} would have no files left once test files are excluded`);
7317
7738
  }
7318
- const derivedPath = path16.join(path16.dirname(sourcePath), `${path16.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7319
- const shownDerived = path16.relative(cwd, derivedPath);
7739
+ const derivedPath = path17.join(path17.dirname(sourcePath), `${path17.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
7740
+ const shownDerived = path17.relative(cwd, derivedPath);
7320
7741
  const text = renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints);
7321
- const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path16.dirname(derivedPath), undefined, derivedPath);
7742
+ const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path17.dirname(derivedPath), undefined, derivedPath);
7322
7743
  const derived = createProgram(ts, derivedProject, original);
7323
7744
  const newErrors = findNewErrors(derived, original, testFiles);
7324
7745
  if (newErrors.length > 0) {