@hughescr/stryker-bun-runner 1.6.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,272 @@
1
1
  // @bun
2
2
  // src/templates/coverage-preload.ts
3
- import { beforeEach, afterEach, afterAll, describe, test, it } from "bun:test";
3
+ import { beforeEach, afterEach, afterAll, describe as describe2, test, it } from "bun:test";
4
4
 
5
5
  // src/coverage/preload-logic.ts
6
- import { appendFileSync, closeSync, constants, openSync, writeSync } from "fs";
7
- var preloadFs = { appendFileSync, closeSync, openSync, writeSync };
6
+ import { appendFileSync, closeSync, constants, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeSync } from "fs";
7
+ import { createRequire } from "module";
8
+
9
+ // src/coverage/load-sensors.ts
10
+ var HEADER_FUNCTION = "stryNS_9fa48";
11
+ var NAMESPACE_KEY = "__stryker__";
12
+ var HEADER_STACK_FRAMES = 8;
13
+ function describe(error) {
14
+ try {
15
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
16
+ } catch {
17
+ return "an error that cannot be described";
18
+ }
19
+ }
20
+ function headerFileFromStack(stack) {
21
+ for (const raw of stack.split(`
22
+ `)) {
23
+ const line = raw.trim();
24
+ if (!line.startsWith(`at ${HEADER_FUNCTION} `)) {
25
+ continue;
26
+ }
27
+ const rest = line.slice(HEADER_FUNCTION.length + 4);
28
+ const location = rest.startsWith("(") && rest.endsWith(")") ? rest.slice(1, -1) : rest;
29
+ const position = /:\d+(?::\d+)?$/.exec(location);
30
+ if (position === null || position.index === 0) {
31
+ return null;
32
+ }
33
+ return location.slice(0, position.index);
34
+ }
35
+ return;
36
+ }
37
+ function captureStack(errorConstructor) {
38
+ const ctor = errorConstructor;
39
+ const limit = ctor.stackTraceLimit;
40
+ const prepare = ctor.prepareStackTrace;
41
+ ctor.stackTraceLimit = HEADER_STACK_FRAMES;
42
+ ctor.prepareStackTrace = undefined;
43
+ try {
44
+ const { stack } = new ctor("stryker-bun-runner load sensor");
45
+ return typeof stack === "string" ? stack : undefined;
46
+ } finally {
47
+ ctor.stackTraceLimit = limit;
48
+ ctor.prepareStackTrace = prepare;
49
+ }
50
+ }
51
+
52
+ class CandidateIndex {
53
+ files;
54
+ byKey = new Map;
55
+ reals;
56
+ groups;
57
+ seen;
58
+ observed = [];
59
+ unseen;
60
+ constructor(files, realpath) {
61
+ this.files = files;
62
+ this.seen = files.map(() => false);
63
+ this.unseen = files.length;
64
+ this.reals = files.map((file) => {
65
+ try {
66
+ const real = realpath(file);
67
+ return real === file ? undefined : real;
68
+ } catch {
69
+ return;
70
+ }
71
+ });
72
+ const byIdentity = new Map;
73
+ for (const [index, file] of files.entries()) {
74
+ const identity = this.reals[index] ?? file;
75
+ const group = byIdentity.get(identity);
76
+ if (group === undefined) {
77
+ byIdentity.set(identity, [index]);
78
+ } else {
79
+ group.push(index);
80
+ }
81
+ }
82
+ this.groups = files.map((file, index) => byIdentity.get(this.reals[index] ?? file));
83
+ for (const [index, file] of files.entries()) {
84
+ this.add(file, this.groups[index]);
85
+ const real = this.reals[index];
86
+ if (real !== undefined) {
87
+ this.add(real, this.groups[index]);
88
+ }
89
+ }
90
+ }
91
+ add(key, group) {
92
+ const known = this.byKey.get(key);
93
+ if (known === undefined) {
94
+ this.byKey.set(key, group);
95
+ } else if (known !== group) {
96
+ this.byKey.set(key, [...new Set([...known, ...group])]);
97
+ }
98
+ }
99
+ lookup(key) {
100
+ return this.byKey.get(key);
101
+ }
102
+ observe(indices, time, sensor, testKey) {
103
+ for (const index of indices) {
104
+ if (!this.seen[index]) {
105
+ this.seen[index] = true;
106
+ this.unseen--;
107
+ this.observed.push({ file: this.files[index], time, sensor, testKey });
108
+ }
109
+ }
110
+ }
111
+ cached(cache) {
112
+ const found = [];
113
+ const swept = new Set;
114
+ for (const [index, file] of this.files.entries()) {
115
+ const group = this.groups[index];
116
+ const real = this.reals[index];
117
+ if (!this.seen[index] && !swept.has(group) && ((file in cache) || real !== undefined && (real in cache))) {
118
+ swept.add(group);
119
+ found.push(...group);
120
+ }
121
+ }
122
+ return found;
123
+ }
124
+ }
125
+ function candidatesOf(index, file, deps) {
126
+ const exact = index.lookup(file);
127
+ if (exact !== undefined) {
128
+ return exact;
129
+ }
130
+ let plain;
131
+ if (file.startsWith("file:")) {
132
+ try {
133
+ plain = deps.fileURLToPath(file);
134
+ } catch {
135
+ return null;
136
+ }
137
+ } else {
138
+ const lastSlash = file.lastIndexOf("/");
139
+ const query = file.indexOf("?", lastSlash + 1);
140
+ plain = query === -1 ? file : file.slice(0, query);
141
+ }
142
+ const spelled = index.lookup(plain);
143
+ if (spelled !== undefined) {
144
+ return spelled;
145
+ }
146
+ let real;
147
+ try {
148
+ real = deps.realpath(plain);
149
+ } catch {
150
+ return [];
151
+ }
152
+ return index.lookup(real) ?? [];
153
+ }
154
+ function installLoadSensors(deps) {
155
+ const problems = new Map;
156
+ const problem = (kind, text) => {
157
+ if (!problems.has(kind)) {
158
+ problems.set(kind, text);
159
+ }
160
+ };
161
+ let sensorMs = 0;
162
+ let time = "by-eager-end";
163
+ let finished = false;
164
+ let busy = false;
165
+ let index;
166
+ let installed;
167
+ const addElapsed = (started) => {
168
+ try {
169
+ if (started !== undefined) {
170
+ sensorMs += deps.now() - started;
171
+ }
172
+ } catch (error) {
173
+ problem("bookkeeping", `the load sensors failed: ${describe(error)}`);
174
+ }
175
+ };
176
+ const measured = (work) => {
177
+ let started;
178
+ try {
179
+ started = deps.now();
180
+ work();
181
+ } catch (error) {
182
+ problem("bookkeeping", `the load sensors failed: ${describe(error)}`);
183
+ } finally {
184
+ addElapsed(started);
185
+ }
186
+ };
187
+ const lookUpCache = (testKey) => {
188
+ if (index !== undefined && index.unseen > 0) {
189
+ index.observe(index.cached(deps.cache), time, "cache", testKey);
190
+ }
191
+ };
192
+ try {
193
+ const candidates = new CandidateIndex(deps.candidates, deps.realpath);
194
+ index = candidates;
195
+ let current = deps.namespace;
196
+ const record = (stack) => {
197
+ const file = stack === undefined ? null : headerFileFromStack(stack);
198
+ if (file === undefined) {
199
+ return;
200
+ }
201
+ const found = file === null ? null : candidatesOf(candidates, file, deps);
202
+ if (found === null) {
203
+ const frame = stack?.split(`
204
+ `).find((line) => line.includes(HEADER_FUNCTION))?.trim() ?? "no stack";
205
+ problem("unreadable", `an instrumented file was evaluated but its path could not be read from the stack (${frame})`);
206
+ return;
207
+ }
208
+ if (found.length > 0) {
209
+ candidates.observe(found, time, "header", time === "later" ? deps.currentTest() : null);
210
+ }
211
+ };
212
+ const getter = function strykerNamespaceSensor() {
213
+ if (!finished && !busy && candidates.unseen > 0) {
214
+ busy = true;
215
+ let started;
216
+ try {
217
+ started = deps.now();
218
+ record(deps.readStack());
219
+ } catch (error) {
220
+ problem("bookkeeping", `the load sensors failed: ${describe(error)}`);
221
+ } finally {
222
+ busy = false;
223
+ addElapsed(started);
224
+ }
225
+ }
226
+ return current;
227
+ };
228
+ Object.defineProperty(deps.global, NAMESPACE_KEY, {
229
+ configurable: true,
230
+ enumerable: true,
231
+ get: getter,
232
+ set(value) {
233
+ current = value;
234
+ }
235
+ });
236
+ installed = getter;
237
+ measured(() => {
238
+ lookUpCache(null);
239
+ });
240
+ } catch (error) {
241
+ problem("install", `the load sensors could not be installed: ${describe(error)}`);
242
+ }
243
+ return {
244
+ markEagerEnd() {
245
+ measured(() => {
246
+ lookUpCache(null);
247
+ });
248
+ time = "later";
249
+ },
250
+ finish() {
251
+ measured(() => {
252
+ lookUpCache(null);
253
+ });
254
+ finished = true;
255
+ try {
256
+ if (installed !== undefined && Object.getOwnPropertyDescriptor(deps.global, NAMESPACE_KEY)?.get !== installed) {
257
+ problem("replaced", "globalThis.__stryker__ was redefined during the run");
258
+ }
259
+ } catch (error) {
260
+ problem("replaced", `globalThis.__stryker__ could not be checked at the end of the run: ${describe(error)}`);
261
+ }
262
+ return { observed: index?.observed ?? [], problems: [...problems.values()], sensorMs };
263
+ }
264
+ };
265
+ }
266
+
267
+ // src/coverage/preload-logic.ts
268
+ var PreloadError = Error;
269
+ var preloadFs = { appendFileSync, closeSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeSync };
8
270
  var HIT_LIMIT_TOKEN_ENV = "__STRYKER_HIT_LIMIT_TOKEN__";
9
271
  var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
10
272
  function getPreloadConfig() {
@@ -106,9 +368,10 @@ ${HIT_LIMIT_SENTINEL} ${token} ${hitCount}
106
368
  }
107
369
  function installHitLimit(strykerNamespace, hitLimit, token, report = (line) => {
108
370
  preloadFs.writeSync(2, line);
109
- }) {
371
+ }, onFirstHit) {
110
372
  let hitCount = 0;
111
373
  let reported = false;
374
+ let firstHitSeen = onFirstHit === undefined;
112
375
  strykerNamespace.hitLimit = hitLimit;
113
376
  Object.defineProperty(strykerNamespace, "hitCount", {
114
377
  configurable: true,
@@ -116,6 +379,12 @@ function installHitLimit(strykerNamespace, hitLimit, token, report = (line) => {
116
379
  get: () => hitCount,
117
380
  set: (value) => {
118
381
  hitCount = value;
382
+ if (!firstHitSeen) {
383
+ firstHitSeen = true;
384
+ try {
385
+ onFirstHit?.();
386
+ } catch {}
387
+ }
119
388
  if (!reported && hitCount > hitLimit) {
120
389
  reported = true;
121
390
  report(formatHitLimitSentinel(token, hitCount));
@@ -170,23 +439,355 @@ function writeCoverageToFile(coverageFile, data) {
170
439
  preloadFs.closeSync(fd);
171
440
  }
172
441
  }
173
- async function readEagerModules(file, deps = {}) {
174
- if (file === null) {
175
- return [];
442
+ var DRY_RUN_PLAN_ENV = "__STRYKER_DRY_RUN_PLAN__";
443
+ var PLAN_FIELDS = new Set(["mode", "eager", "candidates", "recordFile", "nonce"]);
444
+ function isPathList(value) {
445
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string" && entry !== "");
446
+ }
447
+ function isNullOrText(value) {
448
+ return value === null || typeof value === "string" && value !== "";
449
+ }
450
+ function planFieldProblem(plan) {
451
+ const unexpected = Object.keys(plan).find((key) => !PLAN_FIELDS.has(key));
452
+ if (unexpected !== undefined) {
453
+ return `unexpected field ${JSON.stringify(unexpected)}`;
454
+ }
455
+ if (plan.mode !== "publish" && plan.mode !== "discover") {
456
+ return 'mode is neither "publish" nor "discover"';
457
+ }
458
+ if (!isPathList(plan.eager)) {
459
+ return "eager is not an array of paths";
460
+ }
461
+ if (plan.candidates !== null && !isPathList(plan.candidates)) {
462
+ return "candidates is neither null nor an array of paths";
463
+ }
464
+ if (!isNullOrText(plan.recordFile)) {
465
+ return "recordFile is neither null nor a path";
466
+ }
467
+ if (!isNullOrText(plan.nonce)) {
468
+ return "nonce is neither null nor a non-empty string";
469
+ }
470
+ return;
471
+ }
472
+ function planCombinationProblem(plan) {
473
+ if (plan.mode === "discover") {
474
+ if (plan.eager.length > 0) {
475
+ return "a discover plan imports nothing first, but eager is not empty";
476
+ }
477
+ if (plan.candidates === null || plan.recordFile === null || plan.nonce === null) {
478
+ return "a discover plan needs candidates, a recordFile and a nonce";
479
+ }
480
+ }
481
+ if (plan.recordFile === null !== (plan.nonce === null)) {
482
+ return "a plan carries a nonce exactly when it has a recordFile";
483
+ }
484
+ if (plan.candidates !== null && plan.recordFile === null) {
485
+ return "candidates are watched, but there is no recordFile to report on";
176
486
  }
177
- const readJson = deps.readJson ?? ((listFile) => globalThis.Bun.file(listFile).json());
178
- let problem;
487
+ return;
488
+ }
489
+ function planProblem(value) {
490
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
491
+ return "not a JSON object";
492
+ }
493
+ return planFieldProblem(value) ?? planCombinationProblem(value);
494
+ }
495
+ function readDryRunPlan(file, read = (planFile) => preloadFs.readFileSync(planFile, "utf8")) {
496
+ let text;
497
+ try {
498
+ text = read(file);
499
+ } catch (error) {
500
+ throw new Error(describeError(error), { cause: error });
501
+ }
502
+ let value;
179
503
  try {
180
- const list = await readJson(file);
181
- if (Array.isArray(list) && list.every((entry) => typeof entry === "string")) {
182
- return list;
504
+ value = JSON.parse(text);
505
+ } catch (error) {
506
+ throw new Error("not valid JSON", { cause: error });
507
+ }
508
+ const problem = planProblem(value);
509
+ if (problem !== undefined) {
510
+ throw new Error(problem);
511
+ }
512
+ return value;
513
+ }
514
+ function formatDryRunPlanMessage(file, problem) {
515
+ return `[Stryker] Cannot read the dry-run plan ${file} (${problem}); stopping instead of running the tests with nothing imported first.`;
516
+ }
517
+ function moduleCache() {
518
+ return createRequire(import.meta.url).cache;
519
+ }
520
+ function startLoadSensors(candidates, namespace, currentTest) {
521
+ const bun = globalThis.Bun;
522
+ return installLoadSensors({
523
+ global: globalThis,
524
+ namespace,
525
+ candidates,
526
+ cache: moduleCache(),
527
+ realpath: (file) => preloadFs.realpathSync(file),
528
+ fileURLToPath: (url) => bun.fileURLToPath(url),
529
+ readStack: () => captureStack(PreloadError),
530
+ now: () => performance.now(),
531
+ currentTest
532
+ });
533
+ }
534
+ function describeImportError(error) {
535
+ try {
536
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
537
+ } catch {
538
+ return "an error that cannot be described";
539
+ }
540
+ }
541
+ function reachedMutantIds(mutantCoverage) {
542
+ const reached = new Set;
543
+ for (const counts of [mutantCoverage?.static ?? {}, ...Object.values(mutantCoverage?.perTest ?? {})]) {
544
+ for (const [id, count] of Object.entries(counts)) {
545
+ if (count > 0) {
546
+ reached.add(id);
547
+ }
548
+ }
549
+ }
550
+ return [...reached];
551
+ }
552
+ function buildDryRunRecord(plan, parts) {
553
+ const observation = {
554
+ nonce: plan.nonce ?? "",
555
+ complete: true,
556
+ observed: parts.sensors?.observed ?? [],
557
+ problems: parts.sensors?.problems ?? [],
558
+ eagerFailures: [...parts.eagerFailures],
559
+ sensorMs: parts.sensors?.sensorMs ?? 0
560
+ };
561
+ if (plan.mode === "publish") {
562
+ return observation;
563
+ }
564
+ return { ...observation, startedTests: parts.startedTests, reached: reachedMutantIds(parts.coverage) };
565
+ }
566
+ function distinctBy(entries, key) {
567
+ const seen = new Set;
568
+ return entries.filter((entry) => {
569
+ const k = key(entry);
570
+ if (seen.has(k)) {
571
+ return false;
572
+ }
573
+ seen.add(k);
574
+ return true;
575
+ });
576
+ }
577
+ function latestSightings(observations) {
578
+ const kept = new Map;
579
+ for (const sighting of observations) {
580
+ const known = kept.get(sighting.file);
581
+ if (known === undefined || known.time === "by-eager-end" && sighting.time === "later") {
582
+ kept.set(sighting.file, sighting);
583
+ }
584
+ }
585
+ return observations.filter((sighting) => kept.get(sighting.file) === sighting);
586
+ }
587
+ var hasOwnField = Object.hasOwn;
588
+ var ownField = (value, field) => hasOwnField(value, field) ? value[field] : undefined;
589
+ var isProblem = (value) => hasOwnField(value, "problem");
590
+ var isDiscoveryRecord = (record) => hasOwnField(record, "startedTests");
591
+ var isEntryObject = (entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry);
592
+ var isStringEntry = (entry) => typeof entry === "string";
593
+ var isListOf = (value, isEntry) => Array.isArray(value) && value.every((entry) => isEntry(entry));
594
+ var EARLIER_RECORD_PROBLEM = "an earlier record of this launch could not be read";
595
+ function mergeDryRunRecords(previous, next) {
596
+ if (previous === undefined) {
597
+ return next;
598
+ }
599
+ const earlier = isProblem(previous) ? previous : earlierRecordOf(previous.value, next.nonce, isDiscoveryRecord(next));
600
+ if (isProblem(earlier)) {
601
+ return { ...next, problems: [...next.problems, `${EARLIER_RECORD_PROBLEM}: ${earlier.problem}`] };
602
+ }
603
+ const merged = {
604
+ nonce: next.nonce,
605
+ complete: true,
606
+ observed: latestSightings([...earlier.observed, ...next.observed]),
607
+ problems: [...new Set([...earlier.problems, ...next.problems])],
608
+ eagerFailures: distinctBy([...earlier.eagerFailures, ...next.eagerFailures], (failure) => `${failure.file}\x00${failure.error}`),
609
+ sensorMs: earlier.sensorMs + next.sensorMs
610
+ };
611
+ if (!isDiscoveryRecord(next)) {
612
+ return merged;
613
+ }
614
+ return { ...merged, startedTests: earlier.startedTests + next.startedTests, reached: [...new Set([...earlier.reached, ...next.reached])] };
615
+ }
616
+ function earlierRecordOf(previous, nonce, discovery) {
617
+ if (!isEntryObject(previous)) {
618
+ return { problem: "it is not a JSON object" };
619
+ }
620
+ const field = (name) => ownField(previous, name);
621
+ if (field("nonce") !== nonce) {
622
+ return { problem: "it carries another launch's nonce" };
623
+ }
624
+ if (field("complete") !== true) {
625
+ return { problem: "it is not marked complete" };
626
+ }
627
+ const malformed = malformedEarlierField(field, discovery);
628
+ if (malformed !== undefined) {
629
+ return { problem: `its ${malformed} field is malformed` };
630
+ }
631
+ return {
632
+ observed: field("observed"),
633
+ problems: field("problems"),
634
+ eagerFailures: field("eagerFailures"),
635
+ sensorMs: field("sensorMs"),
636
+ startedTests: discovery ? field("startedTests") : 0,
637
+ reached: discovery ? field("reached") : []
638
+ };
639
+ }
640
+ function isSighting(entry) {
641
+ if (!isEntryObject(entry)) {
642
+ return false;
643
+ }
644
+ const time = ownField(entry, "time");
645
+ const sensor = ownField(entry, "sensor");
646
+ const testKey = ownField(entry, "testKey");
647
+ return typeof ownField(entry, "file") === "string" && (time === "by-eager-end" || time === "later") && (sensor === "header" || sensor === "cache") && (testKey === null || typeof testKey === "string");
648
+ }
649
+ function isImportFailure(entry) {
650
+ return isEntryObject(entry) && typeof ownField(entry, "file") === "string" && typeof ownField(entry, "error") === "string";
651
+ }
652
+ function isDuration(value) {
653
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
654
+ }
655
+ function isCount(value) {
656
+ return Number.isSafeInteger(value) && value >= 0;
657
+ }
658
+ function malformedEarlierField(field, discovery) {
659
+ if (!isListOf(field("observed"), isSighting)) {
660
+ return "observed";
661
+ }
662
+ if (!isListOf(field("problems"), isStringEntry)) {
663
+ return "problems";
664
+ }
665
+ if (!isListOf(field("eagerFailures"), isImportFailure)) {
666
+ return "eagerFailures";
667
+ }
668
+ if (!isDuration(field("sensorMs"))) {
669
+ return "sensorMs";
670
+ }
671
+ if (discovery && !isCount(field("startedTests"))) {
672
+ return "startedTests";
673
+ }
674
+ if (discovery && !isListOf(field("reached"), isStringEntry)) {
675
+ return "reached";
676
+ }
677
+ return;
678
+ }
679
+ function readEarlierRecord(file) {
680
+ let text;
681
+ try {
682
+ text = preloadFs.readFileSync(file, "utf8");
683
+ } catch (error) {
684
+ return error?.code === "ENOENT" ? undefined : { problem: describeImportError(error) };
685
+ }
686
+ try {
687
+ return { value: JSON.parse(text) };
688
+ } catch (error) {
689
+ return { problem: `it is not JSON (${describeImportError(error)})` };
690
+ }
691
+ }
692
+ var PRIVATE_CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
693
+ function writePrivateFileAtomically(file, data) {
694
+ const temporary = `${file}.tmp`;
695
+ try {
696
+ preloadFs.unlinkSync(temporary);
697
+ } catch {}
698
+ const fd = preloadFs.openSync(temporary, PRIVATE_CREATE_FLAGS, 384);
699
+ try {
700
+ try {
701
+ preloadFs.appendFileSync(fd, data, "utf8");
702
+ } finally {
703
+ preloadFs.closeSync(fd);
183
704
  }
184
- problem = "not a JSON array of module paths";
705
+ preloadFs.renameSync(temporary, file);
706
+ } catch (error) {
707
+ try {
708
+ preloadFs.unlinkSync(temporary);
709
+ } catch {}
710
+ throw error;
711
+ }
712
+ }
713
+ var WATCH_LIST_ENV = "__STRYKER_WATCH_LIST__";
714
+ var WITNESS_SENTINEL = "__STRYKER_UNIMPORTED_LOADED__";
715
+ var WATCH_LIST_PROBLEM_SENTINEL = "__STRYKER_WATCH_LIST_UNREADABLE__";
716
+ function formatWitnessLine(token, loaded) {
717
+ return `
718
+ ${WITNESS_SENTINEL} ${token} ${JSON.stringify(loaded)}
719
+ `;
720
+ }
721
+ function formatWatchListProblem(token, problem) {
722
+ return `
723
+ ${WATCH_LIST_PROBLEM_SENTINEL} ${token} ${JSON.stringify(problem)}
724
+ `;
725
+ }
726
+ function isWatchedFile(value) {
727
+ if (typeof value !== "object" || value === null) {
728
+ return false;
729
+ }
730
+ const { file, realpath } = value;
731
+ return typeof file === "string" && file !== "" && typeof realpath === "string" && realpath !== "" && Object.keys(value).length === 2;
732
+ }
733
+ function readWatchList(file, read = (listFile) => preloadFs.readFileSync(listFile, "utf8")) {
734
+ let text;
735
+ try {
736
+ text = read(file);
737
+ } catch (error) {
738
+ throw new Error(describeError(error), { cause: error });
739
+ }
740
+ let value;
741
+ try {
742
+ value = JSON.parse(text);
185
743
  } catch (error) {
186
- problem = describeError(error);
744
+ throw new Error("not valid JSON", { cause: error });
745
+ }
746
+ if (!Array.isArray(value) || !value.every((entry) => isWatchedFile(entry))) {
747
+ throw new Error("not a JSON array of { file, realpath } entries");
748
+ }
749
+ return value;
750
+ }
751
+ function instrumentedCodeHasRun(strykerNamespace) {
752
+ if (strykerNamespace.activeMutant !== undefined || typeof strykerNamespace.hitCount === "number" && strykerNamespace.hitCount > 0) {
753
+ return true;
187
754
  }
188
- (deps.warn ?? console.warn)(`[Stryker] Could not read the eager module list ${file} (${problem}); importing no modules ahead of the tests, so module-level mutants may be attributed to a test instead of to static coverage`);
189
- return [];
755
+ const coverage = strykerNamespace.mutantCoverage;
756
+ return Object.keys(coverage?.static ?? {}).length > 0 || Object.keys(coverage?.perTest ?? {}).length > 0;
757
+ }
758
+ function setUpWitness(deps) {
759
+ const write = deps.write ?? ((line) => {
760
+ preloadFs.writeSync(2, line);
761
+ });
762
+ if (deps.disarmed) {
763
+ return;
764
+ }
765
+ let watched;
766
+ try {
767
+ watched = readWatchList(deps.file, deps.read);
768
+ } catch (error) {
769
+ try {
770
+ write(formatWatchListProblem(deps.token, `${deps.file}: ${error.message}`));
771
+ } catch {}
772
+ return;
773
+ }
774
+ if (watched.length === 0) {
775
+ return;
776
+ }
777
+ const { cache, token } = deps;
778
+ return () => {
779
+ const loaded = [];
780
+ for (const { file, realpath } of watched) {
781
+ if (file in cache || realpath !== file && realpath in cache) {
782
+ loaded.push(file);
783
+ }
784
+ }
785
+ if (loaded.length > 0) {
786
+ try {
787
+ write(formatWitnessLine(token, loaded));
788
+ } catch {}
789
+ }
790
+ };
190
791
  }
191
792
  var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
192
793
  function describeError(error) {
@@ -311,15 +912,29 @@ guardAgainstOrphaning({
311
912
  process.exit(1);
312
913
  }
313
914
  });
314
- Object.defineProperty(describe, "concurrent", { value: describe, writable: true, configurable: true });
915
+ Object.defineProperty(describe2, "concurrent", { value: describe2, writable: true, configurable: true });
315
916
  Object.defineProperty(test, "concurrent", { value: test, writable: true, configurable: true });
316
917
  Object.defineProperty(it, "concurrent", { value: it, writable: true, configurable: true });
317
- var EAGER_MODULES_FILE = __EAGER_MODULES_FILE__;
318
918
  var config = getPreloadConfig();
319
919
  var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken } = config;
320
920
  delete process.env[HIT_LIMIT_TOKEN_ENV];
321
921
  delete process.env[SYNC_TOKEN_ENV];
322
- var shouldCollectCoverage2 = shouldCollectCoverage(config);
922
+ var planFile = process.env[DRY_RUN_PLAN_ENV];
923
+ delete process.env[DRY_RUN_PLAN_ENV];
924
+ var watchListFile = process.env[WATCH_LIST_ENV];
925
+ delete process.env[WATCH_LIST_ENV];
926
+ var plan = null;
927
+ if (planFile !== undefined && !activeMutant) {
928
+ try {
929
+ plan = readDryRunPlan(planFile);
930
+ } catch (error) {
931
+ preloadFs.writeSync(2, `${formatDryRunPlanMessage(planFile, error instanceof Error ? error.message : String(error))}
932
+ `);
933
+ process.exit(1);
934
+ }
935
+ }
936
+ var discovering = plan?.mode === "discover";
937
+ var shouldCollectCoverage2 = shouldCollectCoverage(config) || discovering;
323
938
  var ws = null;
324
939
  var DRAIN_ACK_TIMEOUT_MS = 40000;
325
940
  var perFileCounters = new Map;
@@ -342,7 +957,7 @@ var lastFilePrefix;
342
957
  var lateHits = [];
343
958
  var lastBunMain;
344
959
  var currentFilePrefix = "";
345
- if (syncPort) {
960
+ if (syncPort && !discovering) {
346
961
  ws = await awaitRunnerReady({ syncPort, syncToken: syncToken ?? "", keepOpen: shouldCollectCoverage2 });
347
962
  if (timings) {
348
963
  timings["at.preloadReady"] = nowEpoch();
@@ -353,25 +968,53 @@ var strykerGlobal = initializeStrykerNamespace(g);
353
968
  var mutantCoverage = strykerGlobal.mutantCoverage;
354
969
  var gapTracker = new StaticGapTracker(mutantCoverage);
355
970
  if (activeMutant) {
971
+ const instrumentedBefore = watchListFile !== undefined && instrumentedCodeHasRun(strykerGlobal);
356
972
  setActiveMutant(strykerGlobal, activeMutant);
357
- if (hitLimit !== undefined && hitLimitToken) {
358
- installHitLimit(strykerGlobal, hitLimit, hitLimitToken);
973
+ const onFirstHit = watchListFile !== undefined && hitLimitToken ? setUpWitness({ file: watchListFile, token: hitLimitToken, disarmed: instrumentedBefore, cache: moduleCache() }) : undefined;
974
+ if (hitLimitToken && (hitLimit !== undefined || onFirstHit !== undefined)) {
975
+ installHitLimit(strykerGlobal, hitLimit ?? Number.POSITIVE_INFINITY, hitLimitToken, undefined, onFirstHit);
359
976
  }
360
977
  }
361
- if (shouldCollectCoverage2) {
362
- const EAGER_MODULES = await readEagerModules(EAGER_MODULES_FILE);
978
+ var sensors = null;
979
+ var eagerFailures = [];
980
+ if (shouldCollectCoverage2 && plan !== null) {
981
+ sensors = plan.candidates === null ? null : startLoadSensors(plan.candidates, strykerGlobal, () => strykerGlobal.currentTestId ?? null);
982
+ const EAGER_MODULES = plan.eager;
363
983
  for (const modPath of EAGER_MODULES) {
364
984
  try {
365
985
  await import(modPath);
366
986
  } catch (err) {
987
+ eagerFailures.push({ file: modPath, error: describeImportError(err) });
367
988
  console.warn(`[Stryker] Eager import failed for ${modPath}:`, err);
368
989
  }
369
990
  }
991
+ sensors?.markEagerEnd();
370
992
  if (timings) {
371
993
  timings["at.eagerImported"] = nowEpoch();
372
994
  timings.eagerModules = EAGER_MODULES.length;
373
995
  }
996
+ } else if (timings) {
997
+ timings["at.eagerImported"] = nowEpoch();
998
+ timings.eagerModules = 0;
374
999
  }
1000
+ var startedTests = 0;
1001
+ var writeDryRunRecord = () => {
1002
+ if (plan === null || plan.recordFile === null) {
1003
+ return;
1004
+ }
1005
+ const recordFile = plan.recordFile;
1006
+ try {
1007
+ const report = sensors === null ? null : sensors.finish();
1008
+ if (timings && report !== null) {
1009
+ timings["ms.sensors"] = report.sensorMs;
1010
+ }
1011
+ const record = buildDryRunRecord(plan, { sensors: report, eagerFailures, startedTests, coverage: strykerGlobal.mutantCoverage });
1012
+ const merged = mergeDryRunRecords(readEarlierRecord(recordFile), record);
1013
+ writePrivateFileAtomically(recordFile, JSON.stringify(merged));
1014
+ } catch (error) {
1015
+ console.error(`[Stryker Coverage] Failed to write the dry-run record to ${recordFile}: ${error instanceof Error ? error.message : String(error)}`);
1016
+ }
1017
+ };
375
1018
  var writeCoverageData = () => {
376
1019
  if (!shouldCollectCoverage2 || !coverageFile) {
377
1020
  return;
@@ -393,6 +1036,7 @@ var writeCoverageData = () => {
393
1036
  if (shouldCollectCoverage2) {
394
1037
  beforeEach(() => {
395
1038
  const hookStart = timings ? performance.now() : 0;
1039
+ startedTests++;
396
1040
  const bunMain = String(globalThis.Bun?.main ?? "");
397
1041
  if (bunMain !== lastBunMain) {
398
1042
  lastBunMain = bunMain;
@@ -442,6 +1086,7 @@ if (shouldCollectCoverage2) {
442
1086
  }
443
1087
  writeCoverageData();
444
1088
  lateHits.length = 0;
1089
+ writeDryRunRecord();
445
1090
  if (ws && ws.readyState === WebSocket.OPEN) {
446
1091
  try {
447
1092
  await new Promise((resolve) => {