✅ Assert README example results

Assign every documented matcher result to a variable and assert it with
`assert.equal`, so the compiled README doc-tests verify behavior instead
of merely running the code. The examples import `node:assert` themselves
to stay copy-pasteable; the generator now merges that import into its
prelude assert rather than rejecting it (only `node:test` remains
reserved).
This commit is contained in:
tmu committed 2026-09-24 12:13:36 +00:00
1 parent 30d97a9209
commit d0dd8641f2
3 files changed
+35 -13

No files matched your search

+16 -9
View File
@@ -46,18 +46,14 @@ const OUTPUT_DIR = "src/doc-test/__generated__";
const TYPESCRIPT_LANGS: ReadonlySet<string> = new Set(["ts", "typescript"]);
/**
* Modules the generated file already imports. An example that imports one of
* these would collide with the prelude binding (duplicate `test` / `assert`), so
* it is surfaced as a fatal error and the example is rewritten.
* Modules the generated file already binds. An example that imports `node:test`
* would collide with the prelude `test` binding, so it is surfaced as a fatal
* error. `node:assert` is allowed: it is merged into the prelude assert import.
*/
const PRELUDE_MODULES: ReadonlySet<string> = new Set([
"node:assert",
"node:test",
]);
const PRELUDE_MODULES: ReadonlySet<string> = new Set(["node:test"]);
/** One line of the prelude every generated file starts with. */
const PRELUDE_TEST = 'import { test } from "node:test";';
const PRELUDE_ASSERT = 'import { strict as assert } from "node:assert";';
/** Indentation applied to every fence body line inside the `test` callback. */
const INDENT = " ";
@@ -325,6 +321,17 @@ const handleNode = (state: BuilderState, name: string, node: Block): void => {
}
};
/**
* Guarantee `assert` is in scope in every generated file. The import is merged
* into any `node:assert` import an example already declares, so an example can
* stay self-contained without colliding with the harness.
*/
const ensurePreludeAssert = (named: Map<string, NamedImportGroup>): void => {
addNamedImport(named, { source: "node:assert", isType: false }, [
"strict as assert",
]);
};
/** Walk one Markdown file and collect its cases and hoisted imports. */
const parseDoc = (
name: string,
@@ -339,6 +346,7 @@ const parseDoc = (
for (const node of fromMarkdown(markdown).children) {
handleNode(state, name, node);
}
ensurePreludeAssert(state.named);
return {
named: state.named,
passthrough: state.passthrough,
@@ -368,7 +376,6 @@ const buildHeader = (name: string, imports: readonly string[]): string[] => {
`// Source: ${name}`,
EMPTY,
PRELUDE_TEST,
PRELUDE_ASSERT,
];
if (imports.length > INITIAL_COUNT) {
header.push(EMPTY, ...imports);