@hughescr/stryker-bun-runner 1.3.8 → 1.5.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.
@@ -10,10 +10,17 @@ import {
10
10
  shouldCollectCoverage as shouldCollect,
11
11
  initializeStrykerNamespace,
12
12
  setActiveMutant,
13
+ installHitLimit,
14
+ HIT_LIMIT_TOKEN_ENV,
15
+ SYNC_TOKEN_ENV,
13
16
  formatCoverageData,
14
17
  detectGapWindowBleed,
15
18
  writeCoverageToFile,
16
- startOrphanWatchdog,
19
+ guardAgainstOrphaning,
20
+ orphanDebugLog,
21
+ awaitRunnerReady,
22
+ LIFELINE_FD_ENV,
23
+ ORPHAN_DEBUG_ENV,
17
24
  type StrykerNamespace,
18
25
  type LateHitEntry
19
26
  } from '__PRELOAD_LOGIC_PATH__';
@@ -22,22 +29,26 @@ import {
22
29
  // Section 0: Orphan prevention
23
30
  // ============================================================================
24
31
  // Every bun test child loads this preload script (dryRun AND mutant runs), so
25
- // this watchdog runs unconditionally, regardless of coverage collection.
32
+ // the lifeline is watched unconditionally, regardless of coverage collection.
26
33
  // If the Stryker worker that spawned this process dies (including via
27
34
  // SIGKILL, which gives it no chance to kill its children), this process would
28
- // otherwise run forever, or until its own --timeout is reached — see README
29
- // "Orphan prevention".
30
- const stopOrphanWatchdog = startOrphanWatchdog({
35
+ // otherwise run forever, or until its own --timeout is reached — see
36
+ // "Orphan prevention" in docs/internals.md. The watch is left in place for the life of the process:
37
+ // it arms no timer and does not keep bun test from exiting. Only if the
38
+ // lifeline is unavailable does it fall back to polling process.ppid on an
39
+ // unref'd interval, saying so on stderr when STRYKER_BUN_RUNNER_DEBUG is set.
40
+ guardAgainstOrphaning({
41
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- LIFELINE_FD_ENV from placeholder import
42
+ fdValue: process.env[LIFELINE_FD_ENV],
31
43
  getPpid: () => process.ppid,
44
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call -- from placeholder import
45
+ log: orphanDebugLog(process.env[ORPHAN_DEBUG_ENV], (text: string) => process.stderr.write(text)),
32
46
  onOrphaned: () => {
33
47
  console.warn('[Stryker] Parent process is no longer running — terminating to avoid an orphaned bun test process');
34
48
  // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit -- deliberate self-termination once orphaned; nothing else can stop this process from running forever
35
49
  process.exit(1);
36
50
  },
37
51
  });
38
- afterAll(() => {
39
- stopOrphanWatchdog();
40
- });
41
52
 
42
53
  // Patch .concurrent() to be regular sequential execution
43
54
  // This ensures accurate coverage tracking during mutation testing
@@ -68,7 +79,16 @@ const EAGER_MODULES: string[] = __EAGER_MODULES__;
68
79
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
69
80
  const config = getPreloadConfig();
70
81
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Config from placeholder import
71
- const { syncPort, coverageFile, activeMutant } = config;
82
+ const { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken } = config;
83
+ // Hide the hit-limit token from the test files: anything that can read it
84
+ // could print a sentinel the runner accepts. See formatHitLimitSentinel.
85
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- HIT_LIMIT_TOKEN_ENV from placeholder import
86
+ delete process.env[HIT_LIMIT_TOKEN_ENV];
87
+ // Likewise the sync token: only this preload dials the sync server, so the test
88
+ // files (and a run of this runner inside them) never see it. The project's own
89
+ // [test].preload scripts load before this one, though, and can read both tokens.
90
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- SYNC_TOKEN_ENV from placeholder import
91
+ delete process.env[SYNC_TOKEN_ENV];
72
92
 
73
93
  // Skip coverage collection during mutant runs (only need pass/fail)
74
94
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
@@ -105,13 +125,38 @@ const perFileCounters = new Map<string, number>();
105
125
 
106
126
  // Helper: extract a stable relative file prefix from a Bun.main absolute path.
107
127
  // Strips the Stryker sandbox prefix so keys are portable across runs.
128
+ //
129
+ // Under `inPlace: true` there IS no sandbox segment to strip, and the old
130
+ // fallback here collapsed the path to its basename. That is not a portable
131
+ // prefix, it is an unmatchable one: Stryker resolves a test's fileName against
132
+ // its input files, so `example.spec.ts` became `<projectRoot>/example.spec.ts`
133
+ // matched nothing. Three symptoms followed from that one line — "Test file … not
134
+ // found in input files" warnings, spurious "Interior coverage gap detected"
135
+ // warnings (the prefix is compared for equality against the inspector's
136
+ // normalised URL), and an incremental report whose differ saw every test as
137
+ // changed (+N -N) and so reused almost nothing.
138
+ //
139
+ // Falling back to the path relative to cwd fixes all three: monorepo task
140
+ // runners invoke per-project builds with cwd set to the project root, which is
141
+ // exactly what Stryker keys its input files on. Kept in lockstep with
142
+ // normalizeTestFilePath, which must produce the same string for the equality
143
+ // check above to hold.
108
144
  function extractFilePrefix(bunMain: string): string {
109
145
  if(!bunMain) {
110
146
  return 'unknown';
111
147
  }
112
148
  // Stryker disable next-line Regex: sandbox path extraction pattern
113
149
  const sandboxMatch = /\.stryker-tmp\/sandbox-[^/]+\/(.+)$/.exec(bunMain);
114
- return sandboxMatch ? sandboxMatch[1] : bunMain.replace(/^.*\//, '');
150
+ if(sandboxMatch) {
151
+ return sandboxMatch[1];
152
+ }
153
+ const cwd = process.cwd();
154
+ // Stryker disable next-line ConditionalExpression,BlockStatement,StringLiteral: inPlace path; covered by the preload-logic tests for cwd-relative prefixes
155
+ if(bunMain.startsWith(`${cwd}/`)) {
156
+ return bunMain.slice(cwd.length + 1);
157
+ }
158
+ // Last resort for a path outside cwd entirely (helper files, node_modules).
159
+ return bunMain.replace(/^.*\//, '');
115
160
  }
116
161
 
117
162
  // ============================================================================
@@ -132,63 +177,21 @@ let lastFilePrefix: string | undefined;
132
177
  let staticSnapshotAtLastBoundary = new Map<string, number>();
133
178
  const lateHits: LateHitEntry[] = [];
134
179
 
135
- if(syncPort && shouldCollectCoverage) {
136
- try {
137
- // Install the real 'ready' handler before yielding to the event loop so
138
- // there is no window where an arriving message is silently dropped.
139
- await new Promise<void>((resolve) => {
140
- ws = new WebSocket(`ws://localhost:${syncPort}/sync`);
141
- const timeout = setTimeout(() => {
142
- console.warn('[Stryker] Timeout waiting for ready signal');
143
- resolve();
144
- }, 2000);
145
-
146
- ws.onmessage = (event) => {
147
- if(event.data === 'ready') {
148
- clearTimeout(timeout);
149
- resolve();
150
- }
151
- };
152
-
153
- ws.onerror = () => {
154
- clearTimeout(timeout);
155
- console.warn('[Stryker] Failed to connect to sync server');
156
- resolve();
157
- };
158
- });
159
- } catch (error) {
160
- console.warn('[Stryker] Error during synchronization:', error);
161
- }
162
- } else if(syncPort && !shouldCollectCoverage) {
163
- // No coverage collection, just wait for ready signal
164
- try {
165
- // Install the real 'ready' handler before yielding to the event loop so
166
- // there is no window where an arriving message is silently dropped.
167
- await new Promise<void>((resolve) => {
168
- const wsLocal = new WebSocket(`ws://localhost:${syncPort}/sync`);
169
- const timeout = setTimeout(() => {
170
- wsLocal.close();
171
- console.warn('[Stryker Sync] Timeout waiting for ready signal, proceeding anyway');
172
- resolve();
173
- }, 2000);
174
-
175
- wsLocal.onmessage = (event) => {
176
- if(event.data === 'ready') {
177
- clearTimeout(timeout);
178
- wsLocal.close();
179
- resolve();
180
- }
181
- };
182
-
183
- wsLocal.onerror = () => {
184
- clearTimeout(timeout);
185
- console.warn('[Stryker Sync] Failed to connect to sync server, proceeding anyway');
186
- resolve();
187
- };
188
- });
189
- } catch (error) {
190
- console.warn('[Stryker Sync] Error during synchronization, proceeding anyway:', error);
191
- }
180
+ // Only the dry run sets a sync port. No test may start before the runner says
181
+ // 'ready', which it does once its inspector is connected, TestReporter is
182
+ // enabled and its drain handler is registered: a test that runs earlier is
183
+ // invisible to the runner, and its result and per-test coverage are lost or
184
+ // paired with the wrong test. So the wait has no deadline (the runner bounds its
185
+ // own side and stops this process if it fails), and a sync channel that fails
186
+ // or closes first ends this process with a message instead of running the
187
+ // tests unobserved; the message reaches the user in the dry run's error.
188
+ // All of that is awaitRunnerReady's (preload-logic); keep this a bare call, with
189
+ // no timer, sleep or race of its own (tests/unit/preload-logic.test.ts checks).
190
+ // The socket is kept open for the drain handshake only when collecting coverage.
191
+ if(syncPort) {
192
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
193
+ // A missing token dials a path no sync server serves, so the wait fails loudly.
194
+ ws = await awaitRunnerReady({ syncPort, syncToken: syncToken ?? '', keepOpen: shouldCollectCoverage });
192
195
  }
193
196
 
194
197
  // ============================================================================
@@ -204,6 +207,14 @@ const mutantCoverage = strykerGlobal.mutantCoverage!;
204
207
  if(activeMutant) {
205
208
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
206
209
  setActiveMutant(strykerGlobal, activeMutant);
210
+ // Stryker's infinite-loop protection: arm the instrumenter's hit limit before any
211
+ // instrumented code loads. One bun child runs one mutant, so the count starts at 0
212
+ // here and never needs resetting. See installHitLimit. Armed only with the
213
+ // run's token: without it the runner could not recognise the report.
214
+ if(hitLimit !== undefined && hitLimitToken) {
215
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
216
+ installHitLimit(strykerGlobal, hitLimit, hitLimitToken);
217
+ }
207
218
  }
208
219
 
209
220
  // ============================================================================
@@ -247,7 +258,10 @@ const writeCoverageData = () => {
247
258
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
248
259
  writeCoverageToFile(coverageFile, data);
249
260
  } catch (error) {
250
- console.error('[Stryker Coverage] Failed to write coverage:', error);
261
+ // One self-contained line: the runner surfaces stderr lines starting with
262
+ // '[Stryker Coverage]', and console.error(prefix, error) would put bun's code
263
+ // frame on this line and the actual ENOENT/EACCES text several lines below it.
264
+ console.error(`[Stryker Coverage] Failed to write coverage to ${coverageFile}: ${error instanceof Error ? error.message : String(error)}`);
251
265
  }
252
266
  };
253
267
 
@@ -314,7 +328,8 @@ if(shouldCollectCoverage) {
314
328
  const endedTestId: string | undefined = strykerGlobal.currentTestId;
315
329
  lastEndedTestId = endedTestId;
316
330
  if(endedTestId) {
317
- const sepIdx = endedTestId.indexOf('@@');
331
+ // The LAST '@@': the file prefix may contain one itself (a directory such as tests/x@@y/).
332
+ const sepIdx = endedTestId.lastIndexOf('@@');
318
333
  lastFilePrefix = sepIdx === -1 ? endedTestId : endedTestId.slice(0, sepIdx);
319
334
  }
320
335
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument -- MutantCoverage from placeholder import
@@ -341,7 +356,7 @@ if(shouldCollectCoverage) {
341
356
  // Fully catching trailing leaks would need a deliberate strict-drain
342
357
  // mode (draining the microtask/timer queue before treating the run as
343
358
  // over) — deliberately out of scope here (event-loop starvation risk);
344
- // see README's "Coverage-bleed warning" section.
359
+ // see "Coverage bleed" in docs/internals.md.
345
360
  if(lastEndedTestId !== undefined) {
346
361
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument -- Placeholder import replaced at runtime
347
362
  const bledMutantIds = detectGapWindowBleed(staticSnapshotAtLastBoundary, mutantCoverage.static);
package/package.json CHANGED
@@ -1,11 +1,13 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.3.8",
4
- "description": "Stryker test runner plugin for Bun with perTest coverage support",
3
+ "version": "1.5.0",
4
+ "description": "Stryker mutation testing test runner plugin for Bun (bun test), with per-test coverage",
5
5
  "keywords": [
6
6
  "stryker",
7
7
  "stryker-plugin",
8
+ "stryker-test-runner",
8
9
  "bun",
10
+ "bun-test",
9
11
  "test-runner",
10
12
  "mutation-testing"
11
13
  ],
@@ -33,27 +35,28 @@
33
35
  "dist"
34
36
  ],
35
37
  "scripts": {
36
- "build": "bun build src/index.ts --outdir dist --target node --format esm && bun build src/coverage/preload-logic.ts --outdir dist/coverage --target bun --format esm && dts-bundle-generator --config dts-bundle-generator.config.json && cp -r src/templates dist/",
38
+ "build": "bun build src/index.ts --outdir dist --target node --format esm --packages external && bun build src/coverage/preload-logic.ts --outdir dist/coverage --target bun --format esm --packages external && dts-bundle-generator --config dts-bundle-generator.config.json && cp -r src/templates dist/",
37
39
  "lint": "eslint --cache --format unix .",
38
40
  "mutate": "stryker run",
39
41
  "prepublishOnly": "bun run build",
40
42
  "test": "bun test",
41
- "typecheck": "tsc --noEmit",
43
+ "typecheck": "node node_modules/typescript/bin/tsc --noEmit && node node_modules/typescript/bin/tsc --noEmit -p scripts",
42
44
  "postversion": "git commit -m \"Bump package version to $npm_package_version\" package.json; git flow release start $npm_package_version; git flow release finish -m $npm_package_version $npm_package_version; git checkout develop; git merge main"
43
45
  },
44
46
  "dependencies": {
45
- "@stryker-mutator/api": "9.6.1",
46
- "smol-toml": "1.7.0",
47
- "tinyglobby": "0.2.17",
48
- "ws": "8.21.0"
47
+ "@stryker-mutator/api": "^9.0.0 || ^10.0.0",
48
+ "smol-toml": "^1.7.0",
49
+ "tinyglobby": "^0.2.17",
50
+ "ws": "^8.21.0"
49
51
  },
50
52
  "devDependencies": {
51
53
  "@hughescr/eslint-config-default": "6.0.1",
52
- "@stryker-mutator/core": "9.6.1",
53
- "@stryker-mutator/typescript-checker": "9.6.1",
54
+ "@stryker-mutator/core": "10.0.0",
55
+ "@stryker-mutator/typescript-checker": "10.0.0",
54
56
  "@types/bun": "1.3.14",
55
57
  "@types/node": "26.1.1",
56
58
  "@types/ws": "8.18.1",
59
+ "@typescript/native": "npm:typescript@7.0.2",
57
60
  "dts-bundle-generator": "9.5.1",
58
61
  "eslint": "10.7.0",
59
62
  "eslint-formatter-overview": "2.0.0",
@@ -61,9 +64,14 @@
61
64
  "typescript": "<7.0.0"
62
65
  },
63
66
  "peerDependencies": {
64
- "@stryker-mutator/core": "^9.0.0"
67
+ "@stryker-mutator/core": "^9.0.0 || ^10.0.0",
68
+ "typescript": "<7"
65
69
  },
66
70
  "engines": {
67
- "bun": ">=1.3.7"
71
+ "bun": ">=1.3.7",
72
+ "node": ">=20"
73
+ },
74
+ "patchedDependencies": {
75
+ "@stryker-mutator/typescript-checker@10.0.0": "patches/@stryker-mutator%2Ftypescript-checker@10.0.0.patch"
68
76
  }
69
77
  }