@hughescr/stryker-bun-runner 1.6.1 → 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.
package/README.md CHANGED
@@ -30,7 +30,8 @@ coverage so that each mutant runs only the tests that reach it.
30
30
  - [Requirements and compatibility](#requirements-and-compatibility)
31
31
  - [Configuration](#configuration)
32
32
  - [Example with every option](#example-with-every-option) · [bun.bunArgs](#bunbunargs) ·
33
- [Choosing the test files](#choosing-the-test-files) · [Your bunfig.toml](#your-bunfigtoml)
33
+ [Choosing the test files](#choosing-the-test-files) · [Your bunfig.toml](#your-bunfigtoml) ·
34
+ [coverageAnalysis](#coverageanalysis)
34
35
  - [Which mutated files the dry run imports](#which-mutated-files-the-dry-run-imports)
35
36
  - [Tests run twice](#if-the-dry-run-runs-your-tests-twice) ·
36
37
  [A file fails when imported first](#if-a-mutated-file-fails-when-it-is-imported-before-the-tests) ·
@@ -210,6 +211,14 @@ What can change after you upgrade:
210
211
  - **A file that only a package, a worker or a child process loads** is not seen by the runner.
211
212
  List it in `bun.alwaysImport`. If a mutant run later finds that a package loaded such a file, it
212
213
  stops the Stryker run and names the file ([what to do](#if-a-mutant-run-stops-the-campaign)).
214
+ - **`coverageAnalysis: 'all'` and `'off'` now do what Stryker says they do**
215
+ ([coverageAnalysis](#coverageanalysis)). Before, the runner gave Stryker per-test coverage
216
+ whatever the value, so they behaved like `'perTest'`. Now, with `'all'`, each mutant that some
217
+ test reaches runs your whole suite; with `'off'`, every mutant does, and a mutant no test reaches
218
+ is Survived instead of NoCoverage. If you set either one, the mutant runs get slower; to keep the
219
+ earlier speed, set `'perTest'` (or remove the setting: it is Stryker's default). With
220
+ `incremental`, run once with `--force` after upgrading; after that, see
221
+ [coverageAnalysis](#coverageanalysis) for when to use it again.
213
222
 
214
223
  ## Upgrading from 1.5
215
224
 
@@ -425,6 +434,52 @@ lists only failing tests. Your `[test].preload` files run before the runner's ow
425
434
  [preload](#terms). Details:
426
435
  [the sanitized config](docs/internals.md#your-bunfigtoml-the-sanitized-config).
427
436
 
437
+ ### coverageAnalysis
438
+
439
+ **Leave it at `'perTest'`, Stryker's default, unless you have a reason not to.** Stryker's
440
+ `coverageAnalysis` option decides how much the dry run tells Stryker about which tests reach which
441
+ mutants, and so how many tests each mutant runs:
442
+
443
+ | Value | What the runner records in the dry run | What each mutant runs |
444
+ |---|---|---|
445
+ | `'perTest'` (default) | which tests reach each mutant | only the tests that reach it ([static mutants](#terms): every test); a mutant no test reaches is NoCoverage |
446
+ | `'all'` | only whether some test reaches each mutant | every test, for each mutant that some test reaches; a mutant no test reaches is NoCoverage |
447
+ | `'off'` | nothing about mutants | every test, for every mutant; no mutant is NoCoverage (one no test reaches is Survived) |
448
+
449
+ What differs between the three values is which tests each mutant runs. With `'all'` and `'off'`
450
+ each mutant that some test reaches runs your whole suite, so the mutant runs take longer, often
451
+ much longer, and `'off'` runs the whole suite for the mutants no test reaches too. Some results
452
+ differ with `'off'` as well:
453
+
454
+ - No mutant is NoCoverage: one that no test reaches is run against every test, and is Survived.
455
+ - Stryker sets no hit limit, so a mutant that loops forever is stopped by its timeout instead of
456
+ after a number of hits. It is still Timeout, but each one takes the whole timeout to find.
457
+
458
+ **With `incremental`, use `--force` whenever you need fresh results.** With `'all'` or `'off'`
459
+ Stryker cannot see that a new or changed test now reaches a mutant, so it keeps the earlier result
460
+ of a mutant that was Survived or NoCoverage. With these values, run with `--force` (or set
461
+ `incremental: false`) each time you need results that reflect your current tests, not only once.
462
+
463
+ With `'all'`, Stryker may warn that static mutants take most of the time and suggest
464
+ `ignoreStatic`. With `'all'` every mutant that some test reaches is a [static mutant](#terms) to
465
+ Stryker, and Stryker itself rejects `ignoreStatic` with any value but `'perTest'`, so the
466
+ suggestion does not apply. Set `warnings: { slow: false }` in your Stryker config to silence it.
467
+
468
+ `'off'` is also the simplest dry run: one run of your tests, with no mutated file imported first and
469
+ no coverage recorded, so `bun.alwaysImport` and `bun.importDiscovery` have no effect with it. Use it
470
+ as the way out if per-test tracking ever gets a result wrong, or the dry run fails one of its
471
+ coverage checks and you cannot fix the cause; please also
472
+ [open an issue](https://github.com/hughescr/stryker-bun-runner/issues). Details:
473
+ [coverageAnalysis](docs/internals.md#coverageanalysis).
474
+
475
+ ```javascript
476
+ export default {
477
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
478
+ testRunner: 'bun',
479
+ coverageAnalysis: 'off', // every mutant runs every test
480
+ };
481
+ ```
482
+
428
483
  ## Which mutated files the dry run imports
429
484
 
430
485
  **In the normal case you need to do nothing.** Before the dry run's tests start, the runner imports
@@ -992,7 +1047,9 @@ Every log message: [Log output](docs/internals.md#log-output).
992
1047
  | `Dry run timed out: bun.timeout is <N>ms` (and Stryker reports a timeout) | The dry run outgrew `bun.timeout` plus the 30 s drain handshake allowance. | Raise `bun.timeout` above your full suite's run time. |
993
1048
  | `Bun test process failed with exit code <N>` or `Bun test process terminated by signal <SIGNAL>` | Bun exited abnormally with no failing test (a missing module, a crash). The message includes stderr. | Fix what the stderr shows. |
994
1049
  | `stryker-bun-runner: dry run data-completeness check failed — <problems>` | Usually something in your suite: a test or hook that calls `process.exit`, an error raised outside any test (the message then shows bun's `Unhandled error between tests` blocks), or a test file that fails to load (an unresolvable import, say); the problems listed name it. Otherwise test events were lost on a heavily loaded machine. | The message is bounded; its last line says which option to set (`bun.dryRunOutputFile`) to save everything bun printed on the next run, or, if you set it, names the file it was saved to: open that first. Fix the cause in your suite; otherwise re-run, and report it if it recurs. If the message names a module of yours from a stack frame in one of bun's error blocks, the runner imported that module before any test ran: see [If a mutated file fails when it is imported before the tests](#if-a-mutated-file-fails-when-it-is-imported-before-the-tests). A named module alone does not prove that it caused the error: the message names it only because a stack frame points at it. `Cannot call test() after the test run has completed` (or the same for a hook) means bun had already ended that test file's run when the call was made, so tests registered from that point were not run. See [the completeness gate](docs/internals.md#the-completeness-gate). |
995
- | `stryker-bun-runner: the dry run produced no mutant coverage data` | The coverage preload never ran, could not write, or the process exited before its final `afterAll` (a test calls `process.exit`). An error with `coverageAnalysis: 'perTest'`, a warning with `'all'`. | Fix the cause the message names, or set `coverageAnalysis` to `'all'` or `'off'` to run without per-test coverage. |
1050
+ | `stryker-bun-runner: the dry run produced no mutant coverage data` | The coverage preload never ran, could not write, or the process exited before its final `afterAll` (a test calls `process.exit`). An error with `coverageAnalysis: 'perTest'` or `'all'`. | Fix the cause the message names, or set `coverageAnalysis` to `'off'` to run without coverage. |
1051
+ | `stryker-bun-runner: the dry run's record of which test file ran each test, <file>, was missing, unreadable or empty` (a warning, with `coverageAnalysis: 'off'`) | The same causes as the row above. Each test is then named after the file bun reports for it, so a test that a shared helper file defines is credited to that file. | Fix the cause the message names. |
1052
+ | `stryker-bun-runner: cannot write <file> (<error>), so <registry> still holds an earlier dry run's test names, ...` | The dry run could not replace the file that hands its test names to the other workers, and an earlier run's copy is still there. | Check the temporary directory (space, permissions; see [Temporary files](docs/internals.md#temporary-files)), or remove the file it names, and re-run. |
996
1053
  | `stryker-bun-runner: the first run of the dry run (a plain run of the tests, with no mutated file imported first) did not complete cleanly: <reasons>. The second run was not made.` (or the second and third run, after a discarded one), followed by bun's own output | The [plain run](#terms) of your tests failed. A test that passed only because earlier versions imported a file before the tests fails here. | See [If the first, plain run of the tests fails](#if-the-first-plain-run-of-the-tests-fails). |
997
1054
  | `stryker-bun-runner: <file> was loaded during the second run of the dry run (<where>) but not during the first, so the runner had not imported it before the tests. Add it to bun.alwaysImport. No mutant was scored.` | The plain run did not load the file, but the dry run proper loaded it after the runner's imports, so the two runs did not run the same code. | See [If a test loads a mutated file late](#if-a-test-loads-a-mutated-file-late). |
998
1055
  | `stryker-bun-runner: <n> mutants in <files> (ids <ids>) were reached when the tests ran on their own, and not reached when the <m> files the tests load were imported first, in the second run.` (the message goes on to list the files left out) | The plain run reached mutants that the dry run proper, with the tests' files imported first, did not. Either module-level code depends on a file that was left out of the imports, or the tests do not run the same code every time. | Add the left-out file that the message names to `bun.alwaysImport`, or set `bun.alwaysImport: 'all'`. If you use `--randomize`, also give a `--seed`. |
@@ -1048,7 +1105,7 @@ also fails; see [Inspector diagnostics](docs/internals.md#inspector-diagnostics)
1048
1105
  | `A mutant run could not use its watch list (<problem>), so it could not check for files the dry run missed; its result stands.` | The runner could not read the list of mutated files that the dry run left out, so this mutant run could not check whether a test loaded one of them. | Check the temporary directory; re-run if it recurs. |
1049
1106
  | `Could not write the abort marker in <dir> (<error>)` | A mutant run found a file that the dry run missed (the message above it), but the runner could not save the note that stops the rest of the Stryker run, so the run may go on. | Treat the run's results as incomplete; fix the temporary directory and act on the message above it. |
1050
1107
  | Many mutants Timeout | Stryker's timeout is tight for your suite, or many mutants loop forever. Infinite loops stopped by the hit limit carry the reason `Hit limit reached (count/limit)`: open the mutant in the HTML report, or read `statusReason` in Stryker's JSON report. | For the others, raise `timeoutMS` or `timeoutFactor`. |
1051
- | Every mutant runs the whole suite | No per-test coverage: `coverageAnalysis` is not `'perTest'`, or coverage was missing. | Use `'perTest'` and check the dry-run warnings. |
1108
+ | Every mutant runs the whole suite | No per-test coverage: `coverageAnalysis` is `'all'` or `'off'` ([coverageAnalysis](#coverageanalysis)). | Use `'perTest'`. |
1052
1109
  | The score changed after upgrading this plugin | Scoring has changed over time (for example, a crash without a matching failing test is now Error, and a test file that a mutant stops from loading is Killed). | Expected. See [Upgrading: the dry run imports only what your tests load](#upgrading-the-dry-run-imports-only-what-your-tests-load), [Upgrading from 1.5](#upgrading-from-15), [Upgrading from 1.4](#upgrading-from-14), [How results are scored](#how-results-are-scored), and the [commit history](https://github.com/hughescr/stryker-bun-runner/commits/main) for what changed. |
1053
1110
 
1054
1111
  ## Limitations
package/dist/index.d.ts CHANGED
@@ -482,8 +482,8 @@ export declare class BunTestRunner implements TestRunner {
482
482
  private buildTestsFromInspector;
483
483
  /**
484
484
  * Run all tests (dry run). Stryker always passes `options`; its
485
- * `coverageAnalysis` is read (to judge missing coverage, see
486
- * checkCoverageData), falling back to the Stryker options' value, and its
485
+ * `coverageAnalysis` decides what coverage the dry run collects and returns
486
+ * (see executeDryRun), falling back to the Stryker options' value, and its
487
487
  * `timeout` (dryRunTimeoutMinutes) only to warn when another run of the tests
488
488
  * might not fit (M-budget). bun.timeout bounds each child.
489
489
  */
@@ -505,8 +505,27 @@ export declare class BunTestRunner implements TestRunner {
505
505
  *
506
506
  * Every published run is earlier versions' inspected run with its result held back
507
507
  * until the rules pass; nothing is persisted before that ({@link publishDryRun}).
508
+ *
509
+ * With coverageAnalysis 'off' none of that applies: Stryker gets no coverage, so one
510
+ * plain inspected run of the tests ({@link runWithoutCoverage}). 'all' takes the
511
+ * same steps as 'perTest' and hands Stryker only which mutants were reached
512
+ * ({@link reachedOnly}).
508
513
  */
509
514
  private executeDryRun;
515
+ /**
516
+ * The dry run for coverageAnalysis 'off': Stryker then runs every test against every
517
+ * mutant and uses no coverage, so nothing the import list, the scan or the plain run
518
+ * would establish is used. One inspected run of the tests, with nothing imported first
519
+ * (bun.alwaysImport is not evaluated). The preload still records a key per test start,
520
+ * with no hit (coverageKeysOnly): that is how a test is credited to the test file that
521
+ * ran it, as with 'perTest', when bun's inspector reports the file of a shared helper
522
+ * that defined it; the completeness gate compares those keys too. Its campaign
523
+ * watches no file: with every test run for every mutant there is no coverage plan that
524
+ * a file the dry run missed could leave incomplete.
525
+ */
526
+ private runWithoutCoverage;
527
+ /** One info line naming bun.alwaysImport and bun.importDiscovery, when set: with coverageAnalysis 'off' neither has an effect. */
528
+ private noteOptionsWithoutEffect;
510
529
  /** K: the files of E that bun.alwaysImport keeps, with a warning for each pattern that keeps none. */
511
530
  private selectAlwaysImported;
512
531
  /** `file` relative to the dry run's project directory, as the messages show it (quoted when it must be, see displayName). */
@@ -609,7 +628,7 @@ export declare class BunTestRunner implements TestRunner {
609
628
  /**
610
629
  * Hand Stryker a published run's result: persist the registry (for a green run with the
611
630
  * timeout correction and the campaign: a new generation, the watch list W of the files E
612
- * outside L and `seen`) and give the warnings of a completed run, then return it. Only
631
+ * outside L and `seen`, none with coverageAnalysis 'off') and give the warnings of a completed run, then return it. Only
613
632
  * a Complete result has anything to persist; any other is returned as it is. A run whose
614
633
  * watch list cannot be published with its registry is an Error instead.
615
634
  *
@@ -662,24 +681,30 @@ export declare class BunTestRunner implements TestRunner {
662
681
  * means the preload never ran, could not write (it logs a `[Stryker Coverage]`
663
682
  * line on the child's stderr), or the child exited before that afterAll.
664
683
  *
665
- * - coverageAnalysis 'perTest': the user asked for per-test coverage, and
684
+ * - coverageAnalysis 'perTest' or 'all': the user asked for coverage, and
666
685
  * silently running the full suite per mutant can turn a run of minutes into
667
- * hours — fail the dry run (Error), naming the file and likely causes.
668
- * 'all'/'off' remain available to run without it.
669
- * - 'all' (or unknown): warn with the same explanation; the run is correct, only slower.
670
- * - 'off': Stryker wants no coverage; say nothing.
686
+ * hours (with 'all', Stryker would plan as for 'off') — fail the dry run
687
+ * (Error), naming the file and likely causes. 'off' remains available to run
688
+ * without it. A present but empty coverage is not missing.
689
+ * - unknown: warn with the same explanation; the run is correct, only slower.
690
+ * - 'off': the file holds only the test keys that say which test file ran each
691
+ * test (see runWithoutCoverage); without it a test a shared helper defines is
692
+ * credited to the helper's file, so warn, and go on.
671
693
  * A dry run with failed tests is left alone: Stryker stops on those anyway,
672
694
  * and its failed-test report is the more useful message.
673
695
  *
674
696
  * When coverage exists but covers no mutant at all, every mutant will be
675
697
  * NoCoverage (Stryker's executeNoCoverage) — warn, since that is a legitimate
676
- * outcome only when the tests really never touch the mutated files.
698
+ * outcome only when the tests really never touch the mutated files ('off' records
699
+ * no hit, so it is not judged).
677
700
  *
678
701
  * `[Stryker Coverage]` diagnostics from the preload are otherwise dropped on a
679
702
  * green run (the child's stderr is only shown on failure), so they are
680
703
  * surfaced at warn here, or folded into the missing-coverage message.
681
704
  */
682
705
  private checkCoverageData;
706
+ /** {@link checkCoverageData} for a green dry run whose coverage file was missing, unreadable or empty. */
707
+ private missingCoverageResult;
683
708
  /**
684
709
  * Warn when a completed dry run used more than {@link DRY_RUN_TIMEOUT_WARN_RATIO}
685
710
  * of bun.timeout. bun.timeout now governs only the dry run (mutant runs follow
@@ -708,17 +733,20 @@ export declare class BunTestRunner implements TestRunner {
708
733
  * earlier versions wrote.
709
734
  *
710
735
  * A registry that cannot be written is only warned about, as in earlier versions,
711
- * unless the campaign has a watch list: its mutant runs would then not watch what the
712
- * dry run left out, so the failure is returned, as the dry run's Error message.
736
+ * unless the campaign has a watch list (its mutant runs would then not watch what the
737
+ * dry run left out) or an earlier run's registry stays in place (other workers would
738
+ * load it for this campaign): the failure is then returned, as the dry run's Error message.
713
739
  *
714
- * @returns Undefined, or the Error message when a campaign with a watch list could not be published
740
+ * @returns Undefined, or the Error message when a campaign could not be published (see registryWriteFailed)
715
741
  */
716
742
  private buildAndPersistTestRegistry;
717
743
  /**
718
744
  * A registry write failed: the dry run's Error message (M-publish) when the campaign has a
719
- * watch list, naming the file that could not be written; otherwise a warning, as in
720
- * earlier versions (the worker that ran the dry run still has its in-memory copy; other
721
- * workers fall back to raw names and log a warning), and undefined.
745
+ * watch list, naming the file that could not be written. For any other green run (a
746
+ * campaign) it is an Error too when an earlier run's registry is still in place: other
747
+ * workers would load its test names, test-file selection and the rest for this campaign.
748
+ * Otherwise a warning, as in earlier versions (the worker that ran the dry run still has
749
+ * its in-memory copy; other workers fall back to raw names and log a warning), and undefined.
722
750
  */
723
751
  private registryWriteFailed;
724
752
  /**
@@ -996,8 +1024,9 @@ export declare class BunTestRunner implements TestRunner {
996
1024
  *
997
1025
  * Also collects any cross-test async coverage-bleed observations recorded
998
1026
  * by the preload (see {@link emitCoverageBleedWarnings}) and warns about
999
- * them. This method's sole call site is dryRun, so bleed detection is
1000
- * dry-run-only by construction — mutant runs never reach this code.
1027
+ * them, except with coverageAnalysis 'all' and 'off', which hand Stryker no per-test
1028
+ * attribution for a bleed to get wrong ('off' records no hit at all). This method's sole call site is dryRun,
1029
+ * so bleed detection is dry-run-only by construction — mutant runs never reach this code.
1001
1030
  */
1002
1031
  private collectAndRemapCoverage;
1003
1032
  /**
package/dist/index.js CHANGED
@@ -561,6 +561,9 @@ function refuseMessage(problems, incremental) {
561
561
  function unpublishedCampaignMessage(file, cause, watched) {
562
562
  return `stryker-bun-runner: cannot write ${escapeControlCharacters(file)} (${displayError(cause)}). The mutant runs need it to watch the ${count(watched, "file")} matched by mutate that the dry run ` + "neither imported before the tests nor saw load, so the dry run stops here. No mutant was scored. " + "Make the run's temporary directory writable, or set bun.alwaysImport to 'all' to import every mutated file first, as earlier versions did.";
563
563
  }
564
+ function staleRegistryMessage(file, cause, registry) {
565
+ return `stryker-bun-runner: cannot write ${escapeControlCharacters(file)} (${displayError(cause)}), so ${escapeControlCharacters(registry)} still holds an earlier dry run's test names, ` + "test file selection, durations and coverage by test file. The mutant runs of the other workers would use them for this run, so the dry run stops here. No mutant was scored. " + `Make the run's temporary directory writable, or remove ${escapeControlCharacters(registry)}.`;
566
+ }
564
567
  function seconds(ms) {
565
568
  return (ms / 1000).toFixed(1);
566
569
  }
@@ -580,6 +583,7 @@ import picomatch from "picomatch";
580
583
 
581
584
  // src/coverage/preload-logic.ts
582
585
  import { appendFileSync, closeSync, constants, openSync, readFileSync as readFileSync2, realpathSync as realpathSync2, renameSync, unlinkSync, writeSync } from "node:fs";
586
+ var COVERAGE_KEYS_ONLY_ENV = "__STRYKER_COVERAGE_KEYS_ONLY__";
583
587
  var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
584
588
  var PRELOAD_TIMINGS_ENV = "__STRYKER_PRELOAD_TIMINGS__";
585
589
  var PRELOAD_TIMINGS_PREFIX = "[Stryker Timings] ";
@@ -1590,6 +1594,15 @@ function sumHitsByMutant(coverage) {
1590
1594
  }
1591
1595
  return totals;
1592
1596
  }
1597
+ function reachedOnly(coverage) {
1598
+ const reached = {};
1599
+ for (const [mutantId, total] of sumHitsByMutant(coverage)) {
1600
+ if (total > 0) {
1601
+ reached[mutantId] = total;
1602
+ }
1603
+ }
1604
+ return { static: reached, perTest: {} };
1605
+ }
1593
1606
  function restoreHitTotals(rawCoverage, mapped) {
1594
1607
  const rawTotals = sumHitsByMutant(rawCoverage);
1595
1608
  const result = {
@@ -2568,6 +2581,7 @@ function buildChildEnv(options, spawnDepth) {
2568
2581
  __STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
2569
2582
  __STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
2570
2583
  __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
2584
+ [COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
2571
2585
  __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
2572
2586
  [SYNC_TOKEN_ENV]: options.syncToken,
2573
2587
  [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
@@ -3960,7 +3974,14 @@ class SyncServer {
3960
3974
  this.pendingDrainClients.add(ws);
3961
3975
  return;
3962
3976
  }
3963
- this.drainInFlight ??= this.drainHandler();
3977
+ if (this.drainInFlight === null) {
3978
+ const started = this.drainHandler();
3979
+ this.drainInFlight = started;
3980
+ const settled = () => {
3981
+ this.drainInFlight = null;
3982
+ };
3983
+ started.then(settled).catch(settled);
3984
+ }
3964
3985
  const inFlight = this.drainInFlight;
3965
3986
  (async () => {
3966
3987
  try {
@@ -5192,7 +5213,9 @@ class BunTestRunner {
5192
5213
  this.cachedEagerModulesCwd = eagerCwd;
5193
5214
  this.logger.debug("Resolved %d eager modules from mutate globs", this.cachedEagerModules.length);
5194
5215
  }
5195
- await this.rejectIfCampaignStopped(tempDir, this.cachedEagerModules);
5216
+ if (this.coverageAnalysis !== "off") {
5217
+ await this.rejectIfCampaignStopped(tempDir, this.cachedEagerModules);
5218
+ }
5196
5219
  this.preloadScriptPath = await generatePreloadScript({
5197
5220
  tempDir,
5198
5221
  coverageFile: this.coverageFilePath
@@ -5283,9 +5306,11 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
5283
5306
  }
5284
5307
  this.testFileDurations = parseTestFileDurations(parsed.testFileDurations);
5285
5308
  this.setTestFileCoverage(TestFileCoverage.fromJson(parsed.mutantTestFiles));
5286
- this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5287
- const campaign = parseCampaignState(parsed.campaign);
5288
- this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
5309
+ if (this.coverageAnalysis !== "off") {
5310
+ this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
5311
+ const campaign = parseCampaignState(parsed.campaign);
5312
+ this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
5313
+ }
5289
5314
  this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
5290
5315
  } catch (err) {
5291
5316
  const code = err.code;
@@ -5425,13 +5450,11 @@ ${stack}` : baseFailureMessage;
5425
5450
  this.logger.debug("Running dry run with inspector-based coverage collection...");
5426
5451
  const cwd = process.cwd();
5427
5452
  const eager = this.cachedEagerModules ?? [];
5428
- const always = this.selectAlwaysImported(eager, cwd);
5429
- const ctx = {
5453
+ const launchContext = {
5430
5454
  options,
5431
5455
  coverageAnalysis,
5432
5456
  cwd,
5433
5457
  eager,
5434
- always,
5435
5458
  runDir: this.tempDir ?? tmpdir2(),
5436
5459
  startedAt,
5437
5460
  profile,
@@ -5441,6 +5464,11 @@ ${stack}` : baseFailureMessage;
5441
5464
  if (this.inPlace && this.tempDir !== undefined) {
5442
5465
  await removeQuietly(path15.join(this.tempDir, ABORT_MARKER_FILE));
5443
5466
  }
5467
+ if (coverageAnalysis === "off") {
5468
+ return this.runWithoutCoverage(launchContext);
5469
+ }
5470
+ const always = this.selectAlwaysImported(eager, cwd);
5471
+ const ctx = { ...launchContext, always };
5444
5472
  const legacy = legacyReason(eager, always);
5445
5473
  if (legacy !== null) {
5446
5474
  this.logger.debug("Dry run: %s, so the runner imports all of them before the tests, with no import scan", legacy === "empty" ? "mutate matches no file" : "bun.alwaysImport keeps every file mutate matches");
@@ -5457,6 +5485,23 @@ ${stack}` : baseFailureMessage;
5457
5485
  }
5458
5486
  return this.runTwoRuns(ctx, { kind: "scan" });
5459
5487
  }
5488
+ async runWithoutCoverage(ctx) {
5489
+ this.logger.debug("Dry run: coverageAnalysis is 'off', so the runner imports nothing before the tests, records no mutant coverage and runs the tests once");
5490
+ this.noteOptionsWithoutEffect();
5491
+ this.beforeLaunch(ctx);
5492
+ const imported = [];
5493
+ const pass = await this.runInspectedPass(ctx, imported, undefined);
5494
+ return this.publishDryRun(ctx, { ...pass, list: imported, record: undefined, elapsedMs: 0 });
5495
+ }
5496
+ noteOptionsWithoutEffect() {
5497
+ const set = [
5498
+ ...this.alwaysImport === undefined ? [] : ["bun.alwaysImport"],
5499
+ ...this.importDiscovery === undefined ? [] : ["bun.importDiscovery"]
5500
+ ];
5501
+ if (set.length > 0) {
5502
+ this.logger.info("%s %s no effect with coverageAnalysis 'off': its dry run imports no mutated file before the tests", set.join(" and "), set.length === 1 ? "has" : "have");
5503
+ }
5504
+ }
5460
5505
  selectAlwaysImported(eager, cwd) {
5461
5506
  const selection = selectAlways(eager, this.alwaysImport, cwd);
5462
5507
  for (const pattern of selection.unmatched) {
@@ -5856,7 +5901,8 @@ ${outputLine}`;
5856
5901
  const { tests, testNameIndex, testFileCoverage, processResult, parsed, totalElapsedMs } = publication;
5857
5902
  const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
5858
5903
  ctx.profile?.at("coverageChecked");
5859
- const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched: watchList(ctx.eager, launch.list, seen), eager: ctx.eager } : undefined;
5904
+ const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
5905
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, eager: ctx.eager } : undefined;
5860
5906
  const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
5861
5907
  ctx.profile?.at("registryWritten");
5862
5908
  if (unpublished !== undefined) {
@@ -5921,6 +5967,7 @@ ${outputLine}`;
5921
5967
  preloadScript: this.preloadScriptPath,
5922
5968
  dryRunPlan: planFile,
5923
5969
  coverageFile,
5970
+ coverageKeysOnly: coverageAnalysis === "off",
5924
5971
  inspect: true,
5925
5972
  sequentialMode: true,
5926
5973
  syncPort,
@@ -6082,7 +6129,7 @@ exit=%s timedOut=%s
6082
6129
  }
6083
6130
  }
6084
6131
  async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, inspectorState, run, spawnInfo, profile) {
6085
- const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage, rawCoverage, counterKeyToTestName } = await this.collectAndRemapCoverage(run.coverageFile, testHierarchy, executionOrder, profile);
6132
+ const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage, rawCoverage, counterKeyToTestName } = await this.collectAndRemapCoverage(run.coverageFile, testHierarchy, executionOrder, run.coverageAnalysis, profile);
6086
6133
  profile?.at("coverageMapped");
6087
6134
  const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, [...new Set(executionOrder)], parsed, totalElapsedMs, inspectorIdToProjectFile);
6088
6135
  tests.sort((a, b) => a.name.localeCompare(b.name));
@@ -6106,16 +6153,17 @@ exit=%s timedOut=%s
6106
6153
  if (coverageResult) {
6107
6154
  return { result: coverageResult };
6108
6155
  }
6156
+ const off = run.coverageAnalysis === "off";
6157
+ const complete = { status: DryRunStatus.Complete, tests };
6158
+ if (mutantCoverage !== undefined && !off) {
6159
+ complete.mutantCoverage = run.coverageAnalysis === "all" ? reachedOnly(mutantCoverage) : mutantCoverage;
6160
+ }
6109
6161
  return {
6110
- result: {
6111
- status: DryRunStatus.Complete,
6112
- tests,
6113
- mutantCoverage
6114
- },
6162
+ result: complete,
6115
6163
  publication: {
6116
6164
  tests,
6117
6165
  testNameIndex,
6118
- testFileCoverage,
6166
+ testFileCoverage: off ? undefined : testFileCoverage,
6119
6167
  rawCoverage,
6120
6168
  testNames: counterKeyToTestName,
6121
6169
  processResult: result,
@@ -6126,8 +6174,7 @@ exit=%s timedOut=%s
6126
6174
  }
6127
6175
  checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
6128
6176
  const preloadLines = extractPreloadCoverageDiagnostics(stderr);
6129
- const coverageMissing = coverage === undefined && coverageAnalysis !== "off";
6130
- if (!coverageMissing || tests.some((t) => t.status === TestStatus.Failed)) {
6177
+ if (coverage !== undefined || tests.some((t) => t.status === TestStatus.Failed)) {
6131
6178
  if (preloadLines.length > 0) {
6132
6179
  this.logger.warn(`The coverage preload reported problems on the dry-run child's stderr:
6133
6180
  %s`, preloadLines.join(`
@@ -6138,20 +6185,29 @@ exit=%s timedOut=%s
6138
6185
  }
6139
6186
  return null;
6140
6187
  }
6188
+ return this.missingCoverageResult(coverageAnalysis, preloadLines, coverageFile);
6189
+ }
6190
+ missingCoverageResult(coverageAnalysis, preloadLines, coverageFile) {
6191
+ const file = coverageFile ?? "(none configured)";
6141
6192
  const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
6142
- const parts = [
6143
- `stryker-bun-runner: the dry run produced no mutant coverage data — the coverage file ${coverageFile ?? "(none configured)"} was missing, unreadable or empty. ` + "Without it Stryker runs the full test suite for every mutant, which is far slower than running each mutant's covering tests. " + "Likely causes: the coverage preload never ran (check for a [test].preload in bunfig.toml or bun.bunArgs that replaces or bypasses it), " + `${coverageDir} is not writable, or the bun test child exited before its final afterAll hook wrote the file (e.g. a test calls process.exit).`
6144
- ];
6145
- if (coverageAnalysis === "perTest") {
6146
- parts.push("Failing the dry run because coverageAnalysis is 'perTest'; set coverageAnalysis to 'all' or 'off' to run without per-test coverage instead.");
6147
- }
6148
- if (preloadLines.length > 0) {
6149
- parts.push(`Coverage preload diagnostics from the child's stderr:
6193
+ const causes = "Likely causes: the coverage preload never ran (check for a [test].preload in bunfig.toml or bun.bunArgs that replaces or bypasses it), " + `${coverageDir} is not writable, or the bun test child exited before its final afterAll hook wrote the file (e.g. a test calls process.exit).`;
6194
+ const diagnostics = preloadLines.length > 0 ? [`Coverage preload diagnostics from the child's stderr:
6150
6195
  ${preloadLines.join(`
6151
- `)}`);
6196
+ `)}`] : [];
6197
+ if (coverageAnalysis === "off") {
6198
+ const what = `stryker-bun-runner: the dry run's record of which test file ran each test, ${file}, was missing, unreadable or empty, ` + "so each test is named after the file bun reports for it: a test that a shared helper file defines is credited to that file, not to the test file that ran it.";
6199
+ this.logger.warn("%s", [what, causes, ...diagnostics].join(" "));
6200
+ return null;
6152
6201
  }
6153
- const message = parts.join(" ");
6154
- if (coverageAnalysis === "perTest") {
6202
+ const fails = coverageAnalysis === "perTest" || coverageAnalysis === "all";
6203
+ const what = `stryker-bun-runner: the dry run produced no mutant coverage data — the coverage file ${file} was missing, unreadable or empty. ` + "Without it Stryker runs the full test suite for every mutant, which is far slower than running each mutant's covering tests.";
6204
+ const message = [
6205
+ what,
6206
+ causes,
6207
+ ...fails ? [`Failing the dry run because coverageAnalysis is '${coverageAnalysis}'; set coverageAnalysis to 'off' to run without coverage instead.`] : [],
6208
+ ...diagnostics
6209
+ ].join(" ");
6210
+ if (fails) {
6155
6211
  this.logger.error("%s", message);
6156
6212
  return { status: DryRunStatus.Error, errorMessage: message };
6157
6213
  }
@@ -6199,14 +6255,24 @@ ${preloadLines.join(`
6199
6255
  await this.writeRegistry(indexes, testFileCoverage, campaignInput);
6200
6256
  return;
6201
6257
  } catch (error) {
6202
- return this.registryWriteFailed(error, campaignInput?.watched.length ?? 0);
6258
+ return this.registryWriteFailed(error, campaignInput);
6203
6259
  }
6204
6260
  }
6205
- registryWriteFailed(error, watched) {
6261
+ async registryWriteFailed(failure, campaignInput) {
6262
+ const watched = campaignInput?.watched.length ?? 0;
6206
6263
  if (watched > 0) {
6207
- return error instanceof WriteFailure ? unpublishedCampaignMessage(error.file, error.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(error), watched);
6264
+ return failure instanceof WriteFailure ? unpublishedCampaignMessage(failure.file, failure.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(failure), watched);
6208
6265
  }
6209
- this.warnRegistryWriteFailed(errorText(error));
6266
+ if (campaignInput !== undefined && failure instanceof WriteFailure) {
6267
+ const registryPath = path15.join(path15.dirname(failure.file), REGISTRY_FILE);
6268
+ const earlier = await fsPromises3.lstat(registryPath).catch(() => {
6269
+ return;
6270
+ });
6271
+ if (earlier !== undefined) {
6272
+ return staleRegistryMessage(failure.file, failure.message, registryPath);
6273
+ }
6274
+ }
6275
+ this.warnRegistryWriteFailed(errorText(failure));
6210
6276
  return;
6211
6277
  }
6212
6278
  async writeRegistry(indexes, testFileCoverage, campaignInput) {
@@ -6708,7 +6774,7 @@ ${outputLine}`;
6708
6774
  errorMessage
6709
6775
  };
6710
6776
  }
6711
- async collectAndRemapCoverage(coverageFile, testHierarchy, executionOrder, profile) {
6777
+ async collectAndRemapCoverage(coverageFile, testHierarchy, executionOrder, coverageAnalysis, profile) {
6712
6778
  const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
6713
6779
  if (!coverageFile) {
6714
6780
  return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
@@ -6724,7 +6790,9 @@ ${outputLine}`;
6724
6790
  }
6725
6791
  const testFileCoverage = TestFileCoverage.fromPerTest(rawCoverage.perTest);
6726
6792
  const { coverage, inspectorIdToProjectFile, counterKeyToTestName, rawKeyCount, orphanedKeyCount } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
6727
- this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
6793
+ if (coverageAnalysis !== "all" && coverageAnalysis !== "off") {
6794
+ this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
6795
+ }
6728
6796
  return {
6729
6797
  coverage,
6730
6798
  inspectorIdToProjectFile,
@@ -267,6 +267,7 @@ function installLoadSensors(deps) {
267
267
  // src/coverage/preload-logic.ts
268
268
  var PreloadError = Error;
269
269
  var preloadFs = { appendFileSync, closeSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeSync };
270
+ var COVERAGE_KEYS_ONLY_ENV = "__STRYKER_COVERAGE_KEYS_ONLY__";
270
271
  var HIT_LIMIT_TOKEN_ENV = "__STRYKER_HIT_LIMIT_TOKEN__";
271
272
  var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
272
273
  function getPreloadConfig() {
@@ -276,7 +277,8 @@ function getPreloadConfig() {
276
277
  coverageFile: process.env.__STRYKER_COVERAGE_FILE__,
277
278
  activeMutant: process.env.__STRYKER_ACTIVE_MUTANT__,
278
279
  hitLimit: parseHitLimit(process.env.__STRYKER_HIT_LIMIT__),
279
- hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV]
280
+ hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV],
281
+ keysOnly: process.env[COVERAGE_KEYS_ONLY_ENV] === "1"
280
282
  };
281
283
  }
282
284
  function parseHitLimit(raw) {
@@ -428,6 +430,13 @@ function serializeCoverageData(mutantCoverage, lateHits = [], gapTracker) {
428
430
  };
429
431
  return JSON.stringify(data);
430
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
+ }
431
440
  var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
432
441
  function writeCoverageToFile(coverageFile, data) {
433
442
  const line = typeof data === "string" ? data : JSON.stringify(data);
@@ -916,7 +925,7 @@ Object.defineProperty(describe2, "concurrent", { value: describe2, writable: tru
916
925
  Object.defineProperty(test, "concurrent", { value: test, writable: true, configurable: true });
917
926
  Object.defineProperty(it, "concurrent", { value: it, writable: true, configurable: true });
918
927
  var config = getPreloadConfig();
919
- var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken } = config;
928
+ var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken, keysOnly } = config;
920
929
  delete process.env[HIT_LIMIT_TOKEN_ENV];
921
930
  delete process.env[SYNC_TOKEN_ENV];
922
931
  var planFile = process.env[DRY_RUN_PLAN_ENV];
@@ -1019,7 +1028,8 @@ var writeCoverageData = () => {
1019
1028
  if (!shouldCollectCoverage2 || !coverageFile) {
1020
1029
  return;
1021
1030
  }
1022
- const data = serializeCoverageData(strykerGlobal.mutantCoverage, lateHits, gapTracker);
1031
+ const recorded = keysOnly ? testKeysOnly(strykerGlobal.mutantCoverage) : strykerGlobal.mutantCoverage;
1032
+ const data = serializeCoverageData(recorded, keysOnly ? [] : lateHits, gapTracker);
1023
1033
  if (timings) {
1024
1034
  timings["at.coverageFormatted"] = nowEpoch();
1025
1035
  timings["bytes.coverage"] = data.length;
@@ -1033,6 +1043,45 @@ var writeCoverageData = () => {
1033
1043
  console.error(`[Stryker Coverage] Failed to write coverage to ${coverageFile}: ${error instanceof Error ? error.message : String(error)}`);
1034
1044
  }
1035
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
+ };
1036
1085
  if (shouldCollectCoverage2) {
1037
1086
  beforeEach(() => {
1038
1087
  const hookStart = timings ? performance.now() : 0;
@@ -1087,42 +1136,6 @@ if (shouldCollectCoverage2) {
1087
1136
  writeCoverageData();
1088
1137
  lateHits.length = 0;
1089
1138
  writeDryRunRecord();
1090
- if (ws && ws.readyState === WebSocket.OPEN) {
1091
- try {
1092
- await new Promise((resolve) => {
1093
- const wsForDrain = ws;
1094
- const timeout = setTimeout(() => {
1095
- console.warn("[Stryker] Timeout waiting for drain acknowledgment");
1096
- resolve();
1097
- }, DRAIN_ACK_TIMEOUT_MS);
1098
- wsForDrain.onmessage = (event) => {
1099
- if (event.data === "drained") {
1100
- clearTimeout(timeout);
1101
- resolve();
1102
- }
1103
- };
1104
- wsForDrain.onerror = () => {
1105
- clearTimeout(timeout);
1106
- resolve();
1107
- };
1108
- try {
1109
- if (timings) {
1110
- timings["at.drainRequested"] = nowEpoch();
1111
- }
1112
- wsForDrain.send("drain-request");
1113
- } catch {
1114
- clearTimeout(timeout);
1115
- resolve();
1116
- }
1117
- });
1118
- } catch (error) {
1119
- console.warn("[Stryker] Error during drain handshake:", error);
1120
- }
1121
- }
1122
- if (timings) {
1123
- timings["at.drained"] = nowEpoch();
1124
- preloadFs.writeSync(2, formatPreloadTimings(timings));
1125
- }
1126
- ws?.close();
1139
+ await drainAndClose();
1127
1140
  });
1128
1141
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "description": "Stryker mutation testing test runner plugin for Bun (bun test), with per-test coverage",
5
5
  "keywords": [
6
6
  "stryker",