@cosyte/vitest-config 0.1.2 → 0.1.4
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 +19 -0
- package/README.md +167 -7
- package/bin/cosyte-mutate.js +42 -0
- package/index.js +4 -2
- package/mutate.d.ts +79 -0
- package/mutate.js +264 -0
- package/package.json +52 -4
- package/snippets.d.ts +123 -1
- package/snippets.js +435 -48
- package/stryker.d.ts +56 -0
- package/stryker.js +102 -0
package/snippets.js
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
existsSync,
|
|
3
|
+
mkdirSync,
|
|
4
|
+
readFileSync,
|
|
5
|
+
readdirSync,
|
|
6
|
+
rmSync,
|
|
7
|
+
statSync,
|
|
8
|
+
writeFileSync,
|
|
9
|
+
} from "node:fs";
|
|
2
10
|
import { join, relative } from "node:path";
|
|
3
11
|
import { pathToFileURL } from "node:url";
|
|
4
12
|
|
|
5
|
-
import { afterAll, describe, expect, test } from "vitest";
|
|
13
|
+
import { afterAll, beforeAll, describe, expect, test } from "vitest";
|
|
6
14
|
|
|
7
15
|
/**
|
|
8
16
|
* The doc/code-agreement harness: the documentation analog of the parser conformance runners.
|
|
@@ -27,38 +35,98 @@ import { afterAll, describe, expect, test } from "vitest";
|
|
|
27
35
|
/** Fence languages treated as executable TypeScript. */
|
|
28
36
|
const RUNNABLE_LANGS = new Set(["ts", "typescript", "tsx"]);
|
|
29
37
|
|
|
38
|
+
/**
|
|
39
|
+
* The fence languages that make a block a code sample in every-sample mode: TypeScript and
|
|
40
|
+
* JavaScript. A shell, JSON or text block is not a sample and is never run.
|
|
41
|
+
*/
|
|
42
|
+
export const SAMPLE_LANGS = new Set(["ts", "typescript", "tsx", "js", "javascript", "mjs"]);
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The module extension each sample language is written with in every-sample mode, so a JavaScript
|
|
46
|
+
* sample runs as JavaScript and a `tsx` one as TSX. Any other language is written as `.ts`. A snippet
|
|
47
|
+
* taken without `every` carries no extension and is written as `.ts`, as it always has been.
|
|
48
|
+
*/
|
|
49
|
+
const EXTENSIONS = new Map([
|
|
50
|
+
["tsx", ".tsx"],
|
|
51
|
+
["js", ".mjs"],
|
|
52
|
+
["javascript", ".mjs"],
|
|
53
|
+
["mjs", ".mjs"],
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
/** The fence tag that marks a sample as not run; the words after it are the reason. */
|
|
57
|
+
const NO_RUN = "no-run";
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The fence tag that marks a TypeScript sample as run but not type-checked; the words after it are
|
|
61
|
+
* the reason. It is the only way to leave a sample's types unchecked in every-sample mode.
|
|
62
|
+
*/
|
|
63
|
+
const NO_TYPECHECK = "no-typecheck";
|
|
64
|
+
|
|
65
|
+
/** The module extensions of the samples that are type-checked: the TypeScript ones. */
|
|
66
|
+
const TYPED_EXTENSIONS = new Set([".ts", ".tsx"]);
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The folder under a docs directory that the reference generator owns. Its pages are generated
|
|
70
|
+
* from TSDoc, and their examples are fragments of a signature's documentation, not samples a reader
|
|
71
|
+
* runs, so a suite walking `docsDir` in every-sample mode leaves the folder out unless asked.
|
|
72
|
+
*/
|
|
73
|
+
const GENERATED_DIR = "api";
|
|
74
|
+
|
|
30
75
|
/** Monotonic counter so every emitted temp module gets a unique, cache-busting filename. */
|
|
31
76
|
let moduleCounter = 0;
|
|
32
77
|
|
|
33
78
|
/**
|
|
34
|
-
*
|
|
79
|
+
* A fence opener's indentation and its run of three or more backticks or tildes.
|
|
35
80
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
81
|
+
* Nothing follows the run in the pattern: the info string is the rest of the line, cut off by hand.
|
|
82
|
+
* The earlier form, `\s*(.*)$` after the run, had two quantifiers that could both take the same
|
|
83
|
+
* spaces, so a long line that failed to match cost time quadratic in its length (CodeQL
|
|
84
|
+
* js/polynomial-redos). These docs come from the package being tested, and a markdown file is
|
|
85
|
+
* still input this harness should read in linear time.
|
|
86
|
+
*/
|
|
87
|
+
const FENCE_OPEN = /^(\s*)(`{3,}|~{3,})/;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The characters `.` does not match in a JavaScript regular expression. A fence's info string, a
|
|
91
|
+
* doctest expression and its expected value were each `.+` or `.*` in the earlier patterns, so none
|
|
92
|
+
* of them may hold one; the hand-written parsing below keeps that rule.
|
|
93
|
+
*/
|
|
94
|
+
const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The `; // =>` marker of a doctest assertion. Each quantifier is followed by a character it cannot
|
|
98
|
+
* match, so a scan of a line is linear in its length.
|
|
99
|
+
*/
|
|
100
|
+
const ASSERTION_MARKER = /;\s*\/\/\s*=>/g;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Every fenced block in a markdown string, in document order.
|
|
40
104
|
*
|
|
41
105
|
* @param {string} markdown - The markdown source.
|
|
42
|
-
* @
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* code line (so a failure points at the snippet, not the fence).
|
|
106
|
+
* @returns {Array<{ lang: string | undefined, meta: string[], code: string, line: number }>}
|
|
107
|
+
* `lang` is the first word of the info string, lower-cased; `line` is the 1-based line of the
|
|
108
|
+
* block's first code line.
|
|
46
109
|
*/
|
|
47
|
-
|
|
48
|
-
const runnableTag = opts.runnableTag ?? "runnable";
|
|
110
|
+
function scanFences(markdown) {
|
|
49
111
|
const lines = markdown.split(/\r?\n/);
|
|
112
|
+
// Stryker disable next-line ArrayDeclaration: equivalent, every caller keeps blocks by language.
|
|
50
113
|
const out = [];
|
|
51
114
|
let i = 0;
|
|
115
|
+
// Stryker disable next-line EqualityOperator: equivalent, the line past the end matches no fence.
|
|
52
116
|
while (i < lines.length) {
|
|
53
|
-
const open = lines[i]
|
|
54
|
-
|
|
117
|
+
const open = FENCE_OPEN.exec(lines[i]);
|
|
118
|
+
// Stryker disable next-line StringLiteral,MethodExpression: equivalent, a line that opens no fence
|
|
119
|
+
// never reads it, and the words are trimmed on both sides below.
|
|
120
|
+
const info = open ? lines[i].slice(open[0].length).trimStart() : "";
|
|
121
|
+
if (!open || LINE_TERMINATOR.test(info)) {
|
|
55
122
|
i++;
|
|
56
123
|
continue;
|
|
57
124
|
}
|
|
58
|
-
const [, indent, fence
|
|
125
|
+
const [, indent, fence] = open;
|
|
59
126
|
const firstCodeLine = i + 2; // 1-based line of the first body line
|
|
60
127
|
const body = [];
|
|
61
128
|
let j = i + 1;
|
|
129
|
+
// Stryker disable next-line BooleanLiteral: equivalent, an unclosed block runs to the last line.
|
|
62
130
|
let closed = false;
|
|
63
131
|
while (j < lines.length) {
|
|
64
132
|
const close = lines[j].match(/^(\s*)(`{3,}|~{3,})\s*$/);
|
|
@@ -74,23 +142,137 @@ export function extractRunnableSnippets(markdown, opts = {}) {
|
|
|
74
142
|
body.push(indent && lines[j].startsWith(indent) ? lines[j].slice(indent.length) : lines[j]);
|
|
75
143
|
j++;
|
|
76
144
|
}
|
|
145
|
+
// Stryker disable next-line MethodExpression,Regex: equivalent, every empty word is filtered.
|
|
77
146
|
const tokens = info.trim().split(/\s+/).filter(Boolean);
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
code: body.join("\n"),
|
|
85
|
-
line: firstCodeLine,
|
|
86
|
-
throws: meta.includes("throws"),
|
|
87
|
-
});
|
|
88
|
-
}
|
|
147
|
+
out.push({
|
|
148
|
+
lang: tokens[0]?.toLowerCase(),
|
|
149
|
+
meta: tokens.slice(1),
|
|
150
|
+
code: body.join("\n"),
|
|
151
|
+
line: firstCodeLine,
|
|
152
|
+
});
|
|
89
153
|
i = closed ? j + 1 : j;
|
|
90
154
|
}
|
|
91
155
|
return out;
|
|
92
156
|
}
|
|
93
157
|
|
|
158
|
+
/**
|
|
159
|
+
* Extract the opt-in runnable snippets from a markdown string.
|
|
160
|
+
*
|
|
161
|
+
* A block is runnable when its fence info string names a TypeScript language *and* carries the
|
|
162
|
+
* opt-in tag, e.g. ```` ```ts runnable ````. Everything else (prose, shell, un-tagged `ts` blocks)
|
|
163
|
+
* is ignored: opt-in, never opt-out, so documenting non-executable pseudocode stays possible.
|
|
164
|
+
* The `throws` meta tag marks a block expected to throw rather than run clean.
|
|
165
|
+
*
|
|
166
|
+
* @param {string} markdown - The markdown source.
|
|
167
|
+
* @param {{ runnableTag?: string }} [opts] - Options; `runnableTag` overrides the default `"runnable"`.
|
|
168
|
+
* @returns {Array<{ lang: string, meta: string[], code: string, line: number, throws: boolean }>}
|
|
169
|
+
* One entry per runnable block, in document order. `line` is the 1-based line of the block's first
|
|
170
|
+
* code line (so a failure points at the snippet, not the fence).
|
|
171
|
+
*/
|
|
172
|
+
export function extractRunnableSnippets(markdown, opts = {}) {
|
|
173
|
+
const runnableTag = opts.runnableTag ?? "runnable";
|
|
174
|
+
return scanFences(markdown)
|
|
175
|
+
.filter((block) => RUNNABLE_LANGS.has(block.lang) && block.meta.includes(runnableTag))
|
|
176
|
+
.map((block) => ({ ...block, throws: block.meta.includes("throws") }));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Extract every code sample from a markdown string: each TypeScript or JavaScript block, tagged or
|
|
181
|
+
* not.
|
|
182
|
+
*
|
|
183
|
+
* A sample that cannot run carries `no-run` and its reason in the fence, as in
|
|
184
|
+
* ```` ```ts no-run starts a listener that never closes ````: `skip` is then the reason (the words
|
|
185
|
+
* after `no-run`, which may be empty, and an empty reason is an error the suite reports). A sample
|
|
186
|
+
* that runs but whose types cannot be checked carries `no-typecheck` and its reason the same way,
|
|
187
|
+
* and `noTypecheck` is then the reason. `throws` is read from the tags before either tag only, since
|
|
188
|
+
* the words after it are prose.
|
|
189
|
+
*
|
|
190
|
+
* @param {string} markdown - The markdown source.
|
|
191
|
+
* @returns {Array<{ lang: string, meta: string[], code: string, line: number, throws: boolean, skip: string | null, noTypecheck: string | null, extension: string }>}
|
|
192
|
+
* One entry per sample, in document order. `extension` is the module it runs as: `.mjs` for a
|
|
193
|
+
* JavaScript sample, `.tsx` for a `tsx` one, `.ts` for the rest.
|
|
194
|
+
*/
|
|
195
|
+
export function extractSamples(markdown) {
|
|
196
|
+
return scanFences(markdown)
|
|
197
|
+
.filter((block) => SAMPLE_LANGS.has(block.lang))
|
|
198
|
+
.map((block) => {
|
|
199
|
+
// The first of the two tags that take a reason wins; the words after it are its reason, so a
|
|
200
|
+
// tag written inside a reason is prose.
|
|
201
|
+
const at = block.meta.findIndex((tag) => tag === NO_RUN || tag === NO_TYPECHECK);
|
|
202
|
+
const tags = at === -1 ? block.meta : block.meta.slice(0, at);
|
|
203
|
+
const reason = block.meta.slice(at + 1).join(" ");
|
|
204
|
+
return {
|
|
205
|
+
...block,
|
|
206
|
+
throws: tags.includes("throws"),
|
|
207
|
+
skip: block.meta[at] === NO_RUN ? reason : null,
|
|
208
|
+
noTypecheck: block.meta[at] === NO_TYPECHECK ? reason : null,
|
|
209
|
+
extension: EXTENSIONS.get(block.lang) ?? ".ts",
|
|
210
|
+
};
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Decide what the suite does with each sample in a set of markdown files: run it, skip it with its
|
|
216
|
+
* reason, or report it as invalid (a `no-run` or a `no-typecheck` with no reason). A sample that runs
|
|
217
|
+
* is also type-checked when `every` is on, it is TypeScript, and it carries no `no-typecheck`; its
|
|
218
|
+
* `reason` is then null, and for a `no-typecheck` sample it is that tag's reason.
|
|
219
|
+
*
|
|
220
|
+
* @param {string[]} files - Markdown file paths.
|
|
221
|
+
* @param {{ every?: boolean, root?: string, runnableTag?: string }} [options] - `every` takes every
|
|
222
|
+
* sample rather than only the `runnable` ones; `root` is what labels are relative to (default the
|
|
223
|
+
* working directory).
|
|
224
|
+
* @returns {Array<{ label: string, kind: "run" | "skip" | "invalid", reason: string | null, typecheck: boolean, snippet: object }>}
|
|
225
|
+
*/
|
|
226
|
+
export function planSamples(files, options = {}) {
|
|
227
|
+
const root = options.root ?? process.cwd();
|
|
228
|
+
const plan = [];
|
|
229
|
+
for (const filePath of files) {
|
|
230
|
+
const markdown = readFileSync(filePath, "utf8");
|
|
231
|
+
const samples = options.every
|
|
232
|
+
? extractSamples(markdown)
|
|
233
|
+
: extractRunnableSnippets(markdown, { runnableTag: options.runnableTag }).map((s) => ({
|
|
234
|
+
...s,
|
|
235
|
+
skip: null,
|
|
236
|
+
noTypecheck: null,
|
|
237
|
+
}));
|
|
238
|
+
for (const snippet of samples) {
|
|
239
|
+
const label = `${relative(root, filePath)}:${snippet.line}`;
|
|
240
|
+
if (snippet.noTypecheck === "") {
|
|
241
|
+
plan.push({
|
|
242
|
+
label,
|
|
243
|
+
kind: "invalid",
|
|
244
|
+
reason:
|
|
245
|
+
"a no-typecheck sample names its reason after no-typecheck, as in: ts no-typecheck <why>",
|
|
246
|
+
typecheck: false,
|
|
247
|
+
snippet,
|
|
248
|
+
});
|
|
249
|
+
} else if (snippet.skip === null) {
|
|
250
|
+
plan.push({
|
|
251
|
+
label,
|
|
252
|
+
kind: "run",
|
|
253
|
+
reason: snippet.noTypecheck,
|
|
254
|
+
typecheck:
|
|
255
|
+
options.every === true &&
|
|
256
|
+
snippet.noTypecheck === null &&
|
|
257
|
+
TYPED_EXTENSIONS.has(snippet.extension),
|
|
258
|
+
snippet,
|
|
259
|
+
});
|
|
260
|
+
} else if (snippet.skip === "") {
|
|
261
|
+
plan.push({
|
|
262
|
+
label,
|
|
263
|
+
kind: "invalid",
|
|
264
|
+
reason: "a no-run sample names its reason after no-run, as in: ts no-run <why>",
|
|
265
|
+
typecheck: false,
|
|
266
|
+
snippet,
|
|
267
|
+
});
|
|
268
|
+
} else {
|
|
269
|
+
plan.push({ label, kind: "skip", reason: snippet.skip, typecheck: false, snippet });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return plan;
|
|
274
|
+
}
|
|
275
|
+
|
|
94
276
|
/**
|
|
95
277
|
* Rewrite inline doctest assertions into real `expect(...)` calls.
|
|
96
278
|
*
|
|
@@ -107,16 +289,46 @@ export function rewriteAssertions(code) {
|
|
|
107
289
|
const rewritten = code
|
|
108
290
|
.split(/\r?\n/)
|
|
109
291
|
.map((line) => {
|
|
110
|
-
const m = line
|
|
292
|
+
const m = splitAssertion(line);
|
|
111
293
|
if (!m) return line;
|
|
112
294
|
assertions++;
|
|
113
|
-
|
|
114
|
-
return `${ws}expect(${expr}).toStrictEqual(${expected});`;
|
|
295
|
+
return `${m.ws}expect(${m.expr}).toStrictEqual(${m.expected});`;
|
|
115
296
|
})
|
|
116
297
|
.join("\n");
|
|
117
298
|
return { code: rewritten, assertions };
|
|
118
299
|
}
|
|
119
300
|
|
|
301
|
+
/**
|
|
302
|
+
* Split a doctest line into its indentation, its expression and its expected value.
|
|
303
|
+
*
|
|
304
|
+
* The first `; // =>` with anything after it splits the line: the expression is what lies between
|
|
305
|
+
* the indentation and that marker, the expected value is the rest, trimmed. A line with no such
|
|
306
|
+
* marker, or whose expression or value holds a line terminator, is not an assertion.
|
|
307
|
+
*
|
|
308
|
+
* Parsed by hand rather than by one pattern: `^(\s*)(.+?);\s*\/\/\s*=>\s*(.+?)\s*$` let several
|
|
309
|
+
* quantifiers take the same spaces, so a long line that failed to match cost time quadratic in its
|
|
310
|
+
* length (CodeQL js/polynomial-redos). This is linear. It agrees with that pattern on every line
|
|
311
|
+
* with an expression and a value. Where the expression is empty (`; // => 1`), it emits `expect()`,
|
|
312
|
+
* which fails the snippet; the pattern emitted `expect( )` for an indented line and left an
|
|
313
|
+
* unindented one as it was, a line that asserts nothing.
|
|
314
|
+
*
|
|
315
|
+
* @param {string} line - One source line.
|
|
316
|
+
* @returns {{ ws: string, expr: string, expected: string } | null} The parts, or `null`.
|
|
317
|
+
*/
|
|
318
|
+
function splitAssertion(line) {
|
|
319
|
+
for (const marker of line.matchAll(ASSERTION_MARKER)) {
|
|
320
|
+
const end = marker.index + marker[0].length;
|
|
321
|
+
// Only the last marker can end the line, so this skips at most once.
|
|
322
|
+
if (end === line.length) continue;
|
|
323
|
+
const ws = line.slice(0, line.length - line.trimStart().length);
|
|
324
|
+
const expr = line.slice(ws.length, marker.index);
|
|
325
|
+
const expected = line.slice(end).trim();
|
|
326
|
+
if (LINE_TERMINATOR.test(expr) || LINE_TERMINATOR.test(expected)) return null;
|
|
327
|
+
return { ws, expr, expected };
|
|
328
|
+
}
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
|
|
120
332
|
/**
|
|
121
333
|
* Rewrite the module specifiers in a snippet's `import ... from "<spec>"` clauses.
|
|
122
334
|
*
|
|
@@ -141,21 +353,31 @@ export function remapImports(code, resolveFn) {
|
|
|
141
353
|
* Compile and execute one snippet as an ES module in the running Vitest process.
|
|
142
354
|
*
|
|
143
355
|
* The snippet is remapped, its assertions rewritten, an `expect` import prepended, and the result
|
|
144
|
-
* written to a unique temp
|
|
145
|
-
*
|
|
146
|
-
*
|
|
356
|
+
* written to a unique temp module under `tmpDir` (which MUST live inside the project root so Vitest
|
|
357
|
+
* transforms it: files under `node_modules` are treated as external and would reach Node as raw
|
|
358
|
+
* TypeScript). The module is a `.ts` file unless the snippet names another `extension`, as each
|
|
359
|
+
* sample from {@link extractSamples} does. It is then dynamically imported: Vitest's module runner transforms the TypeScript
|
|
147
360
|
* and runs it. A block tagged `throws` must throw; any other block must run clean. The temp file is
|
|
148
361
|
* always removed afterwards.
|
|
149
362
|
*
|
|
150
363
|
* Exported directly (not only via {@link docSnippetSuite}) so the harness can be unit-tested: a
|
|
151
364
|
* deliberately-wrong snippet must make this reject.
|
|
152
365
|
*
|
|
153
|
-
* @param {{ code: string, throws?: boolean } | string} snippet - A snippet
|
|
154
|
-
*
|
|
155
|
-
*
|
|
366
|
+
* @param {{ code: string, throws?: boolean, extension?: string } | string} snippet - A snippet
|
|
367
|
+
* object or its raw source.
|
|
368
|
+
* @param {{ resolve?: (specifier: string) => string | undefined, tmpDir?: string, throws?: boolean, typeErrors?: Array<{ line: number, code: number, message: string }> }} [opts]
|
|
369
|
+
* Options. `typeErrors` are what {@link typecheckSamples} found in this snippet: when there are
|
|
370
|
+
* any, the snippet fails with them before it runs.
|
|
156
371
|
* @returns {Promise<void>} Resolves on success; rejects (AssertionError or the thrown error) on failure.
|
|
157
372
|
*/
|
|
158
373
|
export async function runSnippet(snippet, opts = {}) {
|
|
374
|
+
const typeErrors = opts.typeErrors ?? [];
|
|
375
|
+
if (typeErrors.length > 0) {
|
|
376
|
+
throw new Error(
|
|
377
|
+
"the sample does not type-check against the package's types:\n" +
|
|
378
|
+
typeErrors.map((e) => ` line ${e.line}: TS${e.code}: ${e.message}`).join("\n"),
|
|
379
|
+
);
|
|
380
|
+
}
|
|
159
381
|
const code = typeof snippet === "string" ? snippet : snippet.code;
|
|
160
382
|
const throwsExpected =
|
|
161
383
|
(typeof snippet === "string" ? false : snippet.throws) || opts.throws || false;
|
|
@@ -165,8 +387,10 @@ export async function runSnippet(snippet, opts = {}) {
|
|
|
165
387
|
const { code: asserted } = rewriteAssertions(remapped);
|
|
166
388
|
const moduleSource = `import { expect } from "vitest";\n${asserted}\n`;
|
|
167
389
|
|
|
390
|
+
// A raw string has no `extension` property, so it is a `.ts` module too.
|
|
391
|
+
const extension = snippet.extension ?? ".ts";
|
|
168
392
|
mkdirSync(tmpDir, { recursive: true });
|
|
169
|
-
const file = join(tmpDir, `snippet-${process.pid}-${moduleCounter++}
|
|
393
|
+
const file = join(tmpDir, `snippet-${process.pid}-${moduleCounter++}${extension}`);
|
|
170
394
|
writeFileSync(file, moduleSource, "utf8");
|
|
171
395
|
try {
|
|
172
396
|
if (throwsExpected) {
|
|
@@ -193,6 +417,113 @@ export async function runSnippet(snippet, opts = {}) {
|
|
|
193
417
|
}
|
|
194
418
|
}
|
|
195
419
|
|
|
420
|
+
/**
|
|
421
|
+
* Compiler options a sample is checked under when no `tsconfig.json` is found: what our libraries'
|
|
422
|
+
* shared TypeScript config sets for module resolution and strictness. `skipLibCheck` keeps the
|
|
423
|
+
* check on the samples, not on the declarations they import.
|
|
424
|
+
*/
|
|
425
|
+
const DEFAULT_COMPILER_OPTIONS = {
|
|
426
|
+
target: "es2023",
|
|
427
|
+
module: "nodenext",
|
|
428
|
+
moduleResolution: "nodenext",
|
|
429
|
+
strict: true,
|
|
430
|
+
skipLibCheck: true,
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Type-check TypeScript samples against the package's types, as a reader who copies one into a
|
|
435
|
+
* project would compile it: each sample is its own module, importing the package by the name it is
|
|
436
|
+
* published under, which TypeScript resolves the way the project does (for a library, to its own
|
|
437
|
+
* built declarations through its `exports`).
|
|
438
|
+
*
|
|
439
|
+
* The compiler options are the project's `tsconfig.json` (the one named, or the one in the working
|
|
440
|
+
* directory when none is named; without either, {@link DEFAULT_COMPILER_OPTIONS}), with what does
|
|
441
|
+
* not fit a sample turned off: emit and its folders, and the unused-name checks, since a sample may
|
|
442
|
+
* declare a name only to show it. The samples are compiled together, as one program, for speed; every sample is a
|
|
443
|
+
* module, so none sees another's names.
|
|
444
|
+
*
|
|
445
|
+
* Needs the `typescript` package, which every TypeScript project has.
|
|
446
|
+
*
|
|
447
|
+
* @param {Array<{ code: string, line: number, extension?: string }>} samples - The samples, as
|
|
448
|
+
* {@link extractSamples} returns them: `line` is the markdown line of the first code line, and an
|
|
449
|
+
* `extension` of `.tsx` compiles a sample as TSX.
|
|
450
|
+
* @param {{ tsconfig?: string, dir?: string }} [options] - `tsconfig` names the config file; `dir`
|
|
451
|
+
* is where each sample is written to be compiled (default `.cosyte-doc-snippets/typecheck` in the
|
|
452
|
+
* working directory), which must sit inside the project so its packages resolve.
|
|
453
|
+
* @returns {Promise<Array<Array<{ line: number, code: number, message: string }>>>} For each sample,
|
|
454
|
+
* in order, its errors, each with the markdown line it is on; empty for a sample that compiles.
|
|
455
|
+
* @throws {Error} When the config cannot be read, or the program as a whole has an error (an option
|
|
456
|
+
* or a missing type library), which would fail every sample alike.
|
|
457
|
+
*/
|
|
458
|
+
export async function typecheckSamples(samples, options = {}) {
|
|
459
|
+
const { default: ts } = await import("typescript");
|
|
460
|
+
const dir = options.dir ?? join(defaultTmpDir(), "typecheck");
|
|
461
|
+
const local = join(process.cwd(), "tsconfig.json");
|
|
462
|
+
const tsconfig = options.tsconfig ?? (existsSync(local) ? local : undefined);
|
|
463
|
+
const fail = (diagnostics) => {
|
|
464
|
+
throw new Error(
|
|
465
|
+
`the samples could not be type-checked: ${diagnostics
|
|
466
|
+
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, " "))
|
|
467
|
+
.join("; ")}`,
|
|
468
|
+
);
|
|
469
|
+
};
|
|
470
|
+
let base = ts.convertCompilerOptionsFromJson(DEFAULT_COMPILER_OPTIONS, dir).options;
|
|
471
|
+
if (tsconfig !== undefined) {
|
|
472
|
+
const parsed = ts.getParsedCommandLineOfConfigFile(tsconfig, undefined, {
|
|
473
|
+
...ts.sys,
|
|
474
|
+
onUnRecoverableConfigFileDiagnostic: (d) => fail([d]),
|
|
475
|
+
});
|
|
476
|
+
// TS18003, "no inputs were found", only says the project's own `include` matched no file; the
|
|
477
|
+
// samples are the inputs here.
|
|
478
|
+
const errors = parsed.errors.filter((d) => d.code !== 18003);
|
|
479
|
+
if (errors.length > 0) fail(errors);
|
|
480
|
+
base = parsed.options;
|
|
481
|
+
}
|
|
482
|
+
const compilerOptions = {
|
|
483
|
+
...base,
|
|
484
|
+
noEmit: true,
|
|
485
|
+
moduleDetection: ts.ModuleDetectionKind.Force,
|
|
486
|
+
jsx: base.jsx ?? ts.JsxEmit.Preserve,
|
|
487
|
+
noUnusedLocals: false,
|
|
488
|
+
noUnusedParameters: false,
|
|
489
|
+
declaration: false,
|
|
490
|
+
declarationMap: false,
|
|
491
|
+
emitDeclarationOnly: false,
|
|
492
|
+
composite: false,
|
|
493
|
+
incremental: false,
|
|
494
|
+
// With an output folder set, TypeScript reads a package's `exports` into that folder as a
|
|
495
|
+
// pointer back to its source, and asks for a root folder to map it by. A sample imports what
|
|
496
|
+
// the package publishes, the built declarations, so neither folder applies.
|
|
497
|
+
outDir: undefined,
|
|
498
|
+
rootDir: undefined,
|
|
499
|
+
declarationDir: undefined,
|
|
500
|
+
};
|
|
501
|
+
mkdirSync(dir, { recursive: true });
|
|
502
|
+
const files = samples.map((sample, index) => {
|
|
503
|
+
const file = join(dir, `sample-${process.pid}-${index}${sample.extension ?? ".ts"}`);
|
|
504
|
+
writeFileSync(file, sample.code, "utf8");
|
|
505
|
+
return file;
|
|
506
|
+
});
|
|
507
|
+
try {
|
|
508
|
+
const program = ts.createProgram({ rootNames: files, options: compilerOptions });
|
|
509
|
+
const whole = [...program.getOptionsDiagnostics(), ...program.getGlobalDiagnostics()];
|
|
510
|
+
if (whole.length > 0) fail(whole);
|
|
511
|
+
return files.map((file, index) => {
|
|
512
|
+
const source = program.getSourceFile(file);
|
|
513
|
+
return [
|
|
514
|
+
...program.getSyntacticDiagnostics(source),
|
|
515
|
+
...program.getSemanticDiagnostics(source),
|
|
516
|
+
].map((d) => ({
|
|
517
|
+
line: samples[index].line + source.getLineAndCharacterOfPosition(d.start).line,
|
|
518
|
+
code: d.code,
|
|
519
|
+
message: ts.flattenDiagnosticMessageText(d.messageText, " "),
|
|
520
|
+
}));
|
|
521
|
+
});
|
|
522
|
+
} finally {
|
|
523
|
+
for (const file of files) rmSync(file, { force: true });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
196
527
|
/**
|
|
197
528
|
* Register a Vitest suite that proves every runnable `docs-content` snippet agrees with the code.
|
|
198
529
|
*
|
|
@@ -211,6 +542,15 @@ export async function runSnippet(snippet, opts = {}) {
|
|
|
211
542
|
* @param {string} [options.runnableTag] - Fence opt-in tag. Default `"runnable"`.
|
|
212
543
|
* @param {string} [options.name] - Suite label. Default `"doc/code agreement"`.
|
|
213
544
|
* @param {boolean} [options.requireSnippet] - Assert at least one runnable snippet exists. Default `false`.
|
|
545
|
+
* @param {boolean} [options.every] - Run every TypeScript and JavaScript sample, not only the
|
|
546
|
+
* `runnable` ones; a `no-run <reason>` sample is listed as skipped with its reason. Each TypeScript
|
|
547
|
+
* sample is also type-checked against the package's types before it runs (see
|
|
548
|
+
* {@link typecheckSamples}), unless it carries `no-typecheck <reason>`, which the test's name then
|
|
549
|
+
* shows. Walking `docsDir`, it leaves out the generated reference under `api/`. Default `false`.
|
|
550
|
+
* @param {boolean} [options.includeGenerated] - In every-sample mode, walk the generated `api/`
|
|
551
|
+
* folder of `docsDir` too. Default `false`.
|
|
552
|
+
* @param {string} [options.tsconfig] - The `tsconfig.json` the samples are type-checked under.
|
|
553
|
+
* Default: the one in the working directory, when there is one.
|
|
214
554
|
* @param {string} [options.tmpDir] - Where temp modules are written (must be inside the project root).
|
|
215
555
|
* @returns {void}
|
|
216
556
|
*/
|
|
@@ -224,9 +564,17 @@ export function docSnippetSuite(options = {}) {
|
|
|
224
564
|
name = "doc/code agreement",
|
|
225
565
|
requireSnippet = false,
|
|
226
566
|
tmpDir = defaultTmpDir(),
|
|
567
|
+
// Stryker disable next-line BooleanLiteral: read while Vitest collects the suite, which Stryker's
|
|
568
|
+
// Vitest runner cannot reach (see below); applied by hand, it fails test/doc-samples-every.test.ts.
|
|
569
|
+
every = false,
|
|
570
|
+
includeGenerated = false,
|
|
571
|
+
tsconfig,
|
|
227
572
|
} = options;
|
|
228
573
|
|
|
229
|
-
|
|
574
|
+
// In every-sample mode the generated reference is left out of a walk: its examples are parts of
|
|
575
|
+
// a signature's documentation, which `cosyte-docs-reference` writes and checks.
|
|
576
|
+
const generated = every && !includeGenerated && docsDir ? join(docsDir, GENERATED_DIR) : null;
|
|
577
|
+
const mdFiles = files ?? (docsDir ? collectMarkdown(docsDir, include, generated) : []);
|
|
230
578
|
|
|
231
579
|
describe(name, () => {
|
|
232
580
|
afterAll(() => {
|
|
@@ -237,17 +585,54 @@ export function docSnippetSuite(options = {}) {
|
|
|
237
585
|
}
|
|
238
586
|
});
|
|
239
587
|
|
|
588
|
+
// From here to the end of the loop the code runs while Vitest collects the suite, and Stryker's
|
|
589
|
+
// Vitest runner switches a mutant on only once the tests run, so none of its mutants reach this
|
|
590
|
+
// region. Each mutant of it was applied by hand instead, and each fails
|
|
591
|
+
// test/doc-samples-every.test.ts.
|
|
592
|
+
// Stryker disable all
|
|
593
|
+
const plan = planSamples(mdFiles, { every, runnableTag });
|
|
594
|
+
// The TypeScript samples are type-checked together before any runs, and each sample's test
|
|
595
|
+
// fails on its own errors.
|
|
596
|
+
const checked = plan.filter((step) => step.typecheck);
|
|
597
|
+
const typeErrors = new Map();
|
|
598
|
+
if (checked.length > 0) {
|
|
599
|
+
beforeAll(async () => {
|
|
600
|
+
const found = await typecheckSamples(
|
|
601
|
+
checked.map((step) => step.snippet),
|
|
602
|
+
{ tsconfig, dir: join(tmpDir, "typecheck") },
|
|
603
|
+
);
|
|
604
|
+
checked.forEach((step, index) => typeErrors.set(step, found[index]));
|
|
605
|
+
}, 120_000);
|
|
606
|
+
}
|
|
240
607
|
let total = 0;
|
|
241
|
-
for (const
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
test(
|
|
247
|
-
await runSnippet(snippet, {
|
|
608
|
+
for (const step of plan) {
|
|
609
|
+
if (step.kind === "run") {
|
|
610
|
+
total++;
|
|
611
|
+
const name =
|
|
612
|
+
step.reason === null ? step.label : `${step.label} (not type-checked: ${step.reason})`;
|
|
613
|
+
test(name, async () => {
|
|
614
|
+
await runSnippet(step.snippet, {
|
|
615
|
+
resolve: resolveFn,
|
|
616
|
+
tmpDir,
|
|
617
|
+
typeErrors: typeErrors.get(step),
|
|
618
|
+
});
|
|
248
619
|
});
|
|
620
|
+
continue;
|
|
621
|
+
}
|
|
622
|
+
if (step.kind === "skip") {
|
|
623
|
+
test.skip(`${step.label} (not run: ${step.reason})`, () => {});
|
|
624
|
+
continue;
|
|
249
625
|
}
|
|
626
|
+
// An invalid sample: a no-run or a no-typecheck with no reason. This test only ever fails, so
|
|
627
|
+
// its lines are proven by separate Vitest runs (test/doc-samples-every.test.ts, "a no-run
|
|
628
|
+
// sample with no reason fails the suite" and "a sample with a type error fails the suite"),
|
|
629
|
+
// whose coverage this run cannot collect.
|
|
630
|
+
/* v8 ignore next 3 */
|
|
631
|
+
test(step.label, () => {
|
|
632
|
+
throw new Error(`${step.label}: ${step.reason}`);
|
|
633
|
+
});
|
|
250
634
|
}
|
|
635
|
+
// Stryker restore all
|
|
251
636
|
|
|
252
637
|
if (requireSnippet) {
|
|
253
638
|
test("carries at least one runnable snippet", () => {
|
|
@@ -273,9 +658,10 @@ function defaultTmpDir() {
|
|
|
273
658
|
*
|
|
274
659
|
* @param {string} dir - Root directory.
|
|
275
660
|
* @param {RegExp} include - Filename filter.
|
|
661
|
+
* @param {string | null} skip - A directory left out of the walk, or null.
|
|
276
662
|
* @returns {string[]} Absolute-or-relative file paths, sorted for stable test ordering.
|
|
277
663
|
*/
|
|
278
|
-
function collectMarkdown(dir, include) {
|
|
664
|
+
function collectMarkdown(dir, include, skip) {
|
|
279
665
|
let entries;
|
|
280
666
|
try {
|
|
281
667
|
entries = readdirSync(dir);
|
|
@@ -291,8 +677,9 @@ function collectMarkdown(dir, include) {
|
|
|
291
677
|
} catch {
|
|
292
678
|
continue;
|
|
293
679
|
}
|
|
294
|
-
if (s.isDirectory())
|
|
295
|
-
|
|
680
|
+
if (s.isDirectory()) {
|
|
681
|
+
if (full !== skip) out.push(...collectMarkdown(full, include, skip));
|
|
682
|
+
} else if (include.test(entry)) out.push(full);
|
|
296
683
|
}
|
|
297
684
|
return out;
|
|
298
685
|
}
|
package/stryker.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** The directory every run writes its reports under, relative to the directory Stryker runs in. */
|
|
2
|
+
export declare const REPORT_DIR: "reports/mutation";
|
|
3
|
+
|
|
4
|
+
/** The full run's JSON report: the mutation score the floor file holds is read from here. */
|
|
5
|
+
export declare const FULL_REPORT: "reports/mutation/mutation.json";
|
|
6
|
+
|
|
7
|
+
/** The changed-files run's JSON report, separate so a partial run is never read as the score. */
|
|
8
|
+
export declare const CHANGED_REPORT: "reports/mutation/changed.json";
|
|
9
|
+
|
|
10
|
+
/** The files a run mutates by default: `src/**\/*.ts` without tests, barrels, declarations, fixtures and generated code. */
|
|
11
|
+
export declare const DEFAULT_MUTATE: readonly string[];
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The HTML report that sits beside a JSON report.
|
|
15
|
+
*
|
|
16
|
+
* @param jsonReport A report path ending in `.json`.
|
|
17
|
+
* @returns The same path ending in `.html`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function htmlReportFor(jsonReport: string): string;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The absolute path of the Vitest runner plugin, resolved from this package so the run works
|
|
23
|
+
* under pnpm.
|
|
24
|
+
*
|
|
25
|
+
* @param resolve Resolves a specifier to a module URL.
|
|
26
|
+
* @returns The plugin's entry file.
|
|
27
|
+
* @throws {Error} When `@stryker-mutator/vitest-runner` is not installed.
|
|
28
|
+
*/
|
|
29
|
+
export declare function resolveVitestRunner(resolve?: (specifier: string) => string): string;
|
|
30
|
+
|
|
31
|
+
/** Options for {@link cosyteStryker}. */
|
|
32
|
+
export interface CosyteStrykerOptions {
|
|
33
|
+
/** The files to mutate, in Stryker's glob form. Defaults to {@link DEFAULT_MUTATE}. */
|
|
34
|
+
mutate?: readonly string[];
|
|
35
|
+
/** The Vitest config file the runner loads. */
|
|
36
|
+
vitestConfig?: string;
|
|
37
|
+
/** Any other Stryker option, merged last. */
|
|
38
|
+
stryker?: Record<string, unknown>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The shared StrykerJS config: the Vitest runner with per-test coverage, static mutants kept,
|
|
43
|
+
* the JSON report at {@link FULL_REPORT}, and no score threshold of its own.
|
|
44
|
+
*
|
|
45
|
+
* @param opts Options.
|
|
46
|
+
* @returns The Stryker config.
|
|
47
|
+
* @example
|
|
48
|
+
* ```js
|
|
49
|
+
* // stryker.config.mjs
|
|
50
|
+
* import { cosyteStryker } from "@cosyte/vitest-config/stryker";
|
|
51
|
+
* export default cosyteStryker();
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export declare function cosyteStryker(
|
|
55
|
+
opts?: CosyteStrykerOptions,
|
|
56
|
+
): Record<string, unknown> & { mutate: string[]; plugins: string[] };
|