From 7bd53148d65e0055bfa8aa2f79f2b4171b58b001 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 22:11:03 -0500 Subject: [PATCH 1/2] refactor(html): move the engine host to src/engine.ts --- package.json | 8 ++++---- scripts/adversarial.ts | 2 +- scripts/bench-fragment.ts | 2 +- scripts/bench-tree.ts | 2 +- scripts/metrics.ts | 22 ++++++++++++++++------ scripts/metrics/protocol.ts | 4 ++-- scripts/metrics/sensitivity.ts | 8 ++++---- scripts/metrics/worker.ts | 2 +- src/{index.ts => engine.ts} | 0 test/complexity.test.ts | 2 +- test/dom.ts | 2 +- test/fast.test.ts | 2 +- test/fragments.ts | 2 +- test/fuzz.ts | 2 +- test/limits.test.ts | 2 +- test/memory-child.ts | 4 ++-- test/replay.test.ts | 2 +- test/tree.test.ts | 2 +- 18 files changed, 40 insertions(+), 30 deletions(-) rename src/{index.ts => engine.ts} (100%) diff --git a/package.json b/package.json index a128e2b..68c9c8f 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "type": "module", "sideEffects": false, "exports": { - ".": "./src/index.ts", + ".": "./src/engine.ts", "./package.json": "./package.json" }, "files": [ @@ -31,14 +31,14 @@ "access": "public", "exports": { ".": { - "types": "./dist/index.d.mts", - "import": "./dist/index.mjs" + "types": "./dist/engine.d.mts", + "import": "./dist/engine.mjs" }, "./package.json": "./package.json" } }, "scripts": { - "build": "pnpm run build:engine && bsh build --dts src/index.ts", + "build": "pnpm run build:engine && bsh build --dts src/engine.ts", "build:engine": "node scripts/engine.mjs", "check:engine": "node scripts/engine.mjs --check", "prepack": "test -f dist/wasm.mjs || { echo \"prepack: run pnpm build first\" >&2; exit 1; }", diff --git a/scripts/adversarial.ts b/scripts/adversarial.ts index bf7b506..ec3ab8b 100644 --- a/scripts/adversarial.ts +++ b/scripts/adversarial.ts @@ -1,7 +1,7 @@ // Times every test/adversarial.ts case at two sizes and flags growth well past linear. // Usage: node scripts/adversarial.ts [--parse5] [--small N] [--large N] [name filter] import { parse as parse5, parseFragment as parse5Fragment } from 'parse5'; -import { parse } from '../src/index.ts'; +import { parse } from '../src/engine.ts'; import { cases, type AdversarialCase } from '../test/adversarial.ts'; const args = process.argv.slice(2); diff --git a/scripts/bench-fragment.ts b/scripts/bench-fragment.ts index d94d289..d1cb586 100644 --- a/scripts/bench-fragment.ts +++ b/scripts/bench-fragment.ts @@ -3,7 +3,7 @@ // and parse5's parseFragment, medians of alternating rounds. Also the cost of a bail. Usage: // node scripts/bench-fragment.ts [rounds] import { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'; -import { parse, replay } from '../src/index.ts'; +import { parse, replay } from '../src/engine.ts'; import { PlainSink } from '../test/dom.ts'; import { parseInDiv, FULL, rng, subsetFragment } from '../test/fragments.ts'; diff --git a/scripts/bench-tree.ts b/scripts/bench-tree.ts index 6608789..933d9a1 100644 --- a/scripts/bench-tree.ts +++ b/scripts/bench-tree.ts @@ -2,7 +2,7 @@ // alternating rounds. Usage: node scripts/bench-tree.ts [rounds] [wasm path] import { readdirSync, readFileSync } from 'node:fs'; import { parse as parse5 } from 'parse5'; -import { parse, replay } from '../src/index.ts'; +import { parse, replay } from '../src/engine.ts'; import { createNode, PlainSink, type Node } from '../test/dom.ts'; interface Engine { diff --git a/scripts/metrics.ts b/scripts/metrics.ts index 57977a2..1ad542d 100644 --- a/scripts/metrics.ts +++ b/scripts/metrics.ts @@ -1,5 +1,5 @@ // The size and speed metrics the engine's hillclimbs judge changes by (docs/benchmarks.md). Builds nothing: it reads -// build/html.wasm, build/tokens.wasm and the current src/index.ts. The readable report goes to stderr, JSON to stdout. +// build/html.wasm, build/tokens.wasm and the current src/engine.ts. The readable report goes to stderr, JSON to stdout. // // node scripts/metrics.ts size, speed, and the comparison parsers // node scripts/metrics.ts --only size size alone (instant) @@ -42,7 +42,7 @@ const root = new URL('../', import.meta.url); const path = (p: string): string => fileURLToPath(new URL(p, root)); const HTML_WASM = path('build/html.wasm'); const TOKENS_WASM = path('build/tokens.wasm'); -const INDEX = path('src/index.ts'); +const INDEX = path('src/engine.ts'); // The ui suite runs @clack/ui from a checkout of bombshell-dev/ui, beside this repo unless UI_DOM names its dom.ts. const UI_DOM = process.env.UI_DOM ?? path('../ui/packages/ui/src/dom.ts'); const CORPUS = new URL('vendor/corpus/', root); @@ -193,7 +193,7 @@ async function sizes(): Promise> { 'html.wasm': size(readFileSync(HTML_WASM)), 'tokens.wasm': size(readFileSync(TOKENS_WASM)), 'wasm.ts': readFileSync(path('src/wasm.ts')).length, - 'index.ts (bundled, minified)': await wrapper(INDEX), + 'engine.ts (bundled, minified)': await wrapper(INDEX), }; } @@ -234,8 +234,8 @@ const candidateSubject = (): EngineSubject => index: read(args['candidate-index'] ?? INDEX), }); -// A .wasm file with --compare-index or the current src/index.ts, or a git ref's committed engine: the wasm its -// src/wasm.ts embeds, and the src/index.ts beside it. +// A .wasm file with --compare-index or the current src/engine.ts, or a git ref's committed engine: the wasm its +// src/wasm.ts embeds, and the src/engine.ts beside it. async function baseSubject(spec: string): Promise { if (spec.endsWith('.wasm')) { return staged({ @@ -249,12 +249,22 @@ async function baseSubject(spec: string): Promise { execFileSync('git', ['show', `${spec}:./${file}`], { cwd: fileURLToPath(root), encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, }); const module = new URL('wasm.ts', stage); writeFileSync(module, show('src/wasm.ts')); const { wasmBytes } = (await import(module.href)) as { wasmBytes(): Uint8Array }; - return staged({ slot: 'a', label: 'base', wasm: wasmBytes(), index: show('src/index.ts') }); + return staged({ slot: 'a', label: 'base', wasm: wasmBytes(), index: engineHost(show) }); +} + +// The module that drives the engine: src/engine.ts, or src/index.ts before the public layers split from it. +function engineHost(show: (file: string) => string): string { + try { + return show('src/engine.ts'); + } catch { + return show('src/index.ts'); + } } // ---- workloads diff --git a/scripts/metrics/protocol.ts b/scripts/metrics/protocol.ts index dfc2860..42360d4 100644 --- a/scripts/metrics/protocol.ts +++ b/scripts/metrics/protocol.ts @@ -1,6 +1,6 @@ // What scripts/metrics.ts and its sampling workers (scripts/metrics/worker.ts) exchange. -/** An engine is a build of html.wasm with the src/index.ts that drives it; a library is a comparison parser. */ +/** An engine is a build of html.wasm with the src/engine.ts that drives it; a library is a comparison parser. */ export type Subject = | { kind: 'engine'; label: string; wasm: string; index: string } | { kind: 'library'; label: string; name: LibraryName }; @@ -31,7 +31,7 @@ export interface WorkerData { subject: Subject; bands: string[][]; corpus: string[]; - /** src/index.ts as a file URL: imports of it resolve to the subject's index instead. */ + /** src/engine.ts as a file URL: imports of it resolve to the subject's index instead. */ realIndex: string; /** packages/ui/src/dom.ts as a file URL, when innerHTML workloads run. */ ui: string | null; diff --git a/scripts/metrics/sensitivity.ts b/scripts/metrics/sensitivity.ts index 1caf24b..433ce39 100644 --- a/scripts/metrics/sensitivity.ts +++ b/scripts/metrics/sensitivity.ts @@ -1,6 +1,6 @@ // Checks that scripts/metrics.ts's A/B mode resolves known differences and finds none between identical engines, // under whatever load the machine has now (docs/benchmarks.md#sensitivity). Builds its variants in a temporary -// directory from build/ and src/index.ts: the wrapper forced onto the full tree builder, html.wasm optimized with -O3 +// directory from build/ and src/engine.ts: the wrapper forced onto the full tree builder, html.wasm optimized with -O3 // instead of -Oz, and the wrapper with a spin loop in parse() that adds about 1.2% to fragment parse() time per 0.01. // Usage: node scripts/metrics/sensitivity.ts [spin factors, default 0.0125 0.025 0.05] import { execFileSync } from 'node:child_process'; @@ -13,16 +13,16 @@ const spins = process.argv.length > 2 ? process.argv.slice(2) : ['0.0125', '0.02 const dir = pathToFileURL(`${mkdtempSync(`${tmpdir()}/html-sensitivity-`)}/`); process.on('exit', () => rmSync(dir, { recursive: true, force: true })); -/** src/index.ts no longer has the line a variant rewrites. */ +/** src/engine.ts no longer has the line a variant rewrites. */ class VariantError extends Error { constructor(anchor: string) { super( - `src/index.ts has no ${JSON.stringify(anchor)} to rewrite; update scripts/metrics/sensitivity.ts`, + `src/engine.ts has no ${JSON.stringify(anchor)} to rewrite; update scripts/metrics/sensitivity.ts`, ); } } -const index = readFileSync(new URL('src/index.ts', root), 'utf8'); +const index = readFileSync(new URL('src/engine.ts', root), 'utf8'); function variant(name: string, edit: { anchor: string; replacement: string }): string { if (!index.includes(edit.anchor)) throw new VariantError(edit.anchor); const file = new URL(`${name}.ts`, dir); diff --git a/scripts/metrics/worker.ts b/scripts/metrics/worker.ts index 28bdc51..ea68b82 100644 --- a/scripts/metrics/worker.ts +++ b/scripts/metrics/worker.ts @@ -10,7 +10,7 @@ import type { OpLog, ParseOptions, TreeSink, -} from '../../src/index.ts'; +} from '../../src/engine.ts'; import type { DefaultTreeAdapterTypes } from 'parse5'; import type { EngineSubject, Prepared, Request, Sample, Workload, WorkerData } from './protocol.ts'; diff --git a/src/index.ts b/src/engine.ts similarity index 100% rename from src/index.ts rename to src/engine.ts diff --git a/test/complexity.test.ts b/test/complexity.test.ts index 02be4ce..80aaeb4 100644 --- a/test/complexity.test.ts +++ b/test/complexity.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { parse } from '../src/index.ts'; +import { parse } from '../src/engine.ts'; import { cases, growth, SCALE } from './adversarial.ts'; // Each case is timed at n and 8n and must grow well under quadratically: linear time gives about 8x, a quadratic diff --git a/test/dom.ts b/test/dom.ts index a8fe7df..91a62dd 100644 --- a/test/dom.ts +++ b/test/dom.ts @@ -5,7 +5,7 @@ import { type ElementNamespace, type QuirksMode, type TreeSink, -} from '../src/index.ts'; +} from '../src/engine.ts'; export interface Node { kind: 'document' | 'fragment' | 'element' | 'text' | 'comment' | 'doctype' | 'pi'; diff --git a/test/fast.test.ts b/test/fast.test.ts index cd4bf32..d4ad755 100644 --- a/test/fast.test.ts +++ b/test/fast.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { parse, replay } from '../src/index.ts'; +import { parse, replay } from '../src/engine.ts'; import { dump, PlainSink, type Node } from './dom.ts'; import { corpusFragments, diff --git a/test/fragments.ts b/test/fragments.ts index acbfc18..60de2c1 100644 --- a/test/fragments.ts +++ b/test/fragments.ts @@ -1,5 +1,5 @@ // Fragment inputs for the fast path's differential test (test/fast.test.ts) and acceptance report -// (scripts/fast-report.ts), and a raw handle on build/html.wasm that exposes what src/index.ts hides: the fast path's +// (scripts/fast-report.ts), and a raw handle on build/html.wasm that exposes what src/engine.ts hides: the fast path's // result and the log's exact bytes. import { readdirSync, readFileSync } from 'node:fs'; import { parse as parse5, type DefaultTreeAdapterTypes } from 'parse5'; diff --git a/test/fuzz.ts b/test/fuzz.ts index cf14fa2..9647733 100644 --- a/test/fuzz.ts +++ b/test/fuzz.ts @@ -8,7 +8,7 @@ // Some iterations also check what must not change a log: a different seed, a fresh instance, a budget it stays within // (and one it does not, which must stop it with the budget's status), and a memory cap (status 0 or 1, never a trap). import { readdirSync, readFileSync } from 'node:fs'; -import { replay, type OpLog } from '../src/index.ts'; +import { replay, type OpLog } from '../src/engine.ts'; import { PlainSink } from './dom.ts'; import { cappedModule, diff --git a/test/limits.test.ts b/test/limits.test.ts index 335d404..303bed3 100644 --- a/test/limits.test.ts +++ b/test/limits.test.ts @@ -1,6 +1,6 @@ import { readdirSync, readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { InvalidLimitError, LimitError, parse } from '../src/index.ts'; +import { InvalidLimitError, LimitError, parse } from '../src/engine.ts'; import { cases } from './adversarial.ts'; import { cappedModule, rawEngine, rawParse, sameRun } from './engine.ts'; import { rng, subsetFragment, wptFragments } from './fragments.ts'; diff --git a/test/memory-child.ts b/test/memory-child.ts index dc93fd5..309c472 100644 --- a/test/memory-child.ts +++ b/test/memory-child.ts @@ -1,5 +1,5 @@ // Run by test/memory.test.ts in its own process: caps the memory of every module compiled here, so the wrapper's -// engine (which src/index.ts caches) runs out of memory without affecting other test files. +// engine (which src/engine.ts caches) runs out of memory without affecting other test files. import { readdirSync, readFileSync } from 'node:fs'; import { capMemory } from './engine.ts'; @@ -8,7 +8,7 @@ WebAssembly.Module = function (bytes: BufferSource) { return new Module(capMemory(new Uint8Array(bytes as ArrayBuffer), 40)); } as unknown as typeof WebAssembly.Module; -const { parse, ResourceError } = await import('../src/index.ts'); +const { parse, ResourceError } = await import('../src/engine.ts'); const root = new URL('../', import.meta.url); // ASCII, so the input buffer needs one byte per character and fits; the arena and the tree do not. diff --git a/test/replay.test.ts b/test/replay.test.ts index 55bf986..c0d8f24 100644 --- a/test/replay.test.ts +++ b/test/replay.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { rawEngine, rawParse } from './engine.ts'; -import { parse, parseBytes, replay } from '../src/index.ts'; +import { parse, parseBytes, replay } from '../src/engine.ts'; import { PlainSink, type Node } from './dom.ts'; function tree(html: string): Node { diff --git a/test/tree.test.ts b/test/tree.test.ts index cfc6d2a..8091efe 100644 --- a/test/tree.test.ts +++ b/test/tree.test.ts @@ -1,6 +1,6 @@ import { readdirSync, readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { Namespace, parse, replay, type FragmentContext } from '../src/index.ts'; +import { Namespace, parse, replay, type FragmentContext } from '../src/engine.ts'; import { dump, PlainSink, type Node } from './dom.ts'; const root = new URL('../', import.meta.url); From 3d55fc00e518c5b4baff05d4f2df16ad91f9c0b3 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 22:11:03 -0500 Subject: [PATCH 2/2] feat(html): parse into a plain tree, a sink or an op log, from strings, bytes, iterables or streams --- .changeset/html-first-release.md | 4 +- docs/benchmarks.md | 8 +- docs/op-log.md | 2 +- package.json | 18 +++- scripts/metrics/worker.ts | 8 +- src/engine.ts | 29 ++++-- src/index.ts | 43 ++++++++ src/input.ts | 121 ++++++++++++++++++++++ src/log.ts | 22 ++++ src/shared.ts | 22 ++++ src/sink.ts | 35 +++++++ src/tree.ts | 113 ++++++++++++++++++++ test/api.test.ts | 171 +++++++++++++++++++++++++++++++ test/dom.ts | 23 +++++ test/tree.test.ts | 16 ++- 15 files changed, 609 insertions(+), 26 deletions(-) create mode 100644 src/index.ts create mode 100644 src/input.ts create mode 100644 src/log.ts create mode 100644 src/shared.ts create mode 100644 src/sink.ts create mode 100644 src/tree.ts create mode 100644 test/api.test.ts diff --git a/.changeset/html-first-release.md b/.changeset/html-first-release.md index 7c18a95..28be598 100644 --- a/.changeset/html-first-release.md +++ b/.changeset/html-first-release.md @@ -2,4 +2,6 @@ '@bomb.sh/html': minor --- -Adds `@bomb.sh/html`, a spec-conformant HTML parser compiled to WebAssembly. `parse()` turns a document or a fragment in a context element into an op log, and `replay()` applies it to any DOM through a `TreeSink`. `parse(html, { limits: { nodes, logBytes } })` stops a parse that builds more than its budget with a `LimitError`. The engine is embedded in the package, seeds its hash tables per instance, and compiles on the first parse. +Adds `@bomb.sh/html`, a spec-conformant HTML parser compiled to WebAssembly. `parse(html)` returns a document tree of plain objects, and `parseFragment(html, { context: 'div' })` parses a fragment the way `innerHTML` does. Both take a string, UTF-8 bytes, or an iterable of either, and return synchronously; given an async iterable or a `ReadableStream`, they return a promise. + +`@bomb.sh/html/sink` parses into any DOM through a `TreeSink`, and `@bomb.sh/html/log` returns the engine's op log and `replay()`s it. `limits: { nodes, logBytes }` stops a parse that builds more than its budget with a `LimitError`, before a sink sees any of it. The engine is embedded in the package, seeds its hash tables per instance, and compiles on the first parse. diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 6268990..96331f2 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -13,7 +13,7 @@ pnpm metrics --only size # size alone, about 1 s pnpm metrics --compare HEAD # A/B against the last commit, about 40 s ``` -The command builds nothing. It reads `build/html.wasm`, `build/tokens.wasm` and the current `src/index.ts`, so run +The command builds nothing. It reads `build/html.wasm`, `build/tokens.wasm` and the current `src/engine.ts`, so run `scripts/build.sh` (or `pnpm test`, which runs it) after changing the engine. The speed section also needs `vendor/corpus`, which `scripts/corpus.sh` fetches and the test script vendors. @@ -24,8 +24,8 @@ operation, plus the commit, whether the tree is dirty, the load average and the | Option | Effect | | --- | --- | | `--only size` / `--only speed` | One section. | -| `--compare ` | A/B: the committed engine at a git ref (the wasm its `src/wasm.ts` embeds, and its `src/index.ts`) against the working tree's `build/html.wasm` and `src/index.ts`. | -| `--compare ` | A/B against a saved build, driven by `--compare-index ` or the current `src/index.ts`. | +| `--compare ` | A/B: the committed engine at a git ref (the wasm its `src/wasm.ts` embeds, and its `src/engine.ts`, or `src/index.ts` before the public layers split from it) against the working tree's `build/html.wasm` and `src/index.ts`. | +| `--compare ` | A/B against a saved build, driven by `--compare-index ` or the current `src/engine.ts`. | | `--candidate `, `--candidate-index ` | Replace the working tree's side of an A/B. | | `--suite fragment\|corpus\|ui` | Run only these suites (repeatable). | | `--samples N`, `--lanes N` | Rounds and sampling lanes: 32 and 8 for an A/B, 32 and 2 otherwise. | @@ -38,7 +38,7 @@ operation, plus the commit, whether the tree is dirty, the load average and the ### Size The size metric is **the brotli -11 size of `build/html.wasm`**, the bytes `src/wasm.ts` embeds. The report also -gives raw and `gzip -9n` sizes of `html.wasm` and `tokens.wasm`, the bytes of `src/wasm.ts`, and `src/index.ts` +gives raw and `gzip -9n` sizes of `html.wasm` and `tokens.wasm`, the bytes of `src/wasm.ts`, and `src/engine.ts` bundled and minified with esbuild (`--bundle --minify --format=esm`, with `wasm.ts` left external). Size is exact: no noise, no sampling. `gzip -9n` omits the file name, so it reads a few bytes below the `gzip -9c` figures that `scripts/build.sh` prints. diff --git a/docs/op-log.md b/docs/op-log.md index 967789b..dc01d56 100644 --- a/docs/op-log.md +++ b/docs/op-log.md @@ -1,7 +1,7 @@ # Op log format `build/html.wasm` does not build a tree. Tree construction appends operations to a log in linear memory, and a host -applies them to its own nodes. `replay()` in `src/index.ts` is the reference consumer. +applies them to its own nodes. `replay()` in `src/engine.ts`, exported from `@bomb.sh/html/log`, is the reference consumer. The log is append-only, so a later streaming parser can hand out a prefix of it while parsing continues. The adoption agency algorithm and foster parenting move nodes that earlier records already placed, so the log has diff --git a/package.json b/package.json index 68c9c8f..61e6a5e 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,9 @@ "type": "module", "sideEffects": false, "exports": { - ".": "./src/engine.ts", + ".": "./src/index.ts", + "./sink": "./src/sink.ts", + "./log": "./src/log.ts", "./package.json": "./package.json" }, "files": [ @@ -31,14 +33,22 @@ "access": "public", "exports": { ".": { - "types": "./dist/engine.d.mts", - "import": "./dist/engine.mjs" + "types": "./dist/index.d.mts", + "import": "./dist/index.mjs" + }, + "./sink": { + "types": "./dist/sink.d.mts", + "import": "./dist/sink.mjs" + }, + "./log": { + "types": "./dist/log.d.mts", + "import": "./dist/log.mjs" }, "./package.json": "./package.json" } }, "scripts": { - "build": "pnpm run build:engine && bsh build --dts src/engine.ts", + "build": "pnpm run build:engine && bsh build --dts src/index.ts src/sink.ts src/log.ts", "build:engine": "node scripts/engine.mjs", "check:engine": "node scripts/engine.mjs --check", "prepack": "test -f dist/wasm.mjs || { echo \"prepack: run pnpm build first\" >&2; exit 1; }", diff --git a/scripts/metrics/worker.ts b/scripts/metrics/worker.ts index ea68b82..69a4685 100644 --- a/scripts/metrics/worker.ts +++ b/scripts/metrics/worker.ts @@ -8,14 +8,14 @@ import type { Attribute, ElementNamespace, OpLog, - ParseOptions, + EngineOptions, TreeSink, } from '../../src/engine.ts'; import type { DefaultTreeAdapterTypes } from 'parse5'; import type { EngineSubject, Prepared, Request, Sample, Workload, WorkerData } from './protocol.ts'; interface Html { - parse(html: string, options?: ParseOptions): OpLog; + parse(html: string, options?: EngineOptions): OpLog; replay(log: OpLog, sink: TreeSink): N[]; } @@ -177,9 +177,9 @@ async function engineImplementation(engine: EngineSubject): Promise + const fragment = (w: Workload): EngineOptions => w.fast ? { context: 'div' } : { context: 'div', fastPath: false }; - const document: ParseOptions = { scripting: true }; + const document: EngineOptions = { scripting: true }; const tree = (w: Workload, source: string): PlainNode => html.replay( diff --git a/src/engine.ts b/src/engine.ts index 1cd85b7..7de3a22 100644 --- a/src/engine.ts +++ b/src/engine.ts @@ -55,15 +55,8 @@ export interface FragmentContext { } export interface ParseOptions { - /** Parse a fragment in this context element instead of a document. */ - context?: string | FragmentContext; /** The scripting flag: `noscript` content is raw text when on. Defaults to off. */ scripting?: boolean; - /** - * Try the fragment fast path first (docs/decisions.md), which gives the same log on the input it accepts. Off - * forces the full tree builder, for testing. Defaults to on. - */ - fastPath?: boolean; /** * Stops a parse that builds more than this, with a LimitError. Unlimited by default. The spec makes some input * build a tree quadratic in its size (`

x

` repeated n times builds about n²/2 elements), so a host @@ -72,6 +65,17 @@ export interface ParseOptions { limits?: ParseLimits; } +/** What the engine takes beyond the public options. The public layers decide context by the function called. */ +export interface EngineOptions extends ParseOptions { + /** Parse a fragment in this context element instead of a document. */ + context?: string | FragmentContext; + /** + * Try the fragment fast path first (docs/decisions.md), which gives the same log on the input it accepts. Off + * forces the full tree builder, for testing. Defaults to on. + */ + fastPath?: boolean; +} + export interface ParseLimits { /** The most nodes the log may create, not counting the root. */ nodes?: number; @@ -264,7 +268,7 @@ function contextFlags(c: FragmentContext): number { * Parses an HTML document, or a fragment when `options.context` is set, into an op log. The engine compiles on the * first call. */ -export function parse(html: string, options: ParseOptions = {}): OpLog { +export function parse(html: string, options: EngineOptions = {}): OpLog { const x = instance(); // V8's UTF-8 encoder runs near 1 GB/s even on one-byte strings, while Buffer's latin1 write is a memcpy, and // ASCII is the same bytes in both. @@ -280,7 +284,7 @@ export function parse(html: string, options: ParseOptions = {}): OpLog { } /** Like parse, for input that is already UTF-8. */ -export function parseBytes(html: Uint8Array, options: ParseOptions = {}): OpLog { +export function parseBytes(html: Uint8Array, options: EngineOptions = {}): OpLog { const x = instance(); const base = reserve(x, html.length); memoryView(x).set(html, base); @@ -326,7 +330,7 @@ function reserve(x: Exports, cap: number): number { } // Parses the len bytes already written at the input buffer. -function run(len: number, options: ParseOptions): OpLog { +function run(len: number, options: EngineOptions): OpLog { const x = instance(); const base = inputBase; let context = 0; @@ -574,3 +578,8 @@ export function replay(log: OpLog, sink: TreeSink): N[] { } return nodes; } + +/** Parses input that the public layers have gathered into one string or one UTF-8 buffer. */ +export function parseInput(input: string | Uint8Array, options: EngineOptions): OpLog { + return typeof input === 'string' ? parse(input, options) : parseBytes(input, options); +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..0451f60 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,43 @@ +import { parseInput, replay, type EngineOptions, type ParseOptions } from './engine.ts'; +import { withInput, type AsyncInput, type Input, type SyncInput } from './input.ts'; +import type { FragmentOptions } from './shared.ts'; +import { TreeBuilder, type Document, type DocumentFragment, type Node } from './tree.ts'; + +export * from './shared.ts'; +export type { + ChildNode, + Comment, + Document, + DocumentFragment, + DocumentType, + Element, + Node, + ParentNode, + ProcessingInstruction, + Text, +} from './tree.ts'; + +/** Parses an HTML document into a tree of plain objects. The engine compiles on the first call. */ +export function parse(input: SyncInput, options?: ParseOptions): Document; +/** Parses an HTML document from an async iterable or stream into a tree of plain objects. */ +export function parse(input: AsyncInput, options?: ParseOptions): Promise; +export function parse(input: Input, options?: ParseOptions): Document | Promise { + return withInput(input, (html) => build(html, options) as Document); +} + +/** Parses an HTML fragment in `options.context`, as `innerHTML` does, into a tree of plain objects. */ +export function parseFragment(input: SyncInput, options: FragmentOptions): DocumentFragment; +/** Parses an HTML fragment from an async iterable or stream into a tree of plain objects. */ +export function parseFragment( + input: AsyncInput, + options: FragmentOptions, +): Promise; +export function parseFragment( + input: Input, + options: FragmentOptions, +): DocumentFragment | Promise { + return withInput(input, (html) => build(html, options) as DocumentFragment); +} + +const build = (html: string | Uint8Array, options: EngineOptions = {}): Node => + replay(parseInput(html, options), new TreeBuilder())[0]!; diff --git a/src/input.ts b/src/input.ts new file mode 100644 index 0000000..193c1ad --- /dev/null +++ b/src/input.ts @@ -0,0 +1,121 @@ +/** Input every layer takes and returns synchronously: a string, UTF-8 bytes, or an iterable of either. */ +export type SyncInput = string | Uint8Array | Iterable; +/** Input every layer takes and returns a promise for. */ +export type AsyncInput = AsyncIterable | ReadableStream; +export type Input = SyncInput | AsyncInput; + +/** Input that is not a string, bytes, an iterable or a stream, or a chunk that is not a string or bytes. */ +export class InputError extends TypeError { + /** What was received instead: `typeof`, or the constructor's name for an object. */ + readonly received: string; + constructor(what: 'input' | 'chunk', received: string) { + super( + what === 'input' + ? `html input must be a string, a Uint8Array, an iterable or a stream, not ${received}` + : `html input chunks must be strings or Uint8Arrays, not ${received}`, + ); + this.received = received; + } +} + +/** What the engine parses: one string, or one buffer of UTF-8. */ +type Gathered = string | Uint8Array; + +const encoder = new TextEncoder(); + +// Gathers chunks in order. Consecutive strings join before encoding, so a surrogate pair split across two string +// chunks stays one character. A UTF-8 byte order mark is dropped when the input starts with bytes, as the spec's +// decoder does; a string's leading U+FEFF is text, and stays. +class Chunks { + #parts: Gathered[] = []; + #strings: string[] = []; + #bytes = false; + + add(chunk: unknown): void { + if (typeof chunk === 'string') { + this.#strings.push(chunk); + return; + } + if (!(chunk instanceof Uint8Array)) { + throw new InputError('chunk', describe(chunk)); + } + if (this.#parts.length === 0 && this.#strings.length === 0) this.#bytes = true; + this.#flush(); + this.#parts.push(chunk); + } + + done(): Gathered { + this.#flush(); + const parts = this.#parts; + if (parts.length === 0) return ''; + if (parts.length === 1) { + const only = parts[0]!; + return typeof only === 'string' ? only : withoutBom(only); + } + const encoded = parts.map((p) => (typeof p === 'string' ? encoder.encode(p) : p)); + let length = 0; + for (const p of encoded) length += p.length; + const out = new Uint8Array(length); + let at = 0; + for (const p of encoded) { + out.set(p, at); + at += p.length; + } + return this.#bytes ? withoutBom(out) : out; + } + + #flush(): void { + if (this.#strings.length === 0) return; + this.#parts.push(this.#strings.join('')); + this.#strings = []; + } +} + +const withoutBom = (bytes: Uint8Array): Uint8Array => + bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? bytes.subarray(3) : bytes; + +function describe(value: unknown): string { + if (value === null) return 'null'; + if (typeof value === 'object') return value.constructor?.name ?? 'an object'; + return typeof value; +} + +const isAsync = (input: object): input is AsyncInput => + Symbol.asyncIterator in input || 'getReader' in input; + +function gather(input: SyncInput): Gathered { + if (typeof input === 'string') return input; + if (input instanceof Uint8Array) return withoutBom(input); + if (input == null || typeof input[Symbol.iterator] !== 'function') { + throw new InputError('input', describe(input)); + } + const chunks = new Chunks(); + for (const chunk of input) chunks.add(chunk); + return chunks.done(); +} + +async function gatherAsync(input: AsyncInput): Promise { + const chunks = new Chunks(); + if (Symbol.asyncIterator in input) { + for await (const chunk of input as AsyncIterable) chunks.add(chunk); + } else { + const reader = (input as ReadableStream).getReader(); + try { + for (let r = await reader.read(); !r.done; r = await reader.read()) chunks.add(r.value); + } finally { + reader.releaseLock(); + } + } + return chunks.done(); +} + +/** + * Gathers input and hands it to parse: synchronously for strings, bytes and iterables, through a promise for async + * iterables and streams. Phase 1 of streaming (docs/api-sketch.md): the engine parses once the input ends. + */ +export function withInput(input: Input, parse: (gathered: Gathered) => T): T | Promise { + if (typeof input === 'string') return parse(input); + if (input !== null && typeof input === 'object' && isAsync(input)) + return gatherAsync(input).then(parse); + return parse(gather(input as SyncInput)); +} diff --git a/src/log.ts b/src/log.ts new file mode 100644 index 0000000..427b9c6 --- /dev/null +++ b/src/log.ts @@ -0,0 +1,22 @@ +import { parseInput, type OpLog, type ParseOptions } from './engine.ts'; +import { withInput, type AsyncInput, type Input, type SyncInput } from './input.ts'; +import type { FragmentOptions } from './shared.ts'; + +export * from './shared.ts'; +export { OpLogError, replay, type OpLog, type TreeSink } from './engine.ts'; + +/** Parses an HTML document into an op log (docs/op-log.md). The engine compiles on the first call. */ +export function parse(input: SyncInput, options?: ParseOptions): OpLog; +/** Parses an HTML document from an async iterable or stream into an op log. */ +export function parse(input: AsyncInput, options?: ParseOptions): Promise; +export function parse(input: Input, options: ParseOptions = {}): OpLog | Promise { + return withInput(input, (html) => parseInput(html, options)); +} + +/** Parses an HTML fragment in `options.context`, as `innerHTML` does, into an op log. */ +export function parseFragment(input: SyncInput, options: FragmentOptions): OpLog; +/** Parses an HTML fragment from an async iterable or stream into an op log. */ +export function parseFragment(input: AsyncInput, options: FragmentOptions): Promise; +export function parseFragment(input: Input, options: FragmentOptions): OpLog | Promise { + return withInput(input, (html) => parseInput(html, options)); +} diff --git a/src/shared.ts b/src/shared.ts new file mode 100644 index 0000000..d246601 --- /dev/null +++ b/src/shared.ts @@ -0,0 +1,22 @@ +export { + InvalidLimitError, + LimitError, + Namespace, + ResourceError, + type Attribute, + type AttributeNamespace, + type ElementNamespace, + type FragmentContext, + type ParseLimits, + type ParseOptions, + type QuirksMode, +} from './engine.ts'; +export { InputError, type AsyncInput, type Input, type SyncInput } from './input.ts'; + +import type { FragmentContext, ParseOptions } from './engine.ts'; + +/** Options for parsing a fragment: the element it is parsed in, as for `innerHTML`. */ +export interface FragmentOptions extends ParseOptions { + /** A local name such as `div`, or a FragmentContext for SVG, MathML, forms and quirks. */ + context: string | FragmentContext; +} diff --git a/src/sink.ts b/src/sink.ts new file mode 100644 index 0000000..9ee18ea --- /dev/null +++ b/src/sink.ts @@ -0,0 +1,35 @@ +import { parseInput, replay, type ParseOptions, type TreeSink } from './engine.ts'; +import { withInput, type AsyncInput, type Input, type SyncInput } from './input.ts'; +import type { FragmentOptions } from './shared.ts'; + +export * from './shared.ts'; +export type { TreeSink } from './engine.ts'; + +// The whole input parses before the sink sees its first call, so a LimitError or ResourceError leaves the sink's +// tree untouched. A future incremental engine may call the sink before an async input ends (docs/api-sketch.md). + +/** Options for parsing into a sink: the TreeSink that builds the host's nodes. */ +export interface SinkOptions extends ParseOptions { + sink: TreeSink; +} + +/** Options for parsing a fragment into a sink. */ +export interface SinkFragmentOptions extends FragmentOptions { + sink: TreeSink; +} + +/** Parses an HTML document into `options.sink`, and returns the root it created. The engine compiles on the first call. */ +export function parse(input: SyncInput, options: SinkOptions): N; +/** Parses an HTML document from an async iterable or stream into `options.sink`. */ +export function parse(input: AsyncInput, options: SinkOptions): Promise; +export function parse(input: Input, options: SinkOptions): N | Promise { + return withInput(input, (html) => replay(parseInput(html, options), options.sink)[0]!); +} + +/** Parses an HTML fragment in `options.context`, as `innerHTML` does, into `options.sink`, and returns the fragment root. */ +export function parseFragment(input: SyncInput, options: SinkFragmentOptions): N; +/** Parses an HTML fragment from an async iterable or stream into `options.sink`. */ +export function parseFragment(input: AsyncInput, options: SinkFragmentOptions): Promise; +export function parseFragment(input: Input, options: SinkFragmentOptions): N | Promise { + return withInput(input, (html) => replay(parseInput(html, options), options.sink)[0]!); +} diff --git a/src/tree.ts b/src/tree.ts new file mode 100644 index 0000000..b89bd24 --- /dev/null +++ b/src/tree.ts @@ -0,0 +1,113 @@ +import type { Attribute, ElementNamespace, QuirksMode, TreeSink } from './engine.ts'; + +export interface Document { + type: 'document'; + mode: QuirksMode; + children: ChildNode[]; +} +export interface DocumentFragment { + type: 'fragment'; + children: ChildNode[]; +} +export interface Element { + type: 'element'; + /** The local name, e.g. `div` or `foreignObject`. */ + name: string; + namespace: ElementNamespace; + /** In source order. */ + attributes: Attribute[]; + children: ChildNode[]; + /** A `template` element's contents. */ + content?: DocumentFragment; +} +export interface Text { + type: 'text'; + data: string; +} +export interface Comment { + type: 'comment'; + data: string; +} +export interface DocumentType { + type: 'doctype'; + name: string; + publicId: string; + systemId: string; +} +export interface ProcessingInstruction { + type: 'processing-instruction'; + target: string; + data: string; +} +export type ParentNode = Document | DocumentFragment | Element; +export type ChildNode = Element | Text | Comment | DocumentType | ProcessingInstruction; +export type Node = ParentNode | ChildNode; + +/** The sink behind `parse` and `parseFragment`: builds plain objects. Parents live here, not on the nodes. */ +export class TreeBuilder implements TreeSink { + #root: Document | DocumentFragment | undefined; + #parents = new Map(); + + createRoot(fragment: boolean): Node { + this.#root = fragment + ? { type: 'fragment', children: [] } + : { type: 'document', mode: 'no-quirks', children: [] }; + return this.#root; + } + createElement(name: string, namespace: ElementNamespace, attributes: readonly Attribute[]): Node { + return { + type: 'element', + name, + namespace, + attributes: attributes as Attribute[], + children: [], + }; + } + createText(data: string): Node { + return { type: 'text', data }; + } + createComment(data: string): Node { + return { type: 'comment', data }; + } + createDoctype(name: string, publicId: string, systemId: string): Node { + return { type: 'doctype', name, publicId, systemId }; + } + createProcessingInstruction(target: string, data: string): Node { + return { type: 'processing-instruction', target, data }; + } + templateContents(template: Node): Node { + const content: DocumentFragment = { type: 'fragment', children: [] }; + (template as Element).content = content; + return content; + } + insert(parent: Node, child: Node, ref: Node | null): void { + const children = (parent as ParentNode).children; + if (ref === null) children.push(child as ChildNode); + else children.splice(children.indexOf(ref as ChildNode), 0, child as ChildNode); + this.#parents.set(child, parent as ParentNode); + } + remove(child: Node): void { + const parent = this.#parents.get(child); + if (parent === undefined) return; + parent.children.splice(parent.children.indexOf(child as ChildNode), 1); + this.#parents.delete(child); + } + moveChildren(from: Node, to: Node): void { + const source = (from as ParentNode).children; + const target = (to as ParentNode).children; + for (const child of source) { + target.push(child); + this.#parents.set(child, to as ParentNode); + } + source.length = 0; + } + appendText(text: Node, data: string): void { + (text as Text).data += data; + } + addAttributes(element: Node, attributes: readonly Attribute[]): void { + (element as Element).attributes.push(...attributes); + } + setQuirksMode(mode: QuirksMode): void { + if (this.#root?.type === 'document') this.#root.mode = mode; + } +} diff --git a/test/api.test.ts b/test/api.test.ts new file mode 100644 index 0000000..045c50d --- /dev/null +++ b/test/api.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from 'vitest'; +import { + InputError, + LimitError, + Namespace, + parse, + parseFragment, + type ChildNode, + type Element, + type Node, +} from '../src/index.ts'; +import * as log from '../src/log.ts'; +import * as sink from '../src/sink.ts'; + +// A compact rendering of the default tree, so each case asserts one literal string. +function show(n: Node): string { + switch (n.type) { + case 'document': + return `#document(${n.mode})[${n.children.map(show).join(',')}]`; + case 'fragment': + return `#fragment[${n.children.map(show).join(',')}]`; + case 'element': { + const attrs = n.attributes.map((a) => ` ${a.name}=${JSON.stringify(a.value)}`).join(''); + const content = n.content ? ` content=${show(n.content)}` : ''; + return `<${n.name}${attrs}${content}>[${n.children.map(show).join(',')}]`; + } + case 'text': + return JSON.stringify(n.data); + case 'comment': + return ``; + case 'doctype': + return ``; + case 'processing-instruction': + return ``; + } +} + +const encode = (s: string): Uint8Array => new TextEncoder().encode(s); +const first = (children: ChildNode[]): Element => children[0] as Element; + +describe('parse', () => { + it('builds a document tree', () => { + expect(show(parse('t

hix

'))).toBe( + '#document(no-quirks)[,[[["t"]],<body>[<p class="a">["hi",<b>["x"]],<!--c-->]]]', + ); + }); + + it('records the quirks mode', () => { + expect(parse('<p>').mode).toBe('quirks'); + }); + + it('applies the scripting flag', () => { + const noscript = (scripting: boolean): string => + show(parseFragment('<noscript><b>x</b></noscript>', { context: 'div', scripting })); + expect(noscript(true)).toBe('#fragment[<noscript>["<b>x</b>"]]'); + expect(noscript(false)).toBe('#fragment[<noscript>[<b>["x"]]]'); + }); +}); + +describe('parseFragment', () => { + it('parses in a context element named by a string', () => { + expect(show(parseFragment('<td>1<td>2', { context: 'tr' }))).toBe( + '#fragment[<td>["1"],<td>["2"]]', + ); + }); + + it('parses in a FragmentContext', () => { + const svg = parseFragment('<circle/>', { context: { name: 'svg', namespace: Namespace.SVG } }); + expect(first(svg.children).namespace).toBe(Namespace.SVG); + }); + + it('puts template contents on content', () => { + expect(show(parseFragment('<template><i>x</i></template>', { context: 'div' }))).toBe( + '#fragment[<template content=#fragment[<i>["x"]]>[]]', + ); + }); + + it('reorders through the adoption agency and foster parenting', () => { + expect(show(parseFragment('<b>1<p>2</b>3</p>', { context: 'div' }))).toBe( + '#fragment[<b>["1"],<p>[<b>["2"],"3"]]', + ); + expect(show(parseFragment('<table>x<tr><td>y</table>', { context: 'div' }))).toBe( + '#fragment["x",<table>[<tbody>[<tr>[<td>["y"]]]]]', + ); + }); +}); + +describe('input', () => { + it('decodes bytes as UTF-8 and drops a byte order mark', () => { + const bytes = new Uint8Array([0xef, 0xbb, 0xbf, ...encode('<b>é</b>')]); + expect(show(parseFragment(bytes, { context: 'div' }))).toBe('#fragment[<b>["é"]]'); + }); + + it('keeps a string’s leading U+FEFF, which is text', () => { + expect(show(parseFragment('x', { context: 'div' }))).toBe('#fragment["x"]'); + }); + + it('joins an iterable of strings across a split surrogate pair', () => { + expect(show(parseFragment(['<b>\uD83D', '\uDE00</b>'], { context: 'div' }))).toBe( + '#fragment[<b>["😀"]]', + ); + }); + + it('joins an iterable of bytes across a split UTF-8 sequence', () => { + const chunks = [encode('<b>é').subarray(0, 4), encode('é</b>').subarray(1)]; + expect(show(parseFragment(chunks, { context: 'div' }))).toBe('#fragment[<b>["é"]]'); + }); + + it('takes mixed chunks from an async iterable and returns a promise', async () => { + async function* chunks(): AsyncGenerator<string | Uint8Array> { + yield '<ul><li>a'; + yield encode('<li>b</ul>'); + } + const result = parseFragment(chunks(), { context: 'div' }); + expect(result).toBeInstanceOf(Promise); + expect(show(await result)).toBe('#fragment[<ul>[<li>["a"],<li>["b"]]]'); + }); + + it('takes a ReadableStream', async () => { + const stream = new ReadableStream<string>({ + start(c) { + c.enqueue('<p>s'); + c.enqueue('tream'); + c.close(); + }, + }); + expect(show(await parseFragment(stream, { context: 'div' }))).toBe('#fragment[<p>["stream"]]'); + }); + + it('takes an empty iterable as empty input', () => { + expect(show(parseFragment([], { context: 'div' }))).toBe('#fragment[]'); + }); + + it('rejects input that is not text', () => { + expect(() => parse(42 as never)).toThrow(new InputError('input', 'number')); + expect(() => parse([1] as never)).toThrow(new InputError('chunk', 'number')); + expect(new InputError('input', 'number').message).toBe( + 'html input must be a string, a Uint8Array, an iterable or a stream, not number', + ); + }); +}); + +describe('layers', () => { + it('log returns an op log that replays into the same tree', () => { + const opLog = log.parseFragment('<p>x', { context: 'div' }); + expect(opLog.fragment).toBe(true); + expect(opLog.nodeCount).toBe(3); + const names: string[] = []; + log.replay(opLog, { + createRoot: () => 'root', + createElement: (name: string) => (names.push(name), name), + createText: (data: string) => (names.push(data), data), + insert: () => {}, + } as unknown as log.TreeSink<string>); + expect(names).toEqual(['p', 'x']); + }); + + it('sink returns the root it created, and an over-budget parse never reaches the sink', () => { + const calls: string[] = []; + const recorder = new Proxy({} as sink.TreeSink<string>, { + get: (_, method: string) => () => (calls.push(method), method), + }); + expect(sink.parseFragment('<p>', { context: 'div', sink: recorder })).toBe('createRoot'); + expect(calls).toEqual(['createRoot', 'createElement', 'insert']); + calls.length = 0; + expect(() => sink.parse('<p>'.repeat(100), { sink: recorder, limits: { nodes: 10 } })).toThrow( + LimitError, + ); + expect(calls).toEqual([]); + }); +}); diff --git a/test/dom.ts b/test/dom.ts index 91a62dd..9236949 100644 --- a/test/dom.ts +++ b/test/dom.ts @@ -6,6 +6,7 @@ import { type QuirksMode, type TreeSink, } from '../src/engine.ts'; +import type { Node as TreeNode } from '../src/tree.ts'; export interface Node { kind: 'document' | 'fragment' | 'element' | 'text' | 'comment' | 'doctype' | 'pi'; @@ -144,3 +145,25 @@ export function dump(root: Node): string { for (const c of root.children) walk(c, 0); return lines.join('\n'); } + +/** The public tree (src/tree.ts) as a test Node, so dump can print it. */ +export function fromTree(n: TreeNode): Node { + const out = createNode(n.type === 'processing-instruction' ? 'pi' : n.type); + if (n.type === 'element') { + out.name = n.name; + out.namespace = n.namespace; + out.attributes = n.attributes; + if (n.content) out.content = fromTree(n.content); + } else if (n.type === 'text' || n.type === 'comment') { + out.data = n.data; + } else if (n.type === 'processing-instruction') { + out.name = n.target; + out.data = n.data; + } else if (n.type === 'doctype') { + out.name = n.name; + out.publicId = n.publicId; + out.systemId = n.systemId; + } + if ('children' in n) out.children = n.children.map(fromTree); + return out; +} diff --git a/test/tree.test.ts b/test/tree.test.ts index 8091efe..123489f 100644 --- a/test/tree.test.ts +++ b/test/tree.test.ts @@ -1,7 +1,8 @@ import { readdirSync, readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; import { Namespace, parse, replay, type FragmentContext } from '../src/engine.ts'; -import { dump, PlainSink, type Node } from './dom.ts'; +import * as api from '../src/index.ts'; +import { dump, fromTree, PlainSink, type Node } from './dom.ts'; const root = new URL('../', import.meta.url); const suite = new URL('vendor/wpt/html/syntax/parsing/resources/', root); @@ -75,6 +76,15 @@ export function treeDump(test: Case, scripting: boolean): string { return dump(replay(log, new PlainSink())[0] as Node); } +/** The same dump through the public API's default tree, which must match replaying into PlainSink. */ +function apiDump(test: Case, scripting: boolean): string { + const tree = + test.fragment === undefined + ? api.parse(test.data, { scripting }) + : api.parseFragment(test.data, { context: context(test.fragment), scripting }); + return dump(fromTree(tree)); +} + const files = readdirSync(suite).filter((f) => f.endsWith('.dat')); describe('WPT tree construction', () => { @@ -89,7 +99,9 @@ describe('WPT tree construction', () => { const id = `${file}#${index}${scripting ? ' script-on' : ''}`; const run = baseline.has(id) ? it.fails : it; run(`${id}: ${JSON.stringify(test.data)}`, () => { - expect(treeDump(test, scripting)).toBe(test.document); + const tree = treeDump(test, scripting); + expect(apiDump(test, scripting)).toBe(tree); + expect(tree).toBe(test.document); }); } });