1/**
2 * @since 4.0.0
3 */
4
5import { createHash } from "node:crypto"
6import { readFile } from "node:fs/promises"
7import { TestRunner } from "vitest"
8import * as Protocol from "./Protocol.ts"
9
10/**
11 * Wraps a Vitest runner so marked documentation files use doctest collectors.
12 *
13 * @category testing
14 * @since 4.0.0
15 */
16export const wrap = (Base: typeof TestRunner): typeof TestRunner => {
17 return class DoctestRunner extends Base {
18 override importFile(filepath: string, source: "collect" | "setup"): unknown {
19 if (source !== "collect") {
20 return super.importFile(filepath, source)
21 }
22
23 return readFile(filepath).then((contents) => {
24 if (!contents.includes("import.meta.vitest")) {
25 return super.importFile(filepath, source)
26 }
27
28 const version = createHash("sha256").update(contents).digest("hex").slice(0, 16)
29 return super.importFile(Protocol.collectorId(filepath, version), source)
30 })
31 }
32 }
33}
34
35/**
36 * Vitest runner that routes marked documentation files to doctest collectors.
37 *
38 * @category testing
39 * @since 4.0.0
40 */
41export default wrap(TestRunner)