@hughescr/stryker-bun-runner 1.6.0 → 1.7.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.
@@ -1,10 +1,273 @@
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 };
270
+ var COVERAGE_KEYS_ONLY_ENV = "__STRYKER_COVERAGE_KEYS_ONLY__";
8
271
  var HIT_LIMIT_TOKEN_ENV = "__STRYKER_HIT_LIMIT_TOKEN__";
9
272
  var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
10
273
  function getPreloadConfig() {
@@ -14,7 +277,8 @@ function getPreloadConfig() {
14
277
  coverageFile: process.env.__STRYKER_COVERAGE_FILE__,
15
278
  activeMutant: process.env.__STRYKER_ACTIVE_MUTANT__,
16
279
  hitLimit: parseHitLimit(process.env.__STRYKER_HIT_LIMIT__),
17
- hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV]
280
+ hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV],
281
+ keysOnly: process.env[COVERAGE_KEYS_ONLY_ENV] === "1"
18
282
  };
19
283
  }
20
284
  function parseHitLimit(raw) {
@@ -106,9 +370,10 @@ ${HIT_LIMIT_SENTINEL} ${token} ${hitCount}
106
370
  }
107
371
  function installHitLimit(strykerNamespace, hitLimit, token, report = (line) => {
108
372
  preloadFs.writeSync(2, line);
109
- }) {
373
+ }, onFirstHit) {
110
374
  let hitCount = 0;
111
375
  let reported = false;
376
+ let firstHitSeen = onFirstHit === undefined;
112
377
  strykerNamespace.hitLimit = hitLimit;
113
378
  Object.defineProperty(strykerNamespace, "hitCount", {
114
379
  configurable: true,
@@ -116,6 +381,12 @@ function installHitLimit(strykerNamespace, hitLimit, token, report = (line) => {
116
381
  get: () => hitCount,
117
382
  set: (value) => {
118
383
  hitCount = value;
384
+ if (!firstHitSeen) {
385
+ firstHitSeen = true;
386
+ try {
387
+ onFirstHit?.();
388
+ } catch {}
389
+ }
119
390
  if (!reported && hitCount > hitLimit) {
120
391
  reported = true;
121
392
  report(formatHitLimitSentinel(token, hitCount));
@@ -159,6 +430,13 @@ function serializeCoverageData(mutantCoverage, lateHits = [], gapTracker) {
159
430
  };
160
431
  return JSON.stringify(data);
161
432
  }
433
+ function testKeysOnly(mutantCoverage) {
434
+ const perTest = {};
435
+ for (const key of Object.keys(mutantCoverage?.perTest ?? {})) {
436
+ perTest[key] = {};
437
+ }
438
+ return { perTest, static: {} };
439
+ }
162
440
  var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
163
441
  function writeCoverageToFile(coverageFile, data) {
164
442
  const line = typeof data === "string" ? data : JSON.stringify(data);
@@ -170,23 +448,355 @@ function writeCoverageToFile(coverageFile, data) {
170
448
  preloadFs.closeSync(fd);
171
449
  }
172
450
  }
173
- async function readEagerModules(file, deps = {}) {
174
- if (file === null) {
175
- return [];
451
+ var DRY_RUN_PLAN_ENV = "__STRYKER_DRY_RUN_PLAN__";
452
+ var PLAN_FIELDS = new Set(["mode", "eager", "candidates", "recordFile", "nonce"]);
453
+ function isPathList(value) {
454
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string" && entry !== "");
455
+ }
456
+ function isNullOrText(value) {
457
+ return value === null || typeof value === "string" && value !== "";
458
+ }
459
+ function planFieldProblem(plan) {
460
+ const unexpected = Object.keys(plan).find((key) => !PLAN_FIELDS.has(key));
461
+ if (unexpected !== undefined) {
462
+ return `unexpected field ${JSON.stringify(unexpected)}`;
463
+ }
464
+ if (plan.mode !== "publish" && plan.mode !== "discover") {
465
+ return 'mode is neither "publish" nor "discover"';
466
+ }
467
+ if (!isPathList(plan.eager)) {
468
+ return "eager is not an array of paths";
469
+ }
470
+ if (plan.candidates !== null && !isPathList(plan.candidates)) {
471
+ return "candidates is neither null nor an array of paths";
472
+ }
473
+ if (!isNullOrText(plan.recordFile)) {
474
+ return "recordFile is neither null nor a path";
475
+ }
476
+ if (!isNullOrText(plan.nonce)) {
477
+ return "nonce is neither null nor a non-empty string";
478
+ }
479
+ return;
480
+ }
481
+ function planCombinationProblem(plan) {
482
+ if (plan.mode === "discover") {
483
+ if (plan.eager.length > 0) {
484
+ return "a discover plan imports nothing first, but eager is not empty";
485
+ }
486
+ if (plan.candidates === null || plan.recordFile === null || plan.nonce === null) {
487
+ return "a discover plan needs candidates, a recordFile and a nonce";
488
+ }
489
+ }
490
+ if (plan.recordFile === null !== (plan.nonce === null)) {
491
+ return "a plan carries a nonce exactly when it has a recordFile";
492
+ }
493
+ if (plan.candidates !== null && plan.recordFile === null) {
494
+ return "candidates are watched, but there is no recordFile to report on";
495
+ }
496
+ return;
497
+ }
498
+ function planProblem(value) {
499
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
500
+ return "not a JSON object";
501
+ }
502
+ return planFieldProblem(value) ?? planCombinationProblem(value);
503
+ }
504
+ function readDryRunPlan(file, read = (planFile) => preloadFs.readFileSync(planFile, "utf8")) {
505
+ let text;
506
+ try {
507
+ text = read(file);
508
+ } catch (error) {
509
+ throw new Error(describeError(error), { cause: error });
510
+ }
511
+ let value;
512
+ try {
513
+ value = JSON.parse(text);
514
+ } catch (error) {
515
+ throw new Error("not valid JSON", { cause: error });
516
+ }
517
+ const problem = planProblem(value);
518
+ if (problem !== undefined) {
519
+ throw new Error(problem);
520
+ }
521
+ return value;
522
+ }
523
+ function formatDryRunPlanMessage(file, problem) {
524
+ return `[Stryker] Cannot read the dry-run plan ${file} (${problem}); stopping instead of running the tests with nothing imported first.`;
525
+ }
526
+ function moduleCache() {
527
+ return createRequire(import.meta.url).cache;
528
+ }
529
+ function startLoadSensors(candidates, namespace, currentTest) {
530
+ const bun = globalThis.Bun;
531
+ return installLoadSensors({
532
+ global: globalThis,
533
+ namespace,
534
+ candidates,
535
+ cache: moduleCache(),
536
+ realpath: (file) => preloadFs.realpathSync(file),
537
+ fileURLToPath: (url) => bun.fileURLToPath(url),
538
+ readStack: () => captureStack(PreloadError),
539
+ now: () => performance.now(),
540
+ currentTest
541
+ });
542
+ }
543
+ function describeImportError(error) {
544
+ try {
545
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
546
+ } catch {
547
+ return "an error that cannot be described";
548
+ }
549
+ }
550
+ function reachedMutantIds(mutantCoverage) {
551
+ const reached = new Set;
552
+ for (const counts of [mutantCoverage?.static ?? {}, ...Object.values(mutantCoverage?.perTest ?? {})]) {
553
+ for (const [id, count] of Object.entries(counts)) {
554
+ if (count > 0) {
555
+ reached.add(id);
556
+ }
557
+ }
558
+ }
559
+ return [...reached];
560
+ }
561
+ function buildDryRunRecord(plan, parts) {
562
+ const observation = {
563
+ nonce: plan.nonce ?? "",
564
+ complete: true,
565
+ observed: parts.sensors?.observed ?? [],
566
+ problems: parts.sensors?.problems ?? [],
567
+ eagerFailures: [...parts.eagerFailures],
568
+ sensorMs: parts.sensors?.sensorMs ?? 0
569
+ };
570
+ if (plan.mode === "publish") {
571
+ return observation;
572
+ }
573
+ return { ...observation, startedTests: parts.startedTests, reached: reachedMutantIds(parts.coverage) };
574
+ }
575
+ function distinctBy(entries, key) {
576
+ const seen = new Set;
577
+ return entries.filter((entry) => {
578
+ const k = key(entry);
579
+ if (seen.has(k)) {
580
+ return false;
581
+ }
582
+ seen.add(k);
583
+ return true;
584
+ });
585
+ }
586
+ function latestSightings(observations) {
587
+ const kept = new Map;
588
+ for (const sighting of observations) {
589
+ const known = kept.get(sighting.file);
590
+ if (known === undefined || known.time === "by-eager-end" && sighting.time === "later") {
591
+ kept.set(sighting.file, sighting);
592
+ }
593
+ }
594
+ return observations.filter((sighting) => kept.get(sighting.file) === sighting);
595
+ }
596
+ var hasOwnField = Object.hasOwn;
597
+ var ownField = (value, field) => hasOwnField(value, field) ? value[field] : undefined;
598
+ var isProblem = (value) => hasOwnField(value, "problem");
599
+ var isDiscoveryRecord = (record) => hasOwnField(record, "startedTests");
600
+ var isEntryObject = (entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry);
601
+ var isStringEntry = (entry) => typeof entry === "string";
602
+ var isListOf = (value, isEntry) => Array.isArray(value) && value.every((entry) => isEntry(entry));
603
+ var EARLIER_RECORD_PROBLEM = "an earlier record of this launch could not be read";
604
+ function mergeDryRunRecords(previous, next) {
605
+ if (previous === undefined) {
606
+ return next;
607
+ }
608
+ const earlier = isProblem(previous) ? previous : earlierRecordOf(previous.value, next.nonce, isDiscoveryRecord(next));
609
+ if (isProblem(earlier)) {
610
+ return { ...next, problems: [...next.problems, `${EARLIER_RECORD_PROBLEM}: ${earlier.problem}`] };
611
+ }
612
+ const merged = {
613
+ nonce: next.nonce,
614
+ complete: true,
615
+ observed: latestSightings([...earlier.observed, ...next.observed]),
616
+ problems: [...new Set([...earlier.problems, ...next.problems])],
617
+ eagerFailures: distinctBy([...earlier.eagerFailures, ...next.eagerFailures], (failure) => `${failure.file}\x00${failure.error}`),
618
+ sensorMs: earlier.sensorMs + next.sensorMs
619
+ };
620
+ if (!isDiscoveryRecord(next)) {
621
+ return merged;
622
+ }
623
+ return { ...merged, startedTests: earlier.startedTests + next.startedTests, reached: [...new Set([...earlier.reached, ...next.reached])] };
624
+ }
625
+ function earlierRecordOf(previous, nonce, discovery) {
626
+ if (!isEntryObject(previous)) {
627
+ return { problem: "it is not a JSON object" };
628
+ }
629
+ const field = (name) => ownField(previous, name);
630
+ if (field("nonce") !== nonce) {
631
+ return { problem: "it carries another launch's nonce" };
632
+ }
633
+ if (field("complete") !== true) {
634
+ return { problem: "it is not marked complete" };
635
+ }
636
+ const malformed = malformedEarlierField(field, discovery);
637
+ if (malformed !== undefined) {
638
+ return { problem: `its ${malformed} field is malformed` };
639
+ }
640
+ return {
641
+ observed: field("observed"),
642
+ problems: field("problems"),
643
+ eagerFailures: field("eagerFailures"),
644
+ sensorMs: field("sensorMs"),
645
+ startedTests: discovery ? field("startedTests") : 0,
646
+ reached: discovery ? field("reached") : []
647
+ };
648
+ }
649
+ function isSighting(entry) {
650
+ if (!isEntryObject(entry)) {
651
+ return false;
652
+ }
653
+ const time = ownField(entry, "time");
654
+ const sensor = ownField(entry, "sensor");
655
+ const testKey = ownField(entry, "testKey");
656
+ return typeof ownField(entry, "file") === "string" && (time === "by-eager-end" || time === "later") && (sensor === "header" || sensor === "cache") && (testKey === null || typeof testKey === "string");
657
+ }
658
+ function isImportFailure(entry) {
659
+ return isEntryObject(entry) && typeof ownField(entry, "file") === "string" && typeof ownField(entry, "error") === "string";
660
+ }
661
+ function isDuration(value) {
662
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
663
+ }
664
+ function isCount(value) {
665
+ return Number.isSafeInteger(value) && value >= 0;
666
+ }
667
+ function malformedEarlierField(field, discovery) {
668
+ if (!isListOf(field("observed"), isSighting)) {
669
+ return "observed";
670
+ }
671
+ if (!isListOf(field("problems"), isStringEntry)) {
672
+ return "problems";
673
+ }
674
+ if (!isListOf(field("eagerFailures"), isImportFailure)) {
675
+ return "eagerFailures";
176
676
  }
177
- const readJson = deps.readJson ?? ((listFile) => globalThis.Bun.file(listFile).json());
178
- let problem;
677
+ if (!isDuration(field("sensorMs"))) {
678
+ return "sensorMs";
679
+ }
680
+ if (discovery && !isCount(field("startedTests"))) {
681
+ return "startedTests";
682
+ }
683
+ if (discovery && !isListOf(field("reached"), isStringEntry)) {
684
+ return "reached";
685
+ }
686
+ return;
687
+ }
688
+ function readEarlierRecord(file) {
689
+ let text;
179
690
  try {
180
- const list = await readJson(file);
181
- if (Array.isArray(list) && list.every((entry) => typeof entry === "string")) {
182
- return list;
691
+ text = preloadFs.readFileSync(file, "utf8");
692
+ } catch (error) {
693
+ return error?.code === "ENOENT" ? undefined : { problem: describeImportError(error) };
694
+ }
695
+ try {
696
+ return { value: JSON.parse(text) };
697
+ } catch (error) {
698
+ return { problem: `it is not JSON (${describeImportError(error)})` };
699
+ }
700
+ }
701
+ var PRIVATE_CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
702
+ function writePrivateFileAtomically(file, data) {
703
+ const temporary = `${file}.tmp`;
704
+ try {
705
+ preloadFs.unlinkSync(temporary);
706
+ } catch {}
707
+ const fd = preloadFs.openSync(temporary, PRIVATE_CREATE_FLAGS, 384);
708
+ try {
709
+ try {
710
+ preloadFs.appendFileSync(fd, data, "utf8");
711
+ } finally {
712
+ preloadFs.closeSync(fd);
183
713
  }
184
- problem = "not a JSON array of module paths";
714
+ preloadFs.renameSync(temporary, file);
185
715
  } catch (error) {
186
- problem = describeError(error);
716
+ try {
717
+ preloadFs.unlinkSync(temporary);
718
+ } catch {}
719
+ throw error;
187
720
  }
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 [];
721
+ }
722
+ var WATCH_LIST_ENV = "__STRYKER_WATCH_LIST__";
723
+ var WITNESS_SENTINEL = "__STRYKER_UNIMPORTED_LOADED__";
724
+ var WATCH_LIST_PROBLEM_SENTINEL = "__STRYKER_WATCH_LIST_UNREADABLE__";
725
+ function formatWitnessLine(token, loaded) {
726
+ return `
727
+ ${WITNESS_SENTINEL} ${token} ${JSON.stringify(loaded)}
728
+ `;
729
+ }
730
+ function formatWatchListProblem(token, problem) {
731
+ return `
732
+ ${WATCH_LIST_PROBLEM_SENTINEL} ${token} ${JSON.stringify(problem)}
733
+ `;
734
+ }
735
+ function isWatchedFile(value) {
736
+ if (typeof value !== "object" || value === null) {
737
+ return false;
738
+ }
739
+ const { file, realpath } = value;
740
+ return typeof file === "string" && file !== "" && typeof realpath === "string" && realpath !== "" && Object.keys(value).length === 2;
741
+ }
742
+ function readWatchList(file, read = (listFile) => preloadFs.readFileSync(listFile, "utf8")) {
743
+ let text;
744
+ try {
745
+ text = read(file);
746
+ } catch (error) {
747
+ throw new Error(describeError(error), { cause: error });
748
+ }
749
+ let value;
750
+ try {
751
+ value = JSON.parse(text);
752
+ } catch (error) {
753
+ throw new Error("not valid JSON", { cause: error });
754
+ }
755
+ if (!Array.isArray(value) || !value.every((entry) => isWatchedFile(entry))) {
756
+ throw new Error("not a JSON array of { file, realpath } entries");
757
+ }
758
+ return value;
759
+ }
760
+ function instrumentedCodeHasRun(strykerNamespace) {
761
+ if (strykerNamespace.activeMutant !== undefined || typeof strykerNamespace.hitCount === "number" && strykerNamespace.hitCount > 0) {
762
+ return true;
763
+ }
764
+ const coverage = strykerNamespace.mutantCoverage;
765
+ return Object.keys(coverage?.static ?? {}).length > 0 || Object.keys(coverage?.perTest ?? {}).length > 0;
766
+ }
767
+ function setUpWitness(deps) {
768
+ const write = deps.write ?? ((line) => {
769
+ preloadFs.writeSync(2, line);
770
+ });
771
+ if (deps.disarmed) {
772
+ return;
773
+ }
774
+ let watched;
775
+ try {
776
+ watched = readWatchList(deps.file, deps.read);
777
+ } catch (error) {
778
+ try {
779
+ write(formatWatchListProblem(deps.token, `${deps.file}: ${error.message}`));
780
+ } catch {}
781
+ return;
782
+ }
783
+ if (watched.length === 0) {
784
+ return;
785
+ }
786
+ const { cache, token } = deps;
787
+ return () => {
788
+ const loaded = [];
789
+ for (const { file, realpath } of watched) {
790
+ if (file in cache || realpath !== file && realpath in cache) {
791
+ loaded.push(file);
792
+ }
793
+ }
794
+ if (loaded.length > 0) {
795
+ try {
796
+ write(formatWitnessLine(token, loaded));
797
+ } catch {}
798
+ }
799
+ };
190
800
  }
191
801
  var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
192
802
  function describeError(error) {
@@ -311,15 +921,29 @@ guardAgainstOrphaning({
311
921
  process.exit(1);
312
922
  }
313
923
  });
314
- Object.defineProperty(describe, "concurrent", { value: describe, writable: true, configurable: true });
924
+ Object.defineProperty(describe2, "concurrent", { value: describe2, writable: true, configurable: true });
315
925
  Object.defineProperty(test, "concurrent", { value: test, writable: true, configurable: true });
316
926
  Object.defineProperty(it, "concurrent", { value: it, writable: true, configurable: true });
317
- var EAGER_MODULES_FILE = __EAGER_MODULES_FILE__;
318
927
  var config = getPreloadConfig();
319
- var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken } = config;
928
+ var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken, keysOnly } = config;
320
929
  delete process.env[HIT_LIMIT_TOKEN_ENV];
321
930
  delete process.env[SYNC_TOKEN_ENV];
322
- var shouldCollectCoverage2 = shouldCollectCoverage(config);
931
+ var planFile = process.env[DRY_RUN_PLAN_ENV];
932
+ delete process.env[DRY_RUN_PLAN_ENV];
933
+ var watchListFile = process.env[WATCH_LIST_ENV];
934
+ delete process.env[WATCH_LIST_ENV];
935
+ var plan = null;
936
+ if (planFile !== undefined && !activeMutant) {
937
+ try {
938
+ plan = readDryRunPlan(planFile);
939
+ } catch (error) {
940
+ preloadFs.writeSync(2, `${formatDryRunPlanMessage(planFile, error instanceof Error ? error.message : String(error))}
941
+ `);
942
+ process.exit(1);
943
+ }
944
+ }
945
+ var discovering = plan?.mode === "discover";
946
+ var shouldCollectCoverage2 = shouldCollectCoverage(config) || discovering;
323
947
  var ws = null;
324
948
  var DRAIN_ACK_TIMEOUT_MS = 40000;
325
949
  var perFileCounters = new Map;
@@ -342,7 +966,7 @@ var lastFilePrefix;
342
966
  var lateHits = [];
343
967
  var lastBunMain;
344
968
  var currentFilePrefix = "";
345
- if (syncPort) {
969
+ if (syncPort && !discovering) {
346
970
  ws = await awaitRunnerReady({ syncPort, syncToken: syncToken ?? "", keepOpen: shouldCollectCoverage2 });
347
971
  if (timings) {
348
972
  timings["at.preloadReady"] = nowEpoch();
@@ -353,30 +977,59 @@ var strykerGlobal = initializeStrykerNamespace(g);
353
977
  var mutantCoverage = strykerGlobal.mutantCoverage;
354
978
  var gapTracker = new StaticGapTracker(mutantCoverage);
355
979
  if (activeMutant) {
980
+ const instrumentedBefore = watchListFile !== undefined && instrumentedCodeHasRun(strykerGlobal);
356
981
  setActiveMutant(strykerGlobal, activeMutant);
357
- if (hitLimit !== undefined && hitLimitToken) {
358
- installHitLimit(strykerGlobal, hitLimit, hitLimitToken);
982
+ const onFirstHit = watchListFile !== undefined && hitLimitToken ? setUpWitness({ file: watchListFile, token: hitLimitToken, disarmed: instrumentedBefore, cache: moduleCache() }) : undefined;
983
+ if (hitLimitToken && (hitLimit !== undefined || onFirstHit !== undefined)) {
984
+ installHitLimit(strykerGlobal, hitLimit ?? Number.POSITIVE_INFINITY, hitLimitToken, undefined, onFirstHit);
359
985
  }
360
986
  }
361
- if (shouldCollectCoverage2) {
362
- const EAGER_MODULES = await readEagerModules(EAGER_MODULES_FILE);
987
+ var sensors = null;
988
+ var eagerFailures = [];
989
+ if (shouldCollectCoverage2 && plan !== null) {
990
+ sensors = plan.candidates === null ? null : startLoadSensors(plan.candidates, strykerGlobal, () => strykerGlobal.currentTestId ?? null);
991
+ const EAGER_MODULES = plan.eager;
363
992
  for (const modPath of EAGER_MODULES) {
364
993
  try {
365
994
  await import(modPath);
366
995
  } catch (err) {
996
+ eagerFailures.push({ file: modPath, error: describeImportError(err) });
367
997
  console.warn(`[Stryker] Eager import failed for ${modPath}:`, err);
368
998
  }
369
999
  }
1000
+ sensors?.markEagerEnd();
370
1001
  if (timings) {
371
1002
  timings["at.eagerImported"] = nowEpoch();
372
1003
  timings.eagerModules = EAGER_MODULES.length;
373
1004
  }
1005
+ } else if (timings) {
1006
+ timings["at.eagerImported"] = nowEpoch();
1007
+ timings.eagerModules = 0;
374
1008
  }
1009
+ var startedTests = 0;
1010
+ var writeDryRunRecord = () => {
1011
+ if (plan === null || plan.recordFile === null) {
1012
+ return;
1013
+ }
1014
+ const recordFile = plan.recordFile;
1015
+ try {
1016
+ const report = sensors === null ? null : sensors.finish();
1017
+ if (timings && report !== null) {
1018
+ timings["ms.sensors"] = report.sensorMs;
1019
+ }
1020
+ const record = buildDryRunRecord(plan, { sensors: report, eagerFailures, startedTests, coverage: strykerGlobal.mutantCoverage });
1021
+ const merged = mergeDryRunRecords(readEarlierRecord(recordFile), record);
1022
+ writePrivateFileAtomically(recordFile, JSON.stringify(merged));
1023
+ } catch (error) {
1024
+ console.error(`[Stryker Coverage] Failed to write the dry-run record to ${recordFile}: ${error instanceof Error ? error.message : String(error)}`);
1025
+ }
1026
+ };
375
1027
  var writeCoverageData = () => {
376
1028
  if (!shouldCollectCoverage2 || !coverageFile) {
377
1029
  return;
378
1030
  }
379
- const data = serializeCoverageData(strykerGlobal.mutantCoverage, lateHits, gapTracker);
1031
+ const recorded = keysOnly ? testKeysOnly(strykerGlobal.mutantCoverage) : strykerGlobal.mutantCoverage;
1032
+ const data = serializeCoverageData(recorded, keysOnly ? [] : lateHits, gapTracker);
380
1033
  if (timings) {
381
1034
  timings["at.coverageFormatted"] = nowEpoch();
382
1035
  timings["bytes.coverage"] = data.length;
@@ -390,9 +1043,49 @@ var writeCoverageData = () => {
390
1043
  console.error(`[Stryker Coverage] Failed to write coverage to ${coverageFile}: ${error instanceof Error ? error.message : String(error)}`);
391
1044
  }
392
1045
  };
1046
+ var drainAndClose = async () => {
1047
+ if (ws && ws.readyState === WebSocket.OPEN) {
1048
+ try {
1049
+ await new Promise((resolve) => {
1050
+ const wsForDrain = ws;
1051
+ const timeout = setTimeout(() => {
1052
+ console.warn("[Stryker] Timeout waiting for drain acknowledgment");
1053
+ resolve();
1054
+ }, DRAIN_ACK_TIMEOUT_MS);
1055
+ wsForDrain.onmessage = (event) => {
1056
+ if (event.data === "drained") {
1057
+ clearTimeout(timeout);
1058
+ resolve();
1059
+ }
1060
+ };
1061
+ wsForDrain.onerror = () => {
1062
+ clearTimeout(timeout);
1063
+ resolve();
1064
+ };
1065
+ try {
1066
+ if (timings) {
1067
+ timings["at.drainRequested"] = nowEpoch();
1068
+ }
1069
+ wsForDrain.send("drain-request");
1070
+ } catch {
1071
+ clearTimeout(timeout);
1072
+ resolve();
1073
+ }
1074
+ });
1075
+ } catch (error) {
1076
+ console.warn("[Stryker] Error during drain handshake:", error);
1077
+ }
1078
+ }
1079
+ if (timings) {
1080
+ timings["at.drained"] = nowEpoch();
1081
+ preloadFs.writeSync(2, formatPreloadTimings(timings));
1082
+ }
1083
+ ws?.close();
1084
+ };
393
1085
  if (shouldCollectCoverage2) {
394
1086
  beforeEach(() => {
395
1087
  const hookStart = timings ? performance.now() : 0;
1088
+ startedTests++;
396
1089
  const bunMain = String(globalThis.Bun?.main ?? "");
397
1090
  if (bunMain !== lastBunMain) {
398
1091
  lastBunMain = bunMain;
@@ -442,42 +1135,7 @@ if (shouldCollectCoverage2) {
442
1135
  }
443
1136
  writeCoverageData();
444
1137
  lateHits.length = 0;
445
- if (ws && ws.readyState === WebSocket.OPEN) {
446
- try {
447
- await new Promise((resolve) => {
448
- const wsForDrain = ws;
449
- const timeout = setTimeout(() => {
450
- console.warn("[Stryker] Timeout waiting for drain acknowledgment");
451
- resolve();
452
- }, DRAIN_ACK_TIMEOUT_MS);
453
- wsForDrain.onmessage = (event) => {
454
- if (event.data === "drained") {
455
- clearTimeout(timeout);
456
- resolve();
457
- }
458
- };
459
- wsForDrain.onerror = () => {
460
- clearTimeout(timeout);
461
- resolve();
462
- };
463
- try {
464
- if (timings) {
465
- timings["at.drainRequested"] = nowEpoch();
466
- }
467
- wsForDrain.send("drain-request");
468
- } catch {
469
- clearTimeout(timeout);
470
- resolve();
471
- }
472
- });
473
- } catch (error) {
474
- console.warn("[Stryker] Error during drain handshake:", error);
475
- }
476
- }
477
- if (timings) {
478
- timings["at.drained"] = nowEpoch();
479
- preloadFs.writeSync(2, formatPreloadTimings(timings));
480
- }
481
- ws?.close();
1138
+ writeDryRunRecord();
1139
+ await drainAndClose();
482
1140
  });
483
1141
  }