@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.
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
- import { StrykerOptions } from '@stryker-mutator/api/core';
3
+ import { PartialStrykerOptions, StrykerOptions } from '@stryker-mutator/api/core';
4
4
  import { Logger } from '@stryker-mutator/api/logging';
5
5
  import { PluginKind } from '@stryker-mutator/api/plugin';
6
- import { DryRunResult, MutantRunOptions, MutantRunResult, TestRunner, TestRunnerCapabilities } from '@stryker-mutator/api/test-runner';
6
+ import { DryRunOptions, DryRunResult, MutantRunOptions, MutantRunResult, TestRunner, TestRunnerCapabilities } from '@stryker-mutator/api/test-runner';
7
7
 
8
8
  /**
9
9
  * Bun test runner for Stryker mutation testing
@@ -18,12 +18,37 @@ export declare class BunTestRunner implements TestRunner {
18
18
  private readonly timeout;
19
19
  private readonly inspectorTimeout;
20
20
  private readonly env?;
21
+ /** `bun.bunArgs` as the user wrote them; validated at init(). */
22
+ private readonly configuredBunArgs?;
23
+ /** `bun.bunArgs` as spawned: the user's `--config`/`-c` is removed (the runner passes its own sanitized one). */
21
24
  private readonly bunArgs?;
25
+ /** {@link bunArgs} for mutant runs: without `--randomize`/`--seed`, which only the dry run keeps (see stripRandomizeArgs). */
26
+ private readonly mutantBunArgs?;
27
+ /**
28
+ * True when the current sanitized bunfig randomizes the test order, so mutant runs use its mutant-run
29
+ * copy (see mutantRunBunfigPath). Set whenever the sanitized bunfig is (re)generated, which every run does first.
30
+ */
31
+ private sanitizedBunfigRandomizes?;
32
+ /** True once the "randomized order is off for mutant runs" debug line has been logged; it is shown once per runner. */
33
+ private loggedRandomizeOff;
34
+ /** Which argv-budget notes (see {@link fitTestFiles}) have been logged; each is shown once per runner. */
35
+ private readonly loggedFileArgNotes;
36
+ /**
37
+ * Each test file's dry-run duration in ms (project-relative file → sum of its tests' durations),
38
+ * from this worker's dry run or the shared registry. Mutant runs hand bun their files in
39
+ * ascending order of it; undefined when neither had any, and the order is then left alone.
40
+ */
41
+ private testFileDurations?;
42
+ /** The user's bunfig named by `--config`/`-c` in `bun.bunArgs`, as written: the source the runner sanitizes and reads `[test].root` from. */
43
+ private readonly sourceBunfig?;
22
44
  private readonly testFilesOverride?;
23
45
  private readonly mutateGlobs;
24
46
  private readonly smol;
25
47
  private readonly maxChildRss?;
26
48
  private readonly rssCheckIntervalMs?;
49
+ private readonly maxSpawnDepth?;
50
+ /** Stryker's coverageAnalysis from the Stryker options; DryRunOptions.coverageAnalysis wins when given. */
51
+ private readonly coverageAnalysis?;
27
52
  private preloadScriptPath?;
28
53
  private coverageFilePath?;
29
54
  private sanitizedBunfigPath?;
@@ -32,16 +57,50 @@ export declare class BunTestRunner implements TestRunner {
32
57
  private cachedTestNames?;
33
58
  private baseNameIndex?;
34
59
  private testNameIndex?;
60
+ /** The auto-discovered test files, valid for `cachedTestFilesCwd` only. Written by discovery alone, never by a selection. */
35
61
  private cachedTestFiles?;
36
62
  private cachedTestFilesCwd?;
63
+ /**
64
+ * The list mutantRun uses for its "run all tests" runs and for validating covering-test
65
+ * narrowing: the effective selection (Stryker's testFiles, bun.testFiles or discovery).
66
+ * Kept apart from {@link cachedTestFiles} so a selection can never be read back as the discovered set.
67
+ */
68
+ private effectiveTestFiles?;
69
+ /**
70
+ * The test files Stryker's own `testFiles` option selected (DryRunOptions.testFiles), as
71
+ * exact absolute paths, valid for `cwd`. Set by dryRun (or loaded from the shared registry
72
+ * by a worker that never ran dryRun). While set it wins over bun.testFiles and
73
+ * auto-discovery, for the dry run and for every "run all tests" fallback after it.
74
+ */
75
+ private strykerTestFiles?;
76
+ /** True once the "Stryker's testFiles overrides bun.testFiles" warning has been logged. */
77
+ private warnedTestFilesConflict;
78
+ /** True once the dist/build-discovery warning has been logged; it is shown once per runner. */
79
+ private warnedBuildOutputTests;
80
+ /** True once the "bunfig retry/rerunEach ignored" warning has been logged; it is shown once per runner. */
81
+ private warnedIgnoredBunfigKeys;
37
82
  private cachedEagerModules?;
38
83
  private cachedEagerModulesCwd?;
39
84
  private lastRegistryTmpPath?;
85
+ /** True once `<bunPath> --version` has passed the startup check; later init() calls skip it. */
86
+ private bunChecked;
87
+ /** The version the startup check reported; set together with {@link bunChecked}. */
88
+ private bunVersion?;
89
+ /** True once the start summary has been logged; it is shown once per runner. */
90
+ private loggedStartSummary;
91
+ /** Stryker's `disableBail` option as given at construction; undefined when Stryker did not supply it. */
92
+ private readonly disableBail?;
93
+ /** Per-mutant warnings: the first of each kind at warn, the rest at debug, one summary per repeated kind at dispose(). */
94
+ private readonly mutantWarnings;
95
+ /** The mutant runs this worker has executed, by the status returned to Stryker. Reset when the end summary is logged. */
96
+ private mutantRunsByStatus;
97
+ /** Mutant runs that had covering tests but ran the full suite anyway (pattern too long, or zero-match retry). Reset with {@link mutantRunsByStatus}. */
98
+ private fullSuiteFallbacks;
40
99
  /**
41
100
  * AbortController for whichever `dryRun`/`mutantRun` child process is
42
101
  * currently in flight, if any. Lets {@link dispose} kill an orphaned child
43
- * if Stryker disposes this runner while a run hasn't finished — see README
44
- * "Orphan prevention".
102
+ * if Stryker disposes this runner while a run hasn't finished — see
103
+ * "Orphan prevention" in docs/internals.md.
45
104
  */
46
105
  private currentAbortController?;
47
106
  constructor(logger: Logger, options: StrykerOptions);
@@ -52,18 +111,24 @@ export declare class BunTestRunner implements TestRunner {
52
111
  * cwd IS the user's real project root, and writing there would both
53
112
  * pollute the user's project and never get cleaned up (dispose()
54
113
  * deliberately never unlinks the registry itself — see its doc comment).
55
- * The temp directory is OS-managed instead.
114
+ * The temp directory is OS-managed instead. Specifically it is the run's
115
+ * private directory (src/utils/private-temp-dir.ts): owned by the current
116
+ * user, mode 0700, re-resolved (and so re-verified) before every write and
117
+ * before the lazy load, so another local user can neither plant nor read a
118
+ * registry.
56
119
  *
57
- * Keyed by sha256(cwd + ':' + ppid): every worker process Stryker spawns
120
+ * Keyed by sha256(cwd + ':' + ppid) (plus the uid, in the directory name): every worker process Stryker spawns
58
121
  * for one run is a direct child of that run's single Stryker main
59
122
  * process, so all of them share BOTH process.cwd() (the sandbox
60
123
  * directory) AND process.ppid (the main process's pid) — and therefore
61
- * independently derive this SAME path with no coordination required. A
124
+ * independently resolve this SAME path with no coordination required
125
+ * (resolveRunTempDir's numbered slots converge too: each call takes the
126
+ * lowest slot that is already ours). A
62
127
  * worker recycled mid-run is still a child of the same main process, so
63
- * it re-derives the same path too (README documents recycled instances
128
+ * it re-derives the same path too (docs/internals.md documents recycled instances
64
129
  * lazily loading the registry). This is the entire sharing contract:
65
130
  * writer (buildAndPersistTestRegistry) and reader (loadRegistryFile) both
66
- * go through this one getter rather than reimplementing the formula, so
131
+ * go through this one method rather than reimplementing the formula, so
67
132
  * they can never disagree by construction.
68
133
  *
69
134
  * process.ppid is what makes this safe for this repo's own dogfooding:
@@ -84,26 +149,140 @@ export declare class BunTestRunner implements TestRunner {
84
149
  * syscall (and a new ENOENT failure mode if the sandbox dir is mid-
85
150
  * teardown) for no benefit.
86
151
  *
87
- * Using a getter that reads process.cwd()/process.ppid at call time
152
+ * Reading process.cwd()/process.ppid at call time
88
153
  * (rather than caching at construction) ensures the path resolves against
89
154
  * Stryker's sandbox directory — which is set by the time these are
90
155
  * invoked — rather than the orchestrator's cwd at module-load time.
91
156
  */
92
- private get registryPath();
93
- private get registryTmpPath();
157
+ private resolveRegistryPath;
158
+ /**
159
+ * Narrow a targeted mutant run to just the test FILES its covering tests live
160
+ * in.
161
+ *
162
+ * `--test-name-pattern` filters at the TEST level, not the file level: bun
163
+ * still loads every test file it was given in order to discover which names
164
+ * match. On a suite of 31 spec files that costs ~330ms per run of which only
165
+ * ~54ms is process startup — and a run that ends up executing two tests pays
166
+ * it in full, on every mutant. Handing bun only the files that can contain a
167
+ * covering test drops the same measurement to ~66ms.
168
+ *
169
+ * Test ids are `<projectFile> > <fullName>` (see buildProjectFileTestName), so
170
+ * the file is already the id's prefix and no extra bookkeeping is needed.
171
+ *
172
+ * Returns undefined — meaning "use the full discovered list" — whenever the
173
+ * narrowing cannot be proven safe:
174
+ * - no filter at all (static mutants, full-suite runs),
175
+ * - any id that carries no parsable file prefix (console-fallback ids), or
176
+ * - any derived file that is not in the discovered list, which would mean the
177
+ * prefix was something other than a real test file.
178
+ *
179
+ * A wrong narrowing would silently skip a covering test and turn a killed
180
+ * mutant into a survivor, so every uncertain case takes the full list.
181
+ */
182
+ private resolveCoveringTestFiles;
183
+ /**
184
+ * `files` in ascending order of their dry-run duration, for a mutant run.
185
+ *
186
+ * Mutant runs bail on the first failing test, and bun runs the files it is given
187
+ * in argument order (measured on bun 1.4.2, for path arguments — see
188
+ * runBunTests). Running the cheapest covering file first means a fast unit test
189
+ * usually kills the mutant before a slow integration file is even loaded.
190
+ *
191
+ * The sort is stable: files that took the same time keep their order (the
192
+ * alphabetical order of the discovered list and of resolveCoveringTestFiles), and
193
+ * files with no recorded duration — every file, when there are no durations at
194
+ * all — go last in their old order. `files` itself is not modified.
195
+ */
196
+ private orderCheapestFirst;
197
+ /**
198
+ * Say once, at debug, that mutant runs do not randomize the test order although
199
+ * the project asked for it (in the bunfig, in bun.bunArgs, or both). They run
200
+ * test files cheapest first and tests in source order, so a mutant's verdict
201
+ * never depends on a random order; the dry run keeps the setting.
202
+ */
203
+ private logRandomizeOffOnce;
94
204
  /**
95
205
  * Get test runner capabilities
96
206
  */
97
207
  capabilities(): TestRunnerCapabilities;
98
208
  /**
209
+ * The files Stryker's own `testFiles` option selected, when they apply to `cwd`.
210
+ * A selection recorded under another cwd (a different sandbox) names files that
211
+ * are not there, so it is ignored rather than trusted.
212
+ */
213
+ private selectedTestFilesFor;
214
+ /**
215
+ * Record (or clear) the selection from DryRunOptions.testFiles for this dry run.
216
+ *
217
+ * Stryker (core 9.6+, also 10) fills `testFiles` with the sandbox-absolute paths of
218
+ * the files matching its `testFiles` option, or leaves it undefined. Only a
219
+ * non-empty array counts; an empty one is treated as unset. Relative entries are
220
+ * resolved against the cwd, so bun gets exact paths (a bare relative argument is a
221
+ * substring filter to `bun test`, which would also run e.g. a `dist/` copy).
222
+ *
223
+ * Precedence for the files bun is handed: Stryker's testFiles > bun.testFiles >
224
+ * auto-discovery. When both Stryker's and bun.testFiles select files and they
225
+ * differ, one warning says Stryker's wins.
226
+ */
227
+ private applyDryRunTestFiles;
228
+ /** Where the test files for `cwd` come from, in the precedence of {@link getOrDiscoverTestFiles}, for the log. */
229
+ private testFilesSource;
230
+ /** Like {@link testFilesSource}, but undefined when the files are auto-discovered rather than chosen by the user. */
231
+ private explicitTestFilesSource;
232
+ /**
233
+ * The test files to hand bun for this spawn, kept within the argv budget (see
234
+ * MAX_TEST_FILE_ARGS_BYTES). `files` is already narrowed and ordered.
235
+ *
236
+ * - Within the budget (as absolute paths, or as the shorter ./-relative ones
237
+ * runBunTests then picks, said once at debug): `files` as given.
238
+ * - Over it, with auto-discovered files: undefined, so bun finds and runs every
239
+ * test file itself. That is the full suite, which is what a full-suite run
240
+ * lists anyway, and a superset of a targeted run's covering files — safe,
241
+ * because a targeted run keeps its --test-name-pattern; it only loses the
242
+ * cheapest-first order (said once at info).
243
+ * - Over it, with files the user chose (bun.testFiles, Stryker's testFiles):
244
+ * `files`, as no other list would keep the selection, and a warning (once)
245
+ * that bun may fail to start.
246
+ *
247
+ * @param explicitSource - What chose the files, or undefined when they were auto-discovered
248
+ */
249
+ private fitTestFiles;
250
+ /** Debug-log how many test files the dry run uses and where they came from. Same precedence as {@link getOrDiscoverTestFiles}. */
251
+ private logTestFilesSource;
252
+ /**
253
+ * Log the one-line start summary (at info, once per runner): the bun version and path, how
254
+ * many test files the runner hands bun and where they came from, the sanitized bunfig, and
255
+ * whether mutant runs bail. Called at the end of init(), so a re-init in another cwd
256
+ * (Stryker's sandbox rotation) does not repeat it.
257
+ *
258
+ * @param testFiles the files {@link getOrDiscoverTestFiles} chose; undefined when discovery
259
+ * found none and bun is left to discover the tests itself
260
+ */
261
+ private logStartSummary;
262
+ /**
263
+ * Warn, once per runner, that Stryker's testFiles option replaces a differing
264
+ * bun.testFiles. Both are compared as sets of resolved absolute paths, so the same
265
+ * files spelled relative vs absolute, or in another order, are not a conflict.
266
+ */
267
+ private warnIfTestFilesOverridden;
268
+ /**
99
269
  * Return the test file list to use for this run.
100
- * When `bun.testFiles` was provided it is returned verbatim and
101
- * auto-discovery is skipped entirely. Otherwise the result is cached after
102
- * the first real discovery call so that subsequent callers (dryRun, mutantRun)
270
+ * Precedence: the files Stryker's own `testFiles` option selected (see
271
+ * {@link applyDryRunTestFiles}), then `bun.testFiles` (returned verbatim), then
272
+ * auto-discovery; the first two skip discovery entirely. A discovery result is
273
+ * cached after the first real call so that subsequent callers (dryRun, mutantRun)
103
274
  * do not re-glob the filesystem.
104
275
  */
105
276
  private getOrDiscoverTestFiles;
106
277
  /**
278
+ * Warn, once per runner, when auto-discovery picked up test files below a
279
+ * `dist` or `build` directory. Bun searches those directories too, so a
280
+ * project whose tsc emits `dist/**\/*.test.js` gets the compiled copies run
281
+ * as well: slower, and a stale compiled test can fail the dry run. Parity
282
+ * with `bun test` is kept on purpose; the warning names the ways out.
283
+ */
284
+ private warnAboutBuildOutputTests;
285
+ /**
107
286
  * Test-file cache hit for a given cwd.
108
287
  * Returns the cached list synchronously when available, or undefined to
109
288
  * signal that async re-discovery is needed (cwd changed or first call).
@@ -114,11 +293,21 @@ export declare class BunTestRunner implements TestRunner {
114
293
  * Initialize the test runner
115
294
  */
116
295
  init(): Promise<void>;
296
+ /** Create/verify the run's private temp directory (see src/utils/private-temp-dir.ts) and remember it as this worker's tempDir. */
297
+ private ensureRunTempDir;
298
+ /**
299
+ * Log the bunfig settings the sanitizer dropped or overrode: each at debug with
300
+ * its reason, and the ones mutation runs cannot honour (retry, rerunEach) in
301
+ * one warning, shown once per runner however often the bunfig is regenerated.
302
+ */
303
+ private reportDroppedBunfigKeys;
117
304
  /**
118
305
  * Regenerate the sanitized bunfig if the worker's cwd has changed (or if this
119
- * is the first spawn). Bun resolves relative paths in a bunfig against the
120
- * bunfig file's location, so keying on cwd ensures preload/root paths land in
121
- * the right sandbox.
306
+ * is the first spawn). The sanitizer anchors the relative `preload`/`root`
307
+ * paths it forwards at this cwd (bun itself resolves relative bunfig paths
308
+ * against the process cwd, not against the bunfig's directory), so keying on
309
+ * cwd ensures those paths land in the right sandbox. Every setting it did not
310
+ * forward is logged at debug; ignored retry/rerun settings warn once per runner.
122
311
  */
123
312
  private ensureSanitizedBunfig;
124
313
  /**
@@ -132,6 +321,11 @@ export declare class BunTestRunner implements TestRunner {
132
321
  * whole file (never a half-initialised registry). Failures are non-fatal — the
133
322
  * worker falls back to raw console names and the lossy pattern reconstruction,
134
323
  * and a warning is logged so the issue is visible.
324
+ *
325
+ * The registry is only ever read from a verified private directory: it is
326
+ * resolved first, outside the try, so a registry another user could have
327
+ * planted is never trusted, and an unsafe temp area (a directory above the
328
+ * run directory) fails the mutant run loudly instead.
135
329
  */
136
330
  private loadRegistryFile;
137
331
  /**
@@ -167,9 +361,24 @@ export declare class BunTestRunner implements TestRunner {
167
361
  */
168
362
  private buildTestsFromInspector;
169
363
  /**
170
- * Run all tests (dry run)
364
+ * Run all tests (dry run). Stryker always passes `options`; only its
365
+ * `coverageAnalysis` is read (to judge missing coverage, see
366
+ * checkCoverageData), falling back to the Stryker options' value. bun.timeout,
367
+ * not `options.timeout` (dryRunTimeoutMinutes), bounds the child.
171
368
  */
172
- dryRun(): Promise<DryRunResult>;
369
+ dryRun(options?: DryRunOptions): Promise<DryRunResult>;
370
+ /**
371
+ * The dry run's coverageAnalysis: Stryker's DryRunOptions value, else the
372
+ * Stryker options' value. Extracted to keep dryRun()'s complexity under the
373
+ * lint threshold.
374
+ */
375
+ private resolveCoverageAnalysis;
376
+ /**
377
+ * Emit the single post-drain `warn` iff {@link collectAbnormalDrainProblems}
378
+ * finds anything; a healthy dry run logs nothing at warn. Extracted from
379
+ * dryRun() to keep its complexity under the lint threshold.
380
+ */
381
+ private warnOnAbnormalDrainData;
173
382
  /**
174
383
  * Post-child-exit dry-run pipeline: collect/remap coverage, build tests
175
384
  * from inspector data, sort them for incremental-mode determinism, run the
@@ -183,6 +392,43 @@ export declare class BunTestRunner implements TestRunner {
183
392
  */
184
393
  private buildGatedDryRunResult;
185
394
  /**
395
+ * Judge the dry run's mutant coverage before it is handed to Stryker.
396
+ *
397
+ * Stryker treats `mutantCoverage: undefined` as "no coverage analysis": every
398
+ * mutant then runs the FULL suite (mutant-test-planner's no-coverage branch),
399
+ * with no message saying why. The coverage preload writes the coverage file in
400
+ * its final afterAll on every dry run — even one that covered nothing writes a
401
+ * line with empty perTest/static — so a dry run that completed without one
402
+ * means the preload never ran, could not write (it logs a `[Stryker Coverage]`
403
+ * line on the child's stderr), or the child exited before that afterAll.
404
+ *
405
+ * - coverageAnalysis 'perTest': the user asked for per-test coverage, and
406
+ * silently running the full suite per mutant can turn a run of minutes into
407
+ * hours — fail the dry run (Error), naming the file and likely causes.
408
+ * 'all'/'off' remain available to run without it.
409
+ * - 'all' (or unknown): warn with the same explanation; the run is correct, only slower.
410
+ * - 'off': Stryker wants no coverage; say nothing.
411
+ * A dry run with failed tests is left alone: Stryker stops on those anyway,
412
+ * and its failed-test report is the more useful message.
413
+ *
414
+ * When coverage exists but covers no mutant at all, every mutant will be
415
+ * NoCoverage (Stryker's executeNoCoverage) — warn, since that is a legitimate
416
+ * outcome only when the tests really never touch the mutated files.
417
+ *
418
+ * `[Stryker Coverage]` diagnostics from the preload are otherwise dropped on a
419
+ * green run (the child's stderr is only shown on failure), so they are
420
+ * surfaced at warn here, or folded into the missing-coverage message.
421
+ */
422
+ private checkCoverageData;
423
+ /**
424
+ * Warn when a completed dry run used more than {@link DRY_RUN_TIMEOUT_WARN_RATIO}
425
+ * of bun.timeout. bun.timeout now governs only the dry run (mutant runs follow
426
+ * Stryker's per-mutant timeout), so this is the one place a too-small value
427
+ * bites: the next, slightly slower dry run is killed. Called once, from the
428
+ * Complete path of the single dry run.
429
+ */
430
+ private warnOnTightDryRunTimeout;
431
+ /**
186
432
  * Build the in-memory test name cache and base-name index, then atomically
187
433
  * persist them — together with the exact-name testNameIndex from
188
434
  * buildTestsFromInspector — to a well-known file so other worker processes
@@ -194,6 +440,12 @@ export declare class BunTestRunner implements TestRunner {
194
440
  */
195
441
  private buildAndPersistTestRegistry;
196
442
  /**
443
+ * Warn that the dry-run registry could not be written. The registry also carries
444
+ * Stryker's testFiles selection, so when one is active the warning adds that other
445
+ * workers will not see it and fall back to bun.testFiles or auto-discovery.
446
+ */
447
+ private warnRegistryWriteFailed;
448
+ /**
197
449
  * Lossy-visibility warns for a mutant run's --test-name-pattern.
198
450
  *
199
451
  * Bun exits 0 on a PARTIAL pattern miss (verified live, bun 1.3.14),
@@ -208,6 +460,28 @@ export declare class BunTestRunner implements TestRunner {
208
460
  */
209
461
  mutantRun(options: MutantRunOptions): Promise<MutantRunResult>;
210
462
  /**
463
+ * Recognise a testFilter that is a list of test FILES rather than test ids.
464
+ *
465
+ * Stryker core's own `testFiles` option (9.6+, also 10) makes the mutant
466
+ * planner give static and no-coverage mutants `testFilter =
467
+ * project.testFiles.map(sandbox.sandboxFileFor)` — absolute paths of test files
468
+ * inside the sandbox (mutant-test-planner.js, verified on 10.0.0) — instead of
469
+ * undefined. Treated as ids they build a --test-name-pattern that matches
470
+ * nothing, forcing a full-suite retry whose deadline kill is then (wrongly)
471
+ * scored as an inconclusive Error. They are the opposite of covering tests:
472
+ * Stryker sized the timeout for exactly these files, so they run as given.
473
+ *
474
+ * Every entry must pass all of: not a known test id (the dry-run registry
475
+ * wins), ends in a test-file suffix, and names an existing regular file
476
+ * (resolved against the cwd when relative). One failing entry — or an empty
477
+ * filter — means this is an ordinary id filter and the answer is undefined.
478
+ * The checks are ordered so a normal id filter costs no I/O.
479
+ *
480
+ * @returns The distinct files, sorted, as Stryker gave them; undefined when
481
+ * the filter is not a file list
482
+ */
483
+ private resolveTestFileFilter;
484
+ /**
211
485
  * Spawn bun for a mutant run and interpret the result. Extracted from
212
486
  * mutantRun so that a --test-name-pattern which matched 0 tests can retry
213
487
  * once with the full suite (testNamePattern undefined) while reusing the
@@ -215,19 +489,76 @@ export declare class BunTestRunner implements TestRunner {
215
489
  * killedBy resolution — avoiding both a false Killed and redundant setup.
216
490
  * The retry always recurses with testNamePattern undefined, so the retry
217
491
  * gate's first conjunct is false on that call: recursion is bounded to
218
- * depth 1 by construction, never a retry-of-a-retry.
492
+ * depth 1 by construction, never a retry-of-a-retry. The retry spends what is
493
+ * left of the same deadline, because Stryker's timer covers both spawns.
219
494
  */
220
495
  private executeMutantRun;
221
496
  /**
497
+ * Count a spawn that had covering tests but no pattern: it runs the whole suite instead of
498
+ * just those tests, because the pattern was too long for argv or because this is the retry
499
+ * of a zero-match pattern. A mutant gets at most one such spawn (the retry never retries),
500
+ * so this counts mutants.
501
+ */
502
+ private countFullSuiteFallback;
503
+ /**
504
+ * The verdict for a mutant run that ran away — it exceeded Stryker's hit limit,
505
+ * or the runner had to kill it — or undefined for a run that ended on its own.
506
+ */
507
+ private classifyRunawayMutantRun;
508
+ /**
509
+ * Error result for a full-suite fallback run killed at the limit derived from
510
+ * Stryker's per-mutant timeout — see classifyRunawayMutantRun.
511
+ */
512
+ private buildInconclusiveFallbackTimeout;
513
+ /**
222
514
  * Build the MutantRunResult for a killed mutant (non-zero exit code).
223
515
  * Handles runtime error detection and killedBy resolution.
224
516
  */
225
517
  private buildMutantKilledResult;
226
518
  /**
227
- * Check if the process failed due to a runtime error (no tests ran).
228
- * Returns a MutantRunResult if this is a runtime error, or null to continue.
519
+ * Error result for a mutant run whose `bun test` child died from a signal
520
+ * without attributable failing-test evidence — see buildMutantKilledResult.
521
+ * Logged at warn (with the output head, like the unattributable-kill path) so
522
+ * a crashing suite is visible rather than silently scored.
523
+ */
524
+ private buildSignalErrorResult;
525
+ /**
526
+ * Classify a non-zero, non-signal, non-timeout mutant run in which no
527
+ * individual test reported a failure. Returns an Error result when there is
528
+ * no evidence the mutant was detected, or null to let the caller score it
529
+ * Killed (with an empty killedBy, since no single test failed).
530
+ *
531
+ * Killed needs evidence that the suite failed, and bun's summary is that
532
+ * evidence: a non-zero ' N fail' (or 'Bailed out after N failures') or
533
+ * ' N error' count. That is exactly what bun prints when a test file cannot
534
+ * load — its import graph throws (TypeError, ReferenceError, …), a source or
535
+ * test file no longer parses, a describe body throws — as an "# Unhandled
536
+ * error between tests" block with no `(fail)` line. Verified on bun 1.4.2: a
537
+ * source module that throws at import gives ' 1 fail' + ' 1 error'; a
538
+ * describe body that throws gives ' 0 fail' + ' 1 error'; under --bail both
539
+ * the throwing import and a source syntax error give 'Bailed out after 1
540
+ * failure'. Stryker's jest and vitest runners score a test file that fails to
541
+ * load as Killed too, and a whole class of mutants (module-level constants,
542
+ * config objects) can only ever be detected this way.
543
+ *
544
+ * Why that is not a false Killed: a load failure in a test FILE and one in a
545
+ * SOURCE file print the same shape, but under mutation only source files are
546
+ * changed, and the dry run — which must pass, and which fails outright on any
547
+ * unattributable fail/error count (see checkDryRunProcessResult and the
548
+ * completeness gate's Signal C) — loaded every one of these files without
549
+ * error. So a load failure seen here was caused by the active mutant. The
550
+ * residual risk is a load failure that depends on which files run together:
551
+ * a targeted run hands bun only the covering tests' files, so a test file
552
+ * that only loads after some other file has run would fail here and not in
553
+ * the dry run. That is a test-isolation defect the same way it is under jest.
554
+ *
555
+ * Error remains for the cases that are no evidence at all: bun's zero-match
556
+ * --test-name-pattern error (a runner pattern gap, not a kill), and a run
557
+ * whose output carries no failure count whatsoever (a missing preload, an
558
+ * unparseable bunfig, a crash that printed no summary). An exit code alone is
559
+ * not evidence that a test caught the mutant.
229
560
  */
230
- private checkRuntimeError;
561
+ private classifyRunWithoutFailedTest;
231
562
  /**
232
563
  * Check for dry run process failures (timeout or non-zero exit).
233
564
  * Returns a DryRunResult to short-circuit if the process failed, or null to proceed.
@@ -249,8 +580,8 @@ export declare class BunTestRunner implements TestRunner {
249
580
  */
250
581
  private formatInspectorFailureDetails;
251
582
  /**
252
- * Diagnostic-only check for the Complete dry-run path: bun reported a failure
253
- * (non-zero exit, or a failed count in its console recap) but nothing in the
583
+ * Diagnostic-only check for the Complete dry-run path: bun's console recap
584
+ * reported a failed count (a non-zero exit always comes with one by this point) but nothing in the
254
585
  * built test results identifies which test failed. This is the observed
255
586
  * incident fingerprint — bun prints e.g. "1 tests failed:" with an empty
256
587
  * recap, the inspector shows no TestStatus.Failed entry, and nothing points
@@ -265,44 +596,28 @@ export declare class BunTestRunner implements TestRunner {
265
596
  /**
266
597
  * Dry-run data-completeness gate.
267
598
  *
268
- * Guards against the inspector event stream silently truncating mid-run
269
- * (observed under CI runner contention): bun's own child-side coverage file
270
- * can be complete while the inspector-derived `executionOrder` is cut off at
271
- * a file boundary, and everything downstream of that (test results, coverage
272
- * attribution) accepted the truncated data silently — a plausible-looking
273
- * but corrupted score, not a loud failure.
599
+ * A dry run may only be reported Complete when every test bun ran, and every
600
+ * per-test coverage key the preload recorded, is accounted for: bun's console
601
+ * summary, the inspector's TestReporter events and the coverage keys must
602
+ * agree EXACTLY (see src/dry-run-completeness.ts for each comparison and the
603
+ * bun behaviour it accounts for). Any unexplained difference fails the dry
604
+ * run (DryRunStatus.Error) with a message naming what was lost, the counts
605
+ * and the likely cause: a Complete run built on lost or merged data would
606
+ * hand Stryker coverage that is silently missing or credited to the wrong
607
+ * tests, and loud failure is preferred to that.
274
608
  *
275
609
  * ONLY evaluated when the run otherwise looks GREEN (zero Failed entries in
276
610
  * the already-built `tests`): an already-failing dry run is handled by
277
611
  * {@link checkDryRunProcessResult} / {@link warnOnUnidentifiedDryRunFailure},
278
- * and this precondition structurally prevents a failing beforeAll (which
279
- * marks the rest of its describe/file Failed) from ever reaching Signal A —
280
- * the incident's own signature was a run that looked completely healthy.
281
- *
282
- * Fires (returns a DryRunStatus.Error result) iff EITHER signal is material:
283
- *
284
- * - Signal A (execution/console shortfall): `consoleTotal` (bun's SUMMARY
285
- * pass+fail counts — deliberately NOT the parser's max(per-line, summary)
286
- * fields, so per-ATTEMPT retry output can never inflate it — see
287
- * ParsedTestResults.summaryPassed/summaryFailed) compared against the
288
- * count of ids in `executionOrder` whose status is neither 'skip' nor
289
- * bun's not-yet-implemented placeholder-test status. Retries do not
290
- * create a shortfall in this direction: empirically (bun 1.3.14), a
291
- * retried test fires ONE TestReporter.start per ATTEMPT for the SAME
292
- * inspector id — so executionOrder, if anything, grows on retries, and
293
- * bun's summary line counts tests, not attempts, either way. A material
294
- * shortfall must clear both an absolute floor and a ratio floor.
295
- *
296
- * - Signal B (orphaned coverage keys): `orphanedKeyCount` (a whole file's
297
- * coverage keys unpaired with any inspector test — see coverage-mapper.ts)
298
- * exceeding a small absolute floor. Deliberately gate-blind for the legacy
299
- * ("test-N") coverage format, which never populates this count — Signal A
300
- * still covers that path since it does not depend on coverage format.
301
- *
302
- * `wasClosedUnexpectedly` is NEVER a standalone trigger — the WS-vs-child-exit
303
- * close race can plausibly be true on a nontrivial fraction of healthy runs —
304
- * it is folded into the Error message only as corroborating context once the
305
- * gate has already fired via Signal A or B.
612
+ * and Stryker stops on its failed tests anyway. That also keeps out hook
613
+ * failures, which bun counts as failures with no inspector events.
614
+ *
615
+ * Besides the data-loss checks, it fails when bun's summary counts failing
616
+ * tests but none of them could be attributed to a test (Signal C, below).
617
+ *
618
+ * `wasClosedUnexpectedly` is NEVER a trigger: bun closes the inspector socket
619
+ * a few ms after the drain acknowledgment on healthy runs. It is added to the
620
+ * message only as context once the gate has already fired.
306
621
  *
307
622
  * @returns A DryRunStatus.Error result if the gate fires, otherwise null.
308
623
  */
@@ -382,10 +697,66 @@ export declare class BunTestRunner implements TestRunner {
382
697
  */
383
698
  private warnUnresolvedKilledBy;
384
699
  /**
700
+ * Log the one-line end summary (at info): this worker's mutant runs by outcome and how many
701
+ * of them ran the full suite as a fallback. Nothing is logged for a worker that ran no
702
+ * mutant, and the tallies restart afterwards so a second dispose() does not repeat the line.
703
+ */
704
+ private logMutantRunSummary;
705
+ /**
385
706
  * Cleanup resources
707
+ *
708
+ * Removes only this worker's own files. The registry, and so the run's private
709
+ * temp directory holding it, is deliberately left in place: Stryker gives a
710
+ * worker no signal that it is the last one, and maxTestRunnerReuse /
711
+ * crash recovery dispose a worker mid-run and start a fresh process that must
712
+ * still find the registry (with concurrency 1, the disposing worker IS the
713
+ * only one, so a "last one out" check would delete it from under its successor).
386
714
  */
387
715
  dispose(): Promise<void>;
388
716
  }
717
+ /** Options for {@link withTestFilesExcludedFromTypeCheck}. */
718
+ export interface TestFilesExcludedFromTypeCheckOptions {
719
+ /** The project directory Stryker runs in (default: `process.cwd()`). */
720
+ cwd?: string;
721
+ }
722
+ /**
723
+ * Point @stryker-mutator/typescript-checker at a copy of the project's tsconfig
724
+ * without the tests, so mutants are type-checked against the code under test only.
725
+ *
726
+ * Reads the config's `tsconfigFile` (default `tsconfig.json`) with the
727
+ * project's own TypeScript and writes `<name>.stryker-checker.json` next to it.
728
+ * That file extends the original and lists as `files` every file of the project
729
+ * except:
730
+ * - test files, by this runner's rules: Bun's naming rules under bunfig's
731
+ * `[test].root`, `bun.testFiles` and Stryker's `testFiles` patterns;
732
+ * - bunfig `[test].preload` scripts;
733
+ * - files that only those (and each other) import, such as test helpers,
734
+ * unless a `mutate` pattern covers them or they shape the types of other
735
+ * files (a global script, or a `declare global` / `declare module "x"`
736
+ * augmentation).
737
+ *
738
+ * A file the remaining code imports still comes in through that import, so the
739
+ * program always compiles as before. Before anything is written the derived
740
+ * program is type-checked once, and the derived file is not used if that finds
741
+ * an error in non-test code that the original program does not have. Returns a
742
+ * copy of `config` with `tsconfigFile` set to the derived file and, when
743
+ * `ignorePatterns` is set, a negation for it appended, so Stryker's sandbox
744
+ * gets it too (Stryker rewrites the `tsconfigFile` chain's paths there).
745
+ *
746
+ * Logs one line per call: `console.info` on success, `console.warn` with the
747
+ * reason on every fallback. Returns `config` itself, writing nothing, when
748
+ * `checkers` does not include `typescript`, typescript cannot be loaded from
749
+ * `cwd`, the tsconfig is missing, has errors or uses project references,
750
+ * includes no test files, would be left with no files at all, leaving the tests
751
+ * out adds type errors, or the derived file cannot be written or belongs to
752
+ * somebody else (it has no generated header).
753
+ *
754
+ * @example
755
+ * // stryker.conf.mjs
756
+ * import { withTestFilesExcludedFromTypeCheck } from '@hughescr/stryker-bun-runner';
757
+ * export default await withTestFilesExcludedFromTypeCheck({ testRunner: 'bun', checkers: ['typescript'] });
758
+ */
759
+ export declare function withTestFilesExcludedFromTypeCheck<T extends PartialStrykerOptions>(config: T, { cwd }?: TestFilesExcludedFromTypeCheckOptions): Promise<T & PartialStrykerOptions>;
389
760
  /**
390
761
  * Configuration options specific to the Bun test runner
391
762
  */
@@ -396,8 +767,11 @@ export interface BunTestRunnerOptions {
396
767
  */
397
768
  bunPath?: string;
398
769
  /**
399
- * Child-process timeout in milliseconds — the maximum wall-clock time that the
400
- * entire `bun test` subprocess is allowed to run before it is killed.
770
+ * Dry-run child-process timeout in milliseconds — the maximum wall-clock time
771
+ * the dry run's `bun test` subprocess may run (plus a fixed 30 s allowance for
772
+ * the coverage drain handshake) before it is killed. Mutant runs follow
773
+ * Stryker's per-mutant `MutantRunOptions.timeout` instead, and fall back to
774
+ * this value only when Stryker supplies none.
401
775
  * @default 10000
402
776
  *
403
777
  * Note: this is distinct from Bun's per-test timeout configured via
@@ -423,14 +797,30 @@ export interface BunTestRunnerOptions {
423
797
  * Stryker's `disableBail` option, so a bail flag configured here would
424
798
  * otherwise silently override that decision.
425
799
  *
800
+ * Flags that would break per-test coverage attribution or the runner's own
801
+ * test selection (`--concurrent`, `--max-concurrency`, `--parallel`,
802
+ * `--test-worker`, `--shard`, `--changed`, `-t`/`--test-name-pattern`,
803
+ * `-u`/`--update-snapshots`, `--pass-with-no-tests`, `--watch`,
804
+ * `--coverage`, `--coverage-reporter`, `--coverage-dir`, `--cwd`,
805
+ * `--inspect`, `--inspect-wait`, `--inspect-brk`), and the flags that re-run
806
+ * tests (`--retry`, `--rerun-each`), make `init()` throw instead of being
807
+ * passed through — see src/utils/bun-args.ts.
808
+ *
809
+ * `--randomize` and `--seed` apply to the dry run only: mutant runs drop them.
810
+ *
811
+ * `--config=<path>` (or `--config <path>` / `-c <path>`) names the bunfig the
812
+ * runner sanitizes and reads `[test].root` from, resolved against the project
813
+ * directory. It is removed from the bun command line, because the runner
814
+ * always passes bun its own sanitized `--config`. Without a path it throws.
815
+ *
426
816
  * @example ['--only', '--verbose']
427
817
  */
428
818
  bunArgs?: string[];
429
819
  /**
430
820
  * Explicit list of test file paths (must be non-empty when provided).
431
- * When provided, BunTestRunner skips auto-discovery (which globs
432
- * `**\/*.test.ts` from the current working directory) and uses exactly this
433
- * list. Useful for restricting mutation testing to a subset, or for callers
821
+ * When provided, BunTestRunner skips auto-discovery (which walks the project
822
+ * the way `bun test` does — `.test`/`_test`/`.spec`/`_spec` files, starting at
823
+ * `[test].root` from bunfig.toml when set) and uses exactly this list. Useful for restricting mutation testing to a subset, or for callers
434
824
  * that run outside Stryker's sandboxed cwd and need to point at a specific
435
825
  * file set. Relative paths resolve against the bun subprocess's cwd.
436
826
  *
@@ -451,17 +841,17 @@ export interface BunTestRunnerOptions {
451
841
  * memory-constrained machines, especially at higher Stryker `concurrency`,
452
842
  * since peak memory during a campaign is roughly
453
843
  * `concurrency × per-run suite footprint` (each run is an isolated process
454
- * that exits when it completes — see README "Memory model").
844
+ * that exits when it completes — see "Memory model" in docs/internals.md).
455
845
  * @default false
456
846
  */
457
847
  smol?: boolean;
458
848
  /**
459
849
  * Soft memory ceiling, in bytes, for each `bun test` child's resident set
460
850
  * size (RSS). When set, the child's RSS is polled periodically; a run that
461
- * exceeds this ceiling is killed and reported as a clean timeout/error for
462
- * that one mutant, rather than being left to grow toward system-wide swap
851
+ * exceeds this ceiling is killed and reported as a Timeout for that one
852
+ * mutant, rather than being left to grow toward system-wide swap
463
853
  * exhaustion. This is a polled userspace check, not a kernel-enforced
464
- * limit — see README "Memory containment" for why a true hard ceiling
854
+ * limit — see "Memory containment" in docs/internals.md for why a true hard ceiling
465
855
  * (rlimit/cgroup) isn't used. Omit to disable.
466
856
  */
467
857
  maxChildRss?: number;
@@ -470,6 +860,25 @@ export interface BunTestRunnerOptions {
470
860
  * @default 1000
471
861
  */
472
862
  rssCheckIntervalMs?: number;
863
+ /**
864
+ * Maximum `bun test` spawn nesting depth before the runner refuses to spawn.
865
+ *
866
+ * The runner can spawn `bun test` from inside a `bun test` it already
867
+ * spawned. If a nested run falls back to auto-discovery while its cwd is the
868
+ * project root, it picks up the project's entire suite — including the test
869
+ * that spawned it — and the nesting never terminates. This ceiling makes that
870
+ * finite: a run at or beyond the limit fails with a non-zero exit code
871
+ * instead of spawning. See "Recursion containment" in docs/internals.md.
872
+ *
873
+ * The default of 1 allows the runner's own `bun test` children and nothing
874
+ * deeper, which is right for every project whose tests do not themselves
875
+ * drive this runner. Raise it to 2 only if yours do — note that the value
876
+ * must be set on the runner instance making the *nested* call, since that is
877
+ * where the ceiling is enforced.
878
+ *
879
+ * @default 1
880
+ */
881
+ maxSpawnDepth?: number;
473
882
  }
474
883
  /**
475
884
  * Extended Stryker options with Bun-specific configuration
@@ -553,6 +962,12 @@ export declare const strykerValidationSchema: {
553
962
  description: string;
554
963
  default: number;
555
964
  };
965
+ maxSpawnDepth: {
966
+ type: string;
967
+ minimum: number;
968
+ description: string;
969
+ default: number;
970
+ };
556
971
  };
557
972
  additionalProperties: boolean;
558
973
  };