@cosyte/vitest-config 0.1.3 → 0.1.6

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/stryker.js ADDED
@@ -0,0 +1,199 @@
1
+ // @cosyte/vitest-config/stryker
2
+ //
3
+ // THE SHARED STRYKERJS CONFIG, for mutation testing with the Vitest runner. It sits in this package
4
+ // because it runs the same Vitest suites over the same source files this package's coverage config
5
+ // measures, and every package that would use it already depends on this one. StrykerJS itself is an
6
+ // optional peer: a package that does not run mutation testing never installs it.
7
+
8
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
9
+ import { join, relative, sep } from "node:path";
10
+ import { fileURLToPath } from "node:url";
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
+
93
+ /** The directory every run writes its reports under, relative to the directory Stryker runs in. */
94
+ export const REPORT_DIR = "reports/mutation";
95
+
96
+ /** The full run's JSON report: the mutation score the floor file holds is read from here. */
97
+ export const FULL_REPORT = `${REPORT_DIR}/mutation.json`;
98
+
99
+ /**
100
+ * The changed-files run's JSON report. It is a separate file so that a run over a few files can
101
+ * never be read as the whole package's score.
102
+ */
103
+ export const CHANGED_REPORT = `${REPORT_DIR}/changed.json`;
104
+
105
+ /**
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.
109
+ */
110
+ export const DEFAULT_MUTATE = Object.freeze([
111
+ "src/**/*.ts",
112
+ "!src/**/*.test.ts",
113
+ "!src/**/*.spec.ts",
114
+ "!src/**/*.d.ts",
115
+ "!src/**/__fixtures__/**",
116
+ "!src/**/generated/**",
117
+ ]);
118
+
119
+ /**
120
+ * The HTML report that sits beside a JSON report, for a person reading the surviving mutants.
121
+ *
122
+ * @param {string} jsonReport A report path ending in `.json`.
123
+ * @returns {string} The same path ending in `.html`.
124
+ */
125
+ export function htmlReportFor(jsonReport) {
126
+ return jsonReport.replace(/\.json$/, ".html");
127
+ }
128
+
129
+ /**
130
+ * The absolute path of the Vitest runner plugin. Stryker loads plugins named by a bare specifier
131
+ * from its own install, and under pnpm that install cannot see a sibling package, so a run would
132
+ * start with no test runner. A path resolved from this package works under pnpm, npm and Yarn.
133
+ *
134
+ * @param {(specifier: string) => string} [resolve] Resolves a specifier to a module URL.
135
+ * @returns {string} The plugin's entry file.
136
+ */
137
+ export function resolveVitestRunner(resolve = (specifier) => import.meta.resolve(specifier)) {
138
+ try {
139
+ return fileURLToPath(resolve("@stryker-mutator/vitest-runner"));
140
+ } catch (cause) {
141
+ throw new Error(
142
+ "@cosyte/vitest-config/stryker: @stryker-mutator/vitest-runner is not installed. Add it and " +
143
+ "@stryker-mutator/core as devDependencies.",
144
+ { cause },
145
+ );
146
+ }
147
+ }
148
+
149
+ /**
150
+ * The shared StrykerJS config for `@cosyte/*` packages: the Vitest runner with per-test coverage
151
+ * in Vitest's forks pool, static mutants ignored, and the JSON report written to {@link FULL_REPORT}. A run never fails on
152
+ * its score (`break: null`): the floor file and `cosyte-ratchet` hold that rule, so there is one
153
+ * place that decides whether a score dropped.
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
+ *
161
+ * @param {object} [opts] Options.
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.
166
+ * @param {string} [opts.vitestConfig] The Vitest config file the runner loads.
167
+ * @param {Record<string, unknown>} [opts.stryker] Any other Stryker option, merged last.
168
+ * @returns {Record<string, unknown> & { mutate: string[], plugins: string[] }} The Stryker config.
169
+ * @example
170
+ * // stryker.config.mjs
171
+ * import { cosyteStryker } from "@cosyte/vitest-config/stryker";
172
+ * export default cosyteStryker();
173
+ */
174
+ export function cosyteStryker(opts = {}) {
175
+ const {
176
+ root,
177
+ mutate = [...DEFAULT_MUTATE, ...findBarrels(root).map((path) => `!${path}`)],
178
+ vitestConfig,
179
+ stryker = {},
180
+ } = opts;
181
+ return {
182
+ testRunner: "vitest",
183
+ plugins: [resolveVitestRunner()],
184
+ coverageAnalysis: "perTest",
185
+ mutate: [...mutate],
186
+ ignoreStatic: true,
187
+ reporters: ["clear-text", "progress-append-only", "html", "json"],
188
+ jsonReporter: { fileName: FULL_REPORT },
189
+ htmlReporter: { fileName: htmlReportFor(FULL_REPORT) },
190
+ thresholds: { high: 100, low: 90, break: null },
191
+ tempDirName: ".stryker-tmp",
192
+ ignorePatterns: ["coverage", "reports", "dist"],
193
+ // Vitest's own default pool, which Stryker's runner does not use unless told: under its
194
+ // default, worker threads, a test that calls process.chdir() fails before any mutant runs.
195
+ vitest:
196
+ vitestConfig === undefined ? { pool: "forks" } : { pool: "forks", configFile: vitestConfig },
197
+ ...stryker,
198
+ };
199
+ }