@hughescr/stryker-bun-runner 1.7.0 → 1.7.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 CHANGED
@@ -219,6 +219,18 @@ What can change after you upgrade:
219
219
  earlier speed, set `'perTest'` (or remove the setting: it is Stryker's default). With
220
220
  `incremental`, run once with `--force` after upgrading; after that, see
221
221
  [coverageAnalysis](#coverageanalysis) for when to use it again.
222
+ - **`.jsx`, `.mts` and `.cts` files are mutated files like the others**
223
+ ([#4](https://github.com/hughescr/stryker-bun-runner/issues/4)). Before, the runner left them out
224
+ of its own list of the files that `mutate` matches, though Stryker mutated them: it never
225
+ imported them before the tests, `bun.alwaysImport` could not name them (and warned that the
226
+ pattern matched none of the files), and nothing named them when no test loaded them. Now the
227
+ module-level code of such a file that your tests load runs before the tests, so results in it
228
+ can change, as for the other files. With `incremental`, run once with `--force` after upgrading.
229
+ - **A file you select as a test is never imported before the tests**, though its name has no test
230
+ suffix and `mutate` matches it (`src/checks.mts` in `bun.testFiles`, say). Before, the runner
231
+ imported it like a source file, and the dry run failed with bun's `Cannot use test during
232
+ preload`. If `bun.alwaysImport` names such a file, it is still not imported, and the runner warns
233
+ about the pattern.
222
234
 
223
235
  ## Upgrading from 1.5
224
236
 
@@ -488,6 +500,13 @@ its mutants are [static mutants](#terms), the same on every run. It does not imp
488
500
  test loads, and a mutant there that no test reaches is NoCoverage. That way a file that fails when
489
501
  it is imported on its own, such as an app's entry point, does not break the dry run.
490
502
 
503
+ The mutated files here are the JavaScript and TypeScript files that `mutate` matches (`.js`,
504
+ `.jsx`, `.mjs`, `.cjs`, `.ts`, `.tsx`, `.mts` and `.cts`), other than declaration files (`.d.ts`,
505
+ `.d.mts`, `.d.cts`) and test files: files whose names end in a test suffix (such as `.test.ts`,
506
+ `_test.mts` or `.spec.jsx`, in any case), and files you select as tests (in `bun.testFiles` or
507
+ Stryker's `testFiles`) whatever their names. A test file is never imported before the tests, even
508
+ when `bun.alwaysImport` names it; the runner warns about a pattern that names only such files.
509
+
491
510
  To find the files, the runner reads the import statements of your test files and preloads
492
511
  (`[test].preload` in your bunfig, and `--preload` in `bun.bunArgs`), with a short `bun` process
493
512
  that runs none of your code. Then:
package/dist/index.d.ts CHANGED
@@ -526,7 +526,19 @@ export declare class BunTestRunner implements TestRunner {
526
526
  private runWithoutCoverage;
527
527
  /** One info line naming bun.alwaysImport and bun.importDiscovery, when set: with coverageAnalysis 'off' neither has an effect. */
528
528
  private noteOptionsWithoutEffect;
529
- /** K: the files of E that bun.alwaysImport keeps, with a warning for each pattern that keeps none. */
529
+ /** The test files this dry run hands bun, and what they expand to: the import scan's roots, and the files E loses. */
530
+ private dryRunTestFiles;
531
+ /**
532
+ * E: the files matched by mutate less the ones this dry run runs as tests (see
533
+ * withoutSelectedTestFiles), which are said at debug. When an entry cannot be expanded
534
+ * (the scan then does not start), the entries themselves are taken: a directory adds only
535
+ * files with a test suffix, which E never holds.
536
+ */
537
+ private withoutTestFilesRun;
538
+ /**
539
+ * K: the files of E that bun.alwaysImport keeps, with a warning for each pattern that keeps
540
+ * none: that it names only test files the dry run runs (`removed`), or that it matches nothing.
541
+ */
530
542
  private selectAlwaysImported;
531
543
  /** `file` relative to the dry run's project directory, as the messages show it (quoted when it must be, see displayName). */
532
544
  private projectPathsOf;
@@ -757,7 +769,8 @@ export declare class BunTestRunner implements TestRunner {
757
769
  private writeRegistry;
758
770
  /**
759
771
  * A new campaign's state for the registry: a new generation, W, and (inPlace only) the
760
- * fingerprint of E; W is written first, under the generation's own name.
772
+ * fingerprint of every file matched by mutate (test files included, as init() computes
773
+ * it in rejectIfCampaignStopped); W is written first, under the generation's own name.
761
774
  */
762
775
  private writeCampaignFiles;
763
776
  /**
package/dist/index.js CHANGED
@@ -1274,9 +1274,14 @@ import path6 from "node:path";
1274
1274
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1275
1275
  import { glob } from "tinyglobby";
1276
1276
 
1277
+ // src/utils/code-files.ts
1278
+ var CODE_EXTENSION_PATTERN = String.raw`(?:[jt]sx?|[mc][jt]s)`;
1279
+ var CODE_FILE_RE = new RegExp(String.raw`\.${CODE_EXTENSION_PATTERN}$`);
1280
+ var DECLARATION_FILE_RE = /\.d\.[mc]?ts$/;
1281
+
1277
1282
  // src/utils/test-name-pattern.ts
1278
1283
  var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
1279
- var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.(?:[jt]sx?|[mc][jt]s)`;
1284
+ var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.${CODE_EXTENSION_PATTERN}`;
1280
1285
  var TEST_FILE_SUFFIX_RE = new RegExp(`${TEST_FILE_SUFFIX_PATTERN}$`, "i");
1281
1286
  var dedupSuffixRe = / \[\d+\]$/;
1282
1287
  var metaRe = /[.*+?^${}()|[\]\\/]/g;
@@ -1336,13 +1341,24 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
1336
1341
  ignore: negativePatterns,
1337
1342
  expandDirectories: false
1338
1343
  });
1339
- const sourceFileRe = /\.(?:tsx?|[cm]?js)$/;
1340
- const dtsRe = /\.d\.[cm]?ts$/;
1341
- const filtered = paths.filter((p) => sourceFileRe.test(p) && !dtsRe.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1344
+ const filtered = paths.filter((p) => CODE_FILE_RE.test(p) && !DECLARATION_FILE_RE.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1342
1345
  const resolved = filtered.map((p) => path6.resolve(p));
1343
1346
  resolved.sort((a, b) => a.localeCompare(b));
1344
1347
  return resolved;
1345
1348
  }
1349
+ async function withoutSelectedTestFiles(eager, testFiles, resolve = realpath2) {
1350
+ if (testFiles.length === 0) {
1351
+ return { kept: [...eager], removed: [] };
1352
+ }
1353
+ const real = async (files) => Promise.all(files.map(async (file) => resolve(file).catch(() => file)));
1354
+ const [eagerReal, testReal] = await Promise.all([real(eager), real(testFiles)]);
1355
+ const tests = new Set([...testFiles, ...testReal]);
1356
+ const isTest = eager.map((file, index) => tests.has(file) || tests.has(eagerReal[index]));
1357
+ return {
1358
+ kept: eager.filter((_file, index) => !isTest[index]),
1359
+ removed: eager.filter((_file, index) => isTest[index])
1360
+ };
1361
+ }
1346
1362
  function resolvePreloadTemplate(moduleDir) {
1347
1363
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1348
1364
  if (isBundled) {
@@ -4687,6 +4703,7 @@ function nonEmptyString(value) {
4687
4703
  var SAVE_TIME_LIMIT_MS = 5000;
4688
4704
  var OUTPUT_FILE_HINT = "To save the full output of the bun test process when this happens, set the bun.dryRunOutputFile option to a file path in your Stryker configuration and run again.";
4689
4705
  var REGISTRY_FILE = "registry.json";
4706
+ var NO_TEST_FILES = { entries: undefined, expanded: undefined };
4690
4707
 
4691
4708
  class WriteFailure extends Error {
4692
4709
  file;
@@ -5449,12 +5466,13 @@ ${stack}` : baseFailureMessage;
5449
5466
  this.applyDryRunTestFiles(options);
5450
5467
  this.logger.debug("Running dry run with inspector-based coverage collection...");
5451
5468
  const cwd = process.cwd();
5452
- const eager = this.cachedEagerModules ?? [];
5469
+ const matched = this.cachedEagerModules ?? [];
5453
5470
  const launchContext = {
5454
5471
  options,
5455
5472
  coverageAnalysis,
5456
5473
  cwd,
5457
- eager,
5474
+ eager: matched,
5475
+ matched,
5458
5476
  runDir: this.tempDir ?? tmpdir2(),
5459
5477
  startedAt,
5460
5478
  profile,
@@ -5467,8 +5485,10 @@ ${stack}` : baseFailureMessage;
5467
5485
  if (coverageAnalysis === "off") {
5468
5486
  return this.runWithoutCoverage(launchContext);
5469
5487
  }
5470
- const always = this.selectAlwaysImported(eager, cwd);
5471
- const ctx = { ...launchContext, always };
5488
+ const tests = matched.length === 0 ? NO_TEST_FILES : await this.dryRunTestFiles(cwd);
5489
+ const { eager, removed } = await this.withoutTestFilesRun(launchContext, tests);
5490
+ const always = this.selectAlwaysImported(eager, removed, cwd);
5491
+ const ctx = { ...launchContext, eager, always, tests };
5472
5492
  const legacy = legacyReason(eager, always);
5473
5493
  if (legacy !== null) {
5474
5494
  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");
@@ -5502,10 +5522,31 @@ ${stack}` : baseFailureMessage;
5502
5522
  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
5523
  }
5504
5524
  }
5505
- selectAlwaysImported(eager, cwd) {
5525
+ async dryRunTestFiles(cwd) {
5526
+ const { testFiles } = await this.dryRunFiles(cwd);
5527
+ return { entries: testFiles, expanded: testFiles === undefined ? undefined : await expandTestFileEntries(testFiles, cwd, this.logger) };
5528
+ }
5529
+ async withoutTestFilesRun(ctx, tests) {
5530
+ const { expanded } = tests;
5531
+ let selected = [];
5532
+ if (expanded !== undefined) {
5533
+ selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path15.resolve(ctx.cwd, entry));
5534
+ }
5535
+ const split = await withoutSelectedTestFiles(ctx.matched, selected);
5536
+ if (split.removed.length > 0) {
5537
+ this.logger.debug("Dry run: %d file(s) matched by mutate are test files the dry run runs, so they are never imported before the tests: %s", split.removed.length, split.removed.map((file) => shownPath(file, ctx.cwd)).join(", "));
5538
+ }
5539
+ return { eager: split.kept, removed: split.removed };
5540
+ }
5541
+ selectAlwaysImported(eager, removed, cwd) {
5506
5542
  const selection = selectAlways(eager, this.alwaysImport, cwd);
5507
5543
  for (const pattern of selection.unmatched) {
5508
- this.logger.warn("bun.alwaysImport pattern %s matches none of the %d files matched by mutate", JSON.stringify(pattern), eager.length);
5544
+ const tests = selectAlways(removed, [pattern], cwd).files;
5545
+ if (tests.length > 0) {
5546
+ this.logger.warn("bun.alwaysImport pattern %s matches only test files the dry run runs (%s), and a test file is never imported before the tests", JSON.stringify(pattern), listText(tests.map((file) => shownPath(file, cwd))));
5547
+ } else {
5548
+ this.logger.warn("bun.alwaysImport pattern %s matches none of the %d files matched by mutate", JSON.stringify(pattern), eager.length);
5549
+ }
5509
5550
  }
5510
5551
  return selection.files;
5511
5552
  }
@@ -5553,15 +5594,14 @@ ${stack}` : baseFailureMessage;
5553
5594
  }
5554
5595
  }
5555
5596
  async importScanInput(ctx) {
5556
- const { testFiles } = await this.dryRunFiles(ctx.cwd);
5557
- if (testFiles === undefined) {
5597
+ const { expanded } = ctx.tests;
5598
+ if (expanded === undefined) {
5558
5599
  return { problem: "the dry run hands bun no list of test files (bun finds them itself), so the runner cannot name the test files to scan" };
5559
5600
  }
5560
5601
  const launch = scanLaunchArguments(this.bunArgs ?? [], { ...process.env, ...this.env }, ctx.cwd);
5561
5602
  if ("problem" in launch) {
5562
5603
  return launch;
5563
5604
  }
5564
- const expanded = await expandTestFileEntries(testFiles, ctx.cwd, this.logger);
5565
5605
  if ("problem" in expanded) {
5566
5606
  return expanded;
5567
5607
  }
@@ -5902,7 +5942,7 @@ ${outputLine}`;
5902
5942
  const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
5903
5943
  ctx.profile?.at("coverageChecked");
5904
5944
  const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
5905
- const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, eager: ctx.eager } : undefined;
5945
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched } : undefined;
5906
5946
  const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
5907
5947
  ctx.profile?.at("registryWritten");
5908
5948
  if (unpublished !== undefined) {
@@ -6317,7 +6357,7 @@ ${preloadLines.join(`
6317
6357
  generation,
6318
6358
  watchList: [...watched],
6319
6359
  watchListFile,
6320
- fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.eager)
6360
+ fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.matched)
6321
6361
  };
6322
6362
  if (watchListFile !== null) {
6323
6363
  const file = path15.join(runDir, watchListFile);
@@ -4,6 +4,12 @@ import { readFileSync, realpathSync, statSync } from "fs";
4
4
  import { createRequire, isBuiltin } from "module";
5
5
  import path from "path";
6
6
  import { pathToFileURL } from "url";
7
+
8
+ // src/utils/code-files.ts
9
+ var CODE_EXTENSION_PATTERN = String.raw`(?:[jt]sx?|[mc][jt]s)`;
10
+ var CODE_FILE_RE = new RegExp(String.raw`\.${CODE_EXTENSION_PATTERN}$`);
11
+
12
+ // src/coverage/import-scan.ts
7
13
  var INSTRUMENTER_GLOBAL_IDIOM = 'globalThis.Math === Math && globalThis || new Function("return this")()';
8
14
 
9
15
  class ScanProblem extends Error {
@@ -533,7 +539,6 @@ function loaderOf(file) {
533
539
  }
534
540
  return /\.[cm]js$/.test(file) ? "js" : "jsx";
535
541
  }
536
- var CODE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/;
537
542
  var JSX_RUNTIME = /^.+\/jsx(?:-dev)?-runtime$/;
538
543
  var DIRECTORY_CONFIGS = ["tsconfig.json", "jsconfig.json"];
539
544
  var RUNTIME = "/jsx-runtime";
@@ -582,6 +587,7 @@ function real(file) {
582
587
  return file;
583
588
  }
584
589
  }
590
+ var SCAN_DEFINE = Object.fromEntries(["process.env.NODE_ENV", "process.env.BUN_ENV", "process.browser"].map((key) => [key, key]));
585
591
 
586
592
  class ImportScan {
587
593
  input;
@@ -594,7 +600,7 @@ class ImportScan {
594
600
  notes = [];
595
601
  tsconfig;
596
602
  transpilers = new Map;
597
- outputScanner = new Bun.Transpiler({ loader: "js" });
603
+ outputScanner = new Bun.Transpiler({ loader: "js", define: SCAN_DEFINE });
598
604
  resolutions = new Map;
599
605
  requires = new Map;
600
606
  configChains = new Map;
@@ -697,7 +703,7 @@ class ImportScan {
697
703
  const key = `${loader} ${autoImportJSX}`;
698
704
  let transpiler = this.transpilers.get(key);
699
705
  if (transpiler === undefined) {
700
- const options = { loader, trimUnusedImports: loader === "ts" || loader === "tsx", autoImportJSX };
706
+ const options = { loader, trimUnusedImports: loader === "ts" || loader === "tsx", autoImportJSX, define: SCAN_DEFINE };
701
707
  try {
702
708
  transpiler = new Bun.Transpiler({ ...options, ...this.tsconfig === undefined ? {} : { tsconfig: this.tsconfig } });
703
709
  } catch (error) {
@@ -790,7 +796,7 @@ class ImportScan {
790
796
  if (importTarget !== requireTarget) {
791
797
  return { kind: "unknown", reason: `${where} resolves differently for import and require` };
792
798
  }
793
- return CODE_FILE.test(importTarget) ? { kind: "follow", file: importTarget } : { kind: "ignore", projectFile: true };
799
+ return CODE_FILE_RE.test(importTarget) ? { kind: "follow", file: importTarget } : { kind: "ignore", projectFile: true };
794
800
  }
795
801
  isProjectCode(target) {
796
802
  return path.isAbsolute(target) && (!this.isPackageCode(target) || this.candidatesAt.has(target));
@@ -890,6 +896,7 @@ if (import.meta.main) {
890
896
  export {
891
897
  INSTRUMENTER_GLOBAL_IDIOM,
892
898
  MACRO_ATTRIBUTE,
899
+ SCAN_DEFINE,
893
900
  ScanProblem,
894
901
  analyseOutput,
895
902
  generatedJsxResolution,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.7.0",
3
+ "version": "1.7.1",
4
4
  "description": "Stryker mutation testing test runner plugin for Bun (bun test), with per-test coverage",
5
5
  "keywords": [
6
6
  "stryker",