@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/CHANGELOG.md +51 -0
- package/README.md +222 -8
- package/bin/cosyte-mutate.js +42 -0
- package/index.d.ts +5 -0
- package/index.js +14 -6
- package/mutate.d.ts +118 -0
- package/mutate.js +444 -0
- package/package.json +52 -4
- package/snippets.d.ts +123 -1
- package/snippets.js +375 -43
- package/stryker.d.ts +76 -0
- package/stryker.js +199 -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,6 +35,43 @@ 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
|
|
|
@@ -55,26 +100,23 @@ const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
|
|
|
55
100
|
const ASSERTION_MARKER = /;\s*\/\/\s*=>/g;
|
|
56
101
|
|
|
57
102
|
/**
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
* A block is runnable when its fence info string names a TypeScript language *and* carries the
|
|
61
|
-
* opt-in tag, e.g. ```` ```ts runnable ````. Everything else (prose, shell, un-tagged `ts` blocks)
|
|
62
|
-
* is ignored: opt-in, never opt-out, so documenting non-executable pseudocode stays possible.
|
|
63
|
-
* The `throws` meta tag marks a block expected to throw rather than run clean.
|
|
103
|
+
* Every fenced block in a markdown string, in document order.
|
|
64
104
|
*
|
|
65
105
|
* @param {string} markdown - The markdown source.
|
|
66
|
-
* @
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
* 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.
|
|
70
109
|
*/
|
|
71
|
-
|
|
72
|
-
const runnableTag = opts.runnableTag ?? "runnable";
|
|
110
|
+
function scanFences(markdown) {
|
|
73
111
|
const lines = markdown.split(/\r?\n/);
|
|
112
|
+
// Stryker disable next-line ArrayDeclaration: equivalent, every caller keeps blocks by language.
|
|
74
113
|
const out = [];
|
|
75
114
|
let i = 0;
|
|
115
|
+
// Stryker disable next-line EqualityOperator: equivalent, the line past the end matches no fence.
|
|
76
116
|
while (i < lines.length) {
|
|
77
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.
|
|
78
120
|
const info = open ? lines[i].slice(open[0].length).trimStart() : "";
|
|
79
121
|
if (!open || LINE_TERMINATOR.test(info)) {
|
|
80
122
|
i++;
|
|
@@ -84,6 +126,7 @@ export function extractRunnableSnippets(markdown, opts = {}) {
|
|
|
84
126
|
const firstCodeLine = i + 2; // 1-based line of the first body line
|
|
85
127
|
const body = [];
|
|
86
128
|
let j = i + 1;
|
|
129
|
+
// Stryker disable next-line BooleanLiteral: equivalent, an unclosed block runs to the last line.
|
|
87
130
|
let closed = false;
|
|
88
131
|
while (j < lines.length) {
|
|
89
132
|
const close = lines[j].match(/^(\s*)(`{3,}|~{3,})\s*$/);
|
|
@@ -99,23 +142,137 @@ export function extractRunnableSnippets(markdown, opts = {}) {
|
|
|
99
142
|
body.push(indent && lines[j].startsWith(indent) ? lines[j].slice(indent.length) : lines[j]);
|
|
100
143
|
j++;
|
|
101
144
|
}
|
|
145
|
+
// Stryker disable next-line MethodExpression,Regex: equivalent, every empty word is filtered.
|
|
102
146
|
const tokens = info.trim().split(/\s+/).filter(Boolean);
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
code: body.join("\n"),
|
|
110
|
-
line: firstCodeLine,
|
|
111
|
-
throws: meta.includes("throws"),
|
|
112
|
-
});
|
|
113
|
-
}
|
|
147
|
+
out.push({
|
|
148
|
+
lang: tokens[0]?.toLowerCase(),
|
|
149
|
+
meta: tokens.slice(1),
|
|
150
|
+
code: body.join("\n"),
|
|
151
|
+
line: firstCodeLine,
|
|
152
|
+
});
|
|
114
153
|
i = closed ? j + 1 : j;
|
|
115
154
|
}
|
|
116
155
|
return out;
|
|
117
156
|
}
|
|
118
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
|
+
|
|
119
276
|
/**
|
|
120
277
|
* Rewrite inline doctest assertions into real `expect(...)` calls.
|
|
121
278
|
*
|
|
@@ -196,21 +353,31 @@ export function remapImports(code, resolveFn) {
|
|
|
196
353
|
* Compile and execute one snippet as an ES module in the running Vitest process.
|
|
197
354
|
*
|
|
198
355
|
* The snippet is remapped, its assertions rewritten, an `expect` import prepended, and the result
|
|
199
|
-
* written to a unique temp
|
|
200
|
-
*
|
|
201
|
-
*
|
|
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
|
|
202
360
|
* and runs it. A block tagged `throws` must throw; any other block must run clean. The temp file is
|
|
203
361
|
* always removed afterwards.
|
|
204
362
|
*
|
|
205
363
|
* Exported directly (not only via {@link docSnippetSuite}) so the harness can be unit-tested: a
|
|
206
364
|
* deliberately-wrong snippet must make this reject.
|
|
207
365
|
*
|
|
208
|
-
* @param {{ code: string, throws?: boolean } | string} snippet - A snippet
|
|
209
|
-
*
|
|
210
|
-
*
|
|
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.
|
|
211
371
|
* @returns {Promise<void>} Resolves on success; rejects (AssertionError or the thrown error) on failure.
|
|
212
372
|
*/
|
|
213
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
|
+
}
|
|
214
381
|
const code = typeof snippet === "string" ? snippet : snippet.code;
|
|
215
382
|
const throwsExpected =
|
|
216
383
|
(typeof snippet === "string" ? false : snippet.throws) || opts.throws || false;
|
|
@@ -220,8 +387,10 @@ export async function runSnippet(snippet, opts = {}) {
|
|
|
220
387
|
const { code: asserted } = rewriteAssertions(remapped);
|
|
221
388
|
const moduleSource = `import { expect } from "vitest";\n${asserted}\n`;
|
|
222
389
|
|
|
390
|
+
// A raw string has no `extension` property, so it is a `.ts` module too.
|
|
391
|
+
const extension = snippet.extension ?? ".ts";
|
|
223
392
|
mkdirSync(tmpDir, { recursive: true });
|
|
224
|
-
const file = join(tmpDir, `snippet-${process.pid}-${moduleCounter++}
|
|
393
|
+
const file = join(tmpDir, `snippet-${process.pid}-${moduleCounter++}${extension}`);
|
|
225
394
|
writeFileSync(file, moduleSource, "utf8");
|
|
226
395
|
try {
|
|
227
396
|
if (throwsExpected) {
|
|
@@ -248,6 +417,113 @@ export async function runSnippet(snippet, opts = {}) {
|
|
|
248
417
|
}
|
|
249
418
|
}
|
|
250
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
|
+
|
|
251
527
|
/**
|
|
252
528
|
* Register a Vitest suite that proves every runnable `docs-content` snippet agrees with the code.
|
|
253
529
|
*
|
|
@@ -266,6 +542,15 @@ export async function runSnippet(snippet, opts = {}) {
|
|
|
266
542
|
* @param {string} [options.runnableTag] - Fence opt-in tag. Default `"runnable"`.
|
|
267
543
|
* @param {string} [options.name] - Suite label. Default `"doc/code agreement"`.
|
|
268
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.
|
|
269
554
|
* @param {string} [options.tmpDir] - Where temp modules are written (must be inside the project root).
|
|
270
555
|
* @returns {void}
|
|
271
556
|
*/
|
|
@@ -279,9 +564,17 @@ export function docSnippetSuite(options = {}) {
|
|
|
279
564
|
name = "doc/code agreement",
|
|
280
565
|
requireSnippet = false,
|
|
281
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,
|
|
282
572
|
} = options;
|
|
283
573
|
|
|
284
|
-
|
|
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) : []);
|
|
285
578
|
|
|
286
579
|
describe(name, () => {
|
|
287
580
|
afterAll(() => {
|
|
@@ -292,17 +585,54 @@ export function docSnippetSuite(options = {}) {
|
|
|
292
585
|
}
|
|
293
586
|
});
|
|
294
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
|
+
}
|
|
295
607
|
let total = 0;
|
|
296
|
-
for (const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
test(
|
|
302
|
-
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
|
+
});
|
|
303
619
|
});
|
|
620
|
+
continue;
|
|
304
621
|
}
|
|
622
|
+
if (step.kind === "skip") {
|
|
623
|
+
test.skip(`${step.label} (not run: ${step.reason})`, () => {});
|
|
624
|
+
continue;
|
|
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
|
+
});
|
|
305
634
|
}
|
|
635
|
+
// Stryker restore all
|
|
306
636
|
|
|
307
637
|
if (requireSnippet) {
|
|
308
638
|
test("carries at least one runnable snippet", () => {
|
|
@@ -328,9 +658,10 @@ function defaultTmpDir() {
|
|
|
328
658
|
*
|
|
329
659
|
* @param {string} dir - Root directory.
|
|
330
660
|
* @param {RegExp} include - Filename filter.
|
|
661
|
+
* @param {string | null} skip - A directory left out of the walk, or null.
|
|
331
662
|
* @returns {string[]} Absolute-or-relative file paths, sorted for stable test ordering.
|
|
332
663
|
*/
|
|
333
|
-
function collectMarkdown(dir, include) {
|
|
664
|
+
function collectMarkdown(dir, include, skip) {
|
|
334
665
|
let entries;
|
|
335
666
|
try {
|
|
336
667
|
entries = readdirSync(dir);
|
|
@@ -346,8 +677,9 @@ function collectMarkdown(dir, include) {
|
|
|
346
677
|
} catch {
|
|
347
678
|
continue;
|
|
348
679
|
}
|
|
349
|
-
if (s.isDirectory())
|
|
350
|
-
|
|
680
|
+
if (s.isDirectory()) {
|
|
681
|
+
if (full !== skip) out.push(...collectMarkdown(full, include, skip));
|
|
682
|
+
} else if (include.test(entry)) out.push(full);
|
|
351
683
|
}
|
|
352
684
|
return out;
|
|
353
685
|
}
|
package/stryker.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
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
|
+
|
|
13
|
+
/** The directory every run writes its reports under, relative to the directory Stryker runs in. */
|
|
14
|
+
export declare const REPORT_DIR: "reports/mutation";
|
|
15
|
+
|
|
16
|
+
/** The full run's JSON report: the mutation score the floor file holds is read from here. */
|
|
17
|
+
export declare const FULL_REPORT: "reports/mutation/mutation.json";
|
|
18
|
+
|
|
19
|
+
/** The changed-files run's JSON report, separate so a partial run is never read as the score. */
|
|
20
|
+
export declare const CHANGED_REPORT: "reports/mutation/changed.json";
|
|
21
|
+
|
|
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
|
+
*/
|
|
26
|
+
export declare const DEFAULT_MUTATE: readonly string[];
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The HTML report that sits beside a JSON report.
|
|
30
|
+
*
|
|
31
|
+
* @param jsonReport A report path ending in `.json`.
|
|
32
|
+
* @returns The same path ending in `.html`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function htmlReportFor(jsonReport: string): string;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The absolute path of the Vitest runner plugin, resolved from this package so the run works
|
|
38
|
+
* under pnpm.
|
|
39
|
+
*
|
|
40
|
+
* @param resolve Resolves a specifier to a module URL.
|
|
41
|
+
* @returns The plugin's entry file.
|
|
42
|
+
* @throws {Error} When `@stryker-mutator/vitest-runner` is not installed.
|
|
43
|
+
*/
|
|
44
|
+
export declare function resolveVitestRunner(resolve?: (specifier: string) => string): string;
|
|
45
|
+
|
|
46
|
+
/** Options for {@link cosyteStryker}. */
|
|
47
|
+
export interface CosyteStrykerOptions {
|
|
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
|
+
*/
|
|
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;
|
|
55
|
+
/** The Vitest config file the runner loads. */
|
|
56
|
+
vitestConfig?: string;
|
|
57
|
+
/** Any other Stryker option, merged last. */
|
|
58
|
+
stryker?: Record<string, unknown>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The shared StrykerJS config: the Vitest runner with per-test coverage, static mutants ignored,
|
|
63
|
+
* the JSON report at {@link FULL_REPORT}, and no score threshold of its own.
|
|
64
|
+
*
|
|
65
|
+
* @param opts Options.
|
|
66
|
+
* @returns The Stryker config.
|
|
67
|
+
* @example
|
|
68
|
+
* ```js
|
|
69
|
+
* // stryker.config.mjs
|
|
70
|
+
* import { cosyteStryker } from "@cosyte/vitest-config/stryker";
|
|
71
|
+
* export default cosyteStryker();
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare function cosyteStryker(
|
|
75
|
+
opts?: CosyteStrykerOptions,
|
|
76
|
+
): Record<string, unknown> & { mutate: string[]; plugins: string[] };
|