@hughescr/stryker-bun-runner 1.5.2 → 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.
- package/README.md +491 -24
- package/dist/index.d.ts +486 -32
- package/dist/index.js +3490 -334
- package/dist/templates/coverage-preload.js +1128 -0
- package/dist/templates/import-scan.js +902 -0
- package/package.json +5 -2
- package/dist/coverage/preload-logic.js +0 -255
- package/dist/templates/coverage-preload.ts +0 -440
|
@@ -1,440 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Coverage preload script
|
|
3
|
-
* This script is loaded before tests run to collect mutation coverage data
|
|
4
|
-
* Note: This is a template file with a placeholder import that gets replaced at runtime
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { beforeEach, afterEach, afterAll, describe, test, it } from 'bun:test';
|
|
8
|
-
import {
|
|
9
|
-
getPreloadConfig,
|
|
10
|
-
shouldCollectCoverage as shouldCollect,
|
|
11
|
-
initializeStrykerNamespace,
|
|
12
|
-
setActiveMutant,
|
|
13
|
-
installHitLimit,
|
|
14
|
-
HIT_LIMIT_TOKEN_ENV,
|
|
15
|
-
SYNC_TOKEN_ENV,
|
|
16
|
-
formatCoverageData,
|
|
17
|
-
detectGapWindowBleed,
|
|
18
|
-
writeCoverageToFile,
|
|
19
|
-
guardAgainstOrphaning,
|
|
20
|
-
orphanDebugLog,
|
|
21
|
-
awaitRunnerReady,
|
|
22
|
-
LIFELINE_FD_ENV,
|
|
23
|
-
ORPHAN_DEBUG_ENV,
|
|
24
|
-
type StrykerNamespace,
|
|
25
|
-
type LateHitEntry
|
|
26
|
-
} from '__PRELOAD_LOGIC_PATH__';
|
|
27
|
-
|
|
28
|
-
// ============================================================================
|
|
29
|
-
// Section 0: Orphan prevention
|
|
30
|
-
// ============================================================================
|
|
31
|
-
// Every bun test child loads this preload script (dryRun AND mutant runs), so
|
|
32
|
-
// the lifeline is watched unconditionally, regardless of coverage collection.
|
|
33
|
-
// If the Stryker worker that spawned this process dies (including via
|
|
34
|
-
// SIGKILL, which gives it no chance to kill its children), this process would
|
|
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],
|
|
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)),
|
|
46
|
-
onOrphaned: () => {
|
|
47
|
-
console.warn('[Stryker] Parent process is no longer running — terminating to avoid an orphaned bun test process');
|
|
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
|
|
49
|
-
process.exit(1);
|
|
50
|
-
},
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
// Patch .concurrent() to be regular sequential execution
|
|
54
|
-
// This ensures accurate coverage tracking during mutation testing
|
|
55
|
-
// Users can still use .concurrent() for faster normal test runs
|
|
56
|
-
// Use Object.defineProperty to override readonly properties
|
|
57
|
-
Object.defineProperty(describe, 'concurrent', { value: describe, writable: true, configurable: true });
|
|
58
|
-
Object.defineProperty(test, 'concurrent', { value: test, writable: true, configurable: true });
|
|
59
|
-
Object.defineProperty(it, 'concurrent', { value: it, writable: true, configurable: true });
|
|
60
|
-
|
|
61
|
-
interface StrykerGlobal {
|
|
62
|
-
[key: string]: unknown
|
|
63
|
-
__stryker__?: StrykerNamespace
|
|
64
|
-
__mutantCoverage__?: {
|
|
65
|
-
'static': Record<string, number>
|
|
66
|
-
perTest: Record<string, Record<string, number>>
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// Eager modules list — placeholder replaced at generation time with a sorted JSON array of absolute
|
|
71
|
-
// paths to all source files being mutated. Importing each module here (before any test code runs,
|
|
72
|
-
// while strykerGlobal.currentTestId is undefined) ensures that all module-level top-level code is
|
|
73
|
-
// executed in the "static" coverage bucket rather than the "perTest" bucket of whichever test
|
|
74
|
-
// happened to trigger the first import. This makes coverage collection deterministic across runs.
|
|
75
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Placeholder replaced at generation time; value is always a valid JSON array literal
|
|
76
|
-
const EAGER_MODULES: string[] = __EAGER_MODULES__;
|
|
77
|
-
|
|
78
|
-
// Get environment variables
|
|
79
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
|
|
80
|
-
const config = getPreloadConfig();
|
|
81
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Config from placeholder import
|
|
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];
|
|
92
|
-
|
|
93
|
-
// Skip coverage collection during mutant runs (only need pass/fail)
|
|
94
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
|
|
95
|
-
const shouldCollectCoverage = shouldCollect(config);
|
|
96
|
-
|
|
97
|
-
// ============================================================================
|
|
98
|
-
// Section 1: WebSocket Sync (receive test start events)
|
|
99
|
-
// ============================================================================
|
|
100
|
-
let ws: WebSocket | null = null;
|
|
101
|
-
|
|
102
|
-
// Bound on how long the final afterAll (below) waits for the runner's drain
|
|
103
|
-
// acknowledgment before giving up and proceeding as if drained — see
|
|
104
|
-
// "Inspector-stream drain handshake" further down.
|
|
105
|
-
// The runner now sends 'drained' once its own wait settles — INCLUDING when
|
|
106
|
-
// it gave up (silence or absolute ceiling) — so this timer only ever governs
|
|
107
|
-
// if the sync channel itself is dead or unresponsive. Deliberately ABOVE the
|
|
108
|
-
// runner-side absolute ceiling (DRAIN_ACK_ABSOLUTE_CEILING_MS in
|
|
109
|
-
// bun-test-runner.ts) so a stuck wait is always governed by that shorter
|
|
110
|
-
// ceiling first.
|
|
111
|
-
const DRAIN_ACK_TIMEOUT_MS = 40_000;
|
|
112
|
-
|
|
113
|
-
// Per-file test counters for per-test coverage tracking.
|
|
114
|
-
//
|
|
115
|
-
// Bun runs multiple test files sequentially inside the same worker process,
|
|
116
|
-
// sharing a single preload module instance. A module-level counter would
|
|
117
|
-
// increment globally across all files, making position N for file B mean
|
|
118
|
-
// "the (N)th test of ALL files combined" rather than "the (N)th test of B".
|
|
119
|
-
// The coverage mapper expects per-file counters that restart at 1 for each
|
|
120
|
-
// file, so we keep a Map<filePrefix, count> and reset per-file naturally.
|
|
121
|
-
//
|
|
122
|
-
// Bun.main is read DYNAMICALLY inside beforeEach (not at module init time)
|
|
123
|
-
// because it changes to reflect the currently-executing test file.
|
|
124
|
-
const perFileCounters = new Map<string, number>();
|
|
125
|
-
|
|
126
|
-
// Helper: extract a stable relative file prefix from a Bun.main absolute path.
|
|
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.
|
|
144
|
-
function extractFilePrefix(bunMain: string): string {
|
|
145
|
-
if(!bunMain) {
|
|
146
|
-
return 'unknown';
|
|
147
|
-
}
|
|
148
|
-
// Stryker disable next-line Regex: sandbox path extraction pattern
|
|
149
|
-
const sandboxMatch = /\.stryker-tmp\/sandbox-[^/]+\/(.+)$/.exec(bunMain);
|
|
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(/^.*\//, '');
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// ============================================================================
|
|
163
|
-
// Cross-test async coverage-bleed detection (gap-window count-delta)
|
|
164
|
-
// ============================================================================
|
|
165
|
-
// Detects fire-and-forget promise chains (or other async work) that keep
|
|
166
|
-
// recording mutant coverage into the `static` bucket after their originating
|
|
167
|
-
// test's afterEach has fired — i.e. between one test ending and the next
|
|
168
|
-
// test beginning ("the gap window"). Diagnostic only: see
|
|
169
|
-
// emitCoverageBleedWarnings in bun-test-runner.ts for how this surfaces as a
|
|
170
|
-
// warning; it never changes coverage attribution.
|
|
171
|
-
//
|
|
172
|
-
// lastEndedTestId / lastFilePrefix / staticSnapshotAtLastBoundary are updated
|
|
173
|
-
// in afterEach (the start of a gap window) and consumed in the NEXT
|
|
174
|
-
// beforeEach (the end of that gap window) — see both hooks below.
|
|
175
|
-
let lastEndedTestId: string | undefined;
|
|
176
|
-
let lastFilePrefix: string | undefined;
|
|
177
|
-
let staticSnapshotAtLastBoundary = new Map<string, number>();
|
|
178
|
-
const lateHits: LateHitEntry[] = [];
|
|
179
|
-
|
|
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 });
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// ============================================================================
|
|
198
|
-
// Section 2: Initialize Stryker Namespace
|
|
199
|
-
// ============================================================================
|
|
200
|
-
const g = globalThis as unknown as StrykerGlobal;
|
|
201
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
|
|
202
|
-
const strykerGlobal = initializeStrykerNamespace(g as Record<string, unknown>);
|
|
203
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- StrykerGlobal from placeholder import
|
|
204
|
-
const mutantCoverage = strykerGlobal.mutantCoverage!;
|
|
205
|
-
|
|
206
|
-
// Set active mutant for mutant runs
|
|
207
|
-
if(activeMutant) {
|
|
208
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
|
|
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
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// ============================================================================
|
|
221
|
-
// Section 3: Eager Module Imports (deterministic static coverage)
|
|
222
|
-
// ============================================================================
|
|
223
|
-
// Force all src modules to execute their top-level code during preload,
|
|
224
|
-
// while strykerGlobal.currentTestId is undefined. Module-level mutants
|
|
225
|
-
// then deterministically record to the `static` bucket instead of the
|
|
226
|
-
// `perTest` entry of whichever test happened to trigger the import first.
|
|
227
|
-
//
|
|
228
|
-
// This block is skipped during mutant runs (shouldCollectCoverage is false)
|
|
229
|
-
// so mutant runs do not pay the startup cost of importing every source file.
|
|
230
|
-
if(shouldCollectCoverage) {
|
|
231
|
-
for(const modPath of EAGER_MODULES) {
|
|
232
|
-
try {
|
|
233
|
-
// eslint-disable-next-line no-await-in-loop -- Sequential eager imports are intentional; parallel import would race on module-level side effects
|
|
234
|
-
await import(modPath);
|
|
235
|
-
} catch(err) {
|
|
236
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- err.message may exist at runtime
|
|
237
|
-
console.warn(`[Stryker] Eager import failed for ${modPath}:`, err);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// ============================================================================
|
|
243
|
-
// Section 4: Coverage Writing Logic
|
|
244
|
-
// ============================================================================
|
|
245
|
-
|
|
246
|
-
// Shared coverage writing logic
|
|
247
|
-
const writeCoverageData = () => {
|
|
248
|
-
if(!shouldCollectCoverage || !coverageFile) {
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// counterToName is not populated (test names are resolved by coverage-mapper
|
|
253
|
-
// from the inspector data, not stored here), so pass an empty Map.
|
|
254
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access -- Placeholder import replaced at runtime
|
|
255
|
-
const data = formatCoverageData(strykerGlobal.mutantCoverage, new Map<string, string>(), lateHits);
|
|
256
|
-
|
|
257
|
-
try {
|
|
258
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
|
|
259
|
-
writeCoverageToFile(coverageFile, data);
|
|
260
|
-
} catch (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)}`);
|
|
265
|
-
}
|
|
266
|
-
};
|
|
267
|
-
|
|
268
|
-
// ============================================================================
|
|
269
|
-
// Section 5: Test Hooks (for per-test coverage tracking)
|
|
270
|
-
// ============================================================================
|
|
271
|
-
if(shouldCollectCoverage) {
|
|
272
|
-
beforeEach(() => {
|
|
273
|
-
// Assign a stable, per-file test ID by combining the normalized test
|
|
274
|
-
// file path with a per-file counter.
|
|
275
|
-
//
|
|
276
|
-
// Key design constraints:
|
|
277
|
-
// 1. Bun runs multiple test files sequentially in one worker process,
|
|
278
|
-
// so the preload module is initialized ONCE for the whole run.
|
|
279
|
-
// 2. However, Bun.main IS updated to the currently-running test file
|
|
280
|
-
// by the time each beforeEach fires.
|
|
281
|
-
// 3. The coverage-mapper expects counters to restart at 1 per file
|
|
282
|
-
// (e.g. "tests/foo.test.ts@@test-1", "tests/bar.test.ts@@test-1"),
|
|
283
|
-
// so we track a separate counter per file prefix.
|
|
284
|
-
//
|
|
285
|
-
// @ts-expect-error -- Bun global is available at runtime but not in TS typings
|
|
286
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- Bun global accessed at runtime
|
|
287
|
-
const bunMain = String((globalThis as unknown as { Bun?: { main?: string } }).Bun?.main ?? '');
|
|
288
|
-
const filePrefix = extractFilePrefix(bunMain);
|
|
289
|
-
|
|
290
|
-
// Gap-window bleed check: this beforeEach is the END of the gap window that
|
|
291
|
-
// started when the previous test's afterEach ran (see afterEach below). Diff
|
|
292
|
-
// the static bucket now against the snapshot taken back then; any mutant whose
|
|
293
|
-
// count increased executed while no test was active — i.e. after the previous
|
|
294
|
-
// test ended.
|
|
295
|
-
if(filePrefix !== lastFilePrefix) {
|
|
296
|
-
// FILE-BOUNDARY SKIP: this test starts a new file relative to the last one
|
|
297
|
-
// that ended. A new file's module-level code (imports, describe-level setup)
|
|
298
|
-
// legitimately executes in this gap and would be indistinguishable from real
|
|
299
|
-
// bleed from here, so we deliberately do not diff across a file boundary.
|
|
300
|
-
// This trades missed cross-file leaks for zero file-boundary false positives,
|
|
301
|
-
// which is the safer default for a diagnostic-only warning.
|
|
302
|
-
lastEndedTestId = undefined;
|
|
303
|
-
staticSnapshotAtLastBoundary = new Map();
|
|
304
|
-
} else if(lastEndedTestId !== undefined) {
|
|
305
|
-
// 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
|
|
306
|
-
const bledMutantIds = detectGapWindowBleed(staticSnapshotAtLastBoundary, mutantCoverage.static);
|
|
307
|
-
if(bledMutantIds.length > 0) {
|
|
308
|
-
lateHits.push({ testId: lastEndedTestId, mutantIds: bledMutantIds });
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
const prevCount = perFileCounters.get(filePrefix) ?? 0;
|
|
313
|
-
const nextCount = prevCount + 1;
|
|
314
|
-
perFileCounters.set(filePrefix, nextCount);
|
|
315
|
-
const testId = `${filePrefix}@@test-${nextCount}`;
|
|
316
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- StrykerGlobal from placeholder import
|
|
317
|
-
strykerGlobal.currentTestId = testId;
|
|
318
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- MutantCoverage from placeholder import
|
|
319
|
-
mutantCoverage.perTest[testId] ??= {};
|
|
320
|
-
});
|
|
321
|
-
|
|
322
|
-
afterEach(() => {
|
|
323
|
-
// Record the gap-window START: which test just ended, and the static bucket's
|
|
324
|
-
// counts at this instant. The NEXT beforeEach (above) diffs against this
|
|
325
|
-
// snapshot to detect any coverage recorded in between — see
|
|
326
|
-
// "Cross-test async coverage-bleed detection" above.
|
|
327
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment -- StrykerGlobal from placeholder import
|
|
328
|
-
const endedTestId: string | undefined = strykerGlobal.currentTestId;
|
|
329
|
-
lastEndedTestId = endedTestId;
|
|
330
|
-
if(endedTestId) {
|
|
331
|
-
// The LAST '@@': the file prefix may contain one itself (a directory such as tests/x@@y/).
|
|
332
|
-
const sepIdx = endedTestId.lastIndexOf('@@');
|
|
333
|
-
lastFilePrefix = sepIdx === -1 ? endedTestId : endedTestId.slice(0, sepIdx);
|
|
334
|
-
}
|
|
335
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument -- MutantCoverage from placeholder import
|
|
336
|
-
staticSnapshotAtLastBoundary = new Map(Object.entries(mutantCoverage.static));
|
|
337
|
-
|
|
338
|
-
// Clear currentTestId so any subsequent code records to static
|
|
339
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- StrykerGlobal from placeholder import
|
|
340
|
-
strykerGlobal.currentTestId = undefined;
|
|
341
|
-
});
|
|
342
|
-
|
|
343
|
-
afterAll(async () => {
|
|
344
|
-
// Final gap check, best-effort: catches bleed that has already recorded a
|
|
345
|
-
// counter delta by the time afterAll runs, with no following beforeEach
|
|
346
|
-
// left to catch it any other way. This preload's afterAll fires once per
|
|
347
|
-
// WORKER PROCESS (empirically verified — Bun runs multiple test files
|
|
348
|
-
// sequentially in one worker sharing this preload module instance), so
|
|
349
|
-
// this is the single final opportunity to detect trailing bleed before
|
|
350
|
-
// coverage is written below.
|
|
351
|
-
//
|
|
352
|
-
// LIMITATION: this only sees hits that execute before afterAll itself
|
|
353
|
-
// runs. A queued timer or promise continuation that is still pending
|
|
354
|
-
// when afterAll fires (and settles afterward, e.g. during process
|
|
355
|
-
// teardown) is never observed — there is no later hook to diff against.
|
|
356
|
-
// Fully catching trailing leaks would need a deliberate strict-drain
|
|
357
|
-
// mode (draining the microtask/timer queue before treating the run as
|
|
358
|
-
// over) — deliberately out of scope here (event-loop starvation risk);
|
|
359
|
-
// see "Coverage bleed" in docs/internals.md.
|
|
360
|
-
if(lastEndedTestId !== undefined) {
|
|
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
|
|
362
|
-
const bledMutantIds = detectGapWindowBleed(staticSnapshotAtLastBoundary, mutantCoverage.static);
|
|
363
|
-
if(bledMutantIds.length > 0) {
|
|
364
|
-
lateHits.push({ testId: lastEndedTestId, mutantIds: bledMutantIds });
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
// Coverage must be finalized — gap check above, then the write itself —
|
|
369
|
-
// BEFORE the drain-ack wait below, not after. The wait yields this
|
|
370
|
-
// process's event loop for up to DRAIN_ACK_TIMEOUT_MS; if it ran first,
|
|
371
|
-
// any stray timer or promise continuation left behind by the last test
|
|
372
|
-
// could fire during that yield, touch mutantCoverage.static, and leak
|
|
373
|
-
// into the persisted snapshot — reintroducing exactly the class of risk
|
|
374
|
-
// the gap-window bleed check above exists to catch. Writing first means
|
|
375
|
-
// the snapshot is already on disk before that window even opens, so
|
|
376
|
-
// nothing that runs during the wait can affect what was persisted.
|
|
377
|
-
writeCoverageData();
|
|
378
|
-
// Clear the accumulator now that it has been written out.
|
|
379
|
-
lateHits.length = 0;
|
|
380
|
-
|
|
381
|
-
// ====================================================================
|
|
382
|
-
// Inspector-stream drain handshake
|
|
383
|
-
// ====================================================================
|
|
384
|
-
// Block (bounded) on a drain acknowledgment from the runner BEFORE
|
|
385
|
-
// closing this socket / allowing this process to exit. Without this,
|
|
386
|
-
// nothing synchronizes "the runner has received and processed every
|
|
387
|
-
// inspector event" with "this child process is allowed to exit" — a
|
|
388
|
-
// contended CPU (e.g. a 2-core CI box) can leave the runner's
|
|
389
|
-
// InspectorClient with an unprocessed backlog at the moment this
|
|
390
|
-
// process exits, silently truncating the inspector stream that dry
|
|
391
|
-
// run's completeness gate depends on.
|
|
392
|
-
//
|
|
393
|
-
// This IS a single bounded `await`, and an `await` genuinely yields
|
|
394
|
-
// this process's event loop for up to DRAIN_ACK_TIMEOUT_MS — it is not
|
|
395
|
-
// a no-op with respect to timer/microtask starvation, and does not
|
|
396
|
-
// pretend to be. What makes it safe here is ordering, not avoidance:
|
|
397
|
-
// writeCoverageData() above already ran and the coverage snapshot is
|
|
398
|
-
// already on disk by the time this wait starts, so anything that
|
|
399
|
-
// executes during the wait cannot alter what was persisted. This must
|
|
400
|
-
// stay the LAST coverage-adjacent step before ws.close() — no
|
|
401
|
-
// coverage-relevant work should be added after it starts. Separately,
|
|
402
|
-
// it does NOT drain THIS process's own microtask/timer queue on
|
|
403
|
-
// purpose (that risk is documented in the LIMITATION comment above); it
|
|
404
|
-
// only waits on a message sent FROM the parent runner process.
|
|
405
|
-
if(ws && ws.readyState === WebSocket.OPEN) {
|
|
406
|
-
try {
|
|
407
|
-
await new Promise<void>((resolve) => {
|
|
408
|
-
const wsForDrain = ws!;
|
|
409
|
-
const timeout = setTimeout(() => {
|
|
410
|
-
console.warn('[Stryker] Timeout waiting for drain acknowledgment');
|
|
411
|
-
resolve();
|
|
412
|
-
}, DRAIN_ACK_TIMEOUT_MS);
|
|
413
|
-
|
|
414
|
-
wsForDrain.onmessage = (event) => {
|
|
415
|
-
if(event.data === 'drained') {
|
|
416
|
-
clearTimeout(timeout);
|
|
417
|
-
resolve();
|
|
418
|
-
}
|
|
419
|
-
};
|
|
420
|
-
|
|
421
|
-
wsForDrain.onerror = () => {
|
|
422
|
-
clearTimeout(timeout);
|
|
423
|
-
resolve();
|
|
424
|
-
};
|
|
425
|
-
|
|
426
|
-
try {
|
|
427
|
-
wsForDrain.send('drain-request');
|
|
428
|
-
} catch {
|
|
429
|
-
clearTimeout(timeout);
|
|
430
|
-
resolve();
|
|
431
|
-
}
|
|
432
|
-
});
|
|
433
|
-
} catch (error) {
|
|
434
|
-
console.warn('[Stryker] Error during drain handshake:', error);
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
ws?.close();
|
|
439
|
-
});
|
|
440
|
-
}
|