Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .changeset/html-first-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 4 additions & 4 deletions docs/benchmarks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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 <ref>` | 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 <file.wasm>` | A/B against a saved build, driven by `--compare-index <file.ts>` or the current `src/index.ts`. |
| `--compare <ref>` | 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 <file.wasm>` | A/B against a saved build, driven by `--compare-index <file.ts>` or the current `src/engine.ts`. |
| `--candidate <file.wasm>`, `--candidate-index <file.ts>` | 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. |
Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/op-log.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
"sideEffects": false,
"exports": {
".": "./src/index.ts",
"./sink": "./src/sink.ts",
"./log": "./src/log.ts",
"./package.json": "./package.json"
},
"files": [
Expand All @@ -34,11 +36,19 @@
"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/index.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; }",
Expand Down
2 changes: 1 addition & 1 deletion scripts/adversarial.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down
2 changes: 1 addition & 1 deletion scripts/bench-fragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
2 changes: 1 addition & 1 deletion scripts/bench-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
22 changes: 16 additions & 6 deletions scripts/metrics.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -193,7 +193,7 @@ async function sizes(): Promise<Record<string, Size | number>> {
'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),
};
}

Expand Down Expand Up @@ -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<EngineSubject> {
if (spec.endsWith('.wasm')) {
return staged({
Expand All @@ -249,12 +249,22 @@ async function baseSubject(spec: string): Promise<EngineSubject> {
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
Expand Down
4 changes: 2 additions & 2 deletions scripts/metrics/protocol.ts
Original file line number Diff line number Diff line change
@@ -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 };
Expand Down Expand Up @@ -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;
Expand Down
8 changes: 4 additions & 4 deletions scripts/metrics/sensitivity.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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);
Expand Down
10 changes: 5 additions & 5 deletions scripts/metrics/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import type {
Attribute,
ElementNamespace,
OpLog,
ParseOptions,
EngineOptions,
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';

interface Html {
parse(html: string, options?: ParseOptions): OpLog;
parse(html: string, options?: EngineOptions): OpLog;
replay<N>(log: OpLog, sink: TreeSink<N>): N[];
}

Expand Down Expand Up @@ -177,9 +177,9 @@ async function engineImplementation(engine: EngineSubject): Promise<Implementati
new Uint8Array(raw.memory.buffer, raw.scratch(), name.length).set(name);
return raw.atom(raw.scratch(), name.length);
};
const fragment = (w: Workload): ParseOptions =>
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(
Expand Down
Loading
Loading