@cosyte/vitest-config 0.1.4 → 0.1.7

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/CHANGELOG.md CHANGED
@@ -1,5 +1,57 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.7
4
+
5
+ ### Patch Changes
6
+
7
+ - 1858905: The package is now published with npm provenance: its `publishConfig` sets `"provenance": true`, so npm shows a provenance statement that ties each release's tarball to the source commit and the workflow run that built it.
8
+ - Updated dependencies [dbc3106]
9
+ - Updated dependencies [c8c11db]
10
+ - Updated dependencies [593195a]
11
+ - Updated dependencies [0c54a26]
12
+ - Updated dependencies [1858905]
13
+ - Updated dependencies [1ba9fe6]
14
+ - Updated dependencies [e447209]
15
+ - @cosyte/script-utils@0.1.15
16
+
17
+ ## 0.1.6
18
+
19
+ ### Patch Changes
20
+
21
+ - ecb933d: Barrels are read, not named. `cosyteVitest` and `cosyteStryker` used to leave every `index.ts` out
22
+ of coverage and mutation testing. They now read each `.ts` file under `src/` (declaration files
23
+ aside) and leave out only a barrel: a file whose every statement is an import that binds names or
24
+ an export of names, with at least one export. So a library's coverage and its default mutate list
25
+ now include:
26
+
27
+ - every `index.ts` that holds any other statement: a function, a class, a constant, a call, a type
28
+ alias, an interface, a side-effect import;
29
+ - every file the reading does not understand, whatever its name.
30
+
31
+ They now leave out a file of nothing but re-exports under any name, not only `index.ts`.
32
+ `DEFAULT_MUTATE` no longer names `index.ts`; `cosyteStryker()` adds a `!` entry for each barrel it
33
+ found. Both take a new `root` option, the directory whose `src/` is read, the working directory by
34
+ default. Tests, declarations, `__fixtures__` and `generated` stay out by name, as before.
35
+
36
+ A library whose `index.ts` holds code measures it for the first time when it adopts this version,
37
+ so its coverage and mutation scores can fall below its floor.
38
+
39
+ `cosyteStryker` now sets `ignoreStatic: true`. A static mutant, in code that runs once when a
40
+ module loads, can be tested only by running every test again; on our HL7 library they were 43% of
41
+ the mutants and about 94% of a full run's time. Ignored mutants are not in the score, so a full
42
+ run's score can move either way, and the ratchet lists an ignored mutant in a pull request's
43
+ changed lines with Stryker's reason. A package whose module-level tables are what it checks passes
44
+ `stryker: { ignoreStatic: false }`.
45
+
46
+ - Updated dependencies [a926e03]
47
+ - @cosyte/script-utils@0.1.10
48
+
49
+ ## 0.1.5
50
+
51
+ ### Patch Changes
52
+
53
+ - 0f9bc66: `cosyte-mutate full` can run in shards. With `COSYTE_MUTATE_SHARD=<k>/<n>` set, it mutates only the files of the config whose 32-bit FNV-1a hash of the path is `k - 1` mod `n`, so every file is in exactly one of the `n` shards, and writes `reports/mutation/shard-<k>-of-<n>.json` and its HTML beside the full report, never `mutation.json`; a shard with no file writes an empty report and exits 0 without starting Stryker, and a malformed value exits 2. With `COSYTE_MUTATE_INCREMENTAL_FILE` set, Stryker keeps its incremental results in that file (`incremental: true`). With neither variable set, a full run is unchanged, and a changed run reads neither. `parseShard`, `fnv1a32`, `filesInShard`, `expandMutate` and `shardReportPath` are exported from `@cosyte/vitest-config/mutate`.
54
+
3
55
  ## 0.1.4
4
56
 
5
57
  ### Patch Changes
package/README.md CHANGED
@@ -86,7 +86,7 @@ gate, which is what stops a well-covered helper directory paying for an untested
86
86
  | `@cosyte/vitest-config/snippets` | the doc/code-agreement harness described under the API below |
87
87
  | `@cosyte/vitest-config/stryker` | `cosyteStryker(options?)`, the shared StrykerJS config |
88
88
  | `@cosyte/vitest-config/mutate` | `runMutate`, the body of the `cosyte-mutate` bin, and its parts |
89
- | `cosyte-mutate` (bin) | `full`, and `changed --base <ref>` |
89
+ | `cosyte-mutate` (bin) | `full`, whole or one shard of it, and `changed --base <ref>` |
90
90
 
91
91
  They are separate subpaths because they are separately adoptable, and importing the config never
92
92
  loads the harness. `extractRunnableSnippets` is the primitive that decides what runs, and it reports
@@ -130,7 +130,7 @@ import { cosyteStryker } from "@cosyte/vitest-config/stryker";
130
130
 
131
131
  const config = cosyteStryker();
132
132
  config.testRunner; // => "vitest"
133
- config.ignoreStatic; // => false
133
+ config.ignoreStatic; // => true
134
134
  config.jsonReporter; // => { fileName: "reports/mutation/mutation.json" }
135
135
  ```
136
136
 
@@ -149,6 +149,41 @@ empty report, so the ratchet can tell "ran, nothing to mutate" from "never ran",
149
149
  `cosyte-mutate` exits 0 when the run finished and 2 when it could not run; it does not judge the
150
150
  score.
151
151
 
152
+ ### A full run in shards
153
+
154
+ A full run of a large library takes hours on one machine, so it can be split across parallel jobs.
155
+ Two variables, read only by `full`, do it:
156
+
157
+ - `COSYTE_MUTATE_SHARD=<k>/<n>` mutates only shard `k` of `n`, and writes `shard-<k>-of-<n>.json`
158
+ in place of the full report.
159
+ - `COSYTE_MUTATE_INCREMENTAL_FILE=<file>` keeps Stryker's incremental results in that file, so a
160
+ later run retests only the mutants whose code or tests changed.
161
+
162
+ ```sh
163
+ COSYTE_MUTATE_SHARD=3/8 COSYTE_MUTATE_INCREMENTAL_FILE=reports/mutation/incremental.json \
164
+ pnpm exec cosyte-mutate full
165
+ ```
166
+
167
+ A shard lists every file the config's `mutate` patterns name under the working directory (never
168
+ inside `node_modules`, `.git` or Stryker's temp directory), and keeps those whose 32-bit FNV-1a hash
169
+ of the path, relative and with forward slashes, is `k - 1` mod `n`. So over shards 1 to `n` every
170
+ file is mutated exactly once, and a file stays in its shard from run to run however many files are
171
+ added elsewhere. The report, `reports/mutation/shard-<k>-of-<n>.json` with its HTML beside it, goes
172
+ where `mutation.json` would, and never as `mutation.json`, so no shard is read as the package's
173
+ score: the shards' reports are merged into one `mutation.json` before `cosyte-ratchet` reads it,
174
+ which is what the weekly mutation workflow in cosyte/.github does. A shard that holds no file writes
175
+ an empty report and exits 0 without starting Stryker. A `COSYTE_MUTATE_SHARD` that is not two whole
176
+ numbers with `1 <= k <= n` exits 2. The incremental file is relative to the working directory and
177
+ reaches Stryker as `incrementalFile`, with `incremental: true`, with or without a shard. Unset or
178
+ empty, neither variable changes anything, and a changed run reads neither.
179
+
180
+ ```ts runnable
181
+ import { filesInShard, fnv1a32 } from "@cosyte/vitest-config/mutate";
182
+
183
+ fnv1a32("src/a.ts") % 2; // => 0
184
+ filesInShard(["src/a.ts", "src/b.ts"], { k: 1, n: 2 }); // => ["src/a.ts"]
185
+ ```
186
+
152
187
  The `/mutate` entry point is the bin's body and the pieces it is built of, for a caller that runs
153
188
  it from its own script. `selectChangedFiles` is the rule a changed run picks its files by:
154
189
 
@@ -166,8 +201,9 @@ picked; // => ["src/a.ts"]
166
201
 
167
202
  ### What the Stryker config sets, and why
168
203
 
169
- `cosyteStryker({ mutate, vitestConfig, stryker })` takes the file list, the Vitest config file, and
170
- any other Stryker option, merged last, so a package can change anything below. What each default is
204
+ `cosyteStryker({ mutate, root, vitestConfig, stryker })` takes the file list, the directory read for
205
+ barrels, the Vitest config file, and any other Stryker option, merged last, so a package can change
206
+ anything below. What each default is
171
207
  and why:
172
208
 
173
209
  | setting | default | why |
@@ -176,12 +212,29 @@ and why:
176
212
  | `vitest.pool` | `forks` | Vitest's own default; Stryker's is threads, where `process.chdir()` throws |
177
213
  | `coverageAnalysis` | `perTest` | each mutant runs only the tests that reach it |
178
214
  | `mutate` | `src/**/*.ts` without tests, barrels, types | the same files `@cosyte/vitest-config` measures coverage over |
179
- | `ignoreStatic` | `false` | static mutants are module-level tables, such as a scanner's patterns: kept |
215
+ | `ignoreStatic` | `true` | a static mutant reruns every test; on a library they are most of a run |
180
216
  | `thresholds.break` | `null` | the floor file decides a drop, not Stryker |
181
217
  | reports | JSON and HTML under `reports/mutation/` | JSON for the ratchet and CI, HTML for a person reading the surviving mutants |
182
218
 
183
- Setting `ignoreStatic: true` makes a run faster and is the override worth arguing about in review: it
184
- drops every mutant in module-level code from the score without an inline reason for any of them.
219
+ A static mutant is one in code that runs once, when a module loads: a table of patterns, a frozen
220
+ map. Stryker can test one only by running every test again, so on a library they take most of a
221
+ run's time: on our HL7 parser, 5,328 of 12,280 mutants were static, and Stryker estimated them at 94%
222
+ of the run. With `ignoreStatic: true` they are left out of the score; coverage still holds every such
223
+ line to having run, and the ratchet lists an ignored mutant in a pull request's changed lines with
224
+ Stryker's reason, so a reviewer sees it. A package whose module-level tables are the thing it checks,
225
+ such as a PHI scanner's patterns, passes `stryker: { ignoreStatic: false }`, and that is the override
226
+ worth arguing about in review.
227
+
228
+ ### Which files are barrels
229
+
230
+ A barrel is a file that holds nothing but re-exports: every statement an import that binds names, or
231
+ an export of names, and at least one export. Coverage and the default mutate list leave barrels out,
232
+ and the rule reads each `.ts` file under `src/` (but declaration files), never its name: an `index.ts`
233
+ that holds a parser is measured, and a file of re-exports with any other name is left out. One
234
+ statement of real code (a declaration, a call, a side-effect import, a type alias) makes a file real
235
+ code, and so does anything the reading does not understand, because a file wrongly called a barrel
236
+ hides code from both gates. Both configs read `src/` under the working directory, or under `root`
237
+ when it is given.
185
238
 
186
239
  ### An exception, and why it needs two comments
187
240
 
@@ -229,7 +282,8 @@ a test fixture's would. Use synthetic data in documentation, as in tests.
229
282
  ### `cosyteVitest(options)`
230
283
 
231
284
  The baseline config: v8 coverage with `text` / `html` / `lcov` / `json-summary` reporters, the standard excludes
232
- (barrels, fixtures, generated code, declarations), and **enabled, gating** per-directory thresholds
285
+ (tests, fixtures, generated code, declarations, and the barrels it finds by reading `src/` under
286
+ `options.root`, the working directory by default), and **enabled, gating** per-directory thresholds
233
287
  at **>= 90**.
234
288
 
235
289
  ### Doc/code agreement: `@cosyte/vitest-config/snippets`
package/index.d.ts CHANGED
@@ -8,6 +8,11 @@ export interface CosyteVitestOptions {
8
8
  coverageThresholds?: Record<string, unknown>;
9
9
  /** Extra Vitest `test` options, merged last. */
10
10
  test?: Record<string, unknown>;
11
+ /**
12
+ * The project root whose `src/` is read for barrels (files that hold nothing but re-exports),
13
+ * which coverage leaves out. Defaults to the working directory.
14
+ */
15
+ root?: string;
11
16
  }
12
17
 
13
18
  /**
package/index.js CHANGED
@@ -1,17 +1,23 @@
1
1
  import { defineConfig } from "vitest/config";
2
2
 
3
+ import { findBarrels } from "./stryker.js";
4
+
3
5
  const GATE = { lines: 90, branches: 90, functions: 90, statements: 90 };
4
6
 
5
7
  /**
6
8
  * Standard Vitest config for `@cosyte/*` packages: v8 coverage with `text`/`html`/`lcov`/`json-summary` reporters,
7
- * the standard excludes (barrels, fixtures, generated, declarations), and **enabled, gating**
8
- * per-directory thresholds at >= 90. List your source subdirectories in `coverageDirs` to get a
9
- * per-directory gate on each (on top of the global gate).
9
+ * the standard excludes (tests, declarations, fixtures, generated code, and the barrels under `src/`),
10
+ * and **enabled, gating** per-directory thresholds at >= 90. List your source subdirectories in
11
+ * `coverageDirs` to get a per-directory gate on each (on top of the global gate).
12
+ *
13
+ * A barrel is a file that holds nothing but re-exports, decided by reading each file under `src/`
14
+ * (see `findBarrels` in `stryker.js`), never by its name: an `index.ts` that holds code is measured.
10
15
  *
11
16
  * @param {object} [opts] - Options.
12
17
  * @param {string[]} [opts.coverageDirs] - `src/<dir>` subdirs to gate per-directory (e.g. `["parser"]`).
13
18
  * @param {Record<string, unknown>} [opts.coverageThresholds] - Extra/override `coverage.thresholds` keys.
14
19
  * @param {Record<string, unknown>} [opts.test] - Extra Vitest `test` options, merged last.
20
+ * @param {string} [opts.root] - The project root whose `src/` is read for barrels; the working directory by default.
15
21
  * @returns {import("vitest/config").UserConfig} The Vitest config.
16
22
  * @example
17
23
  * // vitest.config.ts
@@ -34,10 +40,10 @@ export function cosyteVitest(opts = {}) {
34
40
  exclude: [
35
41
  "**/*.test.ts",
36
42
  "**/*.spec.ts",
37
- "**/index.ts",
38
43
  "**/*.d.ts",
39
44
  "**/__fixtures__/**",
40
45
  "**/generated/**",
46
+ ...findBarrels(opts.root),
41
47
  ],
42
48
  thresholds: { ...GATE, ...perDir, ...(opts.coverageThresholds ?? {}) },
43
49
  },
package/mutate.d.ts CHANGED
@@ -10,6 +10,18 @@ export type ChangeReader = (opts: { base: string; cwd: string }) => {
10
10
  /** The config file a run reads when `--config` names none. */
11
11
  export declare const DEFAULT_CONFIG: "stryker.config.mjs";
12
12
 
13
+ /** The variable a sharded full run reads its share from: `<k>/<n>`. */
14
+ export declare const SHARD_VARIABLE: "COSYTE_MUTATE_SHARD";
15
+
16
+ /** The variable naming the file Stryker reads and writes its incremental results in. */
17
+ export declare const INCREMENTAL_VARIABLE: "COSYTE_MUTATE_INCREMENTAL_FILE";
18
+
19
+ /** One shard of a full run: shard `k` of `n`, from 1. */
20
+ export interface Shard {
21
+ k: number;
22
+ n: number;
23
+ }
24
+
13
25
  /** Thrown for anything that stops a run before Stryker starts. */
14
26
  export declare class MutateUnreadable extends Error {
15
27
  constructor(message: string);
@@ -30,6 +42,31 @@ export declare function selectChangedFiles(input: {
30
42
  patterns: readonly string[];
31
43
  }): string[];
32
44
 
45
+ /**
46
+ * Read `<k>/<n>`, two whole numbers with 1 <= k <= n; null when unset or empty. Throws
47
+ * `MutateUnreadable` on any other value.
48
+ */
49
+ export declare function parseShard(value: string | undefined): Shard | null;
50
+
51
+ /** 32-bit FNV-1a over the UTF-8 bytes of a text: the hash a file's shard is read from. */
52
+ export declare function fnv1a32(text: string): number;
53
+
54
+ /** The files of one shard: those whose `fnv1a32` hash mod `n` is `k - 1`. */
55
+ export declare function filesInShard(files: readonly string[], shard: Shard): string[];
56
+
57
+ /**
58
+ * List the files under `cwd` that the `mutate` patterns name, relative to it, sorted; never inside a
59
+ * `node_modules` or `.git` directory or Stryker's temp directory (default `.stryker-tmp`).
60
+ */
61
+ export declare function expandMutate(input: {
62
+ cwd: string;
63
+ patterns: readonly string[];
64
+ tempDirName?: string;
65
+ }): string[];
66
+
67
+ /** Where a sharded full run writes its JSON report: `shard-<k>-of-<n>.json` beside the full report. */
68
+ export declare function shardReportPath(config: Record<string, unknown>, shard: Shard): string;
69
+
33
70
  /** Where a full run writes its JSON report. */
34
71
  export declare function fullReportPath(config: Record<string, unknown>): string;
35
72
 
@@ -72,6 +109,8 @@ export declare function runStryker(options: Record<string, unknown>): Promise<vo
72
109
  export declare function runMutate(opts: {
73
110
  argv: string[];
74
111
  cwd: string;
112
+ /** Where a full run reads `COSYTE_MUTATE_SHARD` and `COSYTE_MUTATE_INCREMENTAL_FILE`; default `process.env`. */
113
+ env?: Record<string, string | undefined>;
75
114
  out: (text: string) => void;
76
115
  err: (text: string) => void;
77
116
  changes?: ChangeReader;
package/mutate.js CHANGED
@@ -11,10 +11,19 @@
11
11
  // that uses only the Vitest config installs nothing for it. A changed run with no changed source file starts no mutation run: it writes an empty
12
12
  // report, so the ratchet can tell "ran, nothing to mutate" from "never ran", and exits 0.
13
13
  //
14
+ // A SHARDED FULL RUN. A full run of a large library takes hours on one machine, so a CI workflow can
15
+ // split it across parallel jobs. Each job sets COSYTE_MUTATE_SHARD=<k>/<n>: the run lists the files
16
+ // the config names, keeps those whose FNV-1a hash of the path mod n is k - 1, mutates just those,
17
+ // and writes shard-<k>-of-<n>.json beside the full report in place of it, for the workflow to merge.
18
+ // The hash, not a position in a sorted list, decides a file's shard, so a file added elsewhere does
19
+ // not move every other file to another shard. COSYTE_MUTATE_INCREMENTAL_FILE names the file where
20
+ // Stryker keeps its incremental results, so a later run retests only what changed. A changed run
21
+ // reads neither variable, and a full run with neither set runs exactly as it always has.
22
+ //
14
23
  // Exit codes: 0 the run finished (the score is judged by cosyte-ratchet, not here); 2 it could not
15
24
  // run (bad arguments, no config, git could not answer, Stryker failed).
16
25
 
17
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
26
+ import { mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
18
27
  import { dirname, join, matchesGlob, relative, resolve, sep } from "node:path";
19
28
  import { pathToFileURL } from "node:url";
20
29
 
@@ -23,6 +32,12 @@ import { FULL_REPORT, htmlReportFor } from "./stryker.js";
23
32
  /** The config file a run reads when `--config` names none, relative to the working directory. */
24
33
  export const DEFAULT_CONFIG = "stryker.config.mjs";
25
34
 
35
+ /** The variable a sharded full run reads its share from: `<k>/<n>`. */
36
+ export const SHARD_VARIABLE = "COSYTE_MUTATE_SHARD";
37
+
38
+ /** The variable naming the file Stryker reads and writes its incremental results in. */
39
+ export const INCREMENTAL_VARIABLE = "COSYTE_MUTATE_INCREMENTAL_FILE";
40
+
26
41
  /** Thrown for anything that stops a run before Stryker starts. Exit 2. */
27
42
  export class MutateUnreadable extends Error {
28
43
  /**
@@ -46,6 +61,15 @@ changed mutates only the source files changed against the merge base of <ref> a
46
61
  report. With no changed source file it writes an empty report and exits 0.
47
62
  --config the Stryker config file, default ${DEFAULT_CONFIG}, relative to the working directory.
48
63
 
64
+ A full run reads two variables; with neither set it runs as above:
65
+ ${SHARD_VARIABLE}=<k>/<n>
66
+ mutate only shard k of n of the files the config names, and write
67
+ shard-<k>-of-<n>.json beside the full report in place of it (an empty report when the
68
+ shard holds no file). A value that is not <k>/<n> with 1 <= k <= n exits 2.
69
+ ${INCREMENTAL_VARIABLE}=<file>
70
+ where Stryker reads and writes its incremental results, relative to the working
71
+ directory, so a later run retests only what changed.
72
+
49
73
  Exit 0 when the run finished (cosyte-ratchet judges the score), 2 when it could not run.
50
74
  `;
51
75
 
@@ -110,6 +134,85 @@ export function selectChangedFiles({ changed, root, cwd, patterns }) {
110
134
  return picked.sort();
111
135
  }
112
136
 
137
+ /**
138
+ * Read the shard a full run mutates from the value of {@link SHARD_VARIABLE}.
139
+ *
140
+ * @param {string | undefined} value `<k>/<n>`, two whole numbers with 1 <= k <= n.
141
+ * @returns {{ k: number, n: number } | null} The shard, or null when the value is unset or empty.
142
+ */
143
+ export function parseShard(value) {
144
+ if (value === undefined || value === "") return null;
145
+ const match = /^(\d+)\/(\d+)$/.exec(value);
146
+ const k = match === null ? 0 : Number(match[1]);
147
+ const n = match === null ? 0 : Number(match[2]);
148
+ if (k < 1 || k > n) {
149
+ throw new MutateUnreadable(
150
+ `${SHARD_VARIABLE} must be <k>/<n>, two whole numbers with 1 <= k <= n, not ${JSON.stringify(value)}`,
151
+ );
152
+ }
153
+ return { k, n };
154
+ }
155
+
156
+ /**
157
+ * 32-bit FNV-1a over the UTF-8 bytes of a text: the hash a file's shard is read from.
158
+ *
159
+ * @param {string} text The text, here a path relative to the working directory with forward slashes.
160
+ * @returns {number} The hash, an unsigned 32-bit integer.
161
+ */
162
+ export function fnv1a32(text) {
163
+ let hash = 0x811c9dc5;
164
+ // Buffer.from encodes a string as UTF-8 when it is given no encoding.
165
+ for (const byte of Buffer.from(text)) {
166
+ hash = Math.imul(hash ^ byte, 0x01000193) >>> 0;
167
+ }
168
+ return hash;
169
+ }
170
+
171
+ /**
172
+ * The files of one shard: those whose {@link fnv1a32} hash mod `n` is `k - 1`. Over the shards
173
+ * 1 to `n`, every file is in exactly one.
174
+ *
175
+ * @param {readonly string[]} files Paths relative to the working directory, with forward slashes.
176
+ * @param {{ k: number, n: number }} shard The shard.
177
+ * @returns {string[]} The shard's files, in their given order.
178
+ */
179
+ export function filesInShard(files, { k, n }) {
180
+ return files.filter((file) => fnv1a32(file) % n === k - 1);
181
+ }
182
+
183
+ /**
184
+ * List the files under the working directory that a config's `mutate` patterns name, picked by the
185
+ * same rule as {@link selectChangedFiles}. It never enters a `node_modules` or `.git` directory, or
186
+ * Stryker's temp directory.
187
+ *
188
+ * @param {object} input The inputs.
189
+ * @param {string} input.cwd The directory Stryker runs in.
190
+ * @param {readonly string[]} input.patterns The config's `mutate` patterns.
191
+ * @param {string} [input.tempDirName] The config's `tempDirName`, relative to `cwd`.
192
+ * @returns {string[]} The files, relative to `cwd` with forward slashes, sorted.
193
+ */
194
+ export function expandMutate({ cwd, patterns, tempDirName = ".stryker-tmp" }) {
195
+ const root = resolve(cwd);
196
+ const temp = resolve(root, tempDirName);
197
+ const found = [];
198
+ const walk = (dir) => {
199
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
200
+ const path = join(dir, entry.name);
201
+ if (entry.isFile()) found.push(relative(root, path));
202
+ else if (
203
+ entry.isDirectory() &&
204
+ entry.name !== "node_modules" &&
205
+ entry.name !== ".git" &&
206
+ path !== temp
207
+ ) {
208
+ walk(path);
209
+ }
210
+ }
211
+ };
212
+ walk(root);
213
+ return selectChangedFiles({ changed: found, root, cwd: root, patterns });
214
+ }
215
+
113
216
  /**
114
217
  * Where a full run writes its JSON report: the config's `jsonReporter.fileName`, or Stryker's own
115
218
  * default, which is also this package's.
@@ -132,6 +235,17 @@ export function changedReportPath(config) {
132
235
  return join(dirname(fullReportPath(config)), "changed.json");
133
236
  }
134
237
 
238
+ /**
239
+ * Where a sharded full run writes its report: `shard-<k>-of-<n>.json` beside the full report.
240
+ *
241
+ * @param {Record<string, any>} config The loaded Stryker config.
242
+ * @param {{ k: number, n: number }} shard The shard.
243
+ * @returns {string} The path, relative to the working directory.
244
+ */
245
+ export function shardReportPath(config, { k, n }) {
246
+ return join(dirname(fullReportPath(config)), `shard-${k}-of-${n}.json`);
247
+ }
248
+
135
249
  /**
136
250
  * An empty report in the mutation-testing-report-schema shape: no file, no mutant.
137
251
  *
@@ -198,12 +312,74 @@ export async function runStryker(options) {
198
312
  await new Stryker(options).runMutationTest();
199
313
  }
200
314
 
315
+ /**
316
+ * The full run, whole or one shard of it, with Stryker's incremental results or without.
317
+ *
318
+ * @param {object} opts Options.
319
+ * @param {string} opts.cwd The directory Stryker runs in.
320
+ * @param {Record<string, string | undefined>} opts.env Where the two variables are read.
321
+ * @param {(text: string) => void} opts.out Writes to stdout.
322
+ * @param {typeof runStryker} opts.stryker Starts Stryker.
323
+ * @param {string} opts.configFile The config file, absolute.
324
+ * @param {Record<string, any>} opts.config The loaded config.
325
+ * @param {string} opts.name The config file as the command line named it.
326
+ * @returns {Promise<number>} The exit code.
327
+ */
328
+ async function runFull({ cwd, env, out, stryker, configFile, config, name }) {
329
+ const shard = parseShard(env[SHARD_VARIABLE]);
330
+ const incrementalFile = env[INCREMENTAL_VARIABLE];
331
+ const incremental =
332
+ incrementalFile === undefined || incrementalFile === ""
333
+ ? {}
334
+ : { incremental: true, incrementalFile: resolve(cwd, incrementalFile) };
335
+ const sayIncremental = () => {
336
+ if (incrementalFile)
337
+ out(`cosyte-mutate: incremental results read from and written to ${incrementalFile}\n`);
338
+ };
339
+ if (shard === null) {
340
+ // A report left from an earlier run must not outlive a run that failed.
341
+ rmSync(resolve(cwd, fullReportPath(config)), { force: true });
342
+ out(`cosyte-mutate: mutating everything ${name} names\n`);
343
+ sayIncremental();
344
+ await stryker({ configFile, ...incremental });
345
+ return 0;
346
+ }
347
+ const report = shardReportPath(config, shard);
348
+ rmSync(resolve(cwd, report), { force: true });
349
+ const all = expandMutate({ cwd, patterns: config.mutate, tempDirName: config.tempDirName });
350
+ const files = filesInShard(all, shard);
351
+ const which = `shard ${shard.k} of ${shard.n}`;
352
+ if (files.length === 0) {
353
+ mkdirSync(dirname(resolve(cwd, report)), { recursive: true });
354
+ writeFileSync(resolve(cwd, report), emptyReport(cwd));
355
+ out(
356
+ `cosyte-mutate: ${which} holds none of the ${all.length} file(s) ${name} names; nothing to mutate. Wrote an empty ${report}.\n`,
357
+ );
358
+ return 0;
359
+ }
360
+ out(
361
+ `cosyte-mutate: ${which}: mutating ${files.length} of the ${all.length} file(s) ${name} names:\n`,
362
+ );
363
+ for (const file of files) out(` ${file}\n`);
364
+ sayIncremental();
365
+ await stryker({
366
+ configFile,
367
+ mutate: files,
368
+ jsonReporter: { fileName: report },
369
+ htmlReporter: { fileName: htmlReportFor(report) },
370
+ ...incremental,
371
+ });
372
+ return 0;
373
+ }
374
+
201
375
  /**
202
376
  * Run `cosyte-mutate`.
203
377
  *
204
378
  * @param {object} opts Options.
205
379
  * @param {string[]} opts.argv The arguments after the bin's name.
206
380
  * @param {string} opts.cwd The directory Stryker runs in.
381
+ * @param {Record<string, string | undefined>} [opts.env] Where a full run reads
382
+ * {@link SHARD_VARIABLE} and {@link INCREMENTAL_VARIABLE}; the process's environment when left out.
207
383
  * @param {(text: string) => void} opts.out Writes to stdout.
208
384
  * @param {(text: string) => void} opts.err Writes to stderr.
209
385
  * @param {(opts: { base: string, cwd: string }) => { root: string, files: Map<string, Set<number>> }} [opts.changes]
@@ -212,7 +388,15 @@ export async function runStryker(options) {
212
388
  * @param {typeof runStryker} [opts.stryker] Starts Stryker; replaced in tests.
213
389
  * @returns {Promise<number>} The exit code.
214
390
  */
215
- export async function runMutate({ argv, cwd, out, err, changes, stryker = runStryker }) {
391
+ export async function runMutate({
392
+ argv,
393
+ cwd,
394
+ env = process.env,
395
+ out,
396
+ err,
397
+ changes,
398
+ stryker = runStryker,
399
+ }) {
216
400
  if (argv.includes("--help") || argv.includes("-h")) {
217
401
  out(HELP);
218
402
  return 0;
@@ -222,11 +406,7 @@ export async function runMutate({ argv, cwd, out, err, changes, stryker = runStr
222
406
  const configFile = resolve(cwd, options.config);
223
407
  const config = await loadConfig(configFile);
224
408
  if (options.mode === "full") {
225
- // A report left from an earlier run must not outlive a run that failed.
226
- rmSync(resolve(cwd, fullReportPath(config)), { force: true });
227
- out(`cosyte-mutate: mutating everything ${options.config} names\n`);
228
- await stryker({ configFile });
229
- return 0;
409
+ return await runFull({ cwd, env, out, stryker, configFile, config, name: options.config });
230
410
  }
231
411
  const readChanges = changes ?? (await loadChangeReader());
232
412
  const change = readChanges({ base: options.base, cwd });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosyte/vitest-config",
3
- "version": "0.1.4",
3
+ "version": "0.1.7",
4
4
  "description": "Shared Vitest config (v8 coverage, per-directory >=90 gates) and StrykerJS mutation testing config for @cosyte/* packages.",
5
5
  "keywords": [
6
6
  "vitest",
@@ -58,7 +58,8 @@
58
58
  "CHANGELOG.md"
59
59
  ],
60
60
  "publishConfig": {
61
- "access": "public"
61
+ "access": "public",
62
+ "provenance": true
62
63
  },
63
64
  "peerDependencies": {
64
65
  "@stryker-mutator/core": "^10.0.0",
@@ -67,7 +68,7 @@
67
68
  "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
68
69
  "vitest": "^4.0.0 || ^5.0.0",
69
70
  "typescript": ">=5.0.0",
70
- "@cosyte/script-utils": "^0.1.9"
71
+ "@cosyte/script-utils": "^0.1.15"
71
72
  },
72
73
  "peerDependenciesMeta": {
73
74
  "@cosyte/script-utils": {
@@ -87,10 +88,10 @@
87
88
  "@stryker-mutator/core": "10.1.1",
88
89
  "@stryker-mutator/vitest-runner": "10.1.1",
89
90
  "@vitest/coverage-v8": "5.1.0",
90
- "vite": "8.3.6",
91
+ "vite": "8.4.0",
91
92
  "vitest": "5.1.0",
92
93
  "typescript": "5.9.3",
93
- "@cosyte/script-utils": "^0.1.9"
94
+ "@cosyte/script-utils": "^0.1.15"
94
95
  },
95
96
  "scripts": {
96
97
  "test": "vitest run --coverage"
package/stryker.d.ts CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * Whether a source holds nothing but re-exports: every statement an import that binds names or an
3
+ * export of names, and at least one export. Anything else, or anything unread, is real code.
4
+ */
5
+ export declare function isBarrel(source: string): boolean;
6
+
7
+ /**
8
+ * The barrels under `<root>/src` (default: the working directory), by {@link isBarrel}: each `.ts`
9
+ * file but a declaration file, relative to `root` with forward slashes, sorted.
10
+ */
11
+ export declare function findBarrels(root?: string): string[];
12
+
1
13
  /** The directory every run writes its reports under, relative to the directory Stryker runs in. */
2
14
  export declare const REPORT_DIR: "reports/mutation";
3
15
 
@@ -7,7 +19,10 @@ export declare const FULL_REPORT: "reports/mutation/mutation.json";
7
19
  /** The changed-files run's JSON report, separate so a partial run is never read as the score. */
8
20
  export declare const CHANGED_REPORT: "reports/mutation/changed.json";
9
21
 
10
- /** The files a run mutates by default: `src/**\/*.ts` without tests, barrels, declarations, fixtures and generated code. */
22
+ /**
23
+ * The files a run mutates by default, by name: `src/**\/*.ts` without tests, declarations, fixtures
24
+ * and generated code. `cosyteStryker` also leaves out the barrels it finds by reading `src/`.
25
+ */
11
26
  export declare const DEFAULT_MUTATE: readonly string[];
12
27
 
13
28
  /**
@@ -30,8 +45,13 @@ export declare function resolveVitestRunner(resolve?: (specifier: string) => str
30
45
 
31
46
  /** Options for {@link cosyteStryker}. */
32
47
  export interface CosyteStrykerOptions {
33
- /** The files to mutate, in Stryker's glob form. Defaults to {@link DEFAULT_MUTATE}. */
48
+ /**
49
+ * The files to mutate, in Stryker's glob form. Defaults to {@link DEFAULT_MUTATE} without the
50
+ * barrels (files that hold nothing but re-exports) under `<root>/src`.
51
+ */
34
52
  mutate?: readonly string[];
53
+ /** The directory Stryker runs in, read for barrels when `mutate` is left out; the working directory by default. */
54
+ root?: string;
35
55
  /** The Vitest config file the runner loads. */
36
56
  vitestConfig?: string;
37
57
  /** Any other Stryker option, merged last. */
@@ -39,7 +59,7 @@ export interface CosyteStrykerOptions {
39
59
  }
40
60
 
41
61
  /**
42
- * The shared StrykerJS config: the Vitest runner with per-test coverage, static mutants kept,
62
+ * The shared StrykerJS config: the Vitest runner with per-test coverage, static mutants ignored,
43
63
  * the JSON report at {@link FULL_REPORT}, and no score threshold of its own.
44
64
  *
45
65
  * @param opts Options.
package/stryker.js CHANGED
@@ -5,8 +5,91 @@
5
5
  // measures, and every package that would use it already depends on this one. StrykerJS itself is an
6
6
  // optional peer: a package that does not run mutation testing never installs it.
7
7
 
8
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
9
+ import { join, relative, sep } from "node:path";
8
10
  import { fileURLToPath } from "node:url";
9
11
 
12
+ // WHICH SOURCE FILES ARE BARRELS. Coverage and mutation testing leave a barrel out: a file that
13
+ // holds nothing but re-exports has
14
+ // no code of its own to test, and its export lines would only count against a package whose tests
15
+ // import the modules directly. A file is a barrel because of what it holds, never because of its
16
+ // name: an index.ts can hold a whole parser. So each file is read, and it is a barrel only when
17
+ // every statement in it is an import with bindings or an export of names, with at least one
18
+ // export. Anything else, or anything this reading does not understand, is measured: a file
19
+ // wrongly called a barrel hides real code, and a barrel wrongly measured costs one line. The
20
+ // coverage config in index.js reads barrels with the same function.
21
+
22
+ // Whitespace and comments, each read one way only, so a token that fails after them is retried in
23
+ // linear time. A line comment runs to the end of its line: the lookahead stops backtracking from
24
+ // ending it early, where the next repetition would start a new `//` and every split of a run of
25
+ // slashes would be tried. A block comment ends at its first `*/`, so it can neither stretch over
26
+ // the code between two comments nor end anywhere else. A line ends at any of the four terminators
27
+ // JavaScript knows (LF, CR, U+2028, U+2029); `\s` matches all four.
28
+ const LINE = String.raw`[^\n\r

]`;
29
+ const GAP = String.raw`(?:\s|//${LINE}*(?!${LINE})|/\*(?:[^*]|\*(?!/))*\*/)*`;
30
+ // A string holds no raw LF or CR (U+2028 and U+2029 are allowed in one), and `.` after a backslash
31
+ // matches no line terminator, so a line continuation is not read and the file is measured.
32
+ const STRING = String.raw`(?:"(?:[^"\\\n\r]|\\.)*"|'(?:[^'\\\n\r]|\\.)*')`;
33
+ const IDENT = String.raw`[A-Za-z_$][\w$]*`;
34
+ const NAME = `(?:${IDENT}|${STRING})`;
35
+ // `a`, `type a`, `a as b`, `default as b`, `"a-b" as c`.
36
+ const SPECIFIER = String.raw`(?:type\b${GAP})?${NAME}(?:${GAP}as\b${GAP}${NAME})?`;
37
+ const LIST = String.raw`\{${GAP}(?:${SPECIFIER}${GAP}(?:,${GAP}${SPECIFIER}${GAP})*(?:,${GAP})?)?\}`;
38
+ const ATTRIBUTE = `${NAME}${GAP}:${GAP}${STRING}${GAP}`;
39
+ const ATTRIBUTES = String.raw`${GAP}(?:with|assert)${GAP}\{${GAP}(?:${ATTRIBUTE}(?:,${GAP}${ATTRIBUTE})*(?:,${GAP})?)?\}`;
40
+ const FROM = String.raw`${GAP}\bfrom${GAP}${STRING}(?:${ATTRIBUTES})?`;
41
+ const NAMESPACE = String.raw`\*${GAP}as\b${GAP}`;
42
+ // `export * from`, `export * as a from`, `export { a } from`, `export { a }`, each with `type`.
43
+ const EXPORT = String.raw`export(?:${GAP}\btype\b)?${GAP}(?:\*(?:${GAP}as\b${GAP}${NAME})?${FROM}|${LIST}(?:${FROM})?)`;
44
+ // An import that binds a name: `import a from`, `import a, { b } from`, `import * as a from`.
45
+ const IMPORT = String.raw`import\b(?:${GAP}type\b)?${GAP}(?:${IDENT}(?:${GAP},${GAP}(?:${NAMESPACE}${IDENT}|${LIST}))?|${NAMESPACE}${IDENT}|${LIST})${FROM}`;
46
+
47
+ /**
48
+ * Whether a TypeScript or JavaScript source holds nothing but re-exports: every statement is an
49
+ * import that binds names or an export of names (from a module or from those imports), and at
50
+ * least one is an export. A side-effect import, a declaration, a type alias or any other statement
51
+ * makes the file real code.
52
+ *
53
+ * @param {string} source The file's text.
54
+ * @returns {boolean} True for a barrel.
55
+ * @example
56
+ * isBarrel('export * from "./parse.js";\nexport type { Options } from "./types.js";\n'); // true
57
+ * isBarrel('export * from "./parse.js";\nexport const version = "1";\n'); // false
58
+ */
59
+ export function isBarrel(source) {
60
+ const statement = new RegExp(`(?:(${EXPORT})|${IMPORT})${GAP}(?:;${GAP})?`, "y");
61
+ // The leading whitespace and comments; GAP matches at any position, if only the empty string.
62
+ statement.lastIndex = new RegExp(GAP).exec(source)[0].length;
63
+ let exports = 0;
64
+ while (statement.lastIndex < source.length) {
65
+ const match = statement.exec(source);
66
+ if (match === null) return false;
67
+ if (match[1] !== undefined) exports += 1;
68
+ }
69
+ return exports > 0;
70
+ }
71
+
72
+ /**
73
+ * The barrels under `<root>/src`, by {@link isBarrel}: each `.ts` file but a declaration file,
74
+ * relative to `root` with forward slashes, sorted, ready for a coverage `exclude` or, after a `!`,
75
+ * a Stryker `mutate` list. A path with a character a glob reads specially is left out, so it is
76
+ * measured rather than misread. A project without `src/` has none.
77
+ *
78
+ * @param {string} [root] The project root: the directory Vitest or Stryker runs in.
79
+ * @returns {string[]} The barrels.
80
+ */
81
+ export function findBarrels(root = process.cwd()) {
82
+ const src = join(root, "src");
83
+ if (!existsSync(src)) return [];
84
+ return readdirSync(src, { recursive: true, withFileTypes: true })
85
+ .filter((entry) => entry.isFile() && /(?<!\.d)\.ts$/.test(entry.name))
86
+ .map((entry) => join(entry.parentPath, entry.name))
87
+ .filter((path) => isBarrel(String(readFileSync(path))))
88
+ .map((path) => relative(root, path).split(sep).join("/"))
89
+ .filter((path) => /^[\w./-]+$/.test(path))
90
+ .sort();
91
+ }
92
+
10
93
  /** The directory every run writes its reports under, relative to the directory Stryker runs in. */
11
94
  export const REPORT_DIR = "reports/mutation";
12
95
 
@@ -20,15 +103,15 @@ export const FULL_REPORT = `${REPORT_DIR}/mutation.json`;
20
103
  export const CHANGED_REPORT = `${REPORT_DIR}/changed.json`;
21
104
 
22
105
  /**
23
- * The files a run mutates by default: the source `@cosyte/vitest-config` measures coverage over,
24
- * without the files it leaves out (tests, barrels, declarations, fixtures, generated code).
106
+ * The files a run mutates by default, by name: the source `@cosyte/vitest-config` measures coverage
107
+ * over, without the files it leaves out by name (tests, declarations, fixtures, generated code).
108
+ * {@link cosyteStryker} also leaves out the barrels it finds by reading `src/`, as coverage does.
25
109
  */
26
110
  export const DEFAULT_MUTATE = Object.freeze([
27
111
  "src/**/*.ts",
28
112
  "!src/**/*.test.ts",
29
113
  "!src/**/*.spec.ts",
30
114
  "!src/**/*.d.ts",
31
- "!src/**/index.ts",
32
115
  "!src/**/__fixtures__/**",
33
116
  "!src/**/generated/**",
34
117
  ]);
@@ -65,12 +148,21 @@ export function resolveVitestRunner(resolve = (specifier) => import.meta.resolve
65
148
 
66
149
  /**
67
150
  * The shared StrykerJS config for `@cosyte/*` packages: the Vitest runner with per-test coverage
68
- * in Vitest's forks pool, static mutants kept, and the JSON report written to {@link FULL_REPORT}. A run never fails on
151
+ * in Vitest's forks pool, static mutants ignored, and the JSON report written to {@link FULL_REPORT}. A run never fails on
69
152
  * its score (`break: null`): the floor file and `cosyte-ratchet` hold that rule, so there is one
70
153
  * place that decides whether a score dropped.
71
154
  *
155
+ * A static mutant is one in code that runs once, when a module loads (a table of patterns, a
156
+ * frozen map). Stryker can only test one by reloading every test, so on a library such mutants
157
+ * take most of a run's time; they are ignored here, and the coverage gate still holds every such
158
+ * line to having run. A package whose module-level tables are the thing it checks, such as a PHI
159
+ * scanner's patterns, passes `stryker: { ignoreStatic: false }`.
160
+ *
72
161
  * @param {object} [opts] Options.
73
- * @param {readonly string[]} [opts.mutate] The files to mutate, in Stryker's glob form. Defaults to {@link DEFAULT_MUTATE}.
162
+ * @param {readonly string[]} [opts.mutate] The files to mutate, in Stryker's glob form. Defaults to
163
+ * {@link DEFAULT_MUTATE} without the barrels under `<root>/src`.
164
+ * @param {string} [opts.root] The directory Stryker runs in, read for barrels when `mutate` is left
165
+ * out. Defaults to the working directory.
74
166
  * @param {string} [opts.vitestConfig] The Vitest config file the runner loads.
75
167
  * @param {Record<string, unknown>} [opts.stryker] Any other Stryker option, merged last.
76
168
  * @returns {Record<string, unknown> & { mutate: string[], plugins: string[] }} The Stryker config.
@@ -80,13 +172,18 @@ export function resolveVitestRunner(resolve = (specifier) => import.meta.resolve
80
172
  * export default cosyteStryker();
81
173
  */
82
174
  export function cosyteStryker(opts = {}) {
83
- const { mutate = DEFAULT_MUTATE, vitestConfig, stryker = {} } = opts;
175
+ const {
176
+ root,
177
+ mutate = [...DEFAULT_MUTATE, ...findBarrels(root).map((path) => `!${path}`)],
178
+ vitestConfig,
179
+ stryker = {},
180
+ } = opts;
84
181
  return {
85
182
  testRunner: "vitest",
86
183
  plugins: [resolveVitestRunner()],
87
184
  coverageAnalysis: "perTest",
88
185
  mutate: [...mutate],
89
- ignoreStatic: false,
186
+ ignoreStatic: true,
90
187
  reporters: ["clear-text", "progress-append-only", "html", "json"],
91
188
  jsonReporter: { fileName: FULL_REPORT },
92
189
  htmlReporter: { fileName: htmlReportFor(FULL_REPORT) },