From e339302e6c32830dfed323ad82bb156a6b8141a2 Mon Sep 17 00:00:00 2001 From: Jason Korol Date: Wed, 11 Nov 2026 21:43:04 +0000 Subject: [PATCH 01/74] perf(md): convert a page to markdown in about half the time The markdown is unchanged; only where the time goes is. - Parse with parse5 and hast-util-from-parse5 directly, without source positions. Nothing read them, and computing them dominated some pages. - Skip toMdast's structured clone and whitespace pass: it is handed an empty root whose handler converts our own cheap copy, minified by a port of hast-util-minify-whitespace that tests tag names against sets. - Find chrome and shown tab panels by walking properties instead of css selectors over the whole page; resolveStreamed walks directly too. hast-util-from-html stays as a devDependency for one test. Co-Authored-By: Claude --- .changeset/md-faster-conversion.md | 9 + packages/md/package.json | 4 +- packages/md/src/convert/index.ts | 114 ++++++++-- packages/md/src/convert/whitespace.ts | 229 +++++++++++++++++++++ packages/md/test/convert-big-pages.test.ts | 24 +++ vlt-lock.json | 64 +++--- 6 files changed, 390 insertions(+), 54 deletions(-) create mode 100644 .changeset/md-faster-conversion.md create mode 100644 packages/md/src/convert/whitespace.ts diff --git a/.changeset/md-faster-conversion.md b/.changeset/md-faster-conversion.md new file mode 100644 index 0000000..e0d8931 --- /dev/null +++ b/.changeset/md-faster-conversion.md @@ -0,0 +1,9 @@ +--- +'@affordances/md': patch +--- + +Converting a page to markdown takes about half the time, and far less on some pages. The markdown is the same. + +- The html is parsed without each node's place in the source. Nothing read it, and on a page of many lines working it out took longer than everything else together. +- The tree is no longer structured-cloned before it's converted, and its whitespace is collapsed without rebuilding the tag tests for every node. +- A page's chrome and its shown tab panels are found by reading each element's properties rather than with css selectors over the whole page. diff --git a/packages/md/package.json b/packages/md/package.json index 81ba932..790dd7b 100644 --- a/packages/md/package.json +++ b/packages/md/package.json @@ -56,7 +56,7 @@ "test": "vitest run" }, "dependencies": { - "hast-util-from-html": "^2.0.3", + "hast-util-from-parse5": "^8.0.3", "hast-util-select": "^6.0.4", "hast-util-to-mdast": "^10.1.2", "hast-util-to-string": "^3.0.1", @@ -66,6 +66,7 @@ "micromark-extension-gfm": "^3.0.0", "micromark-util-decode-string": "^2.0.1", "micromark-util-normalize-identifier": "^2.0.1", + "parse5": "^7.3.0", "unist-util-visit": "^5.2.0" }, "devDependencies": { @@ -73,6 +74,7 @@ "@types/mdast": "^4", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", + "hast-util-from-html": "^2.0.3", "next": "^16.4.3", "react": "^19.3.1", "react-dom": "^19.3.1" diff --git a/packages/md/src/convert/index.ts b/packages/md/src/convert/index.ts index c73a8af..d5d225a 100644 --- a/packages/md/src/convert/index.ts +++ b/packages/md/src/convert/index.ts @@ -1,4 +1,4 @@ -import type { Element, ElementContent, Nodes as HastNodes, Root as HastRoot } from 'hast' +import type { Element, ElementContent, Root as HastRoot } from 'hast' import type { Html, List, @@ -9,17 +9,19 @@ import type { Root as MdastRoot, TableCell, } from 'mdast' -import { fromHtml } from 'hast-util-from-html' +import { fromParse5 } from 'hast-util-from-parse5' import { select, selectAll } from 'hast-util-select' -import { defaultHandlers, toMdast, type Handle } from 'hast-util-to-mdast' +import { defaultHandlers, defaultNodeHandlers, toMdast, type Handle } from 'hast-util-to-mdast' import { toString } from 'hast-util-to-string' import { gfmToMarkdown } from 'mdast-util-gfm' import { toMarkdown } from 'mdast-util-to-markdown' import { parse, postprocess, preprocess } from 'micromark' +import { parse as parseHtml } from 'parse5' import { gfm } from 'micromark-extension-gfm' import { decodeString } from 'micromark-util-decode-string' import { normalizeIdentifier } from 'micromark-util-normalize-identifier' import { visit } from 'unist-util-visit' +import { minifyWhitespace } from './whitespace.ts' export type Handlers = Record @@ -60,10 +62,17 @@ const ALWAYS_DROP = new Set([ 'video', 'source', ]) -const CHROME = - 'nav, header, footer, aside, dialog, [role=navigation], [role=banner], [role=contentinfo], [role=complementary], [aria-hidden=true], [hidden]' +const CHROME_TAGS = new Set(['nav', 'header', 'footer', 'aside', 'dialog']) +const CHROME_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary']) const isElement = (node: unknown): node is Element => (node as Element)?.type === 'element' +// asked of every element on a page, so read from its properties: a css selector over a whole page costs as much as +// parsing it +const chrome = (el: Element) => + CHROME_TAGS.has(el.tagName) || + CHROME_ROLES.has(String(el.properties.role)) || + String(el.properties.ariaHidden) === 'true' || + (el.properties.hidden != null && el.properties.hidden !== false) const mode = (node: Element) => node.tagName === 'affordances-md' ? String(node.properties.dataMode ?? '') @@ -274,11 +283,19 @@ const prune = (parent: HastRoot | Element, literal = false) => { let tabs: Set | undefined const page: Pruning = { byId: () => (byId ??= ids(parent)), - tabs: () => - (tabs ??= new Set(selectAll('[data-affordances-md=show]', parent).flatMap(labelledBy))), + tabs: () => (tabs ??= new Set(shownPanels(parent).flatMap(labelledBy))), } pruneWith(parent, page, literal) } +// everything marked data-affordances-md="show", in page order +const shownPanels = (parent: HastRoot | Element, found: Element[] = []) => { + for (const child of parent.children) { + if (!isElement(child)) continue + if (String(child.properties.dataAffordancesMd) === 'show') found.push(child) + shownPanels(child, found) + } + return found +} // what prune reads from the whole page, once it needs it: its ids, and the tabs that label a shown panel type Pruning = { byId: () => Map; tabs: () => Set } // a tablist whose panels are shown: each panel is headed by its tab, so the tabs aren't said again @@ -422,15 +439,22 @@ const resolveStreamed = (tree: HastRoot) => { const templates: Element[] = [] const byId = new Map() const parents = new Map() - visit(tree, 'element', (node, _, parent) => { - if (parent) parents.set(node, parent as HastRoot | Element) - const id = node.properties.id - if (id != null) byId.set(String(id), node) - if (node.tagName === 'script') scripts.push(node) - if (node.tagName !== 'template') return - if (id != null) templates.push(node) - if (node.properties.dataBid != null || node.properties.dataPid != null) instructions.push(node) - }) + const walk = (parent: HastRoot | Element) => { + for (const node of parent.children) { + if (!isElement(node)) continue + parents.set(node, parent) + const id = node.properties.id + if (id != null) byId.set(String(id), node) + if (node.tagName === 'script') scripts.push(node) + if (node.tagName === 'template') { + if (id != null) templates.push(node) + if (node.properties.dataBid != null || node.properties.dataPid != null) + instructions.push(node) + } + walk(node) + } + } + walk(tree) const boundaries = new Map() const placeholders = new Map() for (const script of scripts) @@ -500,10 +524,9 @@ const extract = (body: HastRoot, how: Options['extract']): HastRoot => { const main = landmarks.find((m) => m.tagName === 'main') ?? landmarks[0] if (main) return { type: 'root', children: [main] } // the page has no landmark: take the body and drop its chrome, but keep what was marked for agents - const chrome = new Set(selectAll(CHROME, body).filter((el) => !unhidden(el))) const strip = (parent: HastRoot | Element) => { const kept = (parent.children as ElementContent[]).filter( - (child) => !(isElement(child) && chrome.has(child)), + (child) => !(isElement(child) && chrome(child) && !unhidden(child)), ) parent.children = kept for (const child of kept) if (isElement(child)) strip(child) @@ -540,7 +563,7 @@ const PUSH = new RegExp(String.raw`^${CALL}([\s\S]*)\)\s*;?\s*$`) const PUSHED = new RegExp(String.raw`^${CALL}`) // the html tokenizer's raw text (rawtext and rcdata) elements: their text runs to their own end tag. noscript isn't -// one: the page is parsed with scripting off, as hast-util-from-html parses it +// one: the page is parsed with scripting off (fromHtml) const RAW = new Set(['style', 'xmp', 'iframe', 'noembed', 'noframes', 'title', 'textarea']) // a start tag that ends foreign content (svg, math) and is an html element again const BREAKOUT = new Set( @@ -1154,6 +1177,11 @@ const rowScanner = () => { } } +// html as a tree, parsed as hast-util-from-html parses it (scripting off) but without each node's place in the source: +// nothing reads it, and working it out costs more than the parse (most of a conversion, on a page of many lines) +const fromHtml = (html: string) => + fromParse5(parseHtml(html, { scriptingEnabled: false })) as HastRoot + // a page's html with its flight pushes taken out, parsed: the tree and the error rows' digests, or why they can't be // trusted const strippedTree = (html: string, swapped: Swapped) => { @@ -2364,9 +2392,11 @@ const readTree = ( // so a filled slot's children are left out before converting, which copies and walks all of what it's given: // a slot's fallback (a skeleton, last night's table) can be most of a page const filled = new Set(markers.filter((node) => fillOf(node) !== undefined)) - const mdast = toMdast((filled.size ? emptied(content, filled) : content) as HastNodes, { - handlers: { ...handlers, 'affordances-md': marker, ...options.handlers }, - }) as MdastRoot + const mdast = converted(filled.size ? emptied(content, filled) : content, { + ...handlers, + 'affordances-md': marker, + ...options.handlers, + }) const url = meta.canonical ?? options.url if (absolutize(mdast, options.url ?? meta.canonical, options.link)) { inCells(mdast) @@ -2377,6 +2407,46 @@ const readTree = ( } } +// a tree as hast-util-to-mdast converts it, without what it does first: a structured clone of all it's given, so its +// whitespace pass can change it, then that pass. it does both to an empty root instead, whose handler converts this +// copy: only what the whitespace pass changes (children, a text's value) is new, and a node's place in the html, which +// nothing reads, isn't copied at all +const converted = (tree: HastRoot, elements: Handlers): MdastRoot => { + const copy = copied(tree) + minifyWhitespace(copy) + // the first root it converts is the empty one, or rather its clone + let entered = false + return toMdast( + { type: 'root', children: [] }, + { + handlers: elements, + nodeHandlers: { + root: (state, node) => { + if (entered) return defaultNodeHandlers.root(state, node) + entered = true + // the page's ids, as toMdast collects them for its own handlers + const collect = (parent: HastRoot | Element) => { + for (const child of parent.children) { + if (!isElement(child)) continue + const id = String(child.properties.id || '') + if (id && !state.elementById.has(id)) state.elementById.set(id, child) + collect(child) + } + } + collect(copy) + return defaultNodeHandlers.root(state, copy) + }, + }, + }, + ) as MdastRoot +} +const copied = (node: T): T => + (node.type === 'text' + ? { type: 'text', value: node.value } + : 'children' in node + ? { ...node, position: undefined, children: node.children.map(copied) } + : node) as T + // a copy of a tree with these elements' children gone, sharing every part that doesn't hold one const emptied = (node: T, empty: Set): T => { if (isElement(node) && empty.has(node)) return { ...node, children: [] } diff --git a/packages/md/src/convert/whitespace.ts b/packages/md/src/convert/whitespace.ts new file mode 100644 index 0000000..346011d --- /dev/null +++ b/packages/md/src/convert/whitespace.ts @@ -0,0 +1,229 @@ +import type { Element, Nodes, Parents, Text } from 'hast' + +// html's insignificant whitespace, collapsed and trimmed in place as css would lay it out: what hast-util-to-mdast +// does to a tree before converting it, with hast-util-minify-whitespace (MIT, Titus Wormer). that one builds its +// tag-name tests again for every node it asks about, which was a quarter of a conversion; this is its algorithm, +// rule for rule, over sets. the names are its lists' +const BLOCKS = new Set([ + 'address', + 'article', + 'aside', + 'blockquote', + 'body', + 'br', + 'caption', + 'center', + 'col', + 'colgroup', + 'dd', + 'dialog', + 'dir', + 'div', + 'dl', + 'dt', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'head', + 'header', + 'hgroup', + 'hr', + 'html', + 'legend', + 'li', + 'listing', + 'main', + 'menu', + 'nav', + 'ol', + 'optgroup', + 'option', + 'p', + 'plaintext', + 'pre', + 'section', + 'summary', + 'table', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr', + 'ul', + 'wbr', + 'xmp', +]) +// what contributes content of its own, so whitespace beside it counts: embedded content and form controls +const CONTENT = new Set([ + 'audio', + 'canvas', + 'embed', + 'iframe', + 'img', + 'math', + 'object', + 'picture', + 'svg', + 'video', + 'button', + 'input', + 'select', + 'textarea', +]) +const SKIPPABLE = new Set([ + 'area', + 'base', + 'basefont', + 'dialog', + 'datalist', + 'head', + 'link', + 'meta', + 'noembed', + 'noframes', + 'param', + 'rp', + 'script', + 'source', + 'style', + 'template', + 'track', + 'title', +]) + +type Whitespace = 'normal' | 'nowrap' | 'pre' | 'pre-wrap' +// before, after: whether a break comes before or after the node, so whitespace at that edge says nothing +type State = { whitespace: Whitespace; before: boolean | undefined; after: boolean | undefined } +type Result = { ignore: boolean; stripAtStart: boolean; remove: boolean } + +const isElement = (node: Nodes | undefined): node is Element => node?.type === 'element' +const ignorable = (node: Nodes) => node.type === 'comment' || node.type === 'doctype' +const content = (node: Nodes | undefined) => isElement(node) && CONTENT.has(node.tagName) +const blocklike = (node: Nodes) => isElement(node) && BLOCKS.has(node.tagName) +const skippable = (node: Parents) => + (isElement(node) && (Boolean(node.properties.hidden) || SKIPPABLE.has(node.tagName))) || + ignorable(node) +const blank = (value: string) => !/[^ \t\n\f\r]/.test(value) +const collapse = (value: string) => String(value).replace(/[\t\n\v\f\r ]+/g, ' ') +const removable = (character: string) => character === ' ' || character === '\n' + +export const minifyWhitespace = (tree: Nodes) => { + minify(tree, { whitespace: 'normal', before: undefined, after: undefined }) +} + +const minify = (node: Nodes, state: State): Result => { + if ('children' in node) { + const edge = node.type === 'root' || blocklike(node) + return all(node, { + whitespace: whitespaceOf(node, state), + before: edge || state.before, + after: edge || state.after, + }) + } + if (node.type === 'text') { + if (state.whitespace === 'normal') return minifyText(node, state) + // (not `pre-wrap` or `pre`: those keep their whitespace) + if (state.whitespace === 'nowrap') node.value = collapse(node.value) + } + return { ignore: ignorable(node), stripAtStart: false, remove: false } +} + +const minifyText = (node: Text, state: State): Result => { + const value = collapse(node.value) + const result = { ignore: false, stripAtStart: false, remove: false } + let start = 0 + let end = value.length + if (state.before && removable(value.charAt(0))) start++ + if (start !== end && removable(value.charAt(end - 1))) { + if (state.after) end-- + else result.stripAtStart = true + } + if (start === end) result.remove = true + else node.value = value.slice(start, end) + return result +} + +const all = (parent: Parents, state: State): Result => { + let before = state.before + const { after, whitespace } = state + const children = parent.children + let length = children.length + let index = -1 + while (++index < length) { + const result = minify(children[index]!, { + whitespace, + before, + after: collapsableAfter(children, index, after), + }) + if (result.remove) { + children.splice(index, 1) + index-- + length-- + } else if (!result.ignore) { + before = result.stripAtStart + } + // an element that contributes content somehow, a `, + ) + out.push( + '
hidden
', + ) + } + out.push('

Footer

') + for (let i = 0; i < sections; i++) + out.push( + ``, + ) + out.push('') + return out.join('') +} diff --git a/packages/md-core/bench/corpus/urls.txt b/packages/md-core/bench/corpus/urls.txt new file mode 100644 index 0000000..74510cd --- /dev/null +++ b/packages/md-core/bench/corpus/urls.txt @@ -0,0 +1,10 @@ +# real pages for the benchmark corpus, one url per line. bench/fetch.ts saves each to .cache/ under a name derived from +# its url (every non-alphanumeric character becomes _), so keep these stable or the cache names change +https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table +https://docs.npmjs.com/cli/v11/commands/npm-install +https://en.wikipedia.org/wiki/Markdown +https://github.com/vercel/next.js +https://nextjs.org/docs/app/getting-started/installation +https://react.dev/reference/react/useEffect +https://tailwindcss.com/docs/flex +https://www.typescriptlang.org/docs/handbook/2/generics.html diff --git a/packages/md-core/bench/fetch.ts b/packages/md-core/bench/fetch.ts new file mode 100644 index 0000000..6be472c --- /dev/null +++ b/packages/md-core/bench/fetch.ts @@ -0,0 +1,35 @@ +// re-downloads the real pages listed in corpus/urls.txt into corpus/.cache. existing files are kept unless --force, +// so a refetch is an explicit choice: a site changing its page changes every number +import { existsSync, mkdirSync, writeFileSync } from 'node:fs' +import { parseArgs } from 'node:util' +import { cacheDir, fileName, readUrls } from './corpus.ts' + +const { values } = parseArgs({ options: { force: { type: 'boolean', default: false } } }) + +mkdirSync(cacheDir, { recursive: true }) +let failed = 0 +for (const url of readUrls()) { + const file = new URL(fileName(url), cacheDir) + if (existsSync(file) && !values.force) { + console.log(`skip ${url} (cached; --force to refetch)`) + continue + } + try { + const res = await fetch(url, { + headers: { + // a browser-like agent: some sites serve a stripped page to unknown clients + 'user-agent': + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36', + accept: 'text/html', + }, + }) + if (!res.ok) throw new Error(`HTTP ${res.status}`) + const html = await res.text() + writeFileSync(file, html) + console.log(`fetch ${url} (${(html.length / 1024).toFixed(0)} KB)`) + } catch (error) { + failed++ + console.error(`error ${url}: ${(error as Error).message}`) + } +} +if (failed) process.exitCode = 1 diff --git a/packages/md-core/bench/parity.ts b/packages/md-core/bench/parity.ts new file mode 100644 index 0000000..b48057a --- /dev/null +++ b/packages/md-core/bench/parity.ts @@ -0,0 +1,216 @@ +// output parity: md-core against @affordances/md (the reference) on every corpus page +import { mkdirSync, writeFileSync } from 'node:fs' +import { parseArgs } from 'node:util' +import { htmlToMarkdown as reference } from '@affordances/md' +import { filterPages, loadCorpus } from './corpus.ts' +import { table } from './table.ts' + +const { values } = parseArgs({ + options: { + page: { type: 'string' }, + diff: { type: 'string' }, + hunks: { type: 'string', default: '40' }, + write: { type: 'boolean', default: false }, + }, +}) + +const options = { url: 'https://site.test/a' } +const outDir = new URL('./.results/parity/', import.meta.url) + +type Convert = ( + html: string, + o: typeof options, +) => { markdown: string; title?: string; url?: string } +let core: Convert | undefined +let coreFailure = '' +try { + core = (await import('../src/index.ts')).htmlToMarkdown +} catch (error) { + coreFailure = `import failed: ${(error as Error).message.split('\n')[0]}` +} + +// lines as small ints, so the lcs compares numbers, not strings +const intern = (a: string[], b: string[]) => { + const ids = new Map() + const id = (line: string) => { + let n = ids.get(line) + if (n === undefined) ids.set(line, (n = ids.size)) + return n + } + return [Int32Array.from(a, id), Int32Array.from(b, id)] as const +} + +type Op = { kind: ' ' | '-' | '+'; line: string } + +// an lcs over lines with the common prefix and suffix trimmed first: near-identical outputs (the goal) cost almost +// nothing, and the middle is an o(n·m) table of one byte a cell. the reference pages are ~1k lines, so even a fully +// different page is a few mb +const diffLines = (a: string[], b: string[]): { common: number; ops: Op[] } => { + const [x, y] = intern(a, b) + let pre = 0 + while (pre < x.length && pre < y.length && x[pre] === y[pre]) pre++ + let suf = 0 + while ( + suf < x.length - pre && + suf < y.length - pre && + x[x.length - 1 - suf] === y[y.length - 1 - suf] + ) + suf++ + const n = x.length - pre - suf + const m = y.length - pre - suf + // lengths of the lcs of x[i..] and y[j..], two rows at a time; dir records the way back + const dir = new Uint8Array((n + 1) * (m + 1)) + let next = new Int32Array(m + 1) + let cur = new Int32Array(m + 1) + for (let i = n - 1; i >= 0; i--) { + for (let j = m - 1; j >= 0; j--) { + const k = i * (m + 1) + j + if (x[pre + i] === y[pre + j]) { + cur[j] = next[j + 1]! + 1 + dir[k] = 0 + } else if (next[j]! >= cur[j + 1]!) { + cur[j] = next[j]! + dir[k] = 1 + } else { + cur[j] = cur[j + 1]! + dir[k] = 2 + } + } + ;[next, cur] = [cur, next] + } + const ops: Op[] = [] + for (let i = 0; i < pre; i++) ops.push({ kind: ' ', line: a[i]! }) + let i = 0 + let j = 0 + while (i < n && j < m) { + const d = dir[i * (m + 1) + j] + if (d === 0) { + ops.push({ kind: ' ', line: a[pre + i++]! }) + j++ + } else if (d === 1) ops.push({ kind: '-', line: a[pre + i++]! }) + else ops.push({ kind: '+', line: b[pre + j++]! }) + } + while (i < n) ops.push({ kind: '-', line: a[pre + i++]! }) + while (j < m) ops.push({ kind: '+', line: b[pre + j++]! }) + for (let s = x.length - suf; s < x.length; s++) ops.push({ kind: ' ', line: a[s]! }) + return { common: pre + suf + (next[0] ?? 0), ops } +} + +// unified-style hunks with three lines of context +const hunks = (ops: Op[], limit: number) => { + const context = 3 + const out: string[] = [] + let count = 0 + let k = 0 + // line numbers in the reference (a) and md-core (b) before ops[k] + const at: [number, number][] = [] + for (let a = 1, b = 1, i = 0; i < ops.length; i++) { + at.push([a, b]) + if (ops[i]!.kind !== '+') a++ + if (ops[i]!.kind !== '-') b++ + } + while (k < ops.length && count < limit) { + while (k < ops.length && ops[k]!.kind === ' ') k++ + if (k >= ops.length) break + const start = Math.max(0, k - context) + // extend through every change that's within two contexts of the last one + let last = k + for (let i = k; i < ops.length && i - last <= context * 2; i++) + if (ops[i]!.kind !== ' ') last = i + const end = Math.min(ops.length, last + 1 + context) + const slice = ops.slice(start, end) + const [a, b] = at[start]! + const aLen = slice.filter((o) => o.kind !== '+').length + const bLen = slice.filter((o) => o.kind !== '-').length + out.push(`@@ -${a},${aLen} +${b},${bLen} @@`) + for (const o of slice) out.push(`${o.kind}${o.line}`) + count++ + k = end + } + const total = (() => { + let n = 0 + for (let i = 0; i < ops.length; i++) + if (ops[i]!.kind !== ' ' && (i === 0 || ops[i - 1]!.kind === ' ')) n++ + return n + })() + return { text: out.join('\n'), shown: count, total } +} + +// rounded down, so a page that isn't exact never shows 100.0% +const floor1 = (n: number) => (Math.floor(n * 10) / 10).toFixed(1) + +const pages = filterPages(loadCorpus(), values.page) +if (values.write) mkdirSync(outDir, { recursive: true }) + +const rows: string[][] = [] +let refLines = 0 +let common = 0 +let exact = 0 +let compared = 0 +let notImplemented = false +let diffShown = false + +for (const page of pages) { + const ref = reference(page.html, options) + const file = page.name.replace(/[^a-zA-Z0-9.-]+/g, '_') + if (values.write) writeFileSync(new URL(`${file}.reference.md`, outDir), ref.markdown) + const refSplit = ref.markdown.split('\n') + let got: ReturnType | undefined + let failure = coreFailure + if (core && !failure) { + try { + got = core(page.html, options) + } catch (error) { + const message = (error as Error).message.split('\n')[0] ?? String(error) + failure = message.startsWith('not implemented') ? 'not implemented' : `error: ${message}` + if (failure === 'not implemented') notImplemented = true + } + } + if (!got) { + rows.push([page.name, String(refSplit.length), '-', '-', '-', failure]) + continue + } + if (values.write) writeFileSync(new URL(`${file}.core.md`, outDir), got.markdown) + const same = got.markdown === ref.markdown + const { common: c, ops } = same + ? { common: refSplit.length, ops: [] as Op[] } + : diffLines(refSplit, got.markdown.split('\n')) + const fields = [ + got.title === ref.title + ? '' + : `title ${JSON.stringify(got.title)} vs ${JSON.stringify(ref.title)}`, + got.url === ref.url ? '' : `url ${got.url} vs ${ref.url}`, + ].filter(Boolean) + compared++ + refLines += refSplit.length + common += c + if (same) exact++ + rows.push([ + page.name, + String(refSplit.length), + String(got.markdown.split('\n').length), + same ? 'yes' : 'no', + `${floor1((c / refSplit.length) * 100)}%`, + fields.join('; '), + ]) + if (values.diff && !same && page.name.toLowerCase().includes(values.diff.toLowerCase())) { + const h = hunks(ops, Number(values.hunks)) + console.log(`--- ${page.name} (reference)\n+++ ${page.name} (md-core)\n${h.text}`) + if (h.shown < h.total) console.log(`... ${h.total - h.shown} more hunks`) + console.log() + diffShown = true + } +} + +if (values.diff && !diffShown) + console.log(`no differing page matches '${values.diff}' (or md-core produced nothing to diff)\n`) + +console.log( + table(['page', 'ref lines', 'core lines', 'exact', 'lines kept', 'notes'], rows, ['notes']), +) +console.log( + compared + ? `\nparity: ${exact}/${pages.length} exact, ${floor1((common / refLines) * 100)}% of reference lines reproduced in order (over ${compared} page${compared > 1 ? 's' : ''} md-core converted)` + : `\nparity: n/a, md-core ${notImplemented ? 'not implemented' : coreFailure || 'failed on every page'}`, +) +if (values.write) console.log(`outputs written to ${outDir.pathname}`) diff --git a/packages/md-core/bench/run.ts b/packages/md-core/bench/run.ts new file mode 100644 index 0000000..8fc46b2 --- /dev/null +++ b/packages/md-core/bench/run.ts @@ -0,0 +1,372 @@ +// speed benchmark: every tool on every corpus page, median of n timed runs per page +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { cpus } from 'node:os' +import { parseArgs } from 'node:util' +import { setFlagsFromString } from 'node:v8' +import { runInNewContext } from 'node:vm' +import { filterPages, loadCorpus, type Page } from './corpus.ts' +import { kb, ms, pct, table } from './table.ts' + +const { values } = parseArgs({ + options: { + runs: { type: 'string', default: '20' }, + warmup: { type: 'string', default: '3' }, + budget: { type: 'string', default: '300' }, + tool: { type: 'string' }, + page: { type: 'string' }, + json: { type: 'boolean', default: false }, + save: { type: 'string' }, + compare: { type: 'string' }, + 'no-gc': { type: 'boolean', default: false }, + }, +}) + +const runs = Number(values.runs) +const warmup = Number(values.warmup) +// a slow tool stops early once it has minRuns samples and has spent this long (ms) on one page: keeps a full run +// short. tools under ~15 ms a page, the ones the comparison is about, always get all their runs +const budget = Number(values.budget) +const minRuns = Math.min(3, runs) +const url = 'https://site.test/a' +const resultsDir = new URL('./.results/', import.meta.url) + +// a full gc before every sample, so one tool's garbage is never collected on another's clock +let gc: (() => void) | undefined +if (!values['no-gc']) { + setFlagsFromString('--expose-gc') + gc = runInNewContext('gc') as () => void +} + +// setup turns a page into the function that's timed; it may do untimed work first (emit needs a parsed tree) +type Tool = { name: string; setup: (html: string) => () => unknown } +type Status = 'ok' | 'not implemented' | `import failed: ${string}` + +const tools: { tool: Tool; status: Status }[] = [] +const add = (tool: Tool, status: Status = 'ok') => tools.push({ tool, status }) +const failure = (error: unknown) => (error as Error).message.split('\n')[0] ?? String(error) + +const isNotImplemented = (error: unknown) => + error instanceof Error && error.message.startsWith('not implemented') + +// md-core is imported dynamically: it's mid-rewrite and must not take the whole bench down +try { + const core = await import('../src/index.ts') + add({ name: 'md-core', setup: (html) => () => core.htmlToMarkdown(html, { url }).markdown }) +} catch (error) { + add({ name: 'md-core', setup: () => () => '' }, `import failed: ${failure(error)}`) +} + +// the two stages on their own, when they exist. missing files are skipped without a word; a file that exists but +// fails to load is reported, since that's a bug, not a missing stage +const stage = async (file: string) => { + const target = new URL(file, import.meta.url) + try { + return (await import(target.href)) as Record + } catch (error) { + const err = error as { code?: string; url?: string; message: string } + if (err.code === 'ERR_MODULE_NOT_FOUND' && err.message.includes(target.pathname)) + return undefined + console.error(`${file}: failed to load: ${failure(error)}`) + return undefined + } +} +const parseMod = await stage('../src/parse.ts') +const emitMod = await stage('../src/emit.ts') +const parse = + typeof parseMod?.parse === 'function' ? (parseMod.parse as (h: string) => unknown) : undefined +const emit = + typeof emitMod?.emit === 'function' + ? (emitMod.emit as (doc: unknown, options: { url: string }) => unknown) + : undefined +if (parse) add({ name: 'md-core parse', setup: (html) => () => parse(html) }) +if (parse && emit) { + // the tree is parsed once, outside the clock. emit runs on the same tree each time, so anything it caches on the + // tree (attr maps) is warm after the first run + add({ + name: 'md-core emit', + setup: (html) => { + const doc = parse(html) + return () => emit(doc, { url }) + }, + }) +} + +{ + const md = await import('@affordances/md') + add({ name: '@affordances/md', setup: (html) => () => md.htmlToMarkdown(html, { url }).markdown }) + const mdream = await import('mdream') + add({ + name: 'mdream', + setup: (html) => () => mdream.htmlToMarkdown(html, { origin: 'https://site.test' }), + }) + const { default: Turndown } = await import('turndown') + const { gfm } = await import('turndown-plugin-gfm') + const turndown = new Turndown().use(gfm) + add({ name: 'turndown+gfm', setup: (html) => () => turndown.turndown(html) }) + const { NodeHtmlMarkdown } = await import('node-html-markdown') + const nhm = new NodeHtmlMarkdown() + add({ name: 'node-html-markdown', setup: (html) => () => nhm.translate(html) }) +} + +// comma-separated substrings, any of which selects a tool: --tool core,mdream is the quick loop +const wanted = values.tool?.toLowerCase().split(',').filter(Boolean) +const selected = wanted + ? tools.filter(({ tool }) => wanted.some((w) => tool.name.toLowerCase().includes(w))) + : tools +const corpus = loadCorpus() +const pages = filterPages(corpus, values.page) +if (!corpus.some((p) => p.url)) + console.error('no real pages in bench/corpus/.cache: run `node bench/fetch.ts` (synthetic only)') +if (!pages.length || !selected.length) { + console.error('nothing to run: check --tool and --page') + process.exit(1) +} + +// every output goes here, so no engine can prove a result unused and skip the work +let sink = 0 +const keep = (out: unknown) => { + if (typeof out === 'string') sink += out.length + else if (out !== null && typeof out === 'object') sink += 1 + return out +} +const outBytes = (out: unknown) => (typeof out === 'string' ? Buffer.byteLength(out) : undefined) + +type Cell = { + median: number + p25: number + p75: number + runs: number + outBytes?: number | undefined + error?: string | undefined +} +type ToolResult = { + name: string + status: Status + total?: number + mbps?: number + outBytes?: number + spread?: number + pages: Record +} +type Run = { + date: string + node: string + cpu: string + runs: number + warmup: number + gc: boolean + pages: { name: string; bytes: number }[] + tools: ToolResult[] +} + +const delta = (now: number | undefined, then: number | undefined) => + now !== undefined && then ? ` (${pct(now / then - 1)})` : '' + +const quantile = (sorted: number[], q: number) => { + const i = (sorted.length - 1) * q + const lo = Math.floor(i) + const hi = Math.ceil(i) + return (sorted[lo] ?? 0) + ((sorted[hi] ?? 0) - (sorted[lo] ?? 0)) * (i - lo) +} + +const live = selected.map(({ tool, status }) => ({ + tool, + status, + cells: {} as Record, +})) + +// one untimed pass over the corpus first (capped at half a second a tool): the jit sees every kind of page before +// any timing, and it finds tools that can't run at all +for (const entry of live) { + if (entry.status !== 'ok') continue + const t0 = performance.now() + for (const page of pages) { + if (performance.now() - t0 > 500) break + try { + keep(entry.tool.setup(page.html)()) + } catch (error) { + if (isNotImplemented(error)) { + entry.status = 'not implemented' + break + } + } + } +} + +// one tool at a time per page: a full gc, warm-up runs (which also regrow the heap the gc shrank: a gc before every +// sample measured @affordances/md ~50% slow), then the timed runs back to back, so each tool is timed in its own +// steady state and pays only for its own garbage. the tool order rotates page by page, so drift over the run (thermal, +// other load) doesn't always land on the same tool +const bench = (page: Page, index: number) => { + const active = live.filter((e) => e.status === 'ok') + for (let k = 0; k < active.length; k++) { + const e = active[(index + k) % active.length]! + gc?.() + const samples: number[] = [] + let out: unknown + let error: string | undefined + try { + const fn = e.tool.setup(page.html) + for (let w = 0, spent = 0; w < warmup && (w === 0 || spent < budget / 2); w++) { + const t0 = performance.now() + out = keep(fn()) + spent += performance.now() - t0 + } + for (let r = 0, spent = 0; r < runs && (r < minRuns || spent < budget); r++) { + const t0 = performance.now() + const result = fn() + const dt = performance.now() - t0 + keep(result) + samples.push(dt) + spent += dt + } + } catch (err) { + error = failure(err) + } + const sorted = samples.toSorted((a, b) => a - b) + e.cells[page.name] = error + ? { median: 0, p25: 0, p75: 0, runs: 0, error } + : { + median: quantile(sorted, 0.5), + p25: quantile(sorted, 0.25), + p75: quantile(sorted, 0.75), + runs: sorted.length, + outBytes: outBytes(out), + } + } +} + +const progress = !values.json && process.stderr.isTTY +for (const [i, page] of pages.entries()) { + if (progress) process.stderr.write(`\r\x1b[Ktiming ${page.name}`) + bench(page, i) +} +if (progress) process.stderr.write('\r\x1b[K') + +const bytes = new Map(pages.map((p) => [p.name, Buffer.byteLength(p.html)])) +const result: Run = { + date: new Date().toISOString(), + node: process.version, + cpu: cpus()[0]?.model ?? 'unknown', + runs, + warmup, + gc: Boolean(gc), + pages: pages.map((p) => ({ name: p.name, bytes: bytes.get(p.name) ?? 0 })), + tools: live.map((e) => { + const r: ToolResult = { name: e.tool.name, status: e.status, pages: e.cells } + const ok = Object.entries(e.cells).filter(([, c]) => !c.error) + if (e.status === 'ok' && ok.length) { + r.total = ok.reduce((s, [, c]) => s + c.median, 0) + r.mbps = ok.reduce((s, [n]) => s + (bytes.get(n) ?? 0), 0) / 1e6 / (r.total / 1000) + r.outBytes = ok.reduce((s, [, c]) => s + (c.outBytes ?? 0), 0) + r.spread = ok.reduce((s, [, c]) => s + (c.p75 - c.p25), 0) / r.total + } + return r + }), +} + +if (values.save) { + mkdirSync(resultsDir, { recursive: true }) + writeFileSync(new URL(`${values.save}.json`, resultsDir), JSON.stringify(result, null, 2) + '\n') +} + +let base: Run | undefined +if (values.compare) { + try { + base = JSON.parse(readFileSync(new URL(`${values.compare}.json`, resultsDir), 'utf8')) as Run + } catch { + console.error(`no saved run '${values.compare}' in bench/.results`) + process.exit(1) + } +} + +// no process.exit after a big write: it can cut off output going to a pipe +if (values.json) console.log(JSON.stringify(result, null, 2)) +else { + const errors = (r: ToolResult) => Object.values(r.pages).filter((c) => c.error).length + const complete = (r: ToolResult) => r.status === 'ok' && errors(r) === 0 + const rank = (r: ToolResult) => (r.status !== 'ok' ? 2 : errors(r) ? 1 : 0) + // the stage rows sit under md-core, since they're parts of it, not rivals + const isStage = (t: ToolResult) => t.name.startsWith('md-core ') + const sorted = result.tools + .filter((t) => !isStage(t)) + .toSorted((a, b) => rank(a) - rank(b) || (a.total ?? Infinity) - (b.total ?? Infinity)) + .flatMap((t) => (t.name === 'md-core' ? [t, ...result.tools.filter(isStage)] : [t])) + if (!sorted.some((t) => t.name === 'md-core')) sorted.push(...result.tools.filter(isStage)) + const baseTool = (name: string) => base?.tools.find((t) => t.name === name) + + const cell = (t: ToolResult, page: string) => { + const c = t.pages[page] + if (t.status !== 'ok') return '-' + if (!c) return '' + if (c.error) return 'error' + return ms(c.median) + delta(c.median, baseTool(t.name)?.pages[page]?.median) + } + + console.log( + `median ms per page; ${runs} runs after ${warmup} warm-up${gc ? ', gc before each tool on each page' : ''}; ${result.node}, ${result.cpu}${base ? `; deltas vs '${values.compare}' (${base.date.slice(0, 16)})` : ''}\n`, + ) + console.log( + table( + ['page', 'KB', ...sorted.map((t) => t.name)], + pages.map((p) => [p.name, kb(bytes.get(p.name) ?? 0), ...sorted.map((t) => cell(t, p.name))]), + ), + ) + console.log() + + const totalBytes = [...bytes.values()].reduce((a, b) => a + b, 0) + console.log( + table( + ['tool', 'total ms', 'MB/s', 'out KB', 'spread', 'runs', 'notes'], + sorted.map((t) => { + if (t.status !== 'ok') return [t.name, '-', '-', '-', '-', '-', t.status] + const cells = Object.values(t.pages).filter((c) => !c.error) + const counts = cells.map((c) => c.runs) + const n = errors(t) + const prev = baseTool(t.name) + const samePages = + prev && result.pages.every((p) => prev.pages[p.name] && !prev.pages[p.name]!.error) + const notes = [ + n ? `errors on ${n} page${n > 1 ? 's' : ''} (total is partial)` : '', + prev && !samePages ? 'different pages from the saved run' : '', + ].filter(Boolean) + return [ + t.name, + (t.total === undefined ? '-' : ms(t.total)) + + (samePages && complete(t) ? delta(t.total, prev?.total) : ''), + t.mbps?.toFixed(1) ?? '-', + kb(t.outBytes ?? 0), + t.spread === undefined ? '-' : `±${(t.spread * 50).toFixed(0)}%`, + counts.length ? `${Math.min(...counts)}-${Math.max(...counts)}` : '-', + notes.join('; '), + ] + }), + ['notes'], + ), + ) + console.log(`\ncorpus: ${pages.length} pages, ${(totalBytes / 1e6).toFixed(2)} MB`) + + const errorLines = result.tools.flatMap((t) => + Object.entries(t.pages) + .filter(([, c]) => c.error) + .map(([page, c]) => ` ${t.name} on ${page}: ${c.error}`), + ) + if (errorLines.length) console.log(`\nerrors:\n${errorLines.join('\n')}`) + + const core = result.tools.find((t) => t.name === 'md-core') + const mdream = result.tools.find((t) => t.name === 'mdream') + if (core && mdream) { + if (core.status !== 'ok') console.log(`\nmd-core / mdream: md-core ${core.status}`) + else if (!complete(core) || !complete(mdream) || !core.total || !mdream.total) + console.log('\nmd-core / mdream: not comparable (errors on some pages)') + else { + const ratio = core.total / mdream.total + console.log( + `\nmd-core / mdream: ${ratio.toFixed(2)}x (${ratio <= 1 ? `${(1 / ratio).toFixed(2)}x faster` : `${ratio.toFixed(2)}x slower`})`, + ) + } + } +} + +// read, so the sink is observably used +if (sink < 0) console.log(sink) diff --git a/packages/md-core/bench/shims.d.ts b/packages/md-core/bench/shims.d.ts new file mode 100644 index 0000000..b9c3706 --- /dev/null +++ b/packages/md-core/bench/shims.d.ts @@ -0,0 +1,12 @@ +// turndown ships no types and @types/turndown isn't installed; the bench needs only this much +declare module 'turndown' { + export default class TurndownService { + constructor(options?: Record) + use(plugin: unknown): this + turndown(html: string): string + } +} + +declare module 'turndown-plugin-gfm' { + export const gfm: unknown +} diff --git a/packages/md-core/bench/table.ts b/packages/md-core/bench/table.ts new file mode 100644 index 0000000..a7dc6a5 --- /dev/null +++ b/packages/md-core/bench/table.ts @@ -0,0 +1,20 @@ +// a plain-text table: the first column left-aligned, the rest right-aligned (they're numbers) unless named in left +export const table = (head: string[], rows: string[][], left: string[] = []) => { + const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length))) + const line = (cells: string[]) => + cells + .map((c, i) => + i === 0 || left.includes(head[i] ?? '') + ? c.padEnd(widths[i] ?? 0) + : c.padStart(widths[i] ?? 0), + ) + .join(' ') + .trimEnd() + return [line(head), widths.map((w) => '-'.repeat(w)).join(' '), ...rows.map(line)].join('\n') +} + +export const ms = (n: number) => (n < 1 ? n.toFixed(2) : n < 100 ? n.toFixed(1) : n.toFixed(0)) + +export const kb = (bytes: number) => (bytes / 1024).toFixed(0) + +export const pct = (n: number) => `${n >= 0 ? '+' : ''}${(n * 100).toFixed(0)}%` diff --git a/packages/md-core/package.json b/packages/md-core/package.json new file mode 100644 index 0000000..c04f19e --- /dev/null +++ b/packages/md-core/package.json @@ -0,0 +1,28 @@ +{ + "name": "@affordances/md-core", + "version": "0.0.0", + "private": true, + "description": "Experimental single-pass HTML to markdown converter for @affordances/md", + "license": "MIT", + "type": "module", + "sideEffects": false, + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vitest run --passWithNoTests", + "bench": "node bench/run.ts", + "bench:parity": "node bench/parity.ts", + "bench:fetch": "node bench/fetch.ts" + }, + "devDependencies": { + "@affordances/md": "workspace:*", + "hast-util-from-parse5": "^8.0.3", + "mdream": "^2.1.0", + "node-html-markdown": "^2.0.0", + "parse5": "^7.3.0", + "turndown": "^7.2.5", + "turndown-plugin-gfm": "^1.0.2" + } +} diff --git a/packages/md-core/src/attr.ts b/packages/md-core/src/attr.ts new file mode 100644 index 0000000..b5a44f9 --- /dev/null +++ b/packages/md-core/src/attr.ts @@ -0,0 +1,62 @@ +import { decode } from './entities.ts' +import type { Element } from './types.ts' + +// an element's attribute by lowercase name: its decoded value, '' for one without a value, undefined when absent. +// the first of a repeated name wins, as in html. parsed from the tag's source on first use +export const attr = (el: Element, name: string): string | undefined => + el.attrs === '' ? undefined : (el.map ??= parseAttrs(el.attrs)).get(name) + +export const hasAttrs = (el: Element) => el.attrs !== '' + +const space = (c: number) => c === 32 || c === 10 || c === 9 || c === 12 || c === 13 + +// the tokenizer lowercases ascii only, and reads a nul as U+FFFD +const clean = (text: string) => { + let upper = false + for (let i = 0; i < text.length; i++) { + const c = text.charCodeAt(i) + if ((c >= 65 && c <= 90) || c === 0) upper = true + } + return upper + ? text.replace(/[A-Z\0]/g, (c) => + c === '\0' ? '\uFFFD' : String.fromCharCode(c.charCodeAt(0) | 32), + ) + : text +} + +// the html tokenizer's attribute states, over a start tag's source after its name +export const parseAttrs = (source: string): Map => { + const map = new Map() + const n = source.length + let i = 0 + while (i < n) { + let c = source.charCodeAt(i) + if (space(c) || c === 47) { + i++ + continue + } + // a name runs to whitespace, '/' or '='; an '=' first is part of it + const start = i++ + while (i < n && !space((c = source.charCodeAt(i))) && c !== 47 && c !== 61) i++ + const name = clean(source.slice(start, i)) + while (i < n && space(source.charCodeAt(i))) i++ + let value = '' + if (source.charCodeAt(i) === 61) { + i++ + while (i < n && space(source.charCodeAt(i))) i++ + const quote = source.charCodeAt(i) + if (quote === 34 || quote === 39) { + const end = source.indexOf(quote === 34 ? '"' : "'", i + 1) + value = source.slice(i + 1, end < 0 ? n : end) + i = end < 0 ? n : end + 1 + } else { + const from = i + while (i < n && !space(source.charCodeAt(i))) i++ + value = source.slice(from, i) + } + if (value.indexOf('\0') >= 0) value = value.replaceAll('\0', '\uFFFD') + } + if (!map.has(name)) map.set(name, decode(value, true)) + } + return map +} diff --git a/packages/md-core/src/emit-convert.ts b/packages/md-core/src/emit-convert.ts new file mode 100644 index 0000000..3ebc41d --- /dev/null +++ b/packages/md-core/src/emit-convert.ts @@ -0,0 +1,1205 @@ +import { + BREAK, + CODE, + DELETE, + EMPHASIS, + HEADING, + HTML, + IMAGE, + INLINE_CODE, + isPhrasing, + LINK, + LIST, + LIST_ITEM, + Md, + PARAGRAPH, + ROOT, + STRONG, + TABLE, + TABLE_CELL, + TABLE_ROW, + TEXT, + THEMATIC_BREAK, + BLOCKQUOTE, +} from './emit-markdown.ts' +import { + classes, + DATA_TITLE, + flags, + kidsOf, + linkLabel, + MDAST, + NOWRAP as NOWRAP_ATTR, + read, + SPAN, + ALIGN, + text, + TITLE, +} from './emit-prune.ts' +import type { Element, Node, Options } from './types.ts' + +// the page's content as the emitter's tree, as hast-util-to-mdast (MIT, Titus Wormer) converts it with +// @affordances/md's handlers. whitespace is collapsed on the way, as hast-util-minify-whitespace would before: the +// state it carries from one text to the next (`before`), and what comes after an element, are threaded through the walk + +// whitespace, as css lays it out +const BLOCKS = new Set( + 'address article aside blockquote body br caption center col colgroup dd dialog dir div dl dt figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html legend li listing main menu nav ol optgroup option p plaintext pre section summary table tbody td tfoot th thead tr ul wbr xmp'.split( + ' ', + ), +) +// what has content of its own, so whitespace beside it counts +const CONTENT = new Set( + 'audio canvas embed iframe img math object picture svg video button input select textarea'.split( + ' ', + ), +) +const SKIPPABLE = new Set( + 'area base basefont dialog datalist head link meta noembed noframes param rp script source style template track title'.split( + ' ', + ), +) +const NORMAL = 0 +const NOWRAP = 1 +const PRE = 2 + +// the whitespace walk's state: whether whitespace at the start of the next text says nothing, whether it does at the +// end of the element being converted, and how whitespace is laid out there +let before: boolean | undefined +let after: boolean | undefined +let mode = NORMAL + +const whitespaceOf = (el: Element, current: number) => { + switch (el.tag) { + case 'listing': + case 'plaintext': + case 'xmp': + return PRE + case 'nobr': + return NOWRAP + case 'pre': + return PRE + case 'td': + case 'th': + return flags(el) & NOWRAP_ATTR ? NOWRAP : current + case 'textarea': + return PRE + } + return current +} + +const blank = (value: string) => { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i) + if (code !== 32 && code !== 9 && code !== 10 && code !== 12 && code !== 13) return false + } + return true +} +// runs of whitespace as one space +const SPREAD = /[\t\n\v\f\r]| {2}/ +const collapse = (value: string) => + SPREAD.test(value) ? value.replace(/[\t\n\v\f\r ]+/g, ' ') : value + +// whether whitespace at the end of nodes[index] says nothing: a block comes next (true), or content (false) +const collapsableAfter = ( + nodes: Node[], + index: number, + end: boolean | undefined, +): boolean | undefined => { + while (++index < nodes.length) { + const node = nodes[index]! + if (typeof node === 'string') { + if (!blank(node)) return false + continue + } + if (CONTENT.has(node.tag)) return false + if (BLOCKS.has(node.tag)) return true + if (!SKIPPABLE.has(node.tag)) { + const result = collapsableAfter(kidsOf(node), -1, undefined) + if (result !== undefined) return result + } + } + return end +} + +// a text as whitespace leaves it, or undefined when nothing's left +const minified = (value: string, nodes: Node[], index: number): string | undefined => { + if (mode !== NORMAL) { + before = false + return mode === NOWRAP ? collapse(value) : value + } + value = collapse(value) + let start = 0 + let end = value.length + let strip = false + if (before && value.charCodeAt(0) === 32) start++ + if (start !== end && value.charCodeAt(end - 1) === 32) { + if (collapsableAfter(nodes, index, after)) end-- + else strip = true + } + if (start === end) return undefined + before = strip + return start === 0 && end === value.length ? value : value.slice(start, end) +} + +// an element's whitespace: set up for what's in it, then what it leaves for what follows +const enterElement = (el: Element, nodes: Node[], index: number) => { + const block = BLOCKS.has(el.tag) + const end = block ? true : collapsableAfter(nodes, index, after) + const saved = { after, mode } + before = block || before + after = end + mode = whitespaceOf(el, mode) + return saved +} +const exitElement = (el: Element, saved: { after: boolean | undefined; mode: number }) => { + const strip = Boolean(before || after) + after = saved.after + mode = saved.mode + before = CONTENT.has(el.tag) ? false : strip +} +// an element whose children are converted on their own, as if in place: a block, so the same whatever's beside it +const asBlock = (el: Element, convert: () => T): T => { + const saved = { after, mode } + before = true + after = true + mode = whitespaceOf(el, mode) + const result = convert() + after = saved.after + mode = saved.mode + before = true + return result +} + +// what a conversion needs from the page and the options +let base: string | undefined +let relink: Options['link'] +// a table's cells are a table's: one inside is its text +let inTable = false +// elements left out where they are (a details' summary, a figure's caption made the code's title), and controls +// left out of a form's prose +let skips = new Set() +let controls = 0 +let titledCode: Element | undefined +let titledAs = '' +export const startConvert = (options: Options, page: string | undefined) => { + base = page + relink = options.link + inTable = false + skips = new Set() + controls = 0 + titledCode = undefined + before = undefined + after = undefined + mode = NORMAL + urls.clear() + setBase(page) +} + +const node = (type: number, kids?: Md[], value?: string) => new Md(type, kids, value) +const textNode = (value: string) => new Md(TEXT, undefined, value) +// a text that may hold a line ending (one not collapsed: preformatted, or from an attribute), flagged in its depth +const unsafeText = (value: string) => { + const made = new Md(TEXT, undefined, value) + made.depth = 1 + return made +} +const pushOne = (out: Md[], result: Md) => { + const last = out[out.length - 1] + if (result.type === TEXT && last !== undefined && last.type === TEXT) { + last.value += result.value + last.depth |= result.depth + } else out.push(result) +} +const push = (out: Md[], results: Md[]) => { + for (const result of results) pushOne(out, result) +} + +// an element's children, converted, appended to out +export const all = (parent: Element, out: Md[] = []): Md[] => { + const kids = kidsOf(parent) + for (let i = 0; i < kids.length; i++) { + const kid = kids[i]! + if (typeof kid === 'string') { + const collapsed = mode === NORMAL ? 0 : 1 + const value = minified(kid, kids, i) + if (value === undefined) continue + const last = out[out.length - 1] + if (last !== undefined && last.type === TEXT) { + last.value += value + last.depth |= collapsed + } else { + const fresh = new Md(TEXT, undefined, value) + fresh.depth = collapsed + out.push(fresh) + } + continue + } + if (skips.size !== 0 && skips.has(kid)) { + before = true + continue + } + // whitespace in it: a block's edges say nothing; an inline element's end says what follows it says + const info = INFO.get(kid.tag) ?? 0 + const kind = info & KIND_MASK + const block = (info & IS_BLOCK) !== 0 + const savedAfter = after + const savedMode = mode + const end = block ? true : collapsableAfter(kids, i, after) + if (block) before = true + after = end + if (info & IS_SPACED) mode = whitespaceOf(kid, mode) + let result: Md | Md[] | undefined + if (controls !== 0 && CONTROL_TAGS.has(kid.tag)) result = walkOnly(kid) + else if (kind === PASS && !(flags(kid) & MDAST)) all(kid, out) + else result = one(kid, kind, parent) + const strip = before || end + after = savedAfter + mode = savedMode + before = info & IS_CONTENT ? false : Boolean(strip) + if (result === undefined) continue + if (result instanceof Md) pushOne(out, result) + else push(out, result) + } + return out +} +// the whitespace an element leaves, without what it says +const walkOnly = (el: Element): undefined => { + if (!BLOCKS.has(el.tag) && !CONTENT.has(el.tag)) all(el) + return undefined +} +const CONTROL_TAGS = new Set([ + 'input', + 'select', + 'textarea', + 'button', + 'label', + 'legend', + 'option', + 'datalist', + 'output', +]) + +// what each tag becomes, as hast-util-to-mdast's handlers (and @affordances/md's) say +const PASS = 0 +const IGNORE = 1 +const FLOW = 2 +const PARAGRAPH_TAG = 3 +const HEADING_TAG = 4 +const LINK_TAG = 5 +const IMAGE_TAG = 6 +const BREAK_TAG = 7 +const RULE = 8 +const WBR = 9 +const STRONG_TAG = 10 +const QUOTE = 11 +const LIST_TAG = 12 +const ITEM = 13 +const DEFINITIONS = 14 +const CODE_BLOCK = 15 +const TABLE_TAG = 16 +const ROW = 17 +const CELL = 18 +const Q = 19 +const RAW = 20 +const DETAILS = 21 +const TITLED = 22 +const FORM = 23 +const CODE_TAG = 24 +const EMPHASIS_TAG = 25 +const DELETE_TAG = 26 +const KIND = new Map() +const kinds = (kind: number, tags: string) => { + for (const tag of tags.split(' ')) KIND.set(tag, kind) +} +kinds( + IGNORE, + 'applet area basefont bgsound caption col colgroup command content datalist dialog element embed frame frameset isindex keygen link math menu menuitem meta nextid noembed noframes optgroup option param script shadow source spacer style svg template title track input select textarea button base', +) +kinds( + FLOW, + 'address article aside body center fieldset figcaption footer header hgroup html legend main multicol nav picture section', +) +kinds(PARAGRAPH_TAG, 'p summary') +kinds(HEADING_TAG, 'h1 h2 h3 h4 h5 h6') +kinds(LINK_TAG, 'a') +kinds(IMAGE_TAG, 'img image') +kinds(BREAK_TAG, 'br') +kinds(RULE, 'hr') +kinds(WBR, 'wbr') +kinds(STRONG_TAG, 'b strong') +kinds(QUOTE, 'blockquote') +kinds(LIST_TAG, 'ul ol dir') +kinds(ITEM, 'li dt dd') +kinds(DEFINITIONS, 'dl') +kinds(CODE_BLOCK, 'pre listing plaintext xmp') +kinds(TABLE_TAG, 'table') +kinds(ROW, 'tr') +kinds(CELL, 'td th') +kinds(Q, 'q') +kinds(RAW, 'sup sub') +kinds(DETAILS, 'details') +kinds(TITLED, 'div figure') +kinds(FORM, 'form') +kinds(CODE_TAG, 'code kbd samp tt var') +kinds(EMPHASIS_TAG, 'em i mark u') +kinds(DELETE_TAG, 'del s strike') +// with each tag's kind, how whitespace sees it: a block, content, or an element with whitespace of its own +const KIND_MASK = 255 +const IS_BLOCK = 256 +const IS_CONTENT = 512 +const IS_SPACED = 1024 +const INFO = new Map() +for (const tag of new Set([...KIND.keys(), ...BLOCKS, ...CONTENT, 'nobr', 'textarea'])) + INFO.set( + tag, + (KIND.get(tag) ?? PASS) | + (BLOCKS.has(tag) ? IS_BLOCK : 0) | + (CONTENT.has(tag) ? IS_CONTENT : 0) | + (['pre', 'listing', 'plaintext', 'xmp', 'td', 'th', 'nobr', 'textarea'].includes(tag) + ? IS_SPACED + : 0), + ) + +const one = (el: Element, kind: number, parent: Element): Md | Md[] | undefined => { + if (el.attrs !== '' && flags(el) & MDAST && read(el, 'data-mdast') === 'ignore') + return walkOnly(el) + switch (kind) { + case PASS: + return all(el) + case IGNORE: + return walkOnly(el) + case FLOW: + return toFlow(all(el)) + case PARAGRAPH_TAG: { + const kids = dropBreaks(all(el)) + return kids.length ? node(PARAGRAPH, kids) : undefined + } + case HEADING_TAG: { + const heading = node(HEADING, dropBreaks(all(el))) + heading.depth = el.tag.charCodeAt(1) - 48 + return heading + } + case LINK_TAG: + return link(el, parent) + case IMAGE_TAG: + return image(el) + case BREAK_TAG: + return node(BREAK) + case RULE: + return node(THEMATIC_BREAK) + case WBR: + return textNode('\u200B') + case STRONG_TAG: + return node(STRONG, all(el)) + case QUOTE: + return node(BLOCKQUOTE, toFlow(all(el))) + case LIST_TAG: + return list(el) + case ITEM: + return listItem(el) + case DEFINITIONS: + return definitions(el) + case CODE_BLOCK: + return code(el) + case TABLE_TAG: + return table(el) + case ROW: + return node(TABLE_ROW, specific(all(el), TABLE_CELL)) + case CELL: + return cell(el) + case Q: { + const contents = all(el) + const head = contents[0] + const tail = contents[contents.length - 1] + if (head?.type === TEXT) head.value = '"' + head.value + else contents.unshift(textNode('"')) + if (tail?.type === TEXT) tail.value += '"' + else contents.push(textNode('"')) + return contents + } + case RAW: + return [ + node(HTML, undefined, `<${el.tag}>`), + ...all(el), + node(HTML, undefined, ``), + ] + case DETAILS: + return details(el) + case TITLED: + return titled(el) + case FORM: + return form(el) + case CODE_TAG: + return node(INLINE_CODE, undefined, toText(el)) + case EMPHASIS_TAG: + return node(EMPHASIS, all(el)) + case DELETE_TAG: + return node(DELETE, all(el)) + } + return all(el) +} + +const dropBreaks = (nodes: Md[]) => { + let start = 0 + let end = nodes.length + while (start < end && nodes[start]!.type === BREAK) start++ + while (end > start && nodes[end - 1]!.type === BREAK) end-- + return start === 0 && end === nodes.length ? nodes : nodes.slice(start, end) +} + +// flow content: runs of phrasing become paragraphs; a link or deletion holding blocks is pushed inside each block +const LEAVES = new Set([TEXT, INLINE_CODE, BREAK, IMAGE, HTML, CODE, THEMATIC_BREAK]) +const wrapNeeded = (nodes: Md[]): boolean => { + for (const item of nodes) + if (!isPhrasing(item) || (item.kids.length && wrapNeeded(item.kids))) return true + return false +} +const clone = (from: Md): Md => { + const copy = new Md(from.type, [], from.value) + copy.url = from.url + copy.title = from.title + copy.lang = from.lang + copy.meta = from.meta + copy.depth = from.depth + copy.ordered = from.ordered + copy.spread = from.spread + copy.checked = from.checked + copy.align = from.align && [...from.align] + copy.rowSpan = from.rowSpan + copy.colSpan = from.colSpan + return copy +} +const flatten = (nodes: Md[]): Md[] => { + let out: Md[] | undefined + for (let i = 0; i < nodes.length; i++) { + const item = nodes[i]! + if ((item.type === DELETE || item.type === LINK) && wrapNeeded(item.kids)) { + out ??= nodes.slice(0, i) + out.push(...split(item)) + } else out?.push(item) + } + return out ?? nodes +} +const split = (parent: Md): Md[] => + runs( + parent.kids, + (run) => { + const copy = clone(parent) + copy.kids = run + return [copy] + }, + (child) => { + if (!LEAVES.has(child.type)) { + const outer = clone(parent) + const inner = clone(child) + outer.kids = child.kids + inner.kids.push(outer) + return inner + } + return clone(child) + }, + ) +const runs = (nodes: Md[], onPhrasing: (run: Md[]) => Md[], onOther: (item: Md) => Md): Md[] => { + const flat = flatten(nodes) + const result: Md[] = [] + let queue: Md[] = [] + for (const item of flat) { + if (isPhrasing(item)) queue.push(item) + else { + if (queue.length) { + result.push(...onPhrasing(queue)) + queue = [] + } + result.push(onOther(item)) + } + } + if (queue.length) result.push(...onPhrasing(queue)) + return result +} +const whitespaceOnly = (value: string) => /^[ \t\n\f\r]*$/.test(value) +const toFlow = (nodes: Md[]): Md[] => + runs( + nodes, + (run) => + run.every((item) => item.type === TEXT && whitespaceOnly(item.value)) + ? [] + : [node(PARAGRAPH, dropBreaks(run))], + (item) => item, + ) +const rootKids = (nodes: Md[]) => (wrapNeeded(nodes) ? toFlow(nodes) : nodes) + +// children of one type, with what isn't one moved into the next (or the last) +const specific = (nodes: Md[], type: number): Md[] => { + const results: Md[] = [] + let queue: Md[] = [] + for (const item of nodes) { + if (item.type === type) { + if (queue.length) { + item.kids.unshift(...queue) + queue = [] + } + results.push(item) + } else queue.push(item) + } + if (queue.length) { + let last = results[results.length - 1] + if (!last) results.push((last = node(type))) + last.kids.push(...queue) + } + return results +} + +// urls: what a browser makes of an href, read without parsing when it's a shape a browser leaves as written (a +// #fragment, an /absolute/path, an http(s) url with a plain host) and made only of characters it never escapes +const urls = new Map() +const parse = (url: string, against: string): URL | null => { + let parsed = urls.get(url) + if (parsed === undefined) { + try { + parsed = new URL(url, against) + } catch { + parsed = null + } + urls.set(url, parsed) + } + return parsed +} +// characters no part of an http(s) url escapes (no dot segment either: those are resolved) +const PLAIN = /^[A-Za-z0-9\-._~!$&()*+,;=:@%/?#]*$/ +const DOT_SEGMENT = /\/\.|%2e/i +const HTTP = /^(https?):\/\/([a-z0-9-]+(?:\.[a-z0-9-]+)*\.?)(?=[/?#]|$)/ +const NUMERIC_LABEL = /(?:^|\.)(?:0x[0-9a-f]*|\d+)\.?$/ +// the shape an href is, when it's one of those: 'fragment', 'path', or an http url's length up to its path +const shape = (url: string): 'fragment' | 'path' | number | undefined => { + const head = url.charCodeAt(0) + if (head === 35) return PLAIN.test(url) && url.indexOf('#', 1) < 0 ? 'fragment' : undefined + if (head === 47) { + if (url.charCodeAt(1) === 47 || !PLAIN.test(url) || DOT_SEGMENT.test(url)) return undefined + return 'path' + } + if (head !== 104) return undefined + const match = HTTP.exec(url) + if (!match || NUMERIC_LABEL.test(match[2]!)) return undefined + if (!PLAIN.test(url) || DOT_SEGMENT.test(url.slice(match[0].length))) return undefined + return match[0].length +} +const LINK_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:']) +const IMAGE_SCHEMES = new Set(['http:', 'https:']) +// whether a url's scheme is one of these, as a browser reads it; a relative url is the page's own, http(s) +const RELATIVE = 'https://relative.invalid/' +const allowed = (url: string, schemes: Set) => { + if (shape(url) !== undefined) return true + let scheme: string | undefined + try { + scheme = new URL(url, RELATIVE).protocol + } catch { + return false + } + return schemes.has(scheme) +} +// the page's url, as the shapes above need it +let baseHref = '' +let baseOrigin = '' +let plainBase = false +const setBase = (page: string | undefined) => { + plainBase = false + if (!page) return + try { + const url = new URL(page) + baseHref = url.href.split('#')[0]! + baseOrigin = url.protocol + '//' + url.host + plainBase = + (url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password + } catch { + // a base that isn't a url leaves links as written + } +} +// a link's url once it's absolute, then through the link hook +const resolve = (url: string, image: boolean) => { + if (!base) return url + let href: string | undefined + const kind = plainBase ? shape(url) : undefined + if (kind === 'fragment') href = baseHref + url + else if (kind === 'path') href = baseOrigin + url + else if (typeof kind === 'number') + href = + kind === url.length + ? url + '/' + : url.charCodeAt(kind) === 47 + ? url + : url.slice(0, kind) + '/' + url.slice(kind) + else { + const absolute = parse(url, base) + if (!absolute) return url + href = absolute.href + } + if (!image && relink && !url.startsWith('#')) { + const swapped = relink(new URL(href)) + if (swapped) return swapped + } + return href +} + +const HEADINGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) +const link = (el: Element, parent: Element) => { + const href = (read(el, 'href') ?? '').trim() + const children = all(el) + if (!href || href === '#' || !allowed(href, LINK_SCHEMES)) return children + // a heading's link to its own anchor is the heading + if (href.startsWith('#') && HEADINGS.has(parent.tag)) return children + const result = node(LINK, children) + result.url = resolve(href, false) + result.title = flags(el) & TITLE ? (read(el, 'title') ?? null) : null + // an icon or avatar link reads as its label + if (!children.some((child) => child.type !== TEXT || child.value.trim())) { + const name = linkLabel(el) + if (!name) return undefined + result.kids = [unsafeText(name)] + } + return result +} + +const image = (el: Element) => { + const alt = (read(el, 'alt') ?? '').trim() + const src = read(el, 'src') + if (!alt || !src || !allowed(src, IMAGE_SCHEMES)) return undefined + const result = node(IMAGE, undefined, alt) + result.url = resolve(src, true) + result.title = flags(el) & TITLE ? (read(el, 'title') ?? null) : null + return result +} + +// the first child that isn't whitespace the walk drops +const firstKid = (el: Element): Node | undefined => { + for (const kid of kidsOf(el)) + if (typeof kid !== 'string' || !/^[\t\n\v\f\r ]*$/.test(kid)) return kid + return undefined +} +const checkbox = (kid: Node | undefined): Element | undefined => { + if (kid === undefined || typeof kid === 'string') return undefined + if (kid.tag === 'input') { + const type = read(kid, 'type') + return type === 'checkbox' || type === 'radio' ? kid : undefined + } + return kid.tag === 'p' ? checkbox(firstKid(kid)) : undefined +} +// hast-util-phrasing's elements +const PHRASING_TAGS = new Set( + 'a abbr area b bdi bdo br button cite code data datalist del dfn em i input ins kbd keygen label map mark meter noscript output progress q ruby s samp script select small span strong sub sup template textarea time u var wbr audio canvas embed iframe img math object picture svg video'.split( + ' ', + ), +) +// whether an item is loose: a

, or a second block, at any depth +const spreadOut = (el: Element): boolean => { + let seenFlow = false + for (const kid of kidsOf(el)) { + if (typeof kid === 'string' || PHRASING_TAGS.has(kid.tag)) continue + if (kid.tag === 'p' || seenFlow || spreadOut(kid)) return true + seenFlow = true + } + return false +} +const listItem = (el: Element) => { + const box = checkbox(firstKid(el)) + const item = node(LIST_ITEM) + item.checked = box ? read(box, 'checked') !== undefined : null + item.spread = spreadOut(el) + item.kids = toFlow(all(el)) + return item +} +const list = (el: Element) => { + const result = node(LIST, specific(all(el), LIST_ITEM)) + result.ordered = el.tag === 'ol' + if (result.ordered) { + const start = read(el, 'start') + // as hast reads it: a number when it is one, and 0 is no start + const value = + start !== undefined && start !== '' && !Number.isNaN(Number(start)) ? Number(start) : start + result.depth = value ? Number.parseInt(String(value), 10) : 1 + } + result.spread = result.kids.length > 1 && result.kids.some((item) => item.spread) + return result +} + +// **term**: definition, one paragraph per pair +const FLOW_TYPES = new Set([PARAGRAPH, HEADING, LIST, BLOCKQUOTE, CODE, TABLE, THEMATIC_BREAK]) +const says = (item: Md): boolean => + item.type === TEXT ? item.value.trim() !== '' : LEAVES.has(item.type) || item.kids.some(says) +const definitions = (el: Element) => { + const out: Md[] = [] + let terms: Md[][] = [] + const pairs = kidsOf(el).flatMap((kid) => + typeof kid !== 'string' && kid.tag === 'div' ? kidsOf(kid) : [kid], + ) + for (const kid of pairs) { + if (typeof kid === 'string') continue + if (kid.tag === 'dt') terms.push(asBlock(kid, () => all(kid))) + else if (kid.tag === 'dd') { + const strong: Md[] = [] + for (const term of terms.filter((parts) => + parts.some((part) => part.type !== TEXT || part.value.trim()), + )) { + if (strong.length) strong.push(textNode(', ')) + strong.push(node(STRONG, term)) + } + const lead = strong.length ? [...strong, textNode(': ')] : strong + const first = node(PARAGRAPH, [...lead]) + const flow: Md[] = [first] + let open: Md | undefined = first + for (const part of asBlock(kid, () => all(kid))) { + if (part.type === PARAGRAPH && open === first && first.kids.length === lead.length) { + first.kids.push(...part.kids) + open = undefined + } else if (FLOW_TYPES.has(part.type)) { + flow.push(part) + open = undefined + } else if (open) open.kids.push(part) + else flow.push((open = node(PARAGRAPH, [part]))) + } + out.push(...flow.filter((block) => block.type !== PARAGRAPH || block.kids.length)) + terms = [] + } + } + return out +} + +const details = (el: Element) => { + const summary = kidsOf(el).find( + (kid): kid is Element => typeof kid !== 'string' && kid.tag === 'summary', + ) + const head: Md[] = [] + if (summary) { + const inherited = before + head.push( + node(PARAGRAPH, [ + node( + STRONG, + asBlock(summary, () => all(summary)), + ), + ]), + ) + before = inherited + skips.add(summary) + } + const rest = all(el) + if (summary) skips.delete(summary) + return [...head, ...toFlow(rest)] +} + +// a form says what it says, without its controls (the field summary is @affordances/md's alone, for now) +const form = (el: Element) => { + controls++ + const flow = toFlow(all(el)) + controls-- + return flow +} + +// a code block's language: a language-* class on its , data-language on it or the

, or a class on the 
+const classLanguage = (el: Element | undefined) =>
+  el &&
+  classes(el)
+    .find((name) => name.startsWith('language-'))
+    ?.slice('language-'.length)
+const codeOf = (pre: Element) =>
+  kidsOf(pre).find((kid): kid is Element => typeof kid !== 'string' && kid.tag === 'code')
+const languageOf = (pre: Element) => {
+  const inner = codeOf(pre)
+  const said = [inner && read(inner, 'data-language'), read(pre, 'data-language')]
+    .map((language) => (language ?? '').trim())
+    .find(Boolean)
+  return (classLanguage(inner) ?? said ?? classLanguage(pre))?.split(/\s/)[0] || null
+}
+const code = (el: Element) => {
+  const result = node(CODE, undefined, toText(el).replace(/[\r\n]+$/, ''))
+  if (el.tag !== 'pre') return result
+  result.lang = languageOf(el)
+  const title = el === titledCode ? titledAs : read(el, 'data-title')
+  if (title) result.meta = `title=${JSON.stringify(title)}`
+  return result
+}
+// a code block's title where highlighters put it: a figcaption before it in its figure, or data-title on what holds it
+const descendants = (el: Element, found: Element[], tags: Set) => {
+  for (const kid of kidsOf(el))
+    if (typeof kid !== 'string') {
+      if (tags.has(kid.tag)) found.push(kid)
+      descendants(kid, found, tags)
+    }
+  return found
+}
+const PRE_TAGS = new Set(['pre'])
+const CAPTION_OR_PRE = new Set(['figcaption', 'pre'])
+const titled = (el: Element) => {
+  const flow = () => toFlow(all(el))
+  if (el.tag !== 'figure' && !(flags(el) & DATA_TITLE)) return flow()
+  const [pre, ...more] = descendants(el, [], PRE_TAGS)
+  if (!pre || more.length || read(pre, 'data-title') || pre === titledCode || !languageOf(pre))
+    return flow()
+  let caption: Element | undefined
+  if (el.tag === 'figure') {
+    const order = descendants(el, [], CAPTION_OR_PRE)
+    caption = order.slice(0, order.indexOf(pre)).find((at) => at.tag === 'figcaption')
+  }
+  const title = text(caption) || (read(el, 'data-title') ?? '').trim()
+  if (!title) return flow()
+  const saved = titledCode
+  const savedAs = titledAs
+  titledCode = pre
+  titledAs = title
+  if (caption) skips.add(caption)
+  const result = flow()
+  if (caption) skips.delete(caption)
+  titledCode = saved
+  titledAs = savedAs
+  return result
+}
+
+// a cell is one line: blocks in it are separated by a space
+const cell = (el: Element) => {
+  const result = node(TABLE_CELL, all(el))
+  if (flags(el) & SPAN) {
+    const rowSpan = read(el, 'rowspan')
+    const colSpan = read(el, 'colspan')
+    if (rowSpan) result.rowSpan = Number.parseInt(rowSpan, 10) || 1
+    if (colSpan) result.colSpan = Number.parseInt(colSpan, 10) || 1
+  }
+  if (!result.kids.some((kid) => kid.type === PARAGRAPH)) return result
+  const parts: Md[][] = []
+  let run: Md[] = []
+  for (const kid of result.kids) {
+    if (kid.type !== PARAGRAPH) {
+      run.push(kid)
+      continue
+    }
+    parts.push(run, kid.kids)
+    run = []
+  }
+  parts.push(run)
+  const said = parts.filter((part) => part.some(says))
+  const kids: Md[] = []
+  said.forEach((part, i) => {
+    const last = i ? said[i - 1]!.at(-1) : undefined
+    if (i && !(last?.type === TEXT && /\s$/.test(last.value))) kids.push(textNode(' '))
+    kids.push(...part)
+  })
+  result.kids = kids
+  return result
+}
+
+const table = (el: Element): Md => {
+  if (inTable) return unsafeText(toText(el))
+  inTable = true
+  const { align, headless } = inspect(el)
+  const rows = specific(all(el), TABLE_ROW)
+  if (headless) rows.unshift(node(TABLE_ROW))
+  for (const row of rows) row.kids = specific(row.kids, TABLE_CELL)
+  let columns = 1
+  for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
+    const cells = rows[rowIndex]!.kids
+    for (let cellIndex = 0; cellIndex < cells.length; cellIndex++) {
+      const at = cells[cellIndex]!
+      const colSpan = at.colSpan || 1
+      const rowSpan = at.rowSpan || 1
+      if (colSpan > 1 || rowSpan > 1) {
+        for (let other = rowIndex; other < rowIndex + rowSpan; other++) {
+          for (let col = cellIndex; col < cellIndex + colSpan; col++) {
+            if (!rows[other]) break
+            const added = other !== rowIndex || col !== cellIndex ? [node(TABLE_CELL)] : []
+            rows[other]!.kids.splice(col, 0, ...added)
+          }
+        }
+      }
+      at.colSpan = 0
+      at.rowSpan = 0
+    }
+    if (cells.length > columns) columns = cells.length
+  }
+  for (const row of rows) while (row.kids.length < columns) row.kids.push(node(TABLE_CELL))
+  while (align.length < columns) align.push(null)
+  inTable = false
+  const result = node(TABLE, rows)
+  result.align = align
+  return result
+}
+const inspect = (el: Element) => {
+  const align: (string | null)[] = [null]
+  let headless = true
+  let rowIndex = 0
+  let cellIndex = 0
+  const walk = (parent: Element) => {
+    for (const kid of kidsOf(parent)) {
+      if (typeof kid === 'string') continue
+      if (kid.tag === 'table') continue
+      if (kid.tag === 'th' || kid.tag === 'td') {
+        if (!align[cellIndex]) {
+          const value = (flags(kid) & ALIGN && read(kid, 'align')) || null
+          if (value === 'center' || value === 'left' || value === 'right' || value === null)
+            align[cellIndex] = value
+        }
+        if (headless && rowIndex < 2 && kid.tag === 'th') headless = false
+        cellIndex++
+      } else if (kid.tag === 'thead') headless = false
+      else if (kid.tag === 'tr') {
+        rowIndex++
+        cellIndex = 0
+      }
+      walk(kid)
+    }
+  }
+  walk(el)
+  return { align, headless }
+}
+
+// an element's text as a browser renders it (hast-util-to-text, MIT, Titus Wormer), over text the whitespace walk
+// has already collapsed: code, a code block, a table in a table
+const BLOCK_OR_CAPTION = new Set(
+  'address article aside blockquote body caption center dd dialog dir dl dt div figure figcaption footer form h1 h2 h3 h4 h5 h6 header hgroup hr html legend li listing main menu nav ol p plaintext pre section ul xmp'.split(
+    ' ',
+  ),
+)
+const NOT_RENDERED = new Set([
+  'datalist',
+  'head',
+  'noembed',
+  'noframes',
+  'noscript',
+  'rp',
+  'script',
+  'style',
+  'template',
+  'title',
+])
+const TABLE_PARTS = new Set([
+  'caption',
+  'col',
+  'colgroup',
+  'tbody',
+  'td',
+  'tfoot',
+  'th',
+  'thead',
+  'tr',
+])
+const ROW_GROUPS = new Set(['tbody', 'tfoot', 'thead'])
+type Info = {
+  breakBefore: boolean | number | string | undefined
+  breakAfter: boolean | number | string | undefined
+  rowAfter: boolean | undefined
+  normal: boolean
+}
+type Piece = string | number
+const isBr = (kid: Node | undefined) =>
+  kid !== undefined && typeof kid !== 'string' && kid.tag === 'br'
+const isRow = (kid: Node) => typeof kid !== 'string' && kid.tag === 'tr'
+const isCell = (kid: Node) => typeof kid !== 'string' && (kid.tag === 'td' || kid.tag === 'th')
+const rowOrGroupWithRow = (kid: Node) =>
+  typeof kid !== 'string' &&
+  (kid.tag === 'tr' || (ROW_GROUPS.has(kid.tag) && kidsOf(kid).some(isRow)))
+const afterIn = (kids: Node[], index: number, test: (kid: Node) => boolean) => {
+  while (++index < kids.length) if (test(kids[index]!)) return true
+  return false
+}
+const inTableTag = (tag: string) => tag === 'table' || ROW_GROUPS.has(tag)
+
+export const toText = (el: Element): string => {
+  const block = BLOCK_OR_CAPTION.has(el.tag)
+  const tableish = inTableTag(el.tag)
+  const normal = whitespaceOf(el, NORMAL) === NORMAL
+  const kids = kidsOf(el)
+  const results: Piece[] = []
+  for (let i = 0; i < kids.length; i++) {
+    const next = kids[i + 1]
+    collect(kids, i, el, results, {
+      breakAfter: next ? isBr(next) : block,
+      breakBefore: i ? undefined : block,
+      rowAfter: tableish && el.tag === 'table' ? afterIn(kids, i, rowOrGroupWithRow) : undefined,
+      normal,
+    })
+  }
+  return joinPieces(results)
+}
+const joinPieces = (results: Piece[]) => {
+  let result = ''
+  let count: number | undefined
+  for (const value of results) {
+    if (typeof value === 'number') {
+      if (count !== undefined && value > count) count = value
+    } else if (value) {
+      if (count !== undefined && count > -1) result += '\n'.repeat(count) || ' '
+      count = -1
+      result += value
+    }
+  }
+  return result
+}
+const collect = (kids: Node[], index: number, parent: Element, out: Piece[], info: Info) => {
+  const kid = kids[index]!
+  if (typeof kid === 'string') {
+    // preformatted text is as written, and what's beside it doesn't matter
+    const value = mode === PRE ? kid : minified(kid, kids, index)
+    if (value === undefined) return
+    if (
+      blank(value) &&
+      (parent.tag === 'table' || parent.tag === 'tr' || ROW_GROUPS.has(parent.tag))
+    ) {
+      const previous = kids[index - 1]
+      const following = kids[index + 1]
+      if (
+        (!previous || (typeof previous !== 'string' && TABLE_PARTS.has(previous.tag))) &&
+        (!following || (typeof following !== 'string' && TABLE_PARTS.has(following.tag)))
+      )
+        return
+    }
+    if (info.normal) collectText(value, info, out)
+    else out.push(value)
+    return
+  }
+  if (mode === PRE) {
+    collectElement(kid, index, kids, parent, info, out)
+    return
+  }
+  const saved = enterElement(kid, kids, index)
+  collectElement(kid, index, kids, parent, info, out)
+  exitElement(kid, saved)
+}
+const collectElement = (
+  el: Element,
+  position: number,
+  siblings: Node[],
+  _parent: Element,
+  info: Info,
+  out: Piece[],
+) => {
+  const normal = info.normal && whitespaceOf(el, NORMAL) === NORMAL
+  if (NOT_RENDERED.has(el.tag) || (el.tag === 'dialog' && read(el, 'open') === undefined)) {
+    walkOnly(el)
+    return
+  }
+  let prefix: number | undefined
+  let suffix: number | string | undefined
+  if (el.tag === 'br') suffix = '\n'
+  else if (el.tag === 'tr' && (info.rowAfter || afterIn(siblings, position, isRow))) suffix = '\n'
+  else if (el.tag === 'p') {
+    prefix = 2
+    suffix = 2
+  } else if (BLOCK_OR_CAPTION.has(el.tag)) {
+    prefix = 1
+    suffix = 1
+  }
+  const kids = kidsOf(el)
+  const tableish = inTableTag(el.tag)
+  const items: Piece[] = []
+  for (let i = 0; i < kids.length; i++) {
+    const next = kids[i + 1]
+    collect(kids, i, el, items, {
+      breakAfter: next ? isBr(next) : suffix,
+      breakBefore: i ? undefined : prefix,
+      rowAfter: tableish
+        ? el.tag === 'table'
+          ? afterIn(kids, i, rowOrGroupWithRow)
+          : info.rowAfter
+        : undefined,
+      normal,
+    })
+  }
+  if (isCell(el) && afterIn(siblings, position, isCell)) items.push('\t')
+  if (prefix) out.push(prefix)
+  out.push(...items)
+  if (suffix) out.push(suffix)
+}
+const BIDI = /[؜‎‏‪-‮⁦-⁩]/g
+const collectText = (value: string, info: Info, out: Piece[]) => {
+  const lines: string[] = []
+  let start = 0
+  while (start <= value.length) {
+    const found = value.indexOf('\n', start)
+    const end = found < 0 ? value.length : found
+    lines.push(
+      trimAndCollapse(
+        value.slice(start, end).replace(BIDI, ''),
+        start === 0 ? info.breakBefore : true,
+        end === value.length ? info.breakAfter : true,
+      ),
+    )
+    start = end + 1
+  }
+  let join: number | undefined
+  for (let index = 0; index < lines.length; index++) {
+    const line = lines[index]!
+    if (
+      line.charCodeAt(line.length - 1) === 0x200b ||
+      (index < lines.length - 1 && lines[index + 1]!.charCodeAt(0) === 0x200b)
+    ) {
+      out.push(line)
+      join = undefined
+    } else if (line) {
+      if (typeof join === 'number') out.push(join)
+      out.push(line)
+      join = 0
+    } else if (index === 0 || index === lines.length - 1) out.push(0)
+  }
+}
+const trimAndCollapse = (value: string, breakBefore: unknown, breakAfter: unknown) => {
+  const result: string[] = []
+  const spaces = /[\t ]+/g
+  let start = 0
+  let end: number | undefined
+  while (start < value.length) {
+    spaces.lastIndex = start
+    const match = spaces.exec(value)
+    end = match ? match.index : value.length
+    if (!start && !end && match && !breakBefore) result.push('')
+    if (start !== end) result.push(value.slice(start, end))
+    start = match ? end + match[0].length : end
+  }
+  if (start !== end && !breakAfter) result.push('')
+  return result.join(' ')
+}
+
+// the walk over the content's root, as hast-util-to-mdast's root handler: wrapped when it holds blocks
+export const convertRoot = (root: Element): Md => {
+  before = true
+  after = true
+  mode = NORMAL
+  const result = node(ROOT, rootKids(all(root)))
+  tidy(result)
+  return result
+}
+
+// what hast-util-to-mdast does last: adjacent texts as one, the line ending's spaces, a paragraph's (heading's,
+// root's) outer spaces, and empty texts gone
+const TRIMMED = new Set([PARAGRAPH, HEADING, ROOT])
+const edgeSpace = (char: number) => char === 32 || char === 9
+
+const tidy = (parent: Md) => {
+  const kids = parent.kids
+  const trims = TRIMMED.has(parent.type)
+  for (let index = 0; index < kids.length; index++) {
+    const item = kids[index]!
+    if (item.type !== TEXT) {
+      if (item.kids.length) tidy(item)
+      continue
+    }
+    const previous = kids[index - 1]
+    if (previous?.type === TEXT) {
+      previous.value += item.value
+      previous.depth |= item.depth
+      kids.splice(index, 1)
+      index -= 2
+      continue
+    }
+    let value = item.value
+    if (item.depth !== 0 && (value.includes('\n') || value.includes('\r')))
+      value = value.replace(/[\t ]*(\r?\n|\r)[\t ]*/, '$1')
+    if (trims) {
+      if (index === 0 && edgeSpace(value.charCodeAt(0))) value = value.replace(/^[\t ]+/, '')
+      if (index === kids.length - 1 && edgeSpace(value.charCodeAt(value.length - 1)))
+        value = value.replace(/[\t ]+$/, '')
+    }
+    item.value = value
+    if (!value) {
+      kids.splice(index, 1)
+      index--
+    }
+  }
+}
diff --git a/packages/md-core/src/emit-markdown.ts b/packages/md-core/src/emit-markdown.ts
new file mode 100644
index 0000000..63273bb
--- /dev/null
+++ b/packages/md-core/src/emit-markdown.ts
@@ -0,0 +1,1378 @@
+// markdown from the emitter's lean tree, written the way mdast-util-to-markdown (MIT, Titus Wormer) writes an mdast
+// tree with @affordances/md's options: bullet -, emphasis _, strong *, rule -, fenced code, and gfm (tables, task
+// lists, strikethrough, autolink literals with their escapes kept to headings). its rules are ported one for one, over
+// a construct bitmask instead of a stack of names, with a fast path for text that needs no escape
+
+// node types: the phrasing ones are TEXT and up, so phrasing is a comparison
+export const ROOT = 0
+export const PARAGRAPH = 1
+export const HEADING = 2
+export const THEMATIC_BREAK = 3
+export const BLOCKQUOTE = 4
+export const LIST = 5
+export const LIST_ITEM = 6
+export const CODE = 7
+export const TABLE = 8
+export const TABLE_ROW = 9
+export const TABLE_CELL = 10
+export const HTML = 11
+export const TEXT = 12
+export const EMPHASIS = 13
+export const STRONG = 14
+export const DELETE = 15
+export const INLINE_CODE = 16
+export const BREAK = 17
+export const LINK = 18
+export const IMAGE = 19
+
+// one shape for every node, so the walks over them stay monomorphic
+export class Md {
+  type: number
+  kids: Md[]
+  // text, code, inline code, html; an image's alt
+  value: string
+  url: string
+  title: string | null
+  lang: string | null
+  meta: string | null
+  // a heading's depth, an ordered list's start
+  depth: number
+  ordered: boolean
+  spread: boolean
+  checked: boolean | null
+  align: (string | null)[] | null
+  rowSpan: number
+  colSpan: number
+  constructor(type: number, kids: Md[] = [], value = '') {
+    this.type = type
+    this.kids = kids
+    this.value = value
+    this.url = ''
+    this.title = null
+    this.lang = null
+    this.meta = null
+    this.depth = 0
+    this.ordered = false
+    this.spread = false
+    this.checked = null
+    this.align = null
+    this.rowSpan = 0
+    this.colSpan = 0
+  }
+}
+
+export const isPhrasing = (node: Md) => node.type >= TEXT
+
+// constructs, as bits
+const PHRASING = 1
+const HEADING_ATX = 2
+const LABEL = 4
+const REFERENCE = 8
+const AUTOLINK = 16
+const DESTINATION_LITERAL = 32
+const DESTINATION_RAW = 64
+const TITLE_QUOTE = 128
+const TITLE_APOSTROPHE = 256
+const LANG_GRAVE = 512
+const LANG_TILDE = 1024
+const META_GRAVE = 2048
+const META_TILDE = 4096
+const TABLE_CELL_BIT = 8192
+const LINK_BIT = 16384
+const IMAGE_BIT = 32768
+const STRIKETHROUGH = 65536
+const BITS: Record = {
+  phrasing: PHRASING,
+  headingAtx: HEADING_ATX,
+  label: LABEL,
+  reference: REFERENCE,
+  autolink: AUTOLINK,
+  destinationLiteral: DESTINATION_LITERAL,
+  destinationRaw: DESTINATION_RAW,
+  titleQuote: TITLE_QUOTE,
+  titleApostrophe: TITLE_APOSTROPHE,
+  codeFencedLangGraveAccent: LANG_GRAVE,
+  codeFencedLangTilde: LANG_TILDE,
+  codeFencedMetaGraveAccent: META_GRAVE,
+  codeFencedMetaTilde: META_TILDE,
+  tableCell: TABLE_CELL_BIT,
+  link: LINK_BIT,
+  image: IMAGE_BIT,
+  strikethrough: STRIKETHROUGH,
+}
+const maskOf = (names: string[] | string | undefined) =>
+  [names ?? []].flat().reduce((mask, name) => mask | (BITS[name] ?? 0), 0)
+
+type Unsafe = {
+  character: string
+  inConstruct?: string | string[]
+  notInConstruct?: string[]
+  before?: string
+  after?: string
+  atBreak?: boolean
+}
+const FULL_PHRASING_SPANS = [
+  'autolink',
+  'destinationLiteral',
+  'destinationRaw',
+  'reference',
+  'titleQuote',
+  'titleApostrophe',
+]
+const LANG_META = [
+  'codeFencedLangGraveAccent',
+  'codeFencedLangTilde',
+  'codeFencedMetaGraveAccent',
+  'codeFencedMetaTilde',
+]
+// mdast-util-to-markdown's unsafe patterns, then gfm's: autolink literals (made heading-only, as @affordances/md
+// does), footnotes, strikethrough, tables and task lists
+const UNSAFE: Unsafe[] = [
+  { character: '\t', after: '[\\r\\n]', inConstruct: 'phrasing' },
+  { character: '\t', before: '[\\r\\n]', inConstruct: 'phrasing' },
+  { character: '\t', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde'] },
+  { character: '\r', inConstruct: [...LANG_META, 'destinationLiteral', 'headingAtx'] },
+  { character: '\n', inConstruct: [...LANG_META, 'destinationLiteral', 'headingAtx'] },
+  { character: '\r', before: '[\\r\\n]', inConstruct: 'phrasing' },
+  { character: '\r', after: '\\r', inConstruct: 'phrasing' },
+  { character: '\n', before: '\\n', inConstruct: 'phrasing' },
+  { character: '\n', after: '[\\r\\n]', inConstruct: 'phrasing' },
+  { character: ' ', after: '[\\r\\n]', inConstruct: 'phrasing' },
+  { character: ' ', before: '[\\r\\n]', inConstruct: 'phrasing' },
+  { character: ' ', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde'] },
+  { character: '!', after: '\\[', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+  { character: '"', inConstruct: 'titleQuote' },
+  { atBreak: true, character: '#' },
+  { character: '#', inConstruct: 'headingAtx', after: '(?:[\r\n]|$)' },
+  {
+    character: '&',
+    after: '[#A-Za-z]',
+    inConstruct: [
+      ...LANG_META,
+      'destinationLiteral',
+      'destinationRaw',
+      'phrasing',
+      'titleApostrophe',
+      'titleQuote',
+    ],
+  },
+  { character: "'", inConstruct: 'titleApostrophe' },
+  { character: '(', inConstruct: 'destinationRaw' },
+  { before: '\\]', character: '(', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+  { atBreak: true, before: '\\d+', character: ')' },
+  { character: ')', inConstruct: 'destinationRaw' },
+  { atBreak: true, character: '*', after: '(?:[ \t\r\n*])' },
+  { character: '*', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+  { atBreak: true, character: '+', after: '(?:[ \t\r\n])' },
+  { atBreak: true, character: '-', after: '(?:[ \t\r\n-])' },
+  { atBreak: true, before: '\\d+', character: '.', after: '(?:[ \t\r\n]|$)' },
+  { atBreak: true, character: '<', after: '[!/?A-Za-z]' },
+  {
+    character: '<',
+    after: '[!/?A-Za-z]',
+    inConstruct: 'phrasing',
+    notInConstruct: FULL_PHRASING_SPANS,
+  },
+  { character: '<', inConstruct: 'destinationLiteral' },
+  { atBreak: true, character: '=' },
+  { atBreak: true, character: '>' },
+  { character: '>', inConstruct: 'destinationLiteral' },
+  { atBreak: true, character: '[' },
+  { character: '[', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+  { character: '[', inConstruct: ['label', 'reference'] },
+  { character: '\\', after: '[\\r\\n]', inConstruct: 'phrasing' },
+  { character: ']', inConstruct: ['label', 'reference'] },
+  { atBreak: true, character: '_' },
+  { character: '_', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+  { atBreak: true, character: '`' },
+  { character: '`', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedMetaGraveAccent'] },
+  { character: '`', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+  { atBreak: true, character: '~' },
+  { character: '<', inConstruct: 'autolink' },
+  { character: '>', inConstruct: 'autolink' },
+  { character: '\u007F', inConstruct: 'autolink' },
+  ...Array.from({ length: 33 }, (_, code) => ({
+    character: String.fromCharCode(code),
+    inConstruct: 'autolink',
+  })),
+  // gfm autolink literals, kept to headings
+  {
+    character: '@',
+    before: '[+\\-.\\w]',
+    after: '[\\-.\\w]',
+    inConstruct: 'headingAtx',
+    notInConstruct: ['autolink', 'link', 'image', 'label'],
+  },
+  {
+    character: '.',
+    before: '[Ww]',
+    after: '[\\-.\\w]',
+    inConstruct: 'headingAtx',
+    notInConstruct: ['autolink', 'link', 'image', 'label'],
+  },
+  {
+    character: ':',
+    before: '[ps]',
+    after: '\\/',
+    inConstruct: 'headingAtx',
+    notInConstruct: ['autolink', 'link', 'image', 'label'],
+  },
+  // footnotes
+  { character: '[', inConstruct: ['label', 'phrasing', 'reference'] },
+  // strikethrough
+  {
+    character: '~',
+    inConstruct: 'phrasing',
+    notInConstruct: [
+      'autolink',
+      'destinationLiteral',
+      'destinationRaw',
+      'reference',
+      'titleQuote',
+      'titleApostrophe',
+    ],
+  },
+  // tables
+  { character: '\r', inConstruct: 'tableCell' },
+  { character: '\n', inConstruct: 'tableCell' },
+  { atBreak: true, character: '|', after: '[\t :-]' },
+  { character: '|', inConstruct: 'tableCell' },
+  { atBreak: true, character: ':', after: '-' },
+  { atBreak: true, character: '-', after: '[:|-]' },
+  // task lists
+  { atBreak: true, character: '-', after: '[:|-]' },
+]
+
+type Pattern = {
+  character: string
+  in: number
+  notIn: number
+  // matches only next to a line ending: never in a value without one
+  newline: boolean
+  // whether it has a before (or is atBreak), or an after
+  before: boolean
+  after: boolean
+  regex: RegExp
+}
+const NEWLINE_ONLY = new Set(['[\\r\\n]', '\\n', '\\r'])
+const PATTERNS: Pattern[] = UNSAFE.map((pattern) => {
+  const before =
+    (pattern.atBreak ? '[\\r\\n][\\t ]*' : '') + (pattern.before ? `(?:${pattern.before})` : '')
+  return {
+    character: pattern.character,
+    // no inConstruct: always in scope
+    in: pattern.inConstruct === undefined ? -1 : maskOf(pattern.inConstruct),
+    notIn: maskOf(pattern.notInConstruct),
+    newline:
+      Boolean(pattern.atBreak) ||
+      NEWLINE_ONLY.has(pattern.before ?? '') ||
+      NEWLINE_ONLY.has(pattern.after ?? ''),
+    before: 'before' in pattern || Boolean(pattern.atBreak),
+    after: 'after' in pattern,
+    regex: new RegExp(
+      (before ? `(${before})` : '') +
+        (/[$()*+.?[\\\]^{|}]/.test(pattern.character) ? '\\' : '') +
+        pattern.character +
+        (pattern.after ? `(?:${pattern.after})` : ''),
+      'g',
+    ),
+  }
+})
+
+// the patterns in scope for a set of constructs, and a test for text that none of them (or a backslash) can touch
+type Scope = { patterns: Pattern[]; special: RegExp; bareNewline: boolean }
+const scopes = new Map()
+const scopeOf = (mask: number): Scope => {
+  let scope = scopes.get(mask)
+  if (scope) return scope
+  const patterns = PATTERNS.filter(
+    (pattern) => (pattern.in === -1 || (pattern.in & mask) !== 0) && (pattern.notIn & mask) === 0,
+  )
+  const chars = new Set(['\\'])
+  for (const pattern of patterns) if (!pattern.newline) chars.add(pattern.character)
+  const set = [...chars]
+    .map((char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)
+    .join('')
+  scope = {
+    patterns,
+    special: new RegExp(`[${set}\\r\\n]`),
+    bareNewline: patterns.some(
+      (pattern) => pattern.character === '\n' && !pattern.before && !pattern.after,
+    ),
+  }
+  scopes.set(mask, scope)
+  return scope
+}
+
+// the serializer's state: the constructs it's in, as names (the list handler reads them) and as a mask
+let stack: string[] = []
+let masks: number[] = []
+let mask = 0
+let indexStack: number[] = []
+let bulletCurrent: string | undefined
+let bulletLastUsed: string | undefined
+const enter = (name: string) => {
+  stack.push(name)
+  masks.push(mask)
+  mask |= BITS[name] ?? 0
+}
+const exit = () => {
+  stack.pop()
+  mask = masks.pop()!
+}
+
+// micromark's classes: 1 whitespace, 2 punctuation, 0 anything else (a letter, a digit, a lone surrogate)
+const PUNCTUATION = /[\p{P}\p{S}]/u
+const WHITESPACE = /\s/
+const classes = new Uint8Array(128)
+for (let code = 0; code < 128; code++) {
+  const char = String.fromCharCode(code)
+  classes[code] = code === 32 || WHITESPACE.test(char) ? 1 : PUNCTUATION.test(char) ? 2 : 0
+}
+const classify = (code: number): number => {
+  if (code !== code) return 0
+  if (code < 128) return classes[code]!
+  const char = String.fromCharCode(code)
+  return WHITESPACE.test(char) ? 1 : PUNCTUATION.test(char) ? 2 : 0
+}
+
+const ASCII_PUNCTUATION = /[!-/:-@[-`{-~]/
+const reference = (code: number) => `&#x${code.toString(16).toUpperCase()};`
+// a string's first and last code points
+const high = (code: number) => code >= 0xd800 && code <= 0xdbff
+const low = (code: number) => code >= 0xdc00 && code <= 0xdfff
+const firstCharacter = (value: string) =>
+  high(value.charCodeAt(0)) && low(value.charCodeAt(1)) ? value.slice(0, 2) : value.charAt(0)
+const lastCharacter = (value: string) => {
+  const n = value.length
+  return n > 1 && low(value.charCodeAt(n - 1)) && high(value.charCodeAt(n - 2))
+    ? value.slice(-2)
+    : value.charAt(n - 1)
+}
+const isNewline = (code: number) => code === 10 || code === 13
+
+const escapeBackslashes = (value: string, after: string) => {
+  if (value.indexOf('\\') < 0 && after.indexOf('\\') < 0) return value
+  const expression = /\\(?=[!-/:-@[-`{-~])/g
+  const whole = value + after
+  const results: string[] = []
+  let start = 0
+  let match
+  while ((match = expression.exec(whole))) {
+    if (start !== match.index) results.push(value.slice(start, match.index))
+    results.push('\\')
+    start = match.index
+  }
+  results.push(value.slice(start))
+  return results.join('')
+}
+
+// text made safe to write between before and after in the current constructs: mdast-util-to-markdown's safe()
+const safe = (input: string, before: string, after: string, encode = ''): string => {
+  if (input === '') return escapeBackslashes(input, after)
+  const scope = scopeOf(mask)
+  // the fast path: nothing a pattern could match, and no line ending beside the text to start a construct
+  if (!scope.special.test(input)) {
+    const head = input.charCodeAt(0)
+    const tail = input.charCodeAt(input.length - 1)
+    const lineBefore = before !== '' && isNewline(before.charCodeAt(before.length - 1))
+    const lineAfter = after !== '' && isNewline(after.charCodeAt(0))
+    if (
+      !(lineBefore && atLineStart(input, head)) &&
+      !(lineAfter && (tail === 32 || tail === 9 || tail === 35)) &&
+      !(after === '' && tail === 46)
+    )
+      return input
+  }
+  return slowSafe(scope, input, before, after, encode)
+}
+// what can start a construct at the start of a line: an atBreak pattern's character, a digit (an ordered list), or
+// whitespace
+const LINE_START = new Uint8Array(128)
+for (const char of '#)*+-.<=>[_`~|: \t0123456789') LINE_START[char.charCodeAt(0)] = 1
+const atLineStart = (input: string, head: number) =>
+  head < 128 && LINE_START[head] === 1 && input !== ''
+
+const slowSafe = (scope: Scope, input: string, before: string, after: string, encode: string) => {
+  // what came before matters only from its last line ending (atBreak), or as one character
+  if (before.length > 1) {
+    const line = Math.max(before.lastIndexOf('\n'), before.lastIndexOf('\r'))
+    before = line >= 0 ? before.slice(line) : before.slice(-1)
+  }
+  const value = before + input + after
+  const offset = before.length
+  const end = value.length - after.length
+  const hasNewline = /[\r\n]/.test(value)
+  const positions: number[] = []
+  // per position matched: whether every pattern there had a before (1), an after (2)
+  const infos = new Map()
+  for (const pattern of scope.patterns) {
+    if (pattern.newline && !hasNewline) continue
+    if (input.indexOf(pattern.character) < 0) continue
+    const expression = pattern.regex
+    expression.lastIndex = 0
+    const sides = (pattern.before ? 1 : 0) | (pattern.after ? 2 : 0)
+    let match
+    while ((match = expression.exec(value))) {
+      const position = match.index + (pattern.before ? match[1]!.length : 0)
+      const info = infos.get(position)
+      if (info === undefined) {
+        positions.push(position)
+        infos.set(position, sides)
+      } else infos.set(position, info & sides)
+    }
+  }
+  if (!positions.length) return escapeBackslashes(input, after)
+  positions.sort((a, b) => a - b)
+  const result: string[] = []
+  let start = offset
+  for (let index = 0; index < positions.length; index++) {
+    const position = positions[index]!
+    if (position < start || position >= end) continue
+    // an intraword underscore run (snake_case) needs no escape
+    if (
+      value.charCodeAt(position) === 95 &&
+      position > 0 &&
+      classify(value.charCodeAt(position - 1)) === 0 &&
+      !infos.has(position - 1) &&
+      !(position - 1 === offset && /[*_]/.test(value.charAt(offset - 1)))
+    ) {
+      let sequenceEnd = position + 1
+      while (sequenceEnd < end && value.charCodeAt(sequenceEnd) === 95) sequenceEnd++
+      const skip = sequenceEnd - position - 1
+      if (
+        positions[index + skip] === sequenceEnd - 1 &&
+        sequenceEnd < value.length &&
+        classify(value.charCodeAt(sequenceEnd)) === 0 &&
+        !infos.has(sequenceEnd) &&
+        !(sequenceEnd === end - 1 && /[*_]/.test(value.charAt(end)))
+      ) {
+        index += skip
+        continue
+      }
+    }
+    const info = infos.get(position)!
+    // escaping what follows (or precedes) is enough
+    if (
+      (position + 1 < end &&
+        positions[index + 1] === position + 1 &&
+        info & 2 &&
+        infos.get(position + 1) === 0) ||
+      (position - 1 >= offset &&
+        positions[index - 1] === position - 1 &&
+        info & 1 &&
+        infos.get(position - 1) === 0)
+    )
+      continue
+    if (start !== position) result.push(escapeBackslashes(value.slice(start, position), '\\'))
+    start = position + 1
+    const char = value.charAt(position)
+    result.push(
+      ASCII_PUNCTUATION.test(char) && !encode.includes(char)
+        ? '\\' + char
+        : reference(value.charCodeAt(position)),
+    )
+  }
+  result.push(escapeBackslashes(value.slice(start, end), after))
+  return result.join('')
+}
+
+// emphasis, strong and strikethrough: attention whose markers are chosen once the run around them is known
+type Attention = { children: Item[]; sequences: string[] }
+type Item = string | Attention
+type Token = { value: string; attention: Attention | undefined }
+
+const attentionItem = (node: Md): Attention => {
+  const [construct, sequences] =
+    node.type === EMPHASIS
+      ? ['emphasis', EMPHASIS_SEQUENCES]
+      : node.type === STRONG
+        ? ['strong', STRONG_SEQUENCES]
+        : ['strikethrough', DELETE_SEQUENCES]
+  const sequence = sequences[0]!
+  enter(construct)
+  const children = phrasing(node, sequence, sequence)
+  exit()
+  return { children, sequences }
+}
+const EMPHASIS_SEQUENCES = ['_', '*']
+const STRONG_SEQUENCES = ['**', '__']
+const DELETE_SEQUENCES = ['~~', '~']
+const isAttention = (node: Md) =>
+  node.type === EMPHASIS || node.type === STRONG || node.type === DELETE
+
+const encodeEdge = (tokens: Token[], start: boolean) => {
+  const token = tokens[start ? 0 : tokens.length - 1]
+  if (!token || token.attention) return
+  const character = start ? firstCharacter(token.value) : lastCharacter(token.value)
+  const ref = reference(character.codePointAt(0)!)
+  if (start) token.value = ref + token.value.slice(character.length)
+  else {
+    let value = token.value.slice(0, token.value.length - character.length)
+    let escapes = 0
+    while (value.charCodeAt(value.length - 1 - escapes) === 92) escapes++
+    if (escapes % 2) value += '\\'
+    token.value = value + ref
+  }
+}
+
+const encodeInfo = (outside: number, inside: number, marker: string) => {
+  const outsideKind = classify(outside)
+  const insideKind = classify(inside)
+  if (outsideKind === 0)
+    return insideKind === 0 ? (marker === '_' ? BOTH : NEITHER) : insideKind === 1 ? BOTH : OUTSIDE
+  if (outsideKind === 1) return insideKind === 1 ? BOTH : NEITHER
+  return insideKind === 1 ? INSIDE : NEITHER
+}
+const BOTH = { inside: true, outside: true }
+const NEITHER = { inside: false, outside: false }
+const OUTSIDE = { inside: false, outside: true }
+const INSIDE = { inside: true, outside: false }
+
+const render = (
+  items: Item[],
+  chosen: Map,
+  before: string,
+  after: string,
+): Token[] => {
+  const tokens: Token[] = []
+  let encodeAfter: string | undefined
+  let previous = lastCharacter(before)
+  for (let index = 0; index < items.length; index++) {
+    const item = items[index]!
+    if (typeof item === 'string') {
+      const token: Token = { value: item, attention: undefined }
+      if (encodeAfter && encodeAfter === firstCharacter(item)) encodeEdge([token], true)
+      encodeAfter = undefined
+      tokens.push(token)
+      if (token.value) previous = lastCharacter(token.value)
+      continue
+    }
+    const sequence = chosen.get(item) || item.sequences[0]!
+    const marker = sequence.charAt(0)
+    const next = items[index + 1]
+    const outsideBefore = previous
+    const outsideAfter = firstCharacter(
+      next === undefined
+        ? after
+        : typeof next === 'string'
+          ? next
+          : chosen.get(next) || next.sequences[0]!,
+    )
+    const inside = render(item.children, chosen, sequence, sequence)
+    const head = inside.length > 0 ? inside[0]!.value : ''
+    const open = encodeInfo(
+      outsideBefore.charCodeAt(outsideBefore.length - 1),
+      head.charCodeAt(0),
+      marker,
+    )
+    if (open.inside) encodeEdge(inside, true)
+    const tail = inside.length > 0 ? lastCharacter(inside[inside.length - 1]!.value) : ''
+    const close = encodeInfo(outsideAfter.charCodeAt(0), tail.charCodeAt(tail.length - 1), marker)
+    if (close.inside) encodeEdge(inside, false)
+    if (open.outside && outsideBefore !== '\n' && outsideBefore !== '\r') encodeEdge(tokens, false)
+    if (close.outside) encodeAfter = outsideAfter
+    tokens.push({ value: sequence, attention: item }, ...inside, {
+      value: sequence,
+      attention: item,
+    })
+    previous = sequence.charAt(sequence.length - 1)
+  }
+  return tokens
+}
+
+type Run = {
+  tokens: Token[]
+  markers: Token[]
+  start: number
+  end: number
+  open: boolean
+  close: boolean
+  split: boolean
+}
+const STRICT = new Map([
+  ['*', false],
+  ['_', true],
+])
+const check = (tokens: Token[], before: string, after: string) => {
+  const runs: Run[] = []
+  const wrong = new Map()
+  const runOf = new Map()
+  let index = 0
+  while (index < tokens.length) {
+    if (!tokens[index]!.attention) {
+      index++
+      continue
+    }
+    const marker = tokens[index]!.value.charAt(0)
+    const strict = STRICT.get(marker)
+    let end = index + 1
+    while (end < tokens.length && tokens[end]!.attention && tokens[end]!.value.charAt(0) === marker)
+      end++
+    const head = index ? tokens[index - 1]!.value : before
+    const previous = classify(head.charCodeAt(head.length - 1))
+    const next = classify((end < tokens.length ? tokens[end]!.value : after).charCodeAt(0))
+    const open = !next || (next === 2 && Boolean(previous))
+    const close = !previous || (previous === 2 && Boolean(next))
+    const run: Run = {
+      tokens: tokens.slice(index, end),
+      markers: [],
+      start: 0,
+      end: 0,
+      open: strict ? open && (Boolean(previous) || !close) : open,
+      close: strict ? close && (Boolean(next) || !open) : close,
+      split: strict !== undefined,
+    }
+    for (const token of run.tokens) {
+      wrong.set(token, [...run.tokens])
+      runOf.set(token, run)
+      let size = token.value.length
+      while (size--) run.markers.push(token)
+    }
+    run.end = run.markers.length
+    runs.push(run)
+    index = end
+  }
+  pair(runs, wrong)
+  for (index = 0; index < tokens.length; index++) {
+    const involved = wrong.get(tokens[index]!)
+    if (involved) return { attention: candidates(tokens, involved, runOf), index }
+  }
+  return undefined
+}
+
+const candidates = (tokens: Token[], involved: Token[], runOf: Map) => {
+  const related = new Set()
+  for (const token of tokens) {
+    const siblings = runOf.get(token)
+    if (siblings && token.attention && involved.some((d) => d.attention === token.attention))
+      for (const sibling of siblings.tokens) related.add(sibling.attention!)
+  }
+  const ordered: Attention[] = []
+  for (const token of tokens)
+    if (token.attention && related.delete(token.attention)) ordered.push(token.attention)
+  ordered.reverse()
+  return ordered
+}
+
+const pair = (runs: Run[], wrong: Map) => {
+  const openersByMarker = new Map()
+  for (const closer of runs) {
+    const marker = closer.tokens[0]!.value.charAt(0)
+    let openers = openersByMarker.get(marker)
+    if (!openers) openersByMarker.set(marker, (openers = []))
+    let open = closer.close ? openers.length : 0
+    while (open-- && closer.start < closer.end) {
+      const opener = openers[open]!
+      const openerSize = opener.end - opener.start
+      const closerSize = closer.end - closer.start
+      if (
+        closer.split
+          ? (opener.close || closer.open) && closerSize % 3 && !((openerSize + closerSize) % 3)
+          : openerSize !== opener.markers.length || openerSize !== closerSize
+      )
+        continue
+      const size = closer.split ? (openerSize > 1 && closerSize > 1 ? 2 : 1) : closerSize
+      const opening = opener.markers.slice(opener.end - size, opener.end)
+      const closing = closer.markers.slice(closer.start, closer.start + size)
+      const openToken = opening[0]!
+      const closeToken = closing[0]!
+      if (
+        openToken === opening[size - 1] &&
+        openToken.value.length === size &&
+        closeToken === closing[size - 1] &&
+        closeToken.value.length === size &&
+        openToken.attention === closeToken.attention
+      ) {
+        wrong.delete(openToken)
+        wrong.delete(closeToken)
+      } else {
+        const involved = [...new Set([...opening, ...closing])]
+        for (const token of involved) {
+          const list = wrong.get(token)
+          if (list) list.push(...involved)
+        }
+      }
+      opener.end -= size
+      closer.start += size
+      if (opener.start === opener.end) openers.splice(open, 1)
+      open = openers.length
+    }
+    if (closer.open && closer.start < closer.end) openers.push(closer)
+  }
+}
+
+const improve = (
+  items: Item[],
+  chosen: Map,
+  mistake: { attention: Attention[]; index: number },
+  before: string,
+  after: string,
+) => {
+  for (const attention of mistake.attention) {
+    const current = chosen.get(attention) || attention.sequences[0]
+    for (const sequence of attention.sequences) {
+      if (sequence === current) continue
+      const trial = new Map(chosen)
+      trial.set(attention, sequence)
+      const tokens = render(items, trial, before, after)
+      const next = check(tokens, before, after)
+      if (!next || next.index > mistake.index) return { chosen: trial, mistake: next, tokens }
+    }
+  }
+  return undefined
+}
+
+const serialize = (items: Item[], before: string, after: string) => {
+  let plain = true
+  for (const item of items)
+    if (typeof item !== 'string') {
+      plain = false
+      break
+    }
+  if (plain) return items.join('')
+  let chosen = new Map()
+  const initial = render(items, chosen, before, after)
+  let tokens = initial
+  let mistake = check(tokens, before, after)
+  while (mistake) {
+    const next = improve(items, chosen, mistake, before, after)
+    if (!next) {
+      tokens = initial
+      break
+    }
+    chosen = next.chosen
+    tokens = next.tokens
+    mistake = next.mistake
+  }
+  let result = ''
+  for (const token of tokens) result += token.value
+  return result
+}
+
+// the first character a node writes, for the text before it
+const peek = (node: Md, parent: Md): string => {
+  switch (node.type) {
+    case EMPHASIS:
+      return '_'
+    case STRONG:
+      return '*'
+    case DELETE:
+      return '~'
+    case LINK:
+      return autolinked(node) ? '<' : '['
+    case IMAGE:
+      return '!'
+    case INLINE_CODE:
+      return '`'
+    case HTML:
+      return '<'
+    case TEXT: {
+      // a text's first character is written as it is unless a pattern can escape it there: only its own character
+      // and the one after it can say
+      const value = node.value
+      const head = value.charCodeAt(0)
+      if (
+        value !== '' &&
+        !scopeOf(mask).special.test(value.charAt(0)) &&
+        !((head === 32 || head === 9) && isNewline(value.charCodeAt(1)))
+      )
+        return firstCharacter(value)
+      return firstCharacter(handle(node, parent, '', ''))
+    }
+    default:
+      return firstCharacter(handle(node, parent, '', ''))
+  }
+}
+
+const phrasing = (parent: Md, before: string, after: string): Item[] => {
+  const kids = parent.kids
+  const results: Item[] = []
+  indexStack.push(-1)
+  for (let index = 0; index < kids.length; index++) {
+    const child = kids[index]!
+    indexStack[indexStack.length - 1] = index
+    const next = index + 1 < kids.length ? firstCharacter(peek(kids[index + 1]!, parent)) : after
+    if (isAttention(child)) {
+      const item = attentionItem(child)
+      results.push(item)
+      before = lastCharacter(item.sequences[0]!)
+    } else {
+      const value = handle(child, parent, before, next)
+      if (!value) continue
+      results.push(value)
+      // what a link, an image or inline code ends with is known, without reading what was written
+      before =
+        child.type === LINK
+          ? autolinked(child)
+            ? '>'
+            : ')'
+          : child.type === IMAGE
+            ? ')'
+            : child.type === INLINE_CODE
+              ? '`'
+              : lastCharacter(value)
+    }
+  }
+  indexStack.pop()
+  return results
+}
+const containerPhrasing = (parent: Md, before: string, after: string) =>
+  serialize(phrasing(parent, before, after), before, after)
+
+const containerFlow = (parent: Md): string => {
+  const kids = parent.kids
+  let result = ''
+  indexStack.push(-1)
+  for (let index = 0; index < kids.length; index++) {
+    const child = kids[index]!
+    indexStack[indexStack.length - 1] = index
+    result += handle(child, parent, '\n', '\n')
+    if (child.type !== LIST) bulletLastUsed = undefined
+    if (index < kids.length - 1) result += between(child, kids[index + 1]!, parent)
+  }
+  indexStack.pop()
+  return result
+}
+
+// the blank line between two blocks, or a single line ending in a tight list
+const between = (left: Md, right: Md, parent: Md) => {
+  if (parent.type !== LIST && parent.type !== LIST_ITEM) return '\n\n'
+  if (parent.spread) return '\n\n'
+  if (left.type === HTML) {
+    const kind = htmlKind(left.value)
+    if (kind === undefined || kind === 6 || kind === 7) return '\n\n'
+  }
+  if (left.type === BLOCKQUOTE && right.type === BLOCKQUOTE) return '\n\n'
+  if (
+    left.type === PARAGRAPH &&
+    right.type === LIST &&
+    ((right.ordered && right.depth !== 1) ||
+      (right.kids.length > 0 && right.kids[0]!.kids.length === 0))
+  )
+    return '\n\n'
+  if (left.type === PARAGRAPH && right.type === THEMATIC_BREAK) return '\n\n'
+  let tail = left
+  while (
+    (tail.type === BLOCKQUOTE || tail.type === LIST || tail.type === LIST_ITEM) &&
+    tail.kids.length > 0
+  )
+    tail = tail.kids[tail.kids.length - 1]!
+  if (tail.type !== PARAGRAPH) return '\n'
+  if (right.type === HTML) {
+    const kind = htmlKind(right.value)
+    if (kind === undefined || kind === 7) return '\n\n'
+  }
+  if (
+    (left.type === PARAGRAPH || left !== tail) &&
+    ((right.type === HEADING && setext(right)) || right.type === PARAGRAPH)
+  )
+    return '\n\n'
+  return '\n'
+}
+
+// micromark's html block kinds, as far as what the emitter writes needs:  and  are kind 7
+const htmlKind = (value: string): number | undefined => {
+  if (value.charCodeAt(0) !== 60) return undefined
+  const closing = value.charCodeAt(1) === 47
+  const name = /^[a-z][a-z0-9-]*/i.exec(value.slice(closing ? 2 : 1))?.[0]?.toLowerCase()
+  if (!name) return undefined
+  return HTML_BLOCK_NAMES.has(name) ? 6 : 7
+}
+const HTML_BLOCK_NAMES = new Set(
+  'address article aside base basefont blockquote body caption center col colgroup dd details dialog dir div dl dt fieldset figcaption figure footer form frame frameset h1 h2 h3 h4 h5 h6 head header hr html iframe legend li link main menu menuitem nav noframes ol optgroup option p param search section summary table tbody td tfoot th thead title tr track ul'.split(
+    ' ',
+  ),
+)
+
+// a node's text, as mdast-util-to-string reads it (image alts too)
+const toText = (node: Md): string => {
+  if (node.type === TEXT || node.type === INLINE_CODE || node.type === HTML || node.type === CODE)
+    return node.value
+  if (node.type === IMAGE) return node.value
+  let text = ''
+  for (const kid of node.kids) text += toText(kid)
+  return text
+}
+
+const hasBreak = (node: Md): boolean => {
+  for (const kid of node.kids) {
+    if (kid.type === BREAK) return true
+    if (
+      (kid.type === TEXT || kid.type === INLINE_CODE || kid.type === HTML) &&
+      /[\r\n]/.test(kid.value)
+    )
+      return true
+    if (hasBreak(kid)) return true
+  }
+  return false
+}
+// a heading written setext style: an h1 or h2 that holds a line break
+export const setext = (node: Md) => node.depth < 3 && toText(node) !== '' && hasBreak(node)
+
+// a link written : its text is its url. worked out once, kept in its depth (1 no, 2 yes)
+const autolinked = (node: Md) => {
+  if (node.depth === 0) node.depth = isAutolink(node) ? 2 : 1
+  return node.depth === 2
+}
+const isAutolink = (node: Md) => {
+  if (node.title || !node.url || node.kids.length !== 1 || node.kids[0]!.type !== TEXT) return false
+  const raw = node.kids[0]!.value
+  return (
+    (raw === node.url || 'mailto:' + raw === node.url) &&
+    /^[a-z][+\-.a-z]+:/i.test(node.url) &&
+    !/[\0- <>\u007F]/.test(node.url)
+  )
+}
+
+const indentLines = (
+  value: string,
+  map: (line: string, index: number, blank: boolean) => string,
+) => {
+  const eol = /\r?\n|\r/g
+  let result = ''
+  let start = 0
+  let line = 0
+  let match
+  while ((match = eol.exec(value))) {
+    const text = value.slice(start, match.index)
+    result += map(text, line, !text) + match[0]
+    start = match.index + match[0].length
+    line++
+  }
+  const text = value.slice(start)
+  return result + map(text, line, !text)
+}
+
+const ENCLOSE = /[\0- \u007F]/
+
+const handle = (node: Md, parent: Md | undefined, before: string, after: string): string => {
+  switch (node.type) {
+    case TEXT:
+      return safe(node.value, before, after)
+    case PARAGRAPH: {
+      enter('paragraph')
+      enter('phrasing')
+      const value = containerPhrasing(node, before, after)
+      exit()
+      exit()
+      return value
+    }
+    case HEADING:
+      return heading(node)
+    case ROOT: {
+      if (!node.kids.some(isPhrasing)) return containerFlow(node)
+      enter('phrasing')
+      const value = containerPhrasing(node, before, after)
+      exit()
+      return value
+    }
+    case THEMATIC_BREAK:
+      return '---'
+    case BLOCKQUOTE: {
+      enter('blockquote')
+      const value = indentLines(containerFlow(node), (line, _, blank) =>
+        blank ? '>' + line : '> ' + line,
+      )
+      exit()
+      return value
+    }
+    case LIST:
+      return list(node, parent)
+    case LIST_ITEM:
+      return listItem(node, parent)
+    case CODE:
+      return code(node)
+    case TABLE:
+      return table(node)
+    case TABLE_ROW: {
+      enter('table')
+      const row = rowData(node)
+      exit()
+      const value = markdownTable([row], node.align ?? [])
+      return value.slice(0, value.indexOf('\n'))
+    }
+    case TABLE_CELL:
+      return cell(node)
+    case HTML:
+      return node.value
+    case EMPHASIS:
+    case STRONG:
+    case DELETE: {
+      // outside phrasing (a peek, say): attention on its own
+      enter('phrasing')
+      const value = serialize([attentionItem(node)], before, after)
+      exit()
+      return value
+    }
+    case INLINE_CODE:
+      return inlineCode(node)
+    case BREAK:
+      return scopeOf(mask).bareNewline ? (/[\t ]/.test(before) ? '' : ' ') : '\\\n'
+    case LINK:
+      return link(node, before)
+    case IMAGE:
+      return image(node)
+  }
+  return ''
+}
+
+const heading = (node: Md) => {
+  const rank = Math.max(Math.min(6, node.depth || 1), 1)
+  if (setext(node)) {
+    enter('headingSetext')
+    enter('phrasing')
+    const value = containerPhrasing(node, '\n', '\n')
+    exit()
+    exit()
+    return (
+      value +
+      '\n' +
+      (rank === 1 ? '=' : '-').repeat(
+        value.length - (Math.max(value.lastIndexOf('\r'), value.lastIndexOf('\n')) + 1),
+      )
+    )
+  }
+  const sequence = '#'.repeat(rank)
+  enter('headingAtx')
+  enter('phrasing')
+  let value = containerPhrasing(node, '# ', '\n')
+  const head = value.charCodeAt(0)
+  if (head === 9 || head === 32) value = reference(head) + value.slice(1)
+  value = value ? sequence + ' ' + value : sequence
+  exit()
+  exit()
+  return value
+}
+
+const list = (node: Md, parent: Md | undefined) => {
+  enter('list')
+  const saved = bulletCurrent
+  let bullet = node.ordered ? '.' : '-'
+  const other = node.ordered ? ')' : '*'
+  let different = parent && bulletLastUsed ? bullet === bulletLastUsed : false
+  if (!node.ordered) {
+    const first = node.kids[0]
+    const n = stack.length
+    const at = indexStack.length
+    if (
+      first &&
+      !first.kids[0] &&
+      stack[n - 1] === 'list' &&
+      stack[n - 2] === 'listItem' &&
+      stack[n - 3] === 'list' &&
+      stack[n - 4] === 'listItem' &&
+      indexStack[at - 1] === 0 &&
+      indexStack[at - 2] === 0 &&
+      indexStack[at - 3] === 0
+    )
+      different = true
+    // the rule is - too, so an item that starts with a rule needs the other bullet
+    if (first)
+      for (const item of node.kids)
+        if (item.type === LIST_ITEM && item.kids[0]?.type === THEMATIC_BREAK) {
+          different = true
+          break
+        }
+  }
+  if (different) bullet = other
+  bulletCurrent = bullet
+  const value = containerFlow(node)
+  bulletLastUsed = bullet
+  bulletCurrent = saved
+  exit()
+  return value
+}
+
+const listItem = (node: Md, parent: Md | undefined) => {
+  let bullet = bulletCurrent || '-'
+  if (parent && parent.type === LIST && parent.ordered)
+    bullet = (parent.depth > -1 ? parent.depth : 1) + parent.kids.indexOf(node) + bullet
+  const size = bullet.length + 1
+  enter('listItem')
+  const pad = ' '.repeat(size)
+  let value = indentLines(containerFlow(node), (line, index, blank) =>
+    index ? (blank ? '' : pad) + line : (blank ? bullet : bullet + ' ') + line,
+  )
+  exit()
+  // a task list item
+  if (typeof node.checked === 'boolean' && node.kids[0]?.type === PARAGRAPH)
+    value = value.replace(
+      /^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,
+      (whole) => whole + (node.checked ? '[x] ' : '[ ] '),
+    )
+  return value
+}
+
+const longestStreak = (value: string, substring: string) => {
+  let index = value.indexOf(substring)
+  let expected = index
+  let count = 0
+  let max = 0
+  while (index !== -1) {
+    if (index === expected) {
+      if (++count > max) max = count
+    } else count = 1
+    expected = index + substring.length
+    index = value.indexOf(substring, expected)
+  }
+  return max
+}
+
+const code = (node: Md) => {
+  const raw = node.value
+  const sequence = '`'.repeat(Math.max(longestStreak(raw, '`') + 1, 3))
+  enter('codeFenced')
+  let value = sequence
+  if (node.lang) {
+    enter('codeFencedLangGraveAccent')
+    value += safe(node.lang, value, ' ', '`')
+    exit()
+  }
+  if (node.lang && node.meta) {
+    enter('codeFencedMetaGraveAccent')
+    value += ' '
+    value += safe(node.meta, value, '\n', '`')
+    exit()
+  }
+  value += '\n'
+  if (raw) value += raw + '\n'
+  value += sequence
+  exit()
+  return value
+}
+
+const inlineCode = (node: Md) => {
+  let value = node.value
+  let sequence = '`'
+  if (value.indexOf('`') >= 0)
+    while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) sequence += '`'
+  if (
+    /[^\n\r ]/.test(value) &&
+    ((/^[\n\r ]/.test(value) && /[\n\r ]$/.test(value)) || /^`|`$/.test(value))
+  )
+    value = ' ' + value + ' '
+  // a line ending that would start a construct is a space instead
+  if (/[\r\n]/.test(value))
+    for (const pattern of PATTERNS) {
+      if (!UNSAFE[PATTERNS.indexOf(pattern)]!.atBreak) continue
+      const expression = pattern.regex
+      expression.lastIndex = 0
+      let match
+      while ((match = expression.exec(value))) {
+        let position = match.index
+        if (value.charCodeAt(position) === 10 && value.charCodeAt(position - 1) === 13) position--
+        value = value.slice(0, position) + ' ' + value.slice(match.index + 1)
+      }
+    }
+  value = sequence + value + sequence
+  // in a table, a pipe would end the cell
+  if ((mask & TABLE_CELL_BIT) !== 0) value = value.replace(/\|/g, '\\$&')
+  return value
+}
+
+const destination = (url: string, value: string, title: string | undefined, enclose: boolean) => {
+  if ((!url && typeof title === 'string') || enclose) {
+    enter('destinationLiteral')
+    const out = '<' + safe(url, value + '<', '>') + '>'
+    exit()
+    return out
+  }
+  enter('destinationRaw')
+  const out = safe(url, value, typeof title === 'string' ? ' ' : ')')
+  exit()
+  return out
+}
+const titled = (title: string | undefined, value: string) => {
+  if (typeof title !== 'string') return ''
+  enter('titleQuote')
+  const out = ' "' + safe(title, value + ' "', '"') + '"'
+  exit()
+  return out
+}
+
+const link = (node: Md, before: string) => {
+  if (autolinked(node)) {
+    const savedStack = stack
+    const savedMask = mask
+    stack = stack.filter((name) => name !== 'phrasing')
+    mask &= ~PHRASING
+    enter('autolink')
+    const value = '<' + containerPhrasing(node, '<', '>') + '>'
+    exit()
+    stack = savedStack
+    mask = savedMask
+    return value
+  }
+  enter('link')
+  enter('label')
+  const text = containerPhrasing(node, '[', '](')
+  exit()
+  let value = '[' + text + ']('
+  const enclose = ENCLOSE.test(node.url)
+  const last = before.charAt(before.length - 1)
+  let title = node.title || undefined
+  // text that reads as a definition ([x]: …) at the start of a line gets an empty title, so it isn't one
+  if (!title && !enclose && (last === '\n' || last === '\r')) {
+    let index = 0
+    while (index < text.length && text.charCodeAt(index) !== 93)
+      index += text.charCodeAt(index) === 92 ? 2 : 1
+    if (text.charCodeAt(index + 1) === 58) title = ''
+  }
+  value += destination(node.url, value, title, enclose)
+  value += titled(title, value)
+  value += ')'
+  exit()
+  return value
+}
+
+const image = (node: Md) => {
+  enter('image')
+  enter('label')
+  let value = '![' + safe(node.value, '![', ']') + ']('
+  exit()
+  const title = node.title || undefined
+  if ((!node.url && title) || ENCLOSE.test(node.url)) {
+    enter('destinationLiteral')
+    value += '<' + safe(node.url, value + '<', '>') + '>'
+    exit()
+  } else {
+    enter('destinationRaw')
+    value += safe(node.url, value, title ? ' ' : ')')
+    exit()
+  }
+  value += titled(title, value)
+  value += ')'
+  exit()
+  return value
+}
+
+const cell = (node: Md) => {
+  enter('tableCell')
+  enter('phrasing')
+  const value = containerPhrasing(node, '|', '|')
+  exit()
+  exit()
+  return value
+}
+const rowData = (row: Md) => {
+  enter('tableRow')
+  const cells: string[] = []
+  for (const kid of row.kids) cells.push(cell(kid))
+  exit()
+  return cells
+}
+const table = (node: Md) => {
+  enter('table')
+  const matrix: string[][] = []
+  for (const row of node.kids) matrix.push(rowData(row))
+  exit()
+  return markdownTable(matrix, node.align ?? [])
+}
+
+// markdown-table (MIT, Titus Wormer) as gfm configures it: padded cells, delimiters aligned
+const markdownTable = (matrix: string[][], align: (string | null)[]) => {
+  const longest: number[] = []
+  let most = 0
+  for (const row of matrix) {
+    if (row.length > most) most = row.length
+    for (let column = 0; column < row.length; column++) {
+      const size = row[column]!.length
+      if (longest[column] === undefined || size > longest[column]!) longest[column] = size
+    }
+  }
+  const alignments: number[] = []
+  for (let column = 0; column < most; column++) {
+    const value = align[column]
+    const kind = typeof value === 'string' ? value.codePointAt(0) : 0
+    alignments[column] =
+      kind === 67 || kind === 99
+        ? 99
+        : kind === 76 || kind === 108
+          ? 108
+          : kind === 82 || kind === 114
+            ? 114
+            : 0
+  }
+  const delimiters: string[] = []
+  const delimiterSizes: number[] = []
+  for (let column = 0; column < most; column++) {
+    const kind = alignments[column]
+    const before = kind === 99 || kind === 108 ? ':' : ''
+    const after = kind === 99 || kind === 114 ? ':' : ''
+    let size = Math.max(1, longest[column]! - before.length - after.length)
+    const value = before + '-'.repeat(size) + after
+    size = before.length + size + after.length
+    if (size > longest[column]!) longest[column] = size
+    delimiterSizes[column] = size
+    delimiters[column] = value
+  }
+  const rows = matrix.length ? [matrix[0]!, delimiters, ...matrix.slice(1)] : [delimiters]
+  const lines: string[] = []
+  for (let index = 0; index < rows.length; index++) {
+    const row = rows[index]!
+    let line = ''
+    for (let column = 0; column < most; column++) {
+      const value = row[column] ?? ''
+      const own = index === 1 ? delimiterSizes[column]! : value.length
+      const size = longest[column]! - own
+      const kind = alignments[column]
+      let before = ''
+      let after = ''
+      if (kind === 114) before = ' '.repeat(size)
+      else if (kind === 99) {
+        if (size % 2) {
+          before = ' '.repeat(size / 2 + 0.5)
+          after = ' '.repeat(size / 2 - 0.5)
+        } else before = after = ' '.repeat(size / 2)
+      } else after = ' '.repeat(size)
+      if (!column) line += '|'
+      line += ' ' + before + value + after + ' |'
+    }
+    lines.push(line)
+  }
+  return lines.join('\n')
+}
+
+// the markdown for a root, as toMarkdown writes it
+export const toMarkdown = (root: Md): string => {
+  stack = []
+  masks = []
+  mask = 0
+  indexStack = []
+  bulletCurrent = undefined
+  bulletLastUsed = undefined
+  let result = handle(root, undefined, '\n', '\n')
+  const last = result.charCodeAt(result.length - 1)
+  if (result && last !== 10 && last !== 13) result += '\n'
+  return result
+}
+
+// a heading's text as a reader sees it (headingOf in @affordances/md): what it says, without images or a url shown as
+// itself, nor the brackets right around one
+export const headingText = (node: Md): string | undefined => {
+  const pieces: (string | null)[] = []
+  const walk = (parent: Md) => {
+    for (const kid of parent.kids) {
+      if (kid.type === TEXT || kid.type === INLINE_CODE || kid.type === HTML) pieces.push(kid.value)
+      else if (kid.type === BREAK) pieces.push(' ')
+      else if (kid.type === IMAGE) continue
+      else if (kid.type === LINK && autolinked(kid)) pieces.push(null)
+      else walk(kid)
+    }
+  }
+  walk(node)
+  pieces.forEach((piece, n) => {
+    if (piece !== null) return
+    const before = pieces[n - 1]
+    const after = pieces[n + 1]
+    const open = typeof before === 'string' ? /[([<]\s*$/.exec(before)?.[0] : undefined
+    const close = typeof after === 'string' ? /^\s*([)\]>])/.exec(after) : undefined
+    if (open && close && close[1] === BRACKETS[open.trim()]) {
+      pieces[n - 1] = before!.slice(0, -open.length)
+      pieces[n + 1] = after!.slice(close[0].length)
+    }
+  })
+  return pieces.join('').replace(/\s+/g, ' ').trim() || undefined
+}
+const BRACKETS: Record = { '(': ')', '[': ']', '<': '>' }
diff --git a/packages/md-core/src/emit-prune.ts b/packages/md-core/src/emit-prune.ts
new file mode 100644
index 0000000..31d80d4
--- /dev/null
+++ b/packages/md-core/src/emit-prune.ts
@@ -0,0 +1,670 @@
+import { decode } from './entities.ts'
+import type { Element, Node } from './types.ts'
+
+// what @affordances/md's prune and extract leave of the page, read lazily: kidsOf(el) is an element's children as
+// prune leaves them (hidden things gone, empty links named or gone, inline boxes spaced, repeated links once), cached
+// on the element for the emit call that asked. nothing is copied unless it changes
+
+// the cache, on the element itself: the pruned children and the emit call they're for
+// pk, pe: the pruned children and the emit call they're for; lv, le: whether it's code, and for which call; pf: the
+// attribute names it has that anything here reads (-1 before they're read)
+type Pruned = Element & {
+  pk?: Node[] | undefined
+  pe?: number
+  lv?: boolean
+  le?: number
+  pf?: number
+}
+// the cache's fields, added at once and in one order, so every element the parser made has one shape after
+const touch = (el: Pruned) => {
+  if (el.pe === undefined) {
+    el.pk = undefined
+    el.pe = -1
+    el.lv = false
+    el.le = -1
+    el.pf = -1
+  }
+}
+let epoch = 0
+// chrome (nav, header, footer, …) is stripped too: the page has no 
+let stripChrome = false +export const begin = (strip: boolean) => { + epoch++ + stripChrome = strip + byId = undefined +} +let page: Element | undefined +export const setPage = (root: Element) => { + page = root + byId = undefined +} + +// an element prune made, already pruned +export const made = (from: Element, kids: Node[], tag = from.tag): Element => { + const el: Pruned = { + tag, + attrs: from.attrs, + kids, + up: from.up, + map: from.map, + pk: kids, + pe: epoch, + lv: false, + le: -1, + pf: (from as Pruned).pf ?? -1, + } + return el +} + +const CHROME_TAGS = new Set(['nav', 'header', 'footer', 'aside', 'dialog']) +const CHROME_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary']) + +// the attribute names an element has, of those read here: one scan of its attributes, ever. most elements have +// none of them, and the scan is far cheaper than parsing every element's attributes +const HIDDEN = 1 +const ARIA_HIDDEN = 2 +const STYLE = 4 +const ROLE = 8 +const EDITABLE = 16 +const MARKED = 32 +export const MDAST = 64 +export const DATA_TITLE = 128 +export const NOWRAP = 256 +export const TITLE = 512 +export const SPAN = 1024 +export const ALIGN = 2048 +const PRUNES = HIDDEN | ARIA_HIDDEN | STYLE | ROLE | EDITABLE | MARKED +const space = (code: number) => + code === 32 || code === 9 || code === 10 || code === 12 || code === 13 +// whether the name at start is this word: compared by hand, first character first (most names aren't ours) +const is = (s: string, start: number, word: string) => { + for (let k = 0; k < word.length; k++) + if (s.charCodeAt(start + k) !== word.charCodeAt(k)) return false + return true +} +const named = (s: string, start: number, length: number) => { + const head = s.charCodeAt(start) + switch (length) { + case 4: + return head === 114 && is(s, start, 'role') ? ROLE : 0 + case 5: + return head === 115 && is(s, start, 'style') + ? STYLE + : head === 116 && is(s, start, 'title') + ? TITLE + : head === 97 && is(s, start, 'align') + ? ALIGN + : 0 + case 7: + return (head === 114 && is(s, start, 'rowspan')) || (head === 99 && is(s, start, 'colspan')) + ? SPAN + : 0 + case 6: + return head === 104 && is(s, start, 'hidden') + ? HIDDEN + : head === 110 && is(s, start, 'nowrap') + ? NOWRAP + : 0 + case 9: + return head === 100 && is(s, start, 'data-mode') ? MARKED : 0 + case 10: + return head !== 100 + ? 0 + : is(s, start, 'data-mdast') + ? MDAST + : is(s, start, 'data-title') + ? DATA_TITLE + : 0 + case 11: + return head === 97 && is(s, start, 'aria-hidden') ? ARIA_HIDDEN : 0 + case 15: + return head === 99 && is(s, start, 'contenteditable') ? EDITABLE : 0 + case 19: + return head === 100 && is(s, start, 'data-affordances-md') ? MARKED : 0 + } + return 0 +} +// the attribute names, as the tokenizer reads them, jumping over quoted values (most of the string); names as +// written in lowercase, as pages write them +const scan = (s: string) => { + const n = s.length + let found = 0 + let i = 0 + while (i < n) { + let c = s.charCodeAt(i) + while (space(c) || c === 47) c = s.charCodeAt(++i) + if (i >= n) break + const start = i + if (c === 61) i++ + while (i < n) { + c = s.charCodeAt(i) + if (space(c) || c === 47 || c === 61) break + i++ + } + found |= named(s, start, i - start) + while (space(c)) c = s.charCodeAt(++i) + if (c === 61) { + c = s.charCodeAt(++i) + while (space(c)) c = s.charCodeAt(++i) + if (c === 34 || c === 39) { + const end = s.indexOf(c === 34 ? '"' : "'", i + 1) + i = end < 0 ? n : end + 1 + } else while (i < n && !space(s.charCodeAt(i))) i++ + } + } + return found +} +// one attribute's value, as read() reads it (decoded; '' without a value; the first of a repeated name), without +// parsing the rest: a scan to its name. names as written in lowercase, as with the scan above +export const read = (el: Element, name: string): string | undefined => { + if (el.map !== undefined) return el.map.get(name) + const s = el.attrs + const n = s.length + let i = 0 + while (i < n) { + let c = s.charCodeAt(i) + while (space(c) || c === 47) c = s.charCodeAt(++i) + if (i >= n) break + const start = i + if (c === 61) i++ + while (i < n) { + c = s.charCodeAt(i) + if (space(c) || c === 47 || c === 61) break + i++ + } + const match = i - start === name.length && is(s, start, name) + while (space(c)) c = s.charCodeAt(++i) + let value = '' + if (c === 61) { + c = s.charCodeAt(++i) + while (space(c)) c = s.charCodeAt(++i) + if (c === 34 || c === 39) { + const end = s.indexOf(c === 34 ? '"' : "'", i + 1) + if (match) value = s.slice(i + 1, end < 0 ? n : end) + i = end < 0 ? n : end + 1 + } else { + const from = i + while (i < n && !space(s.charCodeAt(i))) i++ + if (match) value = s.slice(from, i) + } + } + if (match) return decode(value, true) + } + return undefined +} +export const flags = (el: Element): number => { + if (el.attrs === '') return 0 + const cached = el as Pruned + touch(cached) + if (cached.pf! < 0) cached.pf = scan(el.attrs) + return cached.pf! +} +const mentions = (el: Element) => (flags(el) & PRUNES) !== 0 +const marked = (el: Element) => + el.tag === 'affordances-md' ? read(el, 'data-mode') : read(el, 'data-affordances-md') +const unhidden = (el: Element) => { + const mode = flags(el) & MARKED ? marked(el) : undefined + return mode === 'only' || mode === 'show' +} + +// a style attribute's declarations as [property, value], lowercased, without !important +const codePoint = (hex: string) => { + const code = Number.parseInt(hex, 16) + return code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff) + ? '\ufffd' + : String.fromCodePoint(code) +} +const cssText = (style: string) => + style + .replace(/\/\*[\s\S]*?(\*\/|$)/g, '') + .replace(/\\([0-9a-f]{1,6})[ \t\n\r\f]?|\\([^\n0-9a-f])/gi, (_, hex: string, char: string) => + hex ? codePoint(hex) : char, + ) +type Declarations = [property: string, value: string][] +const declarations = (style: string): Declarations => + cssText(style) + .split(';') + .map((declaration) => { + const [property = '', value = ''] = declaration + .split(':') + .map((part) => part.trim().toLowerCase()) + return [property, value.replace(/\s*!\s*important$/, '')] + }) +// display: none, visibility: hidden or content-visibility: hidden, however it's written; a style that can't say +// any of it (no such keyword, no escape, no comment) isn't parsed +const HIDING = /none|hidden|collapse|[\\/]/i +const styleHidden = (style: string | undefined) => + style !== undefined && + HIDING.test(style) && + declarations(style).some( + ([property, keyword]) => + (property === 'display' && keyword === 'none') || + (property === 'visibility' && (keyword === 'hidden' || keyword === 'collapse')) || + (property === 'content-visibility' && keyword === 'hidden'), + ) +// whether a style's display is one of these +const DISPLAY = /display|[\\/]/i +const styleDisplays = (style: string | undefined, display: RegExp) => + style !== undefined && + DISPLAY.test(style) && + declarations(style).some(([property, value]) => property === 'display' && display.test(value)) +export const role = (el: Element) => read(el, 'role') ?? '' +const editor = (el: Element) => { + const r = role(el) + if (r === 'textbox' || r === 'searchbox') return true + const editable = read(el, 'contenteditable') + return editable !== undefined && editable !== 'false' +} + +// what prune leaves out, with everything in it: what's hidden from people (unless marked for agents), what's marked +// skip, and editors, whose text is what someone typed +const dropped = (el: Element): boolean => { + const found = flags(el) + if ((found & PRUNES) === 0) return false + const mode = found & MARKED ? marked(el) : undefined + if (mode === 'skip') return true + if (found & (ROLE | EDITABLE) && editor(el)) return true + if (mode === 'only' || mode === 'show') return false + return ( + (found & HIDDEN) !== 0 || + ((found & ARIA_HIDDEN) !== 0 && read(el, 'aria-hidden') === 'true') || + ((found & STYLE) !== 0 && styleHidden(read(el, 'style'))) + ) +} +const chrome = (el: Element) => { + const maybe = mentions(el) + return ( + (CHROME_TAGS.has(el.tag) || (maybe && CHROME_ROLES.has(role(el)))) && !(maybe && unhidden(el)) + ) +} + +// whether prune drops an element or what holds it +const hiddenAbove = (el: Element) => { + for (let at: Element | null = el; at; at = at.up) if (dropped(at)) return true + return false +} +// the page's
: the outermost, a real
before a role=main, among what prune keeps. the walk reads tags +// alone, and asks whether a landmark it finds is hidden only then +export const findMain = (root: Element): Element | undefined => { + let byRole: Element | undefined + const walk = (parent: Element): Element | undefined => { + for (const kid of parent.kids) { + if (typeof kid === 'string') continue + if (kid.tag === 'main') { + if (!hiddenAbove(kid)) return kid + continue + } + if ( + kid.attrs !== '' && + kid.attrs.indexOf('main') >= 0 && + flags(kid) & ROLE && + role(kid) === 'main' + ) { + if (!hiddenAbove(kid)) byRole ??= kid + continue + } + const found = walk(kid) + if (found) return found + } + return undefined + } + return walk(root) ?? byRole +} + +// the page's ids, among what prune keeps, once a link's label needs them +let byId: Map | undefined +const ids = () => { + if (byId) return byId + byId = new Map() + const walk = (parent: Element) => { + for (const kid of parent.kids) { + if (typeof kid === 'string' || dropped(kid)) continue + const id = read(kid, 'id') + if (id !== undefined && !byId!.has(id)) byId!.set(id, kid) + walk(kid) + } + } + if (page) walk(page) + return byId +} + +const ASCII_SPACE = /[\t\n\f\r ]+/ +export const classes = (el: Element): string[] => { + const value = read(el, 'class') + return value ? value.split(ASCII_SPACE).filter(Boolean) : [] +} + +// an element's text, as hast-util-to-string reads it: every text in it, as written +export const toString = (node: Node): string => { + if (typeof node === 'string') return node + let text = '' + for (const kid of kidsOf(node)) text += typeof kid === 'string' ? kid : toString(kid) + return text +} +export const text = (node: Node | undefined) => + node === undefined ? '' : toString(node).replace(/\s+/g, ' ').trim() + +const VALUED = new Set([ + 'input', + 'select', + 'option', + 'optgroup', + 'textarea', + 'datalist', + 'output', + 'meter', + 'progress', +]) +const VALUE_ROLES = new Set(['spinbutton', 'slider']) +// a control whose text is a value, not a name +const valueBearing = (el: Element) => + VALUED.has(el.tag) || (mentions(el) && (VALUE_ROLES.has(role(el)) || editor(el))) + +// children without the descendants drop picks, at any depth; the same array when nothing goes +const without = (kids: Node[], drop: (el: Element) => boolean): Node[] => { + let out: Node[] | undefined + for (let i = 0; i < kids.length; i++) { + const kid = kids[i]! + if (typeof kid === 'string') { + out?.push(kid) + continue + } + if (drop(kid)) { + out ??= kids.slice(0, i) + continue + } + const inner = kidsOf(kid) + const kept = without(inner, drop) + if (kept !== inner) { + out ??= kids.slice(0, i) + out.push(made(kid, kept)) + } else out?.push(kid) + } + return out ?? kids +} +// children with elements of one tag replaced by what's in them, at any depth +const unwrap = (kids: Node[], tag: string): Node[] => + kids.flatMap((kid): Node[] => + typeof kid === 'string' + ? [kid] + : kid.tag === tag + ? unwrap(kidsOf(kid), tag) + : [made(kid, unwrap(kidsOf(kid), tag))], + ) + +// a name's words: what an element says, without its controls or what's never content +const words = (el: Element | undefined): string => + el && !valueBearing(el) + ? text( + made( + el, + without(kidsOf(el), (inner) => valueBearing(inner) || inner.tag === 'button'), + ), + ) + : '' +// what an icon or avatar link is called without content: its aria-labelledby, aria-label or title +export const linkLabel = (a: Element): string => { + if (a.attrs === '') return '' + const labelledBy = read(a, 'aria-labelledby') + if (labelledBy) { + const names = labelledBy + .split(/\s+/) + .filter(Boolean) + .flatMap((id) => ids().get(id) ?? []) + .map(words) + .filter(Boolean) + .join(' ') + if (names) return names + } + return (read(a, 'aria-label') ?? '').trim() || (read(a, 'title') ?? '').trim() +} + +// images with a description, which an agent can read +const described = (node: Node): Element[] => { + const found: Element[] = [] + const walk = (el: Element) => { + for (const kid of kidsOf(el)) { + if (typeof kid === 'string') continue + if (kid.tag === 'img' && read(kid, 'alt')) found.push(kid) + walk(kid) + } + } + if (typeof node !== 'string') walk(node) + return found +} +const hasDescribed = (node: Node): boolean => { + if (typeof node === 'string') return false + for (const kid of kidsOf(node)) { + if (typeof kid === 'string') continue + if ((kid.tag === 'img' && read(kid, 'alt')) || hasDescribed(kid)) return true + } + return false +} +const nothingToRead = (node: Element) => !toString(node).trim() && !hasDescribed(node) + +const INLINE = new Set(['a', 'span', 'code', 'strong', 'em', 'b', 'i', 'small', 'time', 'abbr']) +const isInline = (node: Node | undefined): node is Element => + node !== undefined && typeof node !== 'string' && INLINE.has(node.tag) +const isBlank = (node: Node | undefined) => typeof node === 'string' && !node.trim() +const emptyBlock = (el: Element) => + !INLINE.has(el.tag) && el.tag !== 'img' && el.tag !== 'br' && nothingToRead(el) +const linkDrop = (el: Element) => valueBearing(el) || emptyBlock(el) + +// links and the text it renders as: its text, else its described images, else its label +const linkText = (a: Element) => + text(a) || + described(a) + .map((img) => `${read(img, 'alt')} ${read(img, 'src')}`) + .join(' ') || + linkLabel(a) + +// a skeleton table (placeholder cells waiting on data): nothing to read in any cell, or a header over empty rows +const cellsOf = (row: Element, tags: Set) => + kidsOf(row).filter((cell): cell is Element => typeof cell !== 'string' && tags.has(cell.tag)) +const CELLS = new Set(['td', 'th']) +const TD = new Set(['td']) +const emptyRow = (row: Element) => + cellsOf(row, CELLS).every((cell) => !text(cell) && !hasDescribed(cell)) +const skeleton = (table: Element) => { + const rows: Element[] = [] + const header = new Set() + const walk = (parent: Element, inHead: boolean) => { + for (const kid of kidsOf(parent)) { + if (typeof kid === 'string') continue + if (kid.tag === 'tr') { + rows.push(kid) + if (inHead) header.add(kid) + } + walk(kid, inHead || kid.tag === 'thead') + } + } + walk(table, false) + const first = rows[0] + if (!header.size && first && !cellsOf(first, TD).length) header.add(first) + const body = rows.filter((row) => !header.has(row)) + return rows.every(emptyRow) || (body.length > 0 && body.every(emptyRow)) +} + +// headers and summaries whose text is a button's read as the button's text +const LABEL_HOSTS = new Set(['th', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'caption', 'summary', 'dt']) +const hasTag = (el: Element, tag: string): boolean => { + for (const kid of kidsOf(el)) + if (typeof kid !== 'string' && (kid.tag === tag || hasTag(kid, tag))) return true + return false +} + +// what a child becomes: itself, something prune made of it, or nothing +const pruned = (kid: Element): Element | undefined => { + if (dropped(kid) || (stripChrome && chrome(kid))) return undefined + if (kid.tag === 'a') { + const inner = kidsOf(kid) + const kept = without(inner, linkDrop) + let link = kept === inner ? kid : made(kid, kept) + if (nothingToRead(link)) { + const label = linkLabel(kid) + if (!label) return undefined + link = made(kid, [label]) + } + return link + } + if (LABEL_HOSTS.has(kid.tag)) { + const inner = kidsOf(kid) + const buttons = hasTag(kid, 'button') + if ( + buttons + ? text( + made( + kid, + without(inner, (el) => el.tag === 'button'), + ), + ) + : text(kid) + ) + return kid + // read as its name, so without what carries a value + const kept = without(inner, valueBearing) + if (buttons) return made(kid, unwrap(kept, 'button')) + return kept === inner ? kid : made(kid, kept) + } + if (kid.tag === 'table' && skeleton(kid)) return undefined + return kid +} + +// whether text in an element is code, as written: no spacing there. cached with the children, 1 or 2 +const literal = (el: Element): boolean => { + const cached = el as Pruned + touch(cached) + if (cached.le === epoch) return cached.lv! + const value = el.tag === 'pre' || el.tag === 'code' || (el.up !== null && literal(el.up)) + cached.le = epoch + cached.lv = value + return value +} + +// display classes and styles: laid out side by side (flex, grid), or a box of its own +const LAID_OUT = /^([\w-]+:)*(inline-)?(flex|grid)$/ +const BOXED = /^([\w-]+:)*(block|flex|grid)$/ +const displays = (el: Element, display: RegExp) => + el.attrs !== '' && + (classes(el).some((name) => display.test(name)) || styleDisplays(read(el, 'style'), display)) +const BOXISH = /block|flex|grid|display|\\/ +const boxed = (node: Node | undefined) => + isInline(node) && BOXISH.test(node.attrs) && displays(node, BOXED) +// a run of one-character elements is one word split for styling, so only longer words are spaced +const word = (node: Node | undefined) => { + const said = isInline(node) ? toString(node).trim() : typeof node === 'string' ? node : '' + return longer(said) ? said : '' +} +// more than one character, counting code points +const longer = (said: string) => { + const trimmed = said.trim() + if (trimmed.length !== 2) return trimmed.length > 2 + const head = trimmed.charCodeAt(0) + const tail = trimmed.charCodeAt(1) + return !(head >= 0xd800 && head <= 0xdbff && tail >= 0xdc00 && tail <= 0xdfff) +} +const edgeLink = (node: Node | undefined, end: boolean): Element | undefined => { + if (!isInline(node)) return undefined + if (node.tag === 'a') return node + const inside = kidsOf(node).filter((kid) => !isBlank(kid)) + return edgeLink(end ? inside.at(-1) : inside[0], end) +} +const soleLink = (node: Node | undefined): Element | undefined => { + if (!isInline(node)) return undefined + if (node.tag === 'a') return node + const inside = kidsOf(node).filter((kid) => !isBlank(kid)) + return inside.length === 1 ? soleLink(inside[0]) : undefined +} +const LETTER_END = /[\p{L}\p{N}]$/u +const LETTER_START = /^[\p{L}\p{N}]/u + +// inline boxes side by side with no text between get a space where a word meets a word (or a link a link, or a box +// anything); then a run of the same link reads once +const spaced = (parent: Element, kids: Node[]): Node[] => { + let out: Node[] | undefined + let items: boolean | undefined + const said: (string | undefined)[] = [] + const boxes: (boolean | undefined)[] = [] + const wordAt = (i: number) => (said[i] ??= word(kids[i])) + const boxedAt = (i: number) => (boxes[i] ??= boxed(kids[i])) + let inlines = 0 + for (let i = 0; i < kids.length; i++) { + const left = kids[i]! + const right = kids[i + 1] + const leftInline = isInline(left) + if (leftInline) inlines++ + out?.push(left) + if (right === undefined) break + const rightInline = isInline(right) + if (!leftInline && !rightInline) continue + if ((!leftInline && typeof left !== 'string') || (!rightInline && typeof right !== 'string')) + continue + let gap: boolean + if (leftInline && rightInline && edgeLink(left, true) && edgeLink(right, false)) gap = true + else { + const leftWord = wordAt(i) + const rightWord = wordAt(i + 1) + const letters = LETTER_END.test(leftWord) && LETTER_START.test(rightWord) + const both = leftWord !== '' && rightWord !== '' + if (!letters && !both) continue + const box = boxedAt(i) || boxedAt(i + 1) + gap = letters || (box && both) + // text beside an element is a box of its own only in a flex or grid container, or beside a box + if (gap && !(leftInline && rightInline)) gap = box || (items ??= displays(parent, LAID_OUT)) + } + if (gap) { + out ??= kids.slice(0, i + 1) + out.push(' ') + } + } + let result = out ?? kids + if (inlines < 2) return result + // a run of the same link, only whitespace between, reads as one + let kept: Node[] | undefined + for (let i = 0; i < result.length; i++) { + const child = result[i]! + const current = soleLink(child) + if (current) { + const list = kept ?? result + let at = kept ? kept.length : i + while (at > 0 && isBlank(list[at - 1])) at-- + const previous = soleLink(list[at - 1]) + if ( + previous && + (read(previous, 'href') ?? '').trim() === (read(current, 'href') ?? '').trim() && + linkText(previous) === linkText(current) + ) { + kept ??= result.slice(0, i) + kept.length = at + continue + } + } + kept?.push(child) + } + result = kept ?? result + return result +} + +// an element's children as prune leaves them +export const kidsOf = (el: Element): Node[] => { + const cached = el as Pruned + if (cached.pe === epoch) return cached.pk! + touch(cached) + const raw = el.kids + let out: Node[] | undefined + for (let i = 0; i < raw.length; i++) { + const kid = raw[i]! + if (typeof kid === 'string') { + out?.push(kid) + continue + } + const kept = pruned(kid) + if (kept !== kid) out ??= raw.slice(0, i) + if (out && kept) out.push(kept) + } + let kids = out ?? raw + if (kids.length > 1 && !literal(el)) kids = spaced(el, kids) + cached.pk = kids + cached.pe = epoch + return kids +} diff --git a/packages/md-core/src/emit.ts b/packages/md-core/src/emit.ts new file mode 100644 index 0000000..8fcfcbd --- /dev/null +++ b/packages/md-core/src/emit.ts @@ -0,0 +1,143 @@ +import { convertRoot, startConvert } from './emit-convert.ts' +import { HEADING, headingText, IMAGE, Md, setext, TEXT, toMarkdown } from './emit-markdown.ts' +import { begin, findMain, made, setPage } from './emit-prune.ts' +import type { Document, Options, Result } from './types.ts' + +// markdown straight from the parser's tree: what @affordances/md's htmlToMarkdown writes for the same page. one walk +// prunes, extracts, collapses whitespace and converts (emit-prune, emit-convert) into a lean tree that's written out +// (emit-markdown); finish adds what the page's head says. +// not here yet, where they'd hook in: markers and slots (prune's mode() and convert's one()), the form +// summary (convert's form()), shown tab panels (prune), streamed suspense boundaries (the parser), custom handlers +export const emit = (doc: Document, options: Options = {}): Result => { + const { head } = doc + const meta = (key: string) => (head.meta.get(key) ?? '').trim() || undefined + const canonical = canonicalOf(head.canonical, options.url) + const base = options.url ?? canonical + // extract: the page's
, else the body without its chrome; or the whole body + const auto = (options.extract ?? 'auto') === 'auto' + begin(false) + setPage(doc.root) + const main = auto ? findMain(doc.root) : undefined + if (auto && !main) begin(true) + startConvert(options, base) + const root = convertRoot(main ? made(doc.root, [main], '#root') : doc.root) + return finish( + root, + { + title: head.title || meta('property og:title'), + description: meta('name description') ?? meta('property og:description'), + canonical, + image: meta('property og:image'), + lang: head.lang || undefined, + jsonLd: head.jsonLd, + }, + canonical ?? options.url, + options, + ) +} + +// the page's canonical, if it's an http(s) url that fits in a Link header +const canonicalOf = (href: string | undefined, base: string | undefined) => { + if (!href) return undefined + try { + const url = new URL(href, base) + return /^https?:$/.test(url.protocol) && !/[,;]/.test(url.href) ? url.href : undefined + } catch { + return undefined + } +} + +type Meta = { + title: string | undefined + description: string | undefined + canonical: string | undefined + image: string | undefined + lang: string | undefined + jsonLd: string[] +} + +// frontmatter, as @affordances/md writes it +const yaml = (data: Record) => { + const lines = Object.entries(data).flatMap(([key, value]) => + value ? [`${key}: ${JSON.stringify(value)}`] : [], + ) + return lines.length ? `---\n${lines.join('\n')}\n---\n\n` : '' +} +const fenced = (lang: string, value: string) => { + const fence = '`'.repeat(Math.max(3, ...(value.match(/`+/g) ?? []).map((run) => run.length + 1))) + return `${fence}${lang}\n${value}\n${fence}` +} +const pretty = (raw: string) => { + try { + return JSON.stringify(JSON.parse(raw), null, 2) + } catch { + return raw + } +} + +const TITLE_SEPARATORS = '·|–—-' +const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +const collapsed = (value: string) => value.replace(/\s+/g, ' ').trim() +// the page's title: its , or its h1 when the <title> is the h1 and the site's name in a template +const pageTitle = (title: string | undefined, h1: string | undefined) => { + const said = title === undefined ? undefined : collapsed(title) + if (!said || !h1) return title + const name = escapeRegExp(h1) + const separator = ` [${TITLE_SEPARATORS}] ` + return new RegExp(`^${name}${separator}\\S|\\S${separator}${name}$`).test(said) ? h1 : title +} + +// a node's text as written: its values, never an image's alt +const valueText = (node: Md): string => { + if (node.type === IMAGE) return '' + if (node.kids.length === 0) return node.value + let text = '' + for (const kid of node.kids) text += valueText(kid) + return text +} + +const isH1 = (node: Md) => node.type === HEADING && node.depth === 1 + +const finish = (root: Md, meta: Meta, url: string | undefined, options: Options): Result => { + const { frontmatter = true, jsonLd = true } = options + // the page's own h1 is its title; without one, the <title> stands in + const hasH1 = root.kids.some(isH1) + if (!hasH1 && meta.title) { + const heading = new Md(HEADING, [new Md(TEXT, undefined, meta.title)]) + heading.depth = 1 + root.kids.unshift(heading) + } + // the block right after the h1 goes when it says exactly the description + const h1 = root.kids.findIndex(isH1) + const next = root.kids[h1 + 1] + if ( + frontmatter && + meta.description && + next && + collapsed(valueText(next)) === collapsed(meta.description) + ) + root.kids.splice(h1 + 1, 1) + let output = toMarkdown(root) + .replace(/\n{3,}/g, '\n\n') + .trim() + const title = hasH1 ? pageTitle(meta.title, firstHeading(root)) : meta.title + if (jsonLd && meta.jsonLd.length) + output += `\n\n${meta.jsonLd.map((raw) => fenced('json', pretty(raw))).join('\n\n')}` + const markdown = + (frontmatter + ? yaml({ + title, + description: meta.description, + url, + image: meta.image, + lang: meta.lang, + }) + : '') + `${output}\n` + return { markdown, title, url, tokens: Math.ceil(markdown.length / 4) } +} + +// the text of the markdown's first # heading: the first h1 written atx style at the top +const firstHeading = (root: Md) => { + for (const node of root.kids) if (isH1(node) && !setext(node)) return headingText(node) + return undefined +} diff --git a/packages/md-core/src/entities-table.ts b/packages/md-core/src/entities-table.ts new file mode 100644 index 0000000..b4819e2 --- /dev/null +++ b/packages/md-core/src/entities-table.ts @@ -0,0 +1,2235 @@ +// generated by test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones +// (decoded without a ';') also under their bare name. do not edit +export const ENTITIES: Record<string, string> = { + AElig: 'Æ', + 'AElig;': 'Æ', + AMP: '&', + 'AMP;': '&', + Aacute: 'Á', + 'Aacute;': 'Á', + 'Abreve;': 'Ă', + Acirc: 'Â', + 'Acirc;': 'Â', + 'Acy;': 'А', + 'Afr;': '𝔄', + Agrave: 'À', + 'Agrave;': 'À', + 'Alpha;': 'Α', + 'Amacr;': 'Ā', + 'And;': '⩓', + 'Aogon;': 'Ą', + 'Aopf;': '𝔸', + 'ApplyFunction;': '⁡', + Aring: 'Å', + 'Aring;': 'Å', + 'Ascr;': '𝒜', + 'Assign;': '≔', + Atilde: 'Ã', + 'Atilde;': 'Ã', + Auml: 'Ä', + 'Auml;': 'Ä', + 'Backslash;': '∖', + 'Barv;': '⫧', + 'Barwed;': '⌆', + 'Bcy;': 'Б', + 'Because;': '∵', + 'Bernoullis;': 'ℬ', + 'Beta;': 'Β', + 'Bfr;': '𝔅', + 'Bopf;': '𝔹', + 'Breve;': '˘', + 'Bscr;': 'ℬ', + 'Bumpeq;': '≎', + 'CHcy;': 'Ч', + COPY: '©', + 'COPY;': '©', + 'Cacute;': 'Ć', + 'Cap;': '⋒', + 'CapitalDifferentialD;': 'ⅅ', + 'Cayleys;': 'ℭ', + 'Ccaron;': 'Č', + Ccedil: 'Ç', + 'Ccedil;': 'Ç', + 'Ccirc;': 'Ĉ', + 'Cconint;': '∰', + 'Cdot;': 'Ċ', + 'Cedilla;': '¸', + 'CenterDot;': '·', + 'Cfr;': 'ℭ', + 'Chi;': 'Χ', + 'CircleDot;': '⊙', + 'CircleMinus;': '⊖', + 'CirclePlus;': '⊕', + 'CircleTimes;': '⊗', + 'ClockwiseContourIntegral;': '∲', + 'CloseCurlyDoubleQuote;': '”', + 'CloseCurlyQuote;': '’', + 'Colon;': '∷', + 'Colone;': '⩴', + 'Congruent;': '≡', + 'Conint;': '∯', + 'ContourIntegral;': '∮', + 'Copf;': 'ℂ', + 'Coproduct;': '∐', + 'CounterClockwiseContourIntegral;': '∳', + 'Cross;': '⨯', + 'Cscr;': '𝒞', + 'Cup;': '⋓', + 'CupCap;': '≍', + 'DD;': 'ⅅ', + 'DDotrahd;': '⤑', + 'DJcy;': 'Ђ', + 'DScy;': 'Ѕ', + 'DZcy;': 'Џ', + 'Dagger;': '‡', + 'Darr;': '↡', + 'Dashv;': '⫤', + 'Dcaron;': 'Ď', + 'Dcy;': 'Д', + 'Del;': '∇', + 'Delta;': 'Δ', + 'Dfr;': '𝔇', + 'DiacriticalAcute;': '´', + 'DiacriticalDot;': '˙', + 'DiacriticalDoubleAcute;': '˝', + 'DiacriticalGrave;': '`', + 'DiacriticalTilde;': '˜', + 'Diamond;': '⋄', + 'DifferentialD;': 'ⅆ', + 'Dopf;': '𝔻', + 'Dot;': '¨', + 'DotDot;': '⃜', + 'DotEqual;': '≐', + 'DoubleContourIntegral;': '∯', + 'DoubleDot;': '¨', + 'DoubleDownArrow;': '⇓', + 'DoubleLeftArrow;': '⇐', + 'DoubleLeftRightArrow;': '⇔', + 'DoubleLeftTee;': '⫤', + 'DoubleLongLeftArrow;': '⟸', + 'DoubleLongLeftRightArrow;': '⟺', + 'DoubleLongRightArrow;': '⟹', + 'DoubleRightArrow;': '⇒', + 'DoubleRightTee;': '⊨', + 'DoubleUpArrow;': '⇑', + 'DoubleUpDownArrow;': '⇕', + 'DoubleVerticalBar;': '∥', + 'DownArrow;': '↓', + 'DownArrowBar;': '⤓', + 'DownArrowUpArrow;': '⇵', + 'DownBreve;': '̑', + 'DownLeftRightVector;': '⥐', + 'DownLeftTeeVector;': '⥞', + 'DownLeftVector;': '↽', + 'DownLeftVectorBar;': '⥖', + 'DownRightTeeVector;': '⥟', + 'DownRightVector;': '⇁', + 'DownRightVectorBar;': '⥗', + 'DownTee;': '⊤', + 'DownTeeArrow;': '↧', + 'Downarrow;': '⇓', + 'Dscr;': '𝒟', + 'Dstrok;': 'Đ', + 'ENG;': 'Ŋ', + ETH: 'Ð', + 'ETH;': 'Ð', + Eacute: 'É', + 'Eacute;': 'É', + 'Ecaron;': 'Ě', + Ecirc: 'Ê', + 'Ecirc;': 'Ê', + 'Ecy;': 'Э', + 'Edot;': 'Ė', + 'Efr;': '𝔈', + Egrave: 'È', + 'Egrave;': 'È', + 'Element;': '∈', + 'Emacr;': 'Ē', + 'EmptySmallSquare;': '◻', + 'EmptyVerySmallSquare;': '▫', + 'Eogon;': 'Ę', + 'Eopf;': '𝔼', + 'Epsilon;': 'Ε', + 'Equal;': '⩵', + 'EqualTilde;': '≂', + 'Equilibrium;': '⇌', + 'Escr;': 'ℰ', + 'Esim;': '⩳', + 'Eta;': 'Η', + Euml: 'Ë', + 'Euml;': 'Ë', + 'Exists;': '∃', + 'ExponentialE;': 'ⅇ', + 'Fcy;': 'Ф', + 'Ffr;': '𝔉', + 'FilledSmallSquare;': '◼', + 'FilledVerySmallSquare;': '▪', + 'Fopf;': '𝔽', + 'ForAll;': '∀', + 'Fouriertrf;': 'ℱ', + 'Fscr;': 'ℱ', + 'GJcy;': 'Ѓ', + GT: '>', + 'GT;': '>', + 'Gamma;': 'Γ', + 'Gammad;': 'Ϝ', + 'Gbreve;': 'Ğ', + 'Gcedil;': 'Ģ', + 'Gcirc;': 'Ĝ', + 'Gcy;': 'Г', + 'Gdot;': 'Ġ', + 'Gfr;': '𝔊', + 'Gg;': '⋙', + 'Gopf;': '𝔾', + 'GreaterEqual;': '≥', + 'GreaterEqualLess;': '⋛', + 'GreaterFullEqual;': '≧', + 'GreaterGreater;': '⪢', + 'GreaterLess;': '≷', + 'GreaterSlantEqual;': '⩾', + 'GreaterTilde;': '≳', + 'Gscr;': '𝒢', + 'Gt;': '≫', + 'HARDcy;': 'Ъ', + 'Hacek;': 'ˇ', + 'Hat;': '^', + 'Hcirc;': 'Ĥ', + 'Hfr;': 'ℌ', + 'HilbertSpace;': 'ℋ', + 'Hopf;': 'ℍ', + 'HorizontalLine;': '─', + 'Hscr;': 'ℋ', + 'Hstrok;': 'Ħ', + 'HumpDownHump;': '≎', + 'HumpEqual;': '≏', + 'IEcy;': 'Е', + 'IJlig;': 'IJ', + 'IOcy;': 'Ё', + Iacute: 'Í', + 'Iacute;': 'Í', + Icirc: 'Î', + 'Icirc;': 'Î', + 'Icy;': 'И', + 'Idot;': 'İ', + 'Ifr;': 'ℑ', + Igrave: 'Ì', + 'Igrave;': 'Ì', + 'Im;': 'ℑ', + 'Imacr;': 'Ī', + 'ImaginaryI;': 'ⅈ', + 'Implies;': '⇒', + 'Int;': '∬', + 'Integral;': '∫', + 'Intersection;': '⋂', + 'InvisibleComma;': '⁣', + 'InvisibleTimes;': '⁢', + 'Iogon;': 'Į', + 'Iopf;': '𝕀', + 'Iota;': 'Ι', + 'Iscr;': 'ℐ', + 'Itilde;': 'Ĩ', + 'Iukcy;': 'І', + Iuml: 'Ï', + 'Iuml;': 'Ï', + 'Jcirc;': 'Ĵ', + 'Jcy;': 'Й', + 'Jfr;': '𝔍', + 'Jopf;': '𝕁', + 'Jscr;': '𝒥', + 'Jsercy;': 'Ј', + 'Jukcy;': 'Є', + 'KHcy;': 'Х', + 'KJcy;': 'Ќ', + 'Kappa;': 'Κ', + 'Kcedil;': 'Ķ', + 'Kcy;': 'К', + 'Kfr;': '𝔎', + 'Kopf;': '𝕂', + 'Kscr;': '𝒦', + 'LJcy;': 'Љ', + LT: '<', + 'LT;': '<', + 'Lacute;': 'Ĺ', + 'Lambda;': 'Λ', + 'Lang;': '⟪', + 'Laplacetrf;': 'ℒ', + 'Larr;': '↞', + 'Lcaron;': 'Ľ', + 'Lcedil;': 'Ļ', + 'Lcy;': 'Л', + 'LeftAngleBracket;': '⟨', + 'LeftArrow;': '←', + 'LeftArrowBar;': '⇤', + 'LeftArrowRightArrow;': '⇆', + 'LeftCeiling;': '⌈', + 'LeftDoubleBracket;': '⟦', + 'LeftDownTeeVector;': '⥡', + 'LeftDownVector;': '⇃', + 'LeftDownVectorBar;': '⥙', + 'LeftFloor;': '⌊', + 'LeftRightArrow;': '↔', + 'LeftRightVector;': '⥎', + 'LeftTee;': '⊣', + 'LeftTeeArrow;': '↤', + 'LeftTeeVector;': '⥚', + 'LeftTriangle;': '⊲', + 'LeftTriangleBar;': '⧏', + 'LeftTriangleEqual;': '⊴', + 'LeftUpDownVector;': '⥑', + 'LeftUpTeeVector;': '⥠', + 'LeftUpVector;': '↿', + 'LeftUpVectorBar;': '⥘', + 'LeftVector;': '↼', + 'LeftVectorBar;': '⥒', + 'Leftarrow;': '⇐', + 'Leftrightarrow;': '⇔', + 'LessEqualGreater;': '⋚', + 'LessFullEqual;': '≦', + 'LessGreater;': '≶', + 'LessLess;': '⪡', + 'LessSlantEqual;': '⩽', + 'LessTilde;': '≲', + 'Lfr;': '𝔏', + 'Ll;': '⋘', + 'Lleftarrow;': '⇚', + 'Lmidot;': 'Ŀ', + 'LongLeftArrow;': '⟵', + 'LongLeftRightArrow;': '⟷', + 'LongRightArrow;': '⟶', + 'Longleftarrow;': '⟸', + 'Longleftrightarrow;': '⟺', + 'Longrightarrow;': '⟹', + 'Lopf;': '𝕃', + 'LowerLeftArrow;': '↙', + 'LowerRightArrow;': '↘', + 'Lscr;': 'ℒ', + 'Lsh;': '↰', + 'Lstrok;': 'Ł', + 'Lt;': '≪', + 'Map;': '⤅', + 'Mcy;': 'М', + 'MediumSpace;': ' ', + 'Mellintrf;': 'ℳ', + 'Mfr;': '𝔐', + 'MinusPlus;': '∓', + 'Mopf;': '𝕄', + 'Mscr;': 'ℳ', + 'Mu;': 'Μ', + 'NJcy;': 'Њ', + 'Nacute;': 'Ń', + 'Ncaron;': 'Ň', + 'Ncedil;': 'Ņ', + 'Ncy;': 'Н', + 'NegativeMediumSpace;': '​', + 'NegativeThickSpace;': '​', + 'NegativeThinSpace;': '​', + 'NegativeVeryThinSpace;': '​', + 'NestedGreaterGreater;': '≫', + 'NestedLessLess;': '≪', + 'NewLine;': '\n', + 'Nfr;': '𝔑', + 'NoBreak;': '⁠', + 'NonBreakingSpace;': ' ', + 'Nopf;': 'ℕ', + 'Not;': '⫬', + 'NotCongruent;': '≢', + 'NotCupCap;': '≭', + 'NotDoubleVerticalBar;': '∦', + 'NotElement;': '∉', + 'NotEqual;': '≠', + 'NotEqualTilde;': '≂̸', + 'NotExists;': '∄', + 'NotGreater;': '≯', + 'NotGreaterEqual;': '≱', + 'NotGreaterFullEqual;': '≧̸', + 'NotGreaterGreater;': '≫̸', + 'NotGreaterLess;': '≹', + 'NotGreaterSlantEqual;': '⩾̸', + 'NotGreaterTilde;': '≵', + 'NotHumpDownHump;': '≎̸', + 'NotHumpEqual;': '≏̸', + 'NotLeftTriangle;': '⋪', + 'NotLeftTriangleBar;': '⧏̸', + 'NotLeftTriangleEqual;': '⋬', + 'NotLess;': '≮', + 'NotLessEqual;': '≰', + 'NotLessGreater;': '≸', + 'NotLessLess;': '≪̸', + 'NotLessSlantEqual;': '⩽̸', + 'NotLessTilde;': '≴', + 'NotNestedGreaterGreater;': '⪢̸', + 'NotNestedLessLess;': '⪡̸', + 'NotPrecedes;': '⊀', + 'NotPrecedesEqual;': '⪯̸', + 'NotPrecedesSlantEqual;': '⋠', + 'NotReverseElement;': '∌', + 'NotRightTriangle;': '⋫', + 'NotRightTriangleBar;': '⧐̸', + 'NotRightTriangleEqual;': '⋭', + 'NotSquareSubset;': '⊏̸', + 'NotSquareSubsetEqual;': '⋢', + 'NotSquareSuperset;': '⊐̸', + 'NotSquareSupersetEqual;': '⋣', + 'NotSubset;': '⊂⃒', + 'NotSubsetEqual;': '⊈', + 'NotSucceeds;': '⊁', + 'NotSucceedsEqual;': '⪰̸', + 'NotSucceedsSlantEqual;': '⋡', + 'NotSucceedsTilde;': '≿̸', + 'NotSuperset;': '⊃⃒', + 'NotSupersetEqual;': '⊉', + 'NotTilde;': '≁', + 'NotTildeEqual;': '≄', + 'NotTildeFullEqual;': '≇', + 'NotTildeTilde;': '≉', + 'NotVerticalBar;': '∤', + 'Nscr;': '𝒩', + Ntilde: 'Ñ', + 'Ntilde;': 'Ñ', + 'Nu;': 'Ν', + 'OElig;': 'Œ', + Oacute: 'Ó', + 'Oacute;': 'Ó', + Ocirc: 'Ô', + 'Ocirc;': 'Ô', + 'Ocy;': 'О', + 'Odblac;': 'Ő', + 'Ofr;': '𝔒', + Ograve: 'Ò', + 'Ograve;': 'Ò', + 'Omacr;': 'Ō', + 'Omega;': 'Ω', + 'Omicron;': 'Ο', + 'Oopf;': '𝕆', + 'OpenCurlyDoubleQuote;': '“', + 'OpenCurlyQuote;': '‘', + 'Or;': '⩔', + 'Oscr;': '𝒪', + Oslash: 'Ø', + 'Oslash;': 'Ø', + Otilde: 'Õ', + 'Otilde;': 'Õ', + 'Otimes;': '⨷', + Ouml: 'Ö', + 'Ouml;': 'Ö', + 'OverBar;': '‾', + 'OverBrace;': '⏞', + 'OverBracket;': '⎴', + 'OverParenthesis;': '⏜', + 'PartialD;': '∂', + 'Pcy;': 'П', + 'Pfr;': '𝔓', + 'Phi;': 'Φ', + 'Pi;': 'Π', + 'PlusMinus;': '±', + 'Poincareplane;': 'ℌ', + 'Popf;': 'ℙ', + 'Pr;': '⪻', + 'Precedes;': '≺', + 'PrecedesEqual;': '⪯', + 'PrecedesSlantEqual;': '≼', + 'PrecedesTilde;': '≾', + 'Prime;': '″', + 'Product;': '∏', + 'Proportion;': '∷', + 'Proportional;': '∝', + 'Pscr;': '𝒫', + 'Psi;': 'Ψ', + QUOT: '"', + 'QUOT;': '"', + 'Qfr;': '𝔔', + 'Qopf;': 'ℚ', + 'Qscr;': '𝒬', + 'RBarr;': '⤐', + REG: '®', + 'REG;': '®', + 'Racute;': 'Ŕ', + 'Rang;': '⟫', + 'Rarr;': '↠', + 'Rarrtl;': '⤖', + 'Rcaron;': 'Ř', + 'Rcedil;': 'Ŗ', + 'Rcy;': 'Р', + 'Re;': 'ℜ', + 'ReverseElement;': '∋', + 'ReverseEquilibrium;': '⇋', + 'ReverseUpEquilibrium;': '⥯', + 'Rfr;': 'ℜ', + 'Rho;': 'Ρ', + 'RightAngleBracket;': '⟩', + 'RightArrow;': '→', + 'RightArrowBar;': '⇥', + 'RightArrowLeftArrow;': '⇄', + 'RightCeiling;': '⌉', + 'RightDoubleBracket;': '⟧', + 'RightDownTeeVector;': '⥝', + 'RightDownVector;': '⇂', + 'RightDownVectorBar;': '⥕', + 'RightFloor;': '⌋', + 'RightTee;': '⊢', + 'RightTeeArrow;': '↦', + 'RightTeeVector;': '⥛', + 'RightTriangle;': '⊳', + 'RightTriangleBar;': '⧐', + 'RightTriangleEqual;': '⊵', + 'RightUpDownVector;': '⥏', + 'RightUpTeeVector;': '⥜', + 'RightUpVector;': '↾', + 'RightUpVectorBar;': '⥔', + 'RightVector;': '⇀', + 'RightVectorBar;': '⥓', + 'Rightarrow;': '⇒', + 'Ropf;': 'ℝ', + 'RoundImplies;': '⥰', + 'Rrightarrow;': '⇛', + 'Rscr;': 'ℛ', + 'Rsh;': '↱', + 'RuleDelayed;': '⧴', + 'SHCHcy;': 'Щ', + 'SHcy;': 'Ш', + 'SOFTcy;': 'Ь', + 'Sacute;': 'Ś', + 'Sc;': '⪼', + 'Scaron;': 'Š', + 'Scedil;': 'Ş', + 'Scirc;': 'Ŝ', + 'Scy;': 'С', + 'Sfr;': '𝔖', + 'ShortDownArrow;': '↓', + 'ShortLeftArrow;': '←', + 'ShortRightArrow;': '→', + 'ShortUpArrow;': '↑', + 'Sigma;': 'Σ', + 'SmallCircle;': '∘', + 'Sopf;': '𝕊', + 'Sqrt;': '√', + 'Square;': '□', + 'SquareIntersection;': '⊓', + 'SquareSubset;': '⊏', + 'SquareSubsetEqual;': '⊑', + 'SquareSuperset;': '⊐', + 'SquareSupersetEqual;': '⊒', + 'SquareUnion;': '⊔', + 'Sscr;': '𝒮', + 'Star;': '⋆', + 'Sub;': '⋐', + 'Subset;': '⋐', + 'SubsetEqual;': '⊆', + 'Succeeds;': '≻', + 'SucceedsEqual;': '⪰', + 'SucceedsSlantEqual;': '≽', + 'SucceedsTilde;': '≿', + 'SuchThat;': '∋', + 'Sum;': '∑', + 'Sup;': '⋑', + 'Superset;': '⊃', + 'SupersetEqual;': '⊇', + 'Supset;': '⋑', + THORN: 'Þ', + 'THORN;': 'Þ', + 'TRADE;': '™', + 'TSHcy;': 'Ћ', + 'TScy;': 'Ц', + 'Tab;': '\t', + 'Tau;': 'Τ', + 'Tcaron;': 'Ť', + 'Tcedil;': 'Ţ', + 'Tcy;': 'Т', + 'Tfr;': '𝔗', + 'Therefore;': '∴', + 'Theta;': 'Θ', + 'ThickSpace;': '  ', + 'ThinSpace;': ' ', + 'Tilde;': '∼', + 'TildeEqual;': '≃', + 'TildeFullEqual;': '≅', + 'TildeTilde;': '≈', + 'Topf;': '𝕋', + 'TripleDot;': '⃛', + 'Tscr;': '𝒯', + 'Tstrok;': 'Ŧ', + Uacute: 'Ú', + 'Uacute;': 'Ú', + 'Uarr;': '↟', + 'Uarrocir;': '⥉', + 'Ubrcy;': 'Ў', + 'Ubreve;': 'Ŭ', + Ucirc: 'Û', + 'Ucirc;': 'Û', + 'Ucy;': 'У', + 'Udblac;': 'Ű', + 'Ufr;': '𝔘', + Ugrave: 'Ù', + 'Ugrave;': 'Ù', + 'Umacr;': 'Ū', + 'UnderBar;': '_', + 'UnderBrace;': '⏟', + 'UnderBracket;': '⎵', + 'UnderParenthesis;': '⏝', + 'Union;': '⋃', + 'UnionPlus;': '⊎', + 'Uogon;': 'Ų', + 'Uopf;': '𝕌', + 'UpArrow;': '↑', + 'UpArrowBar;': '⤒', + 'UpArrowDownArrow;': '⇅', + 'UpDownArrow;': '↕', + 'UpEquilibrium;': '⥮', + 'UpTee;': '⊥', + 'UpTeeArrow;': '↥', + 'Uparrow;': '⇑', + 'Updownarrow;': '⇕', + 'UpperLeftArrow;': '↖', + 'UpperRightArrow;': '↗', + 'Upsi;': 'ϒ', + 'Upsilon;': 'Υ', + 'Uring;': 'Ů', + 'Uscr;': '𝒰', + 'Utilde;': 'Ũ', + Uuml: 'Ü', + 'Uuml;': 'Ü', + 'VDash;': '⊫', + 'Vbar;': '⫫', + 'Vcy;': 'В', + 'Vdash;': '⊩', + 'Vdashl;': '⫦', + 'Vee;': '⋁', + 'Verbar;': '‖', + 'Vert;': '‖', + 'VerticalBar;': '∣', + 'VerticalLine;': '|', + 'VerticalSeparator;': '❘', + 'VerticalTilde;': '≀', + 'VeryThinSpace;': ' ', + 'Vfr;': '𝔙', + 'Vopf;': '𝕍', + 'Vscr;': '𝒱', + 'Vvdash;': '⊪', + 'Wcirc;': 'Ŵ', + 'Wedge;': '⋀', + 'Wfr;': '𝔚', + 'Wopf;': '𝕎', + 'Wscr;': '𝒲', + 'Xfr;': '𝔛', + 'Xi;': 'Ξ', + 'Xopf;': '𝕏', + 'Xscr;': '𝒳', + 'YAcy;': 'Я', + 'YIcy;': 'Ї', + 'YUcy;': 'Ю', + Yacute: 'Ý', + 'Yacute;': 'Ý', + 'Ycirc;': 'Ŷ', + 'Ycy;': 'Ы', + 'Yfr;': '𝔜', + 'Yopf;': '𝕐', + 'Yscr;': '𝒴', + 'Yuml;': 'Ÿ', + 'ZHcy;': 'Ж', + 'Zacute;': 'Ź', + 'Zcaron;': 'Ž', + 'Zcy;': 'З', + 'Zdot;': 'Ż', + 'ZeroWidthSpace;': '​', + 'Zeta;': 'Ζ', + 'Zfr;': 'ℨ', + 'Zopf;': 'ℤ', + 'Zscr;': '𝒵', + aacute: 'á', + 'aacute;': 'á', + 'abreve;': 'ă', + 'ac;': '∾', + 'acE;': '∾̳', + 'acd;': '∿', + acirc: 'â', + 'acirc;': 'â', + acute: '´', + 'acute;': '´', + 'acy;': 'а', + aelig: 'æ', + 'aelig;': 'æ', + 'af;': '⁡', + 'afr;': '𝔞', + agrave: 'à', + 'agrave;': 'à', + 'alefsym;': 'ℵ', + 'aleph;': 'ℵ', + 'alpha;': 'α', + 'amacr;': 'ā', + 'amalg;': '⨿', + amp: '&', + 'amp;': '&', + 'and;': '∧', + 'andand;': '⩕', + 'andd;': '⩜', + 'andslope;': '⩘', + 'andv;': '⩚', + 'ang;': '∠', + 'ange;': '⦤', + 'angle;': '∠', + 'angmsd;': '∡', + 'angmsdaa;': '⦨', + 'angmsdab;': '⦩', + 'angmsdac;': '⦪', + 'angmsdad;': '⦫', + 'angmsdae;': '⦬', + 'angmsdaf;': '⦭', + 'angmsdag;': '⦮', + 'angmsdah;': '⦯', + 'angrt;': '∟', + 'angrtvb;': '⊾', + 'angrtvbd;': '⦝', + 'angsph;': '∢', + 'angst;': 'Å', + 'angzarr;': '⍼', + 'aogon;': 'ą', + 'aopf;': '𝕒', + 'ap;': '≈', + 'apE;': '⩰', + 'apacir;': '⩯', + 'ape;': '≊', + 'apid;': '≋', + 'apos;': "'", + 'approx;': '≈', + 'approxeq;': '≊', + aring: 'å', + 'aring;': 'å', + 'ascr;': '𝒶', + 'ast;': '*', + 'asymp;': '≈', + 'asympeq;': '≍', + atilde: 'ã', + 'atilde;': 'ã', + auml: 'ä', + 'auml;': 'ä', + 'awconint;': '∳', + 'awint;': '⨑', + 'bNot;': '⫭', + 'backcong;': '≌', + 'backepsilon;': '϶', + 'backprime;': '‵', + 'backsim;': '∽', + 'backsimeq;': '⋍', + 'barvee;': '⊽', + 'barwed;': '⌅', + 'barwedge;': '⌅', + 'bbrk;': '⎵', + 'bbrktbrk;': '⎶', + 'bcong;': '≌', + 'bcy;': 'б', + 'bdquo;': '„', + 'becaus;': '∵', + 'because;': '∵', + 'bemptyv;': '⦰', + 'bepsi;': '϶', + 'bernou;': 'ℬ', + 'beta;': 'β', + 'beth;': 'ℶ', + 'between;': '≬', + 'bfr;': '𝔟', + 'bigcap;': '⋂', + 'bigcirc;': '◯', + 'bigcup;': '⋃', + 'bigodot;': '⨀', + 'bigoplus;': '⨁', + 'bigotimes;': '⨂', + 'bigsqcup;': '⨆', + 'bigstar;': '★', + 'bigtriangledown;': '▽', + 'bigtriangleup;': '△', + 'biguplus;': '⨄', + 'bigvee;': '⋁', + 'bigwedge;': '⋀', + 'bkarow;': '⤍', + 'blacklozenge;': '⧫', + 'blacksquare;': '▪', + 'blacktriangle;': '▴', + 'blacktriangledown;': '▾', + 'blacktriangleleft;': '◂', + 'blacktriangleright;': '▸', + 'blank;': '␣', + 'blk12;': '▒', + 'blk14;': '░', + 'blk34;': '▓', + 'block;': '█', + 'bne;': '=⃥', + 'bnequiv;': '≡⃥', + 'bnot;': '⌐', + 'bopf;': '𝕓', + 'bot;': '⊥', + 'bottom;': '⊥', + 'bowtie;': '⋈', + 'boxDL;': '╗', + 'boxDR;': '╔', + 'boxDl;': '╖', + 'boxDr;': '╓', + 'boxH;': '═', + 'boxHD;': '╦', + 'boxHU;': '╩', + 'boxHd;': '╤', + 'boxHu;': '╧', + 'boxUL;': '╝', + 'boxUR;': '╚', + 'boxUl;': '╜', + 'boxUr;': '╙', + 'boxV;': '║', + 'boxVH;': '╬', + 'boxVL;': '╣', + 'boxVR;': '╠', + 'boxVh;': '╫', + 'boxVl;': '╢', + 'boxVr;': '╟', + 'boxbox;': '⧉', + 'boxdL;': '╕', + 'boxdR;': '╒', + 'boxdl;': '┐', + 'boxdr;': '┌', + 'boxh;': '─', + 'boxhD;': '╥', + 'boxhU;': '╨', + 'boxhd;': '┬', + 'boxhu;': '┴', + 'boxminus;': '⊟', + 'boxplus;': '⊞', + 'boxtimes;': '⊠', + 'boxuL;': '╛', + 'boxuR;': '╘', + 'boxul;': '┘', + 'boxur;': '└', + 'boxv;': '│', + 'boxvH;': '╪', + 'boxvL;': '╡', + 'boxvR;': '╞', + 'boxvh;': '┼', + 'boxvl;': '┤', + 'boxvr;': '├', + 'bprime;': '‵', + 'breve;': '˘', + brvbar: '¦', + 'brvbar;': '¦', + 'bscr;': '𝒷', + 'bsemi;': '⁏', + 'bsim;': '∽', + 'bsime;': '⋍', + 'bsol;': '\\', + 'bsolb;': '⧅', + 'bsolhsub;': '⟈', + 'bull;': '•', + 'bullet;': '•', + 'bump;': '≎', + 'bumpE;': '⪮', + 'bumpe;': '≏', + 'bumpeq;': '≏', + 'cacute;': 'ć', + 'cap;': '∩', + 'capand;': '⩄', + 'capbrcup;': '⩉', + 'capcap;': '⩋', + 'capcup;': '⩇', + 'capdot;': '⩀', + 'caps;': '∩︀', + 'caret;': '⁁', + 'caron;': 'ˇ', + 'ccaps;': '⩍', + 'ccaron;': 'č', + ccedil: 'ç', + 'ccedil;': 'ç', + 'ccirc;': 'ĉ', + 'ccups;': '⩌', + 'ccupssm;': '⩐', + 'cdot;': 'ċ', + cedil: '¸', + 'cedil;': '¸', + 'cemptyv;': '⦲', + cent: '¢', + 'cent;': '¢', + 'centerdot;': '·', + 'cfr;': '𝔠', + 'chcy;': 'ч', + 'check;': '✓', + 'checkmark;': '✓', + 'chi;': 'χ', + 'cir;': '○', + 'cirE;': '⧃', + 'circ;': 'ˆ', + 'circeq;': '≗', + 'circlearrowleft;': '↺', + 'circlearrowright;': '↻', + 'circledR;': '®', + 'circledS;': 'Ⓢ', + 'circledast;': '⊛', + 'circledcirc;': '⊚', + 'circleddash;': '⊝', + 'cire;': '≗', + 'cirfnint;': '⨐', + 'cirmid;': '⫯', + 'cirscir;': '⧂', + 'clubs;': '♣', + 'clubsuit;': '♣', + 'colon;': ':', + 'colone;': '≔', + 'coloneq;': '≔', + 'comma;': ',', + 'commat;': '@', + 'comp;': '∁', + 'compfn;': '∘', + 'complement;': '∁', + 'complexes;': 'ℂ', + 'cong;': '≅', + 'congdot;': '⩭', + 'conint;': '∮', + 'copf;': '𝕔', + 'coprod;': '∐', + copy: '©', + 'copy;': '©', + 'copysr;': '℗', + 'crarr;': '↵', + 'cross;': '✗', + 'cscr;': '𝒸', + 'csub;': '⫏', + 'csube;': '⫑', + 'csup;': '⫐', + 'csupe;': '⫒', + 'ctdot;': '⋯', + 'cudarrl;': '⤸', + 'cudarrr;': '⤵', + 'cuepr;': '⋞', + 'cuesc;': '⋟', + 'cularr;': '↶', + 'cularrp;': '⤽', + 'cup;': '∪', + 'cupbrcap;': '⩈', + 'cupcap;': '⩆', + 'cupcup;': '⩊', + 'cupdot;': '⊍', + 'cupor;': '⩅', + 'cups;': '∪︀', + 'curarr;': '↷', + 'curarrm;': '⤼', + 'curlyeqprec;': '⋞', + 'curlyeqsucc;': '⋟', + 'curlyvee;': '⋎', + 'curlywedge;': '⋏', + curren: '¤', + 'curren;': '¤', + 'curvearrowleft;': '↶', + 'curvearrowright;': '↷', + 'cuvee;': '⋎', + 'cuwed;': '⋏', + 'cwconint;': '∲', + 'cwint;': '∱', + 'cylcty;': '⌭', + 'dArr;': '⇓', + 'dHar;': '⥥', + 'dagger;': '†', + 'daleth;': 'ℸ', + 'darr;': '↓', + 'dash;': '‐', + 'dashv;': '⊣', + 'dbkarow;': '⤏', + 'dblac;': '˝', + 'dcaron;': 'ď', + 'dcy;': 'д', + 'dd;': 'ⅆ', + 'ddagger;': '‡', + 'ddarr;': '⇊', + 'ddotseq;': '⩷', + deg: '°', + 'deg;': '°', + 'delta;': 'δ', + 'demptyv;': '⦱', + 'dfisht;': '⥿', + 'dfr;': '𝔡', + 'dharl;': '⇃', + 'dharr;': '⇂', + 'diam;': '⋄', + 'diamond;': '⋄', + 'diamondsuit;': '♦', + 'diams;': '♦', + 'die;': '¨', + 'digamma;': 'ϝ', + 'disin;': '⋲', + 'div;': '÷', + divide: '÷', + 'divide;': '÷', + 'divideontimes;': '⋇', + 'divonx;': '⋇', + 'djcy;': 'ђ', + 'dlcorn;': '⌞', + 'dlcrop;': '⌍', + 'dollar;': '$', + 'dopf;': '𝕕', + 'dot;': '˙', + 'doteq;': '≐', + 'doteqdot;': '≑', + 'dotminus;': '∸', + 'dotplus;': '∔', + 'dotsquare;': '⊡', + 'doublebarwedge;': '⌆', + 'downarrow;': '↓', + 'downdownarrows;': '⇊', + 'downharpoonleft;': '⇃', + 'downharpoonright;': '⇂', + 'drbkarow;': '⤐', + 'drcorn;': '⌟', + 'drcrop;': '⌌', + 'dscr;': '𝒹', + 'dscy;': 'ѕ', + 'dsol;': '⧶', + 'dstrok;': 'đ', + 'dtdot;': '⋱', + 'dtri;': '▿', + 'dtrif;': '▾', + 'duarr;': '⇵', + 'duhar;': '⥯', + 'dwangle;': '⦦', + 'dzcy;': 'џ', + 'dzigrarr;': '⟿', + 'eDDot;': '⩷', + 'eDot;': '≑', + eacute: 'é', + 'eacute;': 'é', + 'easter;': '⩮', + 'ecaron;': 'ě', + 'ecir;': '≖', + ecirc: 'ê', + 'ecirc;': 'ê', + 'ecolon;': '≕', + 'ecy;': 'э', + 'edot;': 'ė', + 'ee;': 'ⅇ', + 'efDot;': '≒', + 'efr;': '𝔢', + 'eg;': '⪚', + egrave: 'è', + 'egrave;': 'è', + 'egs;': '⪖', + 'egsdot;': '⪘', + 'el;': '⪙', + 'elinters;': '⏧', + 'ell;': 'ℓ', + 'els;': '⪕', + 'elsdot;': '⪗', + 'emacr;': 'ē', + 'empty;': '∅', + 'emptyset;': '∅', + 'emptyv;': '∅', + 'emsp13;': ' ', + 'emsp14;': ' ', + 'emsp;': ' ', + 'eng;': 'ŋ', + 'ensp;': ' ', + 'eogon;': 'ę', + 'eopf;': '𝕖', + 'epar;': '⋕', + 'eparsl;': '⧣', + 'eplus;': '⩱', + 'epsi;': 'ε', + 'epsilon;': 'ε', + 'epsiv;': 'ϵ', + 'eqcirc;': '≖', + 'eqcolon;': '≕', + 'eqsim;': '≂', + 'eqslantgtr;': '⪖', + 'eqslantless;': '⪕', + 'equals;': '=', + 'equest;': '≟', + 'equiv;': '≡', + 'equivDD;': '⩸', + 'eqvparsl;': '⧥', + 'erDot;': '≓', + 'erarr;': '⥱', + 'escr;': 'ℯ', + 'esdot;': '≐', + 'esim;': '≂', + 'eta;': 'η', + eth: 'ð', + 'eth;': 'ð', + euml: 'ë', + 'euml;': 'ë', + 'euro;': '€', + 'excl;': '!', + 'exist;': '∃', + 'expectation;': 'ℰ', + 'exponentiale;': 'ⅇ', + 'fallingdotseq;': '≒', + 'fcy;': 'ф', + 'female;': '♀', + 'ffilig;': 'ffi', + 'fflig;': 'ff', + 'ffllig;': 'ffl', + 'ffr;': '𝔣', + 'filig;': 'fi', + 'fjlig;': 'fj', + 'flat;': '♭', + 'fllig;': 'fl', + 'fltns;': '▱', + 'fnof;': 'ƒ', + 'fopf;': '𝕗', + 'forall;': '∀', + 'fork;': '⋔', + 'forkv;': '⫙', + 'fpartint;': '⨍', + frac12: '½', + 'frac12;': '½', + 'frac13;': '⅓', + frac14: '¼', + 'frac14;': '¼', + 'frac15;': '⅕', + 'frac16;': '⅙', + 'frac18;': '⅛', + 'frac23;': '⅔', + 'frac25;': '⅖', + frac34: '¾', + 'frac34;': '¾', + 'frac35;': '⅗', + 'frac38;': '⅜', + 'frac45;': '⅘', + 'frac56;': '⅚', + 'frac58;': '⅝', + 'frac78;': '⅞', + 'frasl;': '⁄', + 'frown;': '⌢', + 'fscr;': '𝒻', + 'gE;': '≧', + 'gEl;': '⪌', + 'gacute;': 'ǵ', + 'gamma;': 'γ', + 'gammad;': 'ϝ', + 'gap;': '⪆', + 'gbreve;': 'ğ', + 'gcirc;': 'ĝ', + 'gcy;': 'г', + 'gdot;': 'ġ', + 'ge;': '≥', + 'gel;': '⋛', + 'geq;': '≥', + 'geqq;': '≧', + 'geqslant;': '⩾', + 'ges;': '⩾', + 'gescc;': '⪩', + 'gesdot;': '⪀', + 'gesdoto;': '⪂', + 'gesdotol;': '⪄', + 'gesl;': '⋛︀', + 'gesles;': '⪔', + 'gfr;': '𝔤', + 'gg;': '≫', + 'ggg;': '⋙', + 'gimel;': 'ℷ', + 'gjcy;': 'ѓ', + 'gl;': '≷', + 'glE;': '⪒', + 'gla;': '⪥', + 'glj;': '⪤', + 'gnE;': '≩', + 'gnap;': '⪊', + 'gnapprox;': '⪊', + 'gne;': '⪈', + 'gneq;': '⪈', + 'gneqq;': '≩', + 'gnsim;': '⋧', + 'gopf;': '𝕘', + 'grave;': '`', + 'gscr;': 'ℊ', + 'gsim;': '≳', + 'gsime;': '⪎', + 'gsiml;': '⪐', + gt: '>', + 'gt;': '>', + 'gtcc;': '⪧', + 'gtcir;': '⩺', + 'gtdot;': '⋗', + 'gtlPar;': '⦕', + 'gtquest;': '⩼', + 'gtrapprox;': '⪆', + 'gtrarr;': '⥸', + 'gtrdot;': '⋗', + 'gtreqless;': '⋛', + 'gtreqqless;': '⪌', + 'gtrless;': '≷', + 'gtrsim;': '≳', + 'gvertneqq;': '≩︀', + 'gvnE;': '≩︀', + 'hArr;': '⇔', + 'hairsp;': ' ', + 'half;': '½', + 'hamilt;': 'ℋ', + 'hardcy;': 'ъ', + 'harr;': '↔', + 'harrcir;': '⥈', + 'harrw;': '↭', + 'hbar;': 'ℏ', + 'hcirc;': 'ĥ', + 'hearts;': '♥', + 'heartsuit;': '♥', + 'hellip;': '…', + 'hercon;': '⊹', + 'hfr;': '𝔥', + 'hksearow;': '⤥', + 'hkswarow;': '⤦', + 'hoarr;': '⇿', + 'homtht;': '∻', + 'hookleftarrow;': '↩', + 'hookrightarrow;': '↪', + 'hopf;': '𝕙', + 'horbar;': '―', + 'hscr;': '𝒽', + 'hslash;': 'ℏ', + 'hstrok;': 'ħ', + 'hybull;': '⁃', + 'hyphen;': '‐', + iacute: 'í', + 'iacute;': 'í', + 'ic;': '⁣', + icirc: 'î', + 'icirc;': 'î', + 'icy;': 'и', + 'iecy;': 'е', + iexcl: '¡', + 'iexcl;': '¡', + 'iff;': '⇔', + 'ifr;': '𝔦', + igrave: 'ì', + 'igrave;': 'ì', + 'ii;': 'ⅈ', + 'iiiint;': '⨌', + 'iiint;': '∭', + 'iinfin;': '⧜', + 'iiota;': '℩', + 'ijlig;': 'ij', + 'imacr;': 'ī', + 'image;': 'ℑ', + 'imagline;': 'ℐ', + 'imagpart;': 'ℑ', + 'imath;': 'ı', + 'imof;': '⊷', + 'imped;': 'Ƶ', + 'in;': '∈', + 'incare;': '℅', + 'infin;': '∞', + 'infintie;': '⧝', + 'inodot;': 'ı', + 'int;': '∫', + 'intcal;': '⊺', + 'integers;': 'ℤ', + 'intercal;': '⊺', + 'intlarhk;': '⨗', + 'intprod;': '⨼', + 'iocy;': 'ё', + 'iogon;': 'į', + 'iopf;': '𝕚', + 'iota;': 'ι', + 'iprod;': '⨼', + iquest: '¿', + 'iquest;': '¿', + 'iscr;': '𝒾', + 'isin;': '∈', + 'isinE;': '⋹', + 'isindot;': '⋵', + 'isins;': '⋴', + 'isinsv;': '⋳', + 'isinv;': '∈', + 'it;': '⁢', + 'itilde;': 'ĩ', + 'iukcy;': 'і', + iuml: 'ï', + 'iuml;': 'ï', + 'jcirc;': 'ĵ', + 'jcy;': 'й', + 'jfr;': '𝔧', + 'jmath;': 'ȷ', + 'jopf;': '𝕛', + 'jscr;': '𝒿', + 'jsercy;': 'ј', + 'jukcy;': 'є', + 'kappa;': 'κ', + 'kappav;': 'ϰ', + 'kcedil;': 'ķ', + 'kcy;': 'к', + 'kfr;': '𝔨', + 'kgreen;': 'ĸ', + 'khcy;': 'х', + 'kjcy;': 'ќ', + 'kopf;': '𝕜', + 'kscr;': '𝓀', + 'lAarr;': '⇚', + 'lArr;': '⇐', + 'lAtail;': '⤛', + 'lBarr;': '⤎', + 'lE;': '≦', + 'lEg;': '⪋', + 'lHar;': '⥢', + 'lacute;': 'ĺ', + 'laemptyv;': '⦴', + 'lagran;': 'ℒ', + 'lambda;': 'λ', + 'lang;': '⟨', + 'langd;': '⦑', + 'langle;': '⟨', + 'lap;': '⪅', + laquo: '«', + 'laquo;': '«', + 'larr;': '←', + 'larrb;': '⇤', + 'larrbfs;': '⤟', + 'larrfs;': '⤝', + 'larrhk;': '↩', + 'larrlp;': '↫', + 'larrpl;': '⤹', + 'larrsim;': '⥳', + 'larrtl;': '↢', + 'lat;': '⪫', + 'latail;': '⤙', + 'late;': '⪭', + 'lates;': '⪭︀', + 'lbarr;': '⤌', + 'lbbrk;': '❲', + 'lbrace;': '{', + 'lbrack;': '[', + 'lbrke;': '⦋', + 'lbrksld;': '⦏', + 'lbrkslu;': '⦍', + 'lcaron;': 'ľ', + 'lcedil;': 'ļ', + 'lceil;': '⌈', + 'lcub;': '{', + 'lcy;': 'л', + 'ldca;': '⤶', + 'ldquo;': '“', + 'ldquor;': '„', + 'ldrdhar;': '⥧', + 'ldrushar;': '⥋', + 'ldsh;': '↲', + 'le;': '≤', + 'leftarrow;': '←', + 'leftarrowtail;': '↢', + 'leftharpoondown;': '↽', + 'leftharpoonup;': '↼', + 'leftleftarrows;': '⇇', + 'leftrightarrow;': '↔', + 'leftrightarrows;': '⇆', + 'leftrightharpoons;': '⇋', + 'leftrightsquigarrow;': '↭', + 'leftthreetimes;': '⋋', + 'leg;': '⋚', + 'leq;': '≤', + 'leqq;': '≦', + 'leqslant;': '⩽', + 'les;': '⩽', + 'lescc;': '⪨', + 'lesdot;': '⩿', + 'lesdoto;': '⪁', + 'lesdotor;': '⪃', + 'lesg;': '⋚︀', + 'lesges;': '⪓', + 'lessapprox;': '⪅', + 'lessdot;': '⋖', + 'lesseqgtr;': '⋚', + 'lesseqqgtr;': '⪋', + 'lessgtr;': '≶', + 'lesssim;': '≲', + 'lfisht;': '⥼', + 'lfloor;': '⌊', + 'lfr;': '𝔩', + 'lg;': '≶', + 'lgE;': '⪑', + 'lhard;': '↽', + 'lharu;': '↼', + 'lharul;': '⥪', + 'lhblk;': '▄', + 'ljcy;': 'љ', + 'll;': '≪', + 'llarr;': '⇇', + 'llcorner;': '⌞', + 'llhard;': '⥫', + 'lltri;': '◺', + 'lmidot;': 'ŀ', + 'lmoust;': '⎰', + 'lmoustache;': '⎰', + 'lnE;': '≨', + 'lnap;': '⪉', + 'lnapprox;': '⪉', + 'lne;': '⪇', + 'lneq;': '⪇', + 'lneqq;': '≨', + 'lnsim;': '⋦', + 'loang;': '⟬', + 'loarr;': '⇽', + 'lobrk;': '⟦', + 'longleftarrow;': '⟵', + 'longleftrightarrow;': '⟷', + 'longmapsto;': '⟼', + 'longrightarrow;': '⟶', + 'looparrowleft;': '↫', + 'looparrowright;': '↬', + 'lopar;': '⦅', + 'lopf;': '𝕝', + 'loplus;': '⨭', + 'lotimes;': '⨴', + 'lowast;': '∗', + 'lowbar;': '_', + 'loz;': '◊', + 'lozenge;': '◊', + 'lozf;': '⧫', + 'lpar;': '(', + 'lparlt;': '⦓', + 'lrarr;': '⇆', + 'lrcorner;': '⌟', + 'lrhar;': '⇋', + 'lrhard;': '⥭', + 'lrm;': '‎', + 'lrtri;': '⊿', + 'lsaquo;': '‹', + 'lscr;': '𝓁', + 'lsh;': '↰', + 'lsim;': '≲', + 'lsime;': '⪍', + 'lsimg;': '⪏', + 'lsqb;': '[', + 'lsquo;': '‘', + 'lsquor;': '‚', + 'lstrok;': 'ł', + lt: '<', + 'lt;': '<', + 'ltcc;': '⪦', + 'ltcir;': '⩹', + 'ltdot;': '⋖', + 'lthree;': '⋋', + 'ltimes;': '⋉', + 'ltlarr;': '⥶', + 'ltquest;': '⩻', + 'ltrPar;': '⦖', + 'ltri;': '◃', + 'ltrie;': '⊴', + 'ltrif;': '◂', + 'lurdshar;': '⥊', + 'luruhar;': '⥦', + 'lvertneqq;': '≨︀', + 'lvnE;': '≨︀', + 'mDDot;': '∺', + macr: '¯', + 'macr;': '¯', + 'male;': '♂', + 'malt;': '✠', + 'maltese;': '✠', + 'map;': '↦', + 'mapsto;': '↦', + 'mapstodown;': '↧', + 'mapstoleft;': '↤', + 'mapstoup;': '↥', + 'marker;': '▮', + 'mcomma;': '⨩', + 'mcy;': 'м', + 'mdash;': '—', + 'measuredangle;': '∡', + 'mfr;': '𝔪', + 'mho;': '℧', + micro: 'µ', + 'micro;': 'µ', + 'mid;': '∣', + 'midast;': '*', + 'midcir;': '⫰', + middot: '·', + 'middot;': '·', + 'minus;': '−', + 'minusb;': '⊟', + 'minusd;': '∸', + 'minusdu;': '⨪', + 'mlcp;': '⫛', + 'mldr;': '…', + 'mnplus;': '∓', + 'models;': '⊧', + 'mopf;': '𝕞', + 'mp;': '∓', + 'mscr;': '𝓂', + 'mstpos;': '∾', + 'mu;': 'μ', + 'multimap;': '⊸', + 'mumap;': '⊸', + 'nGg;': '⋙̸', + 'nGt;': '≫⃒', + 'nGtv;': '≫̸', + 'nLeftarrow;': '⇍', + 'nLeftrightarrow;': '⇎', + 'nLl;': '⋘̸', + 'nLt;': '≪⃒', + 'nLtv;': '≪̸', + 'nRightarrow;': '⇏', + 'nVDash;': '⊯', + 'nVdash;': '⊮', + 'nabla;': '∇', + 'nacute;': 'ń', + 'nang;': '∠⃒', + 'nap;': '≉', + 'napE;': '⩰̸', + 'napid;': '≋̸', + 'napos;': 'ʼn', + 'napprox;': '≉', + 'natur;': '♮', + 'natural;': '♮', + 'naturals;': 'ℕ', + nbsp: ' ', + 'nbsp;': ' ', + 'nbump;': '≎̸', + 'nbumpe;': '≏̸', + 'ncap;': '⩃', + 'ncaron;': 'ň', + 'ncedil;': 'ņ', + 'ncong;': '≇', + 'ncongdot;': '⩭̸', + 'ncup;': '⩂', + 'ncy;': 'н', + 'ndash;': '–', + 'ne;': '≠', + 'neArr;': '⇗', + 'nearhk;': '⤤', + 'nearr;': '↗', + 'nearrow;': '↗', + 'nedot;': '≐̸', + 'nequiv;': '≢', + 'nesear;': '⤨', + 'nesim;': '≂̸', + 'nexist;': '∄', + 'nexists;': '∄', + 'nfr;': '𝔫', + 'ngE;': '≧̸', + 'nge;': '≱', + 'ngeq;': '≱', + 'ngeqq;': '≧̸', + 'ngeqslant;': '⩾̸', + 'nges;': '⩾̸', + 'ngsim;': '≵', + 'ngt;': '≯', + 'ngtr;': '≯', + 'nhArr;': '⇎', + 'nharr;': '↮', + 'nhpar;': '⫲', + 'ni;': '∋', + 'nis;': '⋼', + 'nisd;': '⋺', + 'niv;': '∋', + 'njcy;': 'њ', + 'nlArr;': '⇍', + 'nlE;': '≦̸', + 'nlarr;': '↚', + 'nldr;': '‥', + 'nle;': '≰', + 'nleftarrow;': '↚', + 'nleftrightarrow;': '↮', + 'nleq;': '≰', + 'nleqq;': '≦̸', + 'nleqslant;': '⩽̸', + 'nles;': '⩽̸', + 'nless;': '≮', + 'nlsim;': '≴', + 'nlt;': '≮', + 'nltri;': '⋪', + 'nltrie;': '⋬', + 'nmid;': '∤', + 'nopf;': '𝕟', + not: '¬', + 'not;': '¬', + 'notin;': '∉', + 'notinE;': '⋹̸', + 'notindot;': '⋵̸', + 'notinva;': '∉', + 'notinvb;': '⋷', + 'notinvc;': '⋶', + 'notni;': '∌', + 'notniva;': '∌', + 'notnivb;': '⋾', + 'notnivc;': '⋽', + 'npar;': '∦', + 'nparallel;': '∦', + 'nparsl;': '⫽⃥', + 'npart;': '∂̸', + 'npolint;': '⨔', + 'npr;': '⊀', + 'nprcue;': '⋠', + 'npre;': '⪯̸', + 'nprec;': '⊀', + 'npreceq;': '⪯̸', + 'nrArr;': '⇏', + 'nrarr;': '↛', + 'nrarrc;': '⤳̸', + 'nrarrw;': '↝̸', + 'nrightarrow;': '↛', + 'nrtri;': '⋫', + 'nrtrie;': '⋭', + 'nsc;': '⊁', + 'nsccue;': '⋡', + 'nsce;': '⪰̸', + 'nscr;': '𝓃', + 'nshortmid;': '∤', + 'nshortparallel;': '∦', + 'nsim;': '≁', + 'nsime;': '≄', + 'nsimeq;': '≄', + 'nsmid;': '∤', + 'nspar;': '∦', + 'nsqsube;': '⋢', + 'nsqsupe;': '⋣', + 'nsub;': '⊄', + 'nsubE;': '⫅̸', + 'nsube;': '⊈', + 'nsubset;': '⊂⃒', + 'nsubseteq;': '⊈', + 'nsubseteqq;': '⫅̸', + 'nsucc;': '⊁', + 'nsucceq;': '⪰̸', + 'nsup;': '⊅', + 'nsupE;': '⫆̸', + 'nsupe;': '⊉', + 'nsupset;': '⊃⃒', + 'nsupseteq;': '⊉', + 'nsupseteqq;': '⫆̸', + 'ntgl;': '≹', + ntilde: 'ñ', + 'ntilde;': 'ñ', + 'ntlg;': '≸', + 'ntriangleleft;': '⋪', + 'ntrianglelefteq;': '⋬', + 'ntriangleright;': '⋫', + 'ntrianglerighteq;': '⋭', + 'nu;': 'ν', + 'num;': '#', + 'numero;': '№', + 'numsp;': ' ', + 'nvDash;': '⊭', + 'nvHarr;': '⤄', + 'nvap;': '≍⃒', + 'nvdash;': '⊬', + 'nvge;': '≥⃒', + 'nvgt;': '>⃒', + 'nvinfin;': '⧞', + 'nvlArr;': '⤂', + 'nvle;': '≤⃒', + 'nvlt;': '<⃒', + 'nvltrie;': '⊴⃒', + 'nvrArr;': '⤃', + 'nvrtrie;': '⊵⃒', + 'nvsim;': '∼⃒', + 'nwArr;': '⇖', + 'nwarhk;': '⤣', + 'nwarr;': '↖', + 'nwarrow;': '↖', + 'nwnear;': '⤧', + 'oS;': 'Ⓢ', + oacute: 'ó', + 'oacute;': 'ó', + 'oast;': '⊛', + 'ocir;': '⊚', + ocirc: 'ô', + 'ocirc;': 'ô', + 'ocy;': 'о', + 'odash;': '⊝', + 'odblac;': 'ő', + 'odiv;': '⨸', + 'odot;': '⊙', + 'odsold;': '⦼', + 'oelig;': 'œ', + 'ofcir;': '⦿', + 'ofr;': '𝔬', + 'ogon;': '˛', + ograve: 'ò', + 'ograve;': 'ò', + 'ogt;': '⧁', + 'ohbar;': '⦵', + 'ohm;': 'Ω', + 'oint;': '∮', + 'olarr;': '↺', + 'olcir;': '⦾', + 'olcross;': '⦻', + 'oline;': '‾', + 'olt;': '⧀', + 'omacr;': 'ō', + 'omega;': 'ω', + 'omicron;': 'ο', + 'omid;': '⦶', + 'ominus;': '⊖', + 'oopf;': '𝕠', + 'opar;': '⦷', + 'operp;': '⦹', + 'oplus;': '⊕', + 'or;': '∨', + 'orarr;': '↻', + 'ord;': '⩝', + 'order;': 'ℴ', + 'orderof;': 'ℴ', + ordf: 'ª', + 'ordf;': 'ª', + ordm: 'º', + 'ordm;': 'º', + 'origof;': '⊶', + 'oror;': '⩖', + 'orslope;': '⩗', + 'orv;': '⩛', + 'oscr;': 'ℴ', + oslash: 'ø', + 'oslash;': 'ø', + 'osol;': '⊘', + otilde: 'õ', + 'otilde;': 'õ', + 'otimes;': '⊗', + 'otimesas;': '⨶', + ouml: 'ö', + 'ouml;': 'ö', + 'ovbar;': '⌽', + 'par;': '∥', + para: '¶', + 'para;': '¶', + 'parallel;': '∥', + 'parsim;': '⫳', + 'parsl;': '⫽', + 'part;': '∂', + 'pcy;': 'п', + 'percnt;': '%', + 'period;': '.', + 'permil;': '‰', + 'perp;': '⊥', + 'pertenk;': '‱', + 'pfr;': '𝔭', + 'phi;': 'φ', + 'phiv;': 'ϕ', + 'phmmat;': 'ℳ', + 'phone;': '☎', + 'pi;': 'π', + 'pitchfork;': '⋔', + 'piv;': 'ϖ', + 'planck;': 'ℏ', + 'planckh;': 'ℎ', + 'plankv;': 'ℏ', + 'plus;': '+', + 'plusacir;': '⨣', + 'plusb;': '⊞', + 'pluscir;': '⨢', + 'plusdo;': '∔', + 'plusdu;': '⨥', + 'pluse;': '⩲', + plusmn: '±', + 'plusmn;': '±', + 'plussim;': '⨦', + 'plustwo;': '⨧', + 'pm;': '±', + 'pointint;': '⨕', + 'popf;': '𝕡', + pound: '£', + 'pound;': '£', + 'pr;': '≺', + 'prE;': '⪳', + 'prap;': '⪷', + 'prcue;': '≼', + 'pre;': '⪯', + 'prec;': '≺', + 'precapprox;': '⪷', + 'preccurlyeq;': '≼', + 'preceq;': '⪯', + 'precnapprox;': '⪹', + 'precneqq;': '⪵', + 'precnsim;': '⋨', + 'precsim;': '≾', + 'prime;': '′', + 'primes;': 'ℙ', + 'prnE;': '⪵', + 'prnap;': '⪹', + 'prnsim;': '⋨', + 'prod;': '∏', + 'profalar;': '⌮', + 'profline;': '⌒', + 'profsurf;': '⌓', + 'prop;': '∝', + 'propto;': '∝', + 'prsim;': '≾', + 'prurel;': '⊰', + 'pscr;': '𝓅', + 'psi;': 'ψ', + 'puncsp;': ' ', + 'qfr;': '𝔮', + 'qint;': '⨌', + 'qopf;': '𝕢', + 'qprime;': '⁗', + 'qscr;': '𝓆', + 'quaternions;': 'ℍ', + 'quatint;': '⨖', + 'quest;': '?', + 'questeq;': '≟', + quot: '"', + 'quot;': '"', + 'rAarr;': '⇛', + 'rArr;': '⇒', + 'rAtail;': '⤜', + 'rBarr;': '⤏', + 'rHar;': '⥤', + 'race;': '∽̱', + 'racute;': 'ŕ', + 'radic;': '√', + 'raemptyv;': '⦳', + 'rang;': '⟩', + 'rangd;': '⦒', + 'range;': '⦥', + 'rangle;': '⟩', + raquo: '»', + 'raquo;': '»', + 'rarr;': '→', + 'rarrap;': '⥵', + 'rarrb;': '⇥', + 'rarrbfs;': '⤠', + 'rarrc;': '⤳', + 'rarrfs;': '⤞', + 'rarrhk;': '↪', + 'rarrlp;': '↬', + 'rarrpl;': '⥅', + 'rarrsim;': '⥴', + 'rarrtl;': '↣', + 'rarrw;': '↝', + 'ratail;': '⤚', + 'ratio;': '∶', + 'rationals;': 'ℚ', + 'rbarr;': '⤍', + 'rbbrk;': '❳', + 'rbrace;': '}', + 'rbrack;': ']', + 'rbrke;': '⦌', + 'rbrksld;': '⦎', + 'rbrkslu;': '⦐', + 'rcaron;': 'ř', + 'rcedil;': 'ŗ', + 'rceil;': '⌉', + 'rcub;': '}', + 'rcy;': 'р', + 'rdca;': '⤷', + 'rdldhar;': '⥩', + 'rdquo;': '”', + 'rdquor;': '”', + 'rdsh;': '↳', + 'real;': 'ℜ', + 'realine;': 'ℛ', + 'realpart;': 'ℜ', + 'reals;': 'ℝ', + 'rect;': '▭', + reg: '®', + 'reg;': '®', + 'rfisht;': '⥽', + 'rfloor;': '⌋', + 'rfr;': '𝔯', + 'rhard;': '⇁', + 'rharu;': '⇀', + 'rharul;': '⥬', + 'rho;': 'ρ', + 'rhov;': 'ϱ', + 'rightarrow;': '→', + 'rightarrowtail;': '↣', + 'rightharpoondown;': '⇁', + 'rightharpoonup;': '⇀', + 'rightleftarrows;': '⇄', + 'rightleftharpoons;': '⇌', + 'rightrightarrows;': '⇉', + 'rightsquigarrow;': '↝', + 'rightthreetimes;': '⋌', + 'ring;': '˚', + 'risingdotseq;': '≓', + 'rlarr;': '⇄', + 'rlhar;': '⇌', + 'rlm;': '‏', + 'rmoust;': '⎱', + 'rmoustache;': '⎱', + 'rnmid;': '⫮', + 'roang;': '⟭', + 'roarr;': '⇾', + 'robrk;': '⟧', + 'ropar;': '⦆', + 'ropf;': '𝕣', + 'roplus;': '⨮', + 'rotimes;': '⨵', + 'rpar;': ')', + 'rpargt;': '⦔', + 'rppolint;': '⨒', + 'rrarr;': '⇉', + 'rsaquo;': '›', + 'rscr;': '𝓇', + 'rsh;': '↱', + 'rsqb;': ']', + 'rsquo;': '’', + 'rsquor;': '’', + 'rthree;': '⋌', + 'rtimes;': '⋊', + 'rtri;': '▹', + 'rtrie;': '⊵', + 'rtrif;': '▸', + 'rtriltri;': '⧎', + 'ruluhar;': '⥨', + 'rx;': '℞', + 'sacute;': 'ś', + 'sbquo;': '‚', + 'sc;': '≻', + 'scE;': '⪴', + 'scap;': '⪸', + 'scaron;': 'š', + 'sccue;': '≽', + 'sce;': '⪰', + 'scedil;': 'ş', + 'scirc;': 'ŝ', + 'scnE;': '⪶', + 'scnap;': '⪺', + 'scnsim;': '⋩', + 'scpolint;': '⨓', + 'scsim;': '≿', + 'scy;': 'с', + 'sdot;': '⋅', + 'sdotb;': '⊡', + 'sdote;': '⩦', + 'seArr;': '⇘', + 'searhk;': '⤥', + 'searr;': '↘', + 'searrow;': '↘', + sect: '§', + 'sect;': '§', + 'semi;': ';', + 'seswar;': '⤩', + 'setminus;': '∖', + 'setmn;': '∖', + 'sext;': '✶', + 'sfr;': '𝔰', + 'sfrown;': '⌢', + 'sharp;': '♯', + 'shchcy;': 'щ', + 'shcy;': 'ш', + 'shortmid;': '∣', + 'shortparallel;': '∥', + shy: '­', + 'shy;': '­', + 'sigma;': 'σ', + 'sigmaf;': 'ς', + 'sigmav;': 'ς', + 'sim;': '∼', + 'simdot;': '⩪', + 'sime;': '≃', + 'simeq;': '≃', + 'simg;': '⪞', + 'simgE;': '⪠', + 'siml;': '⪝', + 'simlE;': '⪟', + 'simne;': '≆', + 'simplus;': '⨤', + 'simrarr;': '⥲', + 'slarr;': '←', + 'smallsetminus;': '∖', + 'smashp;': '⨳', + 'smeparsl;': '⧤', + 'smid;': '∣', + 'smile;': '⌣', + 'smt;': '⪪', + 'smte;': '⪬', + 'smtes;': '⪬︀', + 'softcy;': 'ь', + 'sol;': '/', + 'solb;': '⧄', + 'solbar;': '⌿', + 'sopf;': '𝕤', + 'spades;': '♠', + 'spadesuit;': '♠', + 'spar;': '∥', + 'sqcap;': '⊓', + 'sqcaps;': '⊓︀', + 'sqcup;': '⊔', + 'sqcups;': '⊔︀', + 'sqsub;': '⊏', + 'sqsube;': '⊑', + 'sqsubset;': '⊏', + 'sqsubseteq;': '⊑', + 'sqsup;': '⊐', + 'sqsupe;': '⊒', + 'sqsupset;': '⊐', + 'sqsupseteq;': '⊒', + 'squ;': '□', + 'square;': '□', + 'squarf;': '▪', + 'squf;': '▪', + 'srarr;': '→', + 'sscr;': '𝓈', + 'ssetmn;': '∖', + 'ssmile;': '⌣', + 'sstarf;': '⋆', + 'star;': '☆', + 'starf;': '★', + 'straightepsilon;': 'ϵ', + 'straightphi;': 'ϕ', + 'strns;': '¯', + 'sub;': '⊂', + 'subE;': '⫅', + 'subdot;': '⪽', + 'sube;': '⊆', + 'subedot;': '⫃', + 'submult;': '⫁', + 'subnE;': '⫋', + 'subne;': '⊊', + 'subplus;': '⪿', + 'subrarr;': '⥹', + 'subset;': '⊂', + 'subseteq;': '⊆', + 'subseteqq;': '⫅', + 'subsetneq;': '⊊', + 'subsetneqq;': '⫋', + 'subsim;': '⫇', + 'subsub;': '⫕', + 'subsup;': '⫓', + 'succ;': '≻', + 'succapprox;': '⪸', + 'succcurlyeq;': '≽', + 'succeq;': '⪰', + 'succnapprox;': '⪺', + 'succneqq;': '⪶', + 'succnsim;': '⋩', + 'succsim;': '≿', + 'sum;': '∑', + 'sung;': '♪', + sup1: '¹', + 'sup1;': '¹', + sup2: '²', + 'sup2;': '²', + sup3: '³', + 'sup3;': '³', + 'sup;': '⊃', + 'supE;': '⫆', + 'supdot;': '⪾', + 'supdsub;': '⫘', + 'supe;': '⊇', + 'supedot;': '⫄', + 'suphsol;': '⟉', + 'suphsub;': '⫗', + 'suplarr;': '⥻', + 'supmult;': '⫂', + 'supnE;': '⫌', + 'supne;': '⊋', + 'supplus;': '⫀', + 'supset;': '⊃', + 'supseteq;': '⊇', + 'supseteqq;': '⫆', + 'supsetneq;': '⊋', + 'supsetneqq;': '⫌', + 'supsim;': '⫈', + 'supsub;': '⫔', + 'supsup;': '⫖', + 'swArr;': '⇙', + 'swarhk;': '⤦', + 'swarr;': '↙', + 'swarrow;': '↙', + 'swnwar;': '⤪', + szlig: 'ß', + 'szlig;': 'ß', + 'target;': '⌖', + 'tau;': 'τ', + 'tbrk;': '⎴', + 'tcaron;': 'ť', + 'tcedil;': 'ţ', + 'tcy;': 'т', + 'tdot;': '⃛', + 'telrec;': '⌕', + 'tfr;': '𝔱', + 'there4;': '∴', + 'therefore;': '∴', + 'theta;': 'θ', + 'thetasym;': 'ϑ', + 'thetav;': 'ϑ', + 'thickapprox;': '≈', + 'thicksim;': '∼', + 'thinsp;': ' ', + 'thkap;': '≈', + 'thksim;': '∼', + thorn: 'þ', + 'thorn;': 'þ', + 'tilde;': '˜', + times: '×', + 'times;': '×', + 'timesb;': '⊠', + 'timesbar;': '⨱', + 'timesd;': '⨰', + 'tint;': '∭', + 'toea;': '⤨', + 'top;': '⊤', + 'topbot;': '⌶', + 'topcir;': '⫱', + 'topf;': '𝕥', + 'topfork;': '⫚', + 'tosa;': '⤩', + 'tprime;': '‴', + 'trade;': '™', + 'triangle;': '▵', + 'triangledown;': '▿', + 'triangleleft;': '◃', + 'trianglelefteq;': '⊴', + 'triangleq;': '≜', + 'triangleright;': '▹', + 'trianglerighteq;': '⊵', + 'tridot;': '◬', + 'trie;': '≜', + 'triminus;': '⨺', + 'triplus;': '⨹', + 'trisb;': '⧍', + 'tritime;': '⨻', + 'trpezium;': '⏢', + 'tscr;': '𝓉', + 'tscy;': 'ц', + 'tshcy;': 'ћ', + 'tstrok;': 'ŧ', + 'twixt;': '≬', + 'twoheadleftarrow;': '↞', + 'twoheadrightarrow;': '↠', + 'uArr;': '⇑', + 'uHar;': '⥣', + uacute: 'ú', + 'uacute;': 'ú', + 'uarr;': '↑', + 'ubrcy;': 'ў', + 'ubreve;': 'ŭ', + ucirc: 'û', + 'ucirc;': 'û', + 'ucy;': 'у', + 'udarr;': '⇅', + 'udblac;': 'ű', + 'udhar;': '⥮', + 'ufisht;': '⥾', + 'ufr;': '𝔲', + ugrave: 'ù', + 'ugrave;': 'ù', + 'uharl;': '↿', + 'uharr;': '↾', + 'uhblk;': '▀', + 'ulcorn;': '⌜', + 'ulcorner;': '⌜', + 'ulcrop;': '⌏', + 'ultri;': '◸', + 'umacr;': 'ū', + uml: '¨', + 'uml;': '¨', + 'uogon;': 'ų', + 'uopf;': '𝕦', + 'uparrow;': '↑', + 'updownarrow;': '↕', + 'upharpoonleft;': '↿', + 'upharpoonright;': '↾', + 'uplus;': '⊎', + 'upsi;': 'υ', + 'upsih;': 'ϒ', + 'upsilon;': 'υ', + 'upuparrows;': '⇈', + 'urcorn;': '⌝', + 'urcorner;': '⌝', + 'urcrop;': '⌎', + 'uring;': 'ů', + 'urtri;': '◹', + 'uscr;': '𝓊', + 'utdot;': '⋰', + 'utilde;': 'ũ', + 'utri;': '▵', + 'utrif;': '▴', + 'uuarr;': '⇈', + uuml: 'ü', + 'uuml;': 'ü', + 'uwangle;': '⦧', + 'vArr;': '⇕', + 'vBar;': '⫨', + 'vBarv;': '⫩', + 'vDash;': '⊨', + 'vangrt;': '⦜', + 'varepsilon;': 'ϵ', + 'varkappa;': 'ϰ', + 'varnothing;': '∅', + 'varphi;': 'ϕ', + 'varpi;': 'ϖ', + 'varpropto;': '∝', + 'varr;': '↕', + 'varrho;': 'ϱ', + 'varsigma;': 'ς', + 'varsubsetneq;': '⊊︀', + 'varsubsetneqq;': '⫋︀', + 'varsupsetneq;': '⊋︀', + 'varsupsetneqq;': '⫌︀', + 'vartheta;': 'ϑ', + 'vartriangleleft;': '⊲', + 'vartriangleright;': '⊳', + 'vcy;': 'в', + 'vdash;': '⊢', + 'vee;': '∨', + 'veebar;': '⊻', + 'veeeq;': '≚', + 'vellip;': '⋮', + 'verbar;': '|', + 'vert;': '|', + 'vfr;': '𝔳', + 'vltri;': '⊲', + 'vnsub;': '⊂⃒', + 'vnsup;': '⊃⃒', + 'vopf;': '𝕧', + 'vprop;': '∝', + 'vrtri;': '⊳', + 'vscr;': '𝓋', + 'vsubnE;': '⫋︀', + 'vsubne;': '⊊︀', + 'vsupnE;': '⫌︀', + 'vsupne;': '⊋︀', + 'vzigzag;': '⦚', + 'wcirc;': 'ŵ', + 'wedbar;': '⩟', + 'wedge;': '∧', + 'wedgeq;': '≙', + 'weierp;': '℘', + 'wfr;': '𝔴', + 'wopf;': '𝕨', + 'wp;': '℘', + 'wr;': '≀', + 'wreath;': '≀', + 'wscr;': '𝓌', + 'xcap;': '⋂', + 'xcirc;': '◯', + 'xcup;': '⋃', + 'xdtri;': '▽', + 'xfr;': '𝔵', + 'xhArr;': '⟺', + 'xharr;': '⟷', + 'xi;': 'ξ', + 'xlArr;': '⟸', + 'xlarr;': '⟵', + 'xmap;': '⟼', + 'xnis;': '⋻', + 'xodot;': '⨀', + 'xopf;': '𝕩', + 'xoplus;': '⨁', + 'xotime;': '⨂', + 'xrArr;': '⟹', + 'xrarr;': '⟶', + 'xscr;': '𝓍', + 'xsqcup;': '⨆', + 'xuplus;': '⨄', + 'xutri;': '△', + 'xvee;': '⋁', + 'xwedge;': '⋀', + yacute: 'ý', + 'yacute;': 'ý', + 'yacy;': 'я', + 'ycirc;': 'ŷ', + 'ycy;': 'ы', + yen: '¥', + 'yen;': '¥', + 'yfr;': '𝔶', + 'yicy;': 'ї', + 'yopf;': '𝕪', + 'yscr;': '𝓎', + 'yucy;': 'ю', + yuml: 'ÿ', + 'yuml;': 'ÿ', + 'zacute;': 'ź', + 'zcaron;': 'ž', + 'zcy;': 'з', + 'zdot;': 'ż', + 'zeetrf;': 'ℨ', + 'zeta;': 'ζ', + 'zfr;': '𝔷', + 'zhcy;': 'ж', + 'zigrarr;': '⇝', + 'zopf;': '𝕫', + 'zscr;': '𝓏', + 'zwj;': '‍', + 'zwnj;': '‌', +} diff --git a/packages/md-core/src/entities.ts b/packages/md-core/src/entities.ts new file mode 100644 index 0000000..3dd7be4 --- /dev/null +++ b/packages/md-core/src/entities.ts @@ -0,0 +1,84 @@ +import { ENTITIES } from './entities-table.ts' + +// character references, decoded as the html tokenizer does: the full named table (legacy names also without ';', the +// longest one that matches), the attribute exception, and numeric references with the spec's replacements +const NAMED = new Map(Object.entries(ENTITIES)) +// the longest name the table has without a ';' +let LEGACY_MAX = 0 +for (const name of NAMED.keys()) + if (!name.endsWith(';')) LEGACY_MAX = Math.max(LEGACY_MAX, name.length) +// the longest name with its ';', so a run of letters past it can't be one +const NAME_MAX = 32 + +// €-Ÿ are read as windows-1252, as browsers always have; 0 keeps the code point +const C1 = [ + 0x20ac, 0, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, + 0, 0x017d, 0, 0, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, + 0x203a, 0x0153, 0, 0x017e, 0x0178, +] + +const numeric = (code: number) => { + if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return '\uFFFD' + if (code >= 0x80 && code <= 0x9f && C1[code - 0x80]) return String.fromCharCode(C1[code - 0x80]!) + return String.fromCodePoint(code) +} + +const alnum = (c: number) => (c >= 48 && c <= 57) || ((c | 32) >= 97 && (c | 32) <= 122) + +// attribute: decoding an attribute's value, where a legacy name followed by '=' or an alphanumeric isn't a reference +export const decode = (text: string, attribute = false): string => { + let amp = text.indexOf('&') + if (amp < 0) return text + const n = text.length + let out = '' + let from = 0 + while (amp >= 0) { + const i = amp + 1 + let value: string | undefined + let end = i + if (text.charCodeAt(i) === 35) { + // { or {, the ';' optional; with no digits it is only text + let j = i + 1 + const hex = (text.charCodeAt(j) | 32) === 120 + if (hex) j++ + const digits = j + let code = 0 + for (; j < n; j++) { + const c = text.charCodeAt(j) + let digit: number + if (c >= 48 && c <= 57) digit = c - 48 + else if (hex && (c | 32) >= 97 && (c | 32) <= 102) digit = (c | 32) - 87 + else break + // past the last code point it stays past it, without growing toward a float + if (code <= 0x10ffff) code = code * (hex ? 16 : 10) + digit + } + if (j > digits) { + value = numeric(code) + end = text.charCodeAt(j) === 59 ? j + 1 : j + } + } else { + let j = i + while (j < n && j - i <= NAME_MAX && alnum(text.charCodeAt(j))) j++ + if (j > i) { + if (text.charCodeAt(j) === 59) value = NAMED.get(text.slice(i, j + 1)) + if (value !== undefined) end = j + 1 + else + // without its ';', the longest legacy name the letters start with + for (let k = Math.min(j, i + LEGACY_MAX); k > i; k--) { + value = NAMED.get(text.slice(i, k)) + if (value === undefined) continue + const next = text.charCodeAt(k) + if (attribute && (next === 61 || alnum(next))) value = undefined + else end = k + break + } + } + } + if (value !== undefined) { + out += text.slice(from, amp) + value + from = end + } + amp = text.indexOf('&', end) + } + return from === 0 ? text : from >= n ? out : out + text.slice(from) +} diff --git a/packages/md-core/src/index.ts b/packages/md-core/src/index.ts new file mode 100644 index 0000000..8c4489a --- /dev/null +++ b/packages/md-core/src/index.ts @@ -0,0 +1,13 @@ +import { emit } from './emit.ts' +import { parse } from './parse.ts' +import type { Options, Result } from './types.ts' + +export type { Document, Element, Head, Node, Options, Result } from './types.ts' +export { emit } from './emit.ts' +export { parse } from './parse.ts' + +// html to markdown in two passes over the page and none over a generic tree: a skip-scanning parser that builds only +// what can be content, and an emitter that writes markdown straight from that. the output aims to be +// @affordances/md's, byte for byte +export const htmlToMarkdown = (html: string, options: Options = {}): Result => + emit(parse(html), options) diff --git a/packages/md-core/src/parse.ts b/packages/md-core/src/parse.ts new file mode 100644 index 0000000..142bc3c --- /dev/null +++ b/packages/md-core/src/parse.ts @@ -0,0 +1,2886 @@ +import { attr, parseAttrs } from './attr.ts' +import { decode } from './entities.ts' +import { NEVER, type Document, type Element, type Head, type Node } from './types.ts' + +// html to a Document in one scan, as a browser with scripting off reads it. the tokenizer jumps between '<' with +// indexOf, takes raw text (script, style) and attribute values whole, and never builds comments or the doctype. the +// tree builder is the html spec's, as parse5 implements it (the oracle the tests hold this to): insertion modes, +// implied end tags, the adoption agency, foster parenting, foreign content. what NEVER names is still put on the stack +// (the algorithm needs it to know where things end) but never into its parent's kids, its text is never kept, and +// inside svg nothing is kept at all + +// what the parser knows of an element beyond the contract: its tag's number, its namespace, and what it keeps +interface El extends Element { + up: El | null + id: number + ns: number + // what it keeps while the page is parsed: 3 all text, even a dropped element's (inside what the Head reads whole: a + // foreign title, or json-ld); 2 text; 1 no text (a dropped element); 0 nothing at all (inside svg, where nothing can + // ever leave). every element but inside svg keeps its children, dropped ones too, until the parse ends: the + // adoption agency and foster parenting place nodes by them, and the Head is read in their order + rec: number + // whether a dropped child is among its kids, to take out at the end + drops: boolean +} + +const HTML = 0 +const SVG = 1 +const MATH = 2 + +// tag numbers: what the tree builder switches on. unknown tags are 0, and compare by name +const NAMES = ( + 'a address annotation-xml applet area article aside audio b base basefont bgsound big blockquote body br button ' + + 'canvas caption center code col colgroup dd desc details dialog dir div dl dt em embed fieldset figcaption figure ' + + 'font footer foreignObject form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe image img ' + + 'input keygen label li link listing main malignmark marquee math menu meta mglyph mi mn mo ms mtext nav nobr ' + + 'noembed noframes noscript object ol optgroup option p param plaintext pre rb rp rt rtc ruby s script search ' + + 'section select small source span strike strong style sub summary sup svg table tbody td template textarea tfoot ' + + 'th thead title tr track tt u ul var video wbr xmp' +).split(' ') +const IDS = new Map(NAMES.map((name, i) => [name, i + 1])) +const T = (name: string) => { + const id = IDS.get(name) + if (id === undefined) throw new Error(`no tag ${name}`) + return id +} +const set = (names: string) => { + const ids = new Uint8Array(NAMES.length + 1) + for (const name of names.split(' ')) ids[T(name)] = 1 + return ids +} + +const A = T('a') +const ADDRESS = T('address') +const ANNOTATION_XML = T('annotation-xml') +const APPLET = T('applet') +const AREA = T('area') +const ARTICLE = T('article') +const ASIDE = T('aside') +const B = T('b') +const BASE = T('base') +const BASEFONT = T('basefont') +const BGSOUND = T('bgsound') +const BIG = T('big') +const BLOCKQUOTE = T('blockquote') +const BODY = T('body') +const BR = T('br') +const BUTTON = T('button') +const CAPTION = T('caption') +const CENTER = T('center') +const CODE = T('code') +const T_DESC = T('desc') +const COL = T('col') +const COLGROUP = T('colgroup') +const DD = T('dd') +const DETAILS = T('details') +const DIALOG = T('dialog') +const DIR = T('dir') +const DIV = T('div') +const DL = T('dl') +const DT = T('dt') +const EM = T('em') +const EMBED = T('embed') +const FIELDSET = T('fieldset') +const FIGCAPTION = T('figcaption') +const FIGURE = T('figure') +const FONT = T('font') +const FOOTER = T('footer') +const FOREIGN_OBJECT = T('foreignObject') +const FORM = T('form') +const FRAME = T('frame') +const FRAMESET = T('frameset') +const H1 = T('h1') +const H2 = T('h2') +const H3 = T('h3') +const H4 = T('h4') +const H5 = T('h5') +const H6 = T('h6') +const HEAD = T('head') +const HEADER = T('header') +const HGROUP = T('hgroup') +const HR = T('hr') +const HTML_TAG = T('html') +const I = T('i') +const IFRAME = T('iframe') +const IMAGE = T('image') +const IMG = T('img') +const INPUT = T('input') +const KEYGEN = T('keygen') +const LI = T('li') +const LINK = T('link') +const LISTING = T('listing') +const MAIN = T('main') +const MALIGNMARK = T('malignmark') +const MARQUEE = T('marquee') +const MATH_TAG = T('math') +const MENU = T('menu') +const META = T('meta') +const MGLYPH = T('mglyph') +const NAV = T('nav') +const NOBR = T('nobr') +const NOEMBED = T('noembed') +const NOFRAMES = T('noframes') +const NOSCRIPT = T('noscript') +const OBJECT = T('object') +const OL = T('ol') +const OPTGROUP = T('optgroup') +const OPTION = T('option') +const P = T('p') +const PARAM = T('param') +const PLAINTEXT = T('plaintext') +const PRE = T('pre') +const RB = T('rb') +const RP = T('rp') +const RT = T('rt') +const RTC = T('rtc') +const RUBY = T('ruby') +const S = T('s') +const SCRIPT = T('script') +const SEARCH = T('search') +const SECTION = T('section') +const SELECT = T('select') +const SMALL = T('small') +const SOURCE = T('source') +const STRIKE = T('strike') +const STRONG = T('strong') +const STYLE = T('style') +const SUMMARY = T('summary') +const SVG_TAG = T('svg') +const TABLE = T('table') +const TBODY = T('tbody') +const TD = T('td') +const TEMPLATE = T('template') +const TEXTAREA = T('textarea') +const TFOOT = T('tfoot') +const TH = T('th') +const THEAD = T('thead') +const TITLE = T('title') +const TR = T('tr') +const TRACK = T('track') +const TT = T('tt') +const U = T('u') +const UL = T('ul') +const WBR = T('wbr') +const XMP = T('xmp') + +const DROP = set([...NEVER].join(' ')) +// elements the Head is read from +const WATCH = set('html title meta link script') +const SPECIAL_HTML = set( + 'address applet area article aside base basefont bgsound blockquote body br button caption center col colgroup dd ' + + 'details dir div dl dt embed fieldset figcaption figure footer form frame frameset h1 h2 h3 h4 h5 h6 head header ' + + 'hgroup hr html iframe img input li link listing main marquee menu meta nav noembed noframes noscript object ol p ' + + 'param plaintext pre script section select source style summary table tbody td template textarea tfoot th thead ' + + 'title tr track ul wbr xmp', +) +const SPECIAL_MATH = set('mi mo mn ms mtext annotation-xml') +const SPECIAL_SVG = set('title foreignObject desc') +const HEADINGS = set('h1 h2 h3 h4 h5 h6') +const IMPLIED = set('dd dt li optgroup option p rb rp rt rtc') +const IMPLIED_ALL = set( + 'dd dt li optgroup option p rb rp rt rtc caption colgroup tbody td tfoot th thead tr', +) +const SCOPE = set('applet caption html marquee object table td template th') +const LIST_SCOPE = set('applet caption html marquee object table td template th ol ul') +const BUTTON_SCOPE = set('applet caption html marquee object table td template th button') +const TABLE_CONTEXT = set('table template html') +const TABLE_BODY_CONTEXT = set('tbody tfoot thead template html') +const TABLE_ROW_CONTEXT = set('tr template html') +const CELLS = set('td th') +const FOSTERING = set('table tbody tfoot thead tr') +const TABLE_VOID = set('caption col colgroup tbody td tfoot th thead tr') +const MATH_TEXT = set('mi mo mn ms mtext') +const EXITS_FOREIGN = set( + 'b big blockquote body br center code dd div dl dt em embed h1 h2 h3 h4 h5 h6 head hr i img li listing menu meta ' + + 'nobr ol p pre ruby s small span strong strike sub sup table tt u ul var', +) +const SVG_TAGS = new Map( + ( + 'altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix ' + + 'feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feFlood ' + + 'feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight ' + + 'feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath' + ) + .split(' ') + .map((name) => [name.toLowerCase(), name]), +) +// foreign attributes parse5 renames to their local name (the oracle writes that name) +const XML_ATTRS = new Map([ + ['xlink:actuate', 'actuate'], + ['xlink:arcrole', 'arcrole'], + ['xlink:href', 'href'], + ['xlink:role', 'role'], + ['xlink:show', 'show'], + ['xlink:title', 'title'], + ['xlink:type', 'type'], + ['xml:lang', 'lang'], + ['xml:space', 'space'], + ['xmlns', 'xmlns'], + ['xmlns:xlink', 'xlink'], +]) + +// insertion modes +const INITIAL = 0 +const BEFORE_HTML = 1 +const BEFORE_HEAD = 2 +const IN_HEAD = 3 +const IN_HEAD_NOSCRIPT = 4 +const AFTER_HEAD = 5 +const IN_BODY = 6 +const TEXT = 7 +const IN_TABLE = 8 +const IN_TABLE_TEXT = 9 +const IN_CAPTION = 10 +const IN_COLUMN_GROUP = 11 +const IN_TABLE_BODY = 12 +const IN_ROW = 13 +const IN_CELL = 14 +const IN_SELECT = 15 +const IN_SELECT_IN_TABLE = 16 +const IN_TEMPLATE = 17 +const AFTER_BODY = 18 +const IN_FRAMESET = 19 +const AFTER_FRAMESET = 20 +const AFTER_AFTER_BODY = 21 +const AFTER_AFTER_FRAMESET = 22 + +// tokenizer states the tree builder switches to; the rest live inside the scanning functions +const DATA = 0 +const RCDATA = 1 +const RAWTEXT = 2 +const SCRIPT_DATA = 3 +const PLAIN = 4 + +// the token being processed, for the modes that hand it on +const START = 1 +const END = 2 +const CHARS = 3 +const SPACE = 4 +const NUL = 5 +const COMMENT = 6 +const DOCTYPE = 7 +const EOF = 8 + +// the parse's state: module-level, since a parse runs to completion and the hot paths read it constantly +let html = '' +let n = 0 +// the next '&' and '<!--' at or after where they were last looked for (n: none), so neither is searched for twice +let amp = 0 +let commentOpen = 0 +let tstate = DATA +let rawTag = '' + +let doc: El +let stack: El[] = [] +let pCount = 0 +let tmplCount = 0 +// active formatting elements, the most recent last; null is a marker +let afe: (Entry | null)[] = [] +let tmplModes: number[] = [] +let mode = INITIAL +let origMode = INITIAL +let quirks = false +let framesetOk = true +let foster = false +let skipNL = false +let headEl: El | null = null +let formEl: El | null = null +let htmlEl: El | null = null +let bodyEl: El | null = null +let bodyGone = false +let pending: string[] = [] +let pendingText = false +let watched: El[] = [] +let pruned: El[] = [] +// whether a node was put anywhere but after everything before it: then the Head's elements are sorted into tree order +let reordered = false + +let tok = 0 +let tag = '' +let tid = 0 +let tattrs = '' +let tself = false +let ttext = '' + +interface Entry { + el: El + tag: string + id: number + attrs: string +} + +const lowerAscii = (text: string) => + text.replace(/[A-Z\0]/g, (c) => + c === '\0' ? '\uFFFD' : String.fromCharCode(c.charCodeAt(0) | 32), + ) +// the tree builder's whitespace, as parse5 has it: a cr only gets this far from , and isn't +const space = (c: number) => c === 32 || c === 10 || c === 9 || c === 12 +const alpha = (c: number) => (c | 32) >= 97 && (c | 32) <= 122 +const allSpace = (text: string) => { + for (let i = 0; i < text.length; i++) if (!space(text.charCodeAt(i))) return false + return true +} +const quote = (value: string) => value.replaceAll('&', '&').replaceAll('"', '"') +const serialize = (map: Map<string, string>) => { + let out = '' + for (const [name, value] of map) out += ` ${name}="${quote(value)}"` + return out +} + +// tree + +const make = (name: string, id: number, ns: number, attrs: string): El => { + const el: El = { + tag: name, + attrs, + kids: [], + up: null, + map: undefined, + id, + ns, + rec: ns === SVG ? 0 : DROP[id] ? 1 : 2, + drops: false, + } + // the Head's elements; of the scripts and links, only those that could be json-ld or the canonical link + if (WATCH[id]) { + if (id === SCRIPT) { + if (maybe(attrs, 'ld+json') && attr(el, 'type') === 'application/ld+json') { + watched.push(el) + keepAll(el) + } + } else if (id !== LINK || maybe(attrs, 'canonical')) { + watched.push(el) + // a foreign title is read by all the text inside it, even what is in a dropped element + if (id === TITLE && ns !== HTML) keepAll(el) + } + } + return el +} +const keepAll = (el: El) => { + el.rec = 3 +} +// the current node, kept as the stack changes: the tree builder asks for it constantly +let current: El +const cur = () => current +// whether attributes might say something, before parsing them: the word, or a reference that could spell it +const maybe = (attrs: string, word: string) => attrs.indexOf(word) >= 0 || attrs.indexOf('&') >= 0 +const settle = () => { + current = stack[stack.length - 1] ?? doc +} + +const adopted = (parent: El, el: El) => { + if (parent.rec === 3 && el.rec !== 3) keepAll(el) + if (DROP[el.id] && !parent.drops) dropsIn(parent) +} +const dropsIn = (parent: El) => { + parent.drops = true + pruned.push(parent) +} +const appendChild = (parent: El, el: El) => { + el.up = parent + if (parent.rec === 0) return + adopted(parent, el) + parent.kids.push(el) +} +const appendText = (parent: El, text: string) => { + if (parent.rec < 2) return + const kids = parent.kids + const last = kids.length - 1 + if (last >= 0 && typeof kids[last] === 'string') kids[last] += text + else kids.push(text) +} +const insertBefore = (parent: El, el: El, ref: El) => { + el.up = parent + if (parent.rec === 0) return + adopted(parent, el) + reordered = true + const at = parent.kids.lastIndexOf(ref) + if (at < 0) parent.kids.push(el) + else parent.kids.splice(at, 0, el) +} +const insertTextBefore = (parent: El, text: string, ref: El) => { + if (parent.rec < 2) return + const kids = parent.kids + const at = kids.lastIndexOf(ref) + if (at < 0) appendText(parent, text) + else if (at > 0 && typeof kids[at - 1] === 'string') kids[at - 1] += text + else kids.splice(at, 0, text) +} +const detach = (el: El) => { + const parent = el.up + if (!parent) return + el.up = null + const kids = parent.kids + const at = kids.lastIndexOf(el) + if (at < 0) return + kids.splice(at, 1) + // the text either side is one text again + if (at > 0 && typeof kids[at - 1] === 'string' && typeof kids[at] === 'string') { + kids[at - 1] += kids[at] as string + kids.splice(at, 1) + } +} + +const fosterPlace = (): [El, El | null] => { + for (let i = stack.length - 1; i >= 0; i--) { + const el = stack[i]! + if (el.id === TEMPLATE && el.ns === HTML) return [el, null] + if (el.id === TABLE) return el.up ? [el.up, el] : [stack[i - 1]!, null] + } + return [stack[0]!, null] +} +const fosterElement = (el: El) => { + const [parent, before] = fosterPlace() + if (before) insertBefore(parent, el, before) + else appendChild(parent, el) +} +const attach = (el: El) => { + const parent = cur() + if (foster && FOSTERING[parent.id]) fosterElement(el) + else appendChild(parent, el) +} +const insertText = (text: string) => { + const parent = cur() + if (foster && FOSTERING[parent.id]) { + const [at, before] = fosterPlace() + if (before) insertTextBefore(at, text, before) + else appendText(at, text) + } else appendText(parent, text) +} + +// the stack of open elements +const push = (el: El) => { + stack.push(el) + current = el + if (el.ns === HTML) { + if (el.id === P) pCount++ + else if (el.id === TEMPLATE) tmplCount++ + } +} +const gone = (el: El) => { + if (el.ns === HTML) { + if (el.id === P) pCount-- + else if (el.id === TEMPLATE) tmplCount-- + } +} +const pop = () => { + const el = stack.pop() + if (el) gone(el) + current = stack[stack.length - 1] ?? doc +} +const shortenTo = (length: number) => { + while (stack.length > length) pop() +} +const removeEl = (el: El) => { + const at = stack.lastIndexOf(el) + if (at < 0) return + stack.splice(at, 1) + gone(el) + settle() +} + +const insert = (name: string, id: number, ns: number, attrs: string) => { + const el = make(name, id, ns, attrs) + attach(el) + push(el) + return el +} +const insertTok = () => insert(tag, tid, HTML, tattrs) +const appendTok = () => attach(make(tag, tid, HTML, tattrs)) +const insertFake = (name: string, id: number) => insert(name, id, HTML, '') + +const special = (el: El) => + (el.ns === HTML ? SPECIAL_HTML : el.ns === MATH ? SPECIAL_MATH : SPECIAL_SVG)[el.id] === 1 +const foreignScope = (el: El) => (el.ns === SVG ? SPECIAL_SVG : SPECIAL_MATH)[el.id] === 1 + +const inScopeOf = (id: number, boundary: Uint8Array) => { + for (let i = stack.length - 1; i >= 0; i--) { + const el = stack[i]! + if (el.ns === HTML) { + if (el.id === id) return true + if (boundary[el.id]) return false + } else if (foreignScope(el)) return false + } + return true +} +const inScope = (id: number) => inScopeOf(id, SCOPE) +const pInButtonScope = () => pCount > 0 && inScopeOf(P, BUTTON_SCOPE) +const headingInScope = () => { + for (let i = stack.length - 1; i >= 0; i--) { + const el = stack[i]! + if (el.ns === HTML) { + if (HEADINGS[el.id]) return true + if (SCOPE[el.id]) return false + } else if (foreignScope(el)) return false + } + return true +} +const inTableScope = (id: number) => { + for (let i = stack.length - 1; i >= 0; i--) { + const el = stack[i]! + if (el.ns !== HTML) continue + if (el.id === id) return true + if (el.id === TABLE || el.id === HTML_TAG) return false + } + return true +} +const tableBodyInTableScope = () => { + for (let i = stack.length - 1; i >= 0; i--) { + const el = stack[i]! + if (el.ns !== HTML) continue + if (el.id === TBODY || el.id === THEAD || el.id === TFOOT) return true + if (el.id === TABLE || el.id === HTML_TAG) return false + } + return true +} +const inSelectScope = (id: number) => { + for (let i = stack.length - 1; i >= 0; i--) { + const el = stack[i]! + if (el.ns !== HTML) continue + if (el.id === id) return true + if (el.id !== OPTION && el.id !== OPTGROUP) return false + } + return true +} + +const impliedEnds = () => { + while (IMPLIED[cur().id]) pop() +} +const impliedEndsAll = () => { + while (IMPLIED_ALL[cur().id]) pop() +} +const impliedEndsBut = (id: number) => { + for (let c = cur(); c.id !== id && IMPLIED_ALL[c.id]; c = cur()) pop() +} +// pops through the last html element with that tag (at the bottom, any), or everything +const popThrough = (id: number) => { + let i = stack.length - 1 + while (i >= 0 && !(stack[i]!.id === id && (stack[i]!.ns === HTML || i === 0))) i-- + shortenTo(Math.max(i, 0)) +} +const popThroughOf = (ids: Uint8Array) => { + let i = stack.length - 1 + while (i >= 0 && !(ids[stack[i]!.id] && stack[i]!.ns === HTML)) i-- + shortenTo(Math.max(i, 0)) +} +const clearBackTo = (ids: Uint8Array) => { + let i = stack.length - 1 + while (i >= 0 && !(ids[stack[i]!.id] && stack[i]!.ns === HTML)) i-- + shortenTo(i + 1) +} +const closeP = () => { + impliedEndsBut(P) + popThrough(P) +} + +// active formatting elements +const afeByTag = (name: string) => { + for (let i = afe.length - 1; i >= 0; i--) { + const entry = afe[i]! + if (entry === null) return null + if (entry.el.tag === name) return entry + } + return null +} +const afeOf = (el: El) => { + for (let i = afe.length - 1; i >= 0; i--) if (afe[i]?.el === el) return afe[i]! + return undefined +} +const afeRemove = (entry: Entry) => { + const at = afe.lastIndexOf(entry) + if (at >= 0) afe.splice(at, 1) +} +const clearToMarker = () => { + const at = afe.lastIndexOf(null) + afe.length = at < 0 ? 0 : at +} +const attrsOf = (el: El) => (el.attrs === '' ? EMPTY : (el.map ??= parseAttrs(el.attrs))) +const EMPTY = new Map<string, string>() +// noah's ark: no more than three of the same element since the last marker. ported with parse5's indexing (most +// recent first, removing by indexes taken before any removal), since that is the oracle +const noah = (el: El) => { + if (afe.length < 3) return + const own = attrsOf(el) + const list = afe.toReversed() + const candidates: number[] = [] + for (let i = 0; i < list.length; i++) { + const entry = list[i]! + if (entry === null) break + if (entry.el.tag === el.tag && entry.el.ns === el.ns && attrsOf(entry.el).size === own.size) + candidates.push(i) + } + if (candidates.length < 3) return + const lists = candidates.map((i) => attrsOf(list[i]!.el)) + let valid = 0 + for (let c = 0; c < candidates.length; c++) { + let same = true + for (const [name, value] of lists[c]!) if (own.get(name) !== value) same = false + if (same && ++valid >= 3) list.splice(candidates[c]!, 1) + } + afe = list.toReversed() +} +const afePush = (el: El) => { + noah(el) + afe.push({ el, tag: el.tag, id: el.id, attrs: el.attrs }) +} +const reconstruct = () => { + if (afe.length !== 0) rebuild() +} +const rebuild = () => { + const length = afe.length + let i = length - 1 + const last = afe[i]! + if (last === null || stack.lastIndexOf(last.el) >= 0) return + while (i > 0) { + const entry = afe[i - 1]! + if (entry === null || stack.lastIndexOf(entry.el) >= 0) break + i-- + } + for (; i < length; i++) { + const entry = afe[i]! + entry.el = insert(entry.tag, entry.id, entry.el.ns, entry.attrs) + } +} + +// the adoption agency: misnested formatting (<b><p></b>) closed as browsers do +const adoption = () => { + for (let outer = 0; outer < 8; outer++) { + const entry = afeByTag(tag) + if (!entry) { + genericEndInBody() + return + } + if (stack.lastIndexOf(entry.el) < 0) { + afeRemove(entry) + return + } + if (!inScope(tid)) return + const formatting = entry.el + let furthest: El | null = null + let at = stack.length - 1 + for (; at >= 0; at--) { + const el = stack[at]! + if (el === formatting) break + if (special(el)) furthest = el + } + if (!furthest) { + shortenTo(Math.max(at, 0)) + afeRemove(entry) + return + } + let bookmark = entry + let last = furthest + let next = stack[stack.lastIndexOf(furthest) - 1] ?? null + for (let inner = 0, node = next; node !== formatting; inner++, node = next) { + next = stack[stack.lastIndexOf(node!) - 1] ?? null + const nodeEntry = afeOf(node!) + const overflow = nodeEntry && inner >= 3 + if (!nodeEntry || overflow) { + if (overflow) afeRemove(nodeEntry) + removeEl(node!) + } else { + const clone = make(nodeEntry.tag, nodeEntry.id, nodeEntry.el.ns, nodeEntry.attrs) + stack[stack.lastIndexOf(node!)] = clone + settle() + nodeEntry.el = clone + if (last === furthest) bookmark = nodeEntry + detach(last) + appendChild(clone, last) + last = clone + } + } + const common = stack[stack.lastIndexOf(formatting) - 1] ?? null + detach(last) + if (common) { + if (FOSTERING[common.id]) fosterElement(last) + else appendChild(common, last) + } + const clone = make(entry.tag, entry.id, formatting.ns, entry.attrs) + // the furthest block's children move into the new formatting element + reordered = true + clone.kids = furthest.kids + for (const kid of clone.kids) if (typeof kid !== 'string') kid.up = clone + if (furthest.drops) dropsIn(clone) + furthest.kids = [] + appendChild(furthest, clone) + const mark = afe.lastIndexOf(bookmark) + afe.splice(mark + 1, 0, { el: clone, tag: entry.tag, id: entry.id, attrs: entry.attrs }) + afeRemove(entry) + removeEl(formatting) + stack.splice(stack.lastIndexOf(furthest) + 1, 0, clone) + settle() + } +} + +const resetMode = () => { + for (let i = stack.length - 1; i >= 0; i--) { + switch (stack[i]!.id) { + case TR: + mode = IN_ROW + return + case TBODY: + case THEAD: + case TFOOT: + mode = IN_TABLE_BODY + return + case CAPTION: + mode = IN_CAPTION + return + case COLGROUP: + mode = IN_COLUMN_GROUP + return + case TABLE: + mode = IN_TABLE + return + case BODY: + mode = IN_BODY + return + case FRAMESET: + mode = IN_FRAMESET + return + case SELECT: + mode = IN_SELECT + for (let j = i - 1; j > 0; j--) { + const id = stack[j]!.id + if (id === TEMPLATE) break + if (id === TABLE) { + mode = IN_SELECT_IN_TABLE + break + } + } + return + case TEMPLATE: + mode = tmplModes[tmplModes.length - 1]! + return + case HTML_TAG: + mode = headEl ? AFTER_HEAD : BEFORE_HEAD + return + case TD: + case TH: + if (i > 0) { + mode = IN_CELL + return + } + break + case HEAD: + if (i > 0) { + mode = IN_HEAD + return + } + break + } + } + mode = IN_BODY +} + +// foreign content + +const htmlIntegration = (el: El) => { + if (el.ns === SVG) return el.id === FOREIGN_OBJECT || el.id === T_DESC || el.id === TITLE + if (el.ns !== MATH || el.id !== ANNOTATION_XML) return false + const encoding = attr(el, 'encoding')?.toLowerCase() + return encoding === 'text/html' || encoding === 'application/xhtml+xml' +} +const integration = (el: El) => htmlIntegration(el) || (el.ns === MATH && MATH_TEXT[el.id] === 1) +const inForeign = () => { + const c = cur() + return c.ns !== HTML && !integration(c) +} +const foreignStart = () => { + const c = cur() + if (c.ns === HTML) return false + if (tid === SVG_TAG && c.id === ANNOTATION_XML && c.ns === MATH) return false + return !integration(c) || ((tid === MGLYPH || tid === MALIGNMARK) && !htmlIntegration(c)) +} +const popToHtmlOrIntegration = () => { + for (let c = cur(); c.ns !== HTML && !integration(c); c = cur()) pop() +} +// math attributes as the oracle names them: xlink:href is href +const mathAttrs = (source: string) => { + if (!/xlink:|xml:|xmlns/i.test(source)) return source + const map = parseAttrs(source) + let out = '' + for (const [name, value] of map) out += ` ${XML_ATTRS.get(name) ?? name}="${quote(value)}"` + return out +} +const startInForeign = () => { + if ( + EXITS_FOREIGN[tid] || + (tid === FONT && tattrs !== '' && /color|face|size/i.test(tattrs) && fontExits()) + ) { + popToHtmlOrIntegration() + startOutside() + return + } + const ns = cur().ns + let name = tag + let id = tid + let attrs = tattrs + if (ns === SVG) { + name = SVG_TAGS.get(tag) ?? tag + if (name === 'foreignObject') id = FOREIGN_OBJECT + } else if (attrs !== '') attrs = mathAttrs(attrs) + if (!tself) insert(name, id, ns, attrs) + // a self-closed svg child is nothing anyone will read, unless the Head reads it + else if (ns !== SVG || WATCH[id] || cur().rec !== 0) attach(make(name, id, ns, attrs)) +} +const fontExits = () => { + const map = parseAttrs(tattrs) + return map.has('color') || map.has('face') || map.has('size') +} +const endInForeign = () => { + if (tid === P || tid === BR) { + popToHtmlOrIntegration() + endOutside() + return + } + for (let i = stack.length - 1; i > 0; i--) { + const el = stack[i]! + if (el.ns === HTML) { + endOutside() + return + } + if (el.tag === tag || (el.ns === SVG && el.tag.toLowerCase() === tag)) { + shortenTo(i) + return + } + } +} + +// token dispatch + +const dispatch = () => { + switch (tok) { + case START: + return processStart() + case END: + return processEnd() + case CHARS: + return onChars(ttext) + case SPACE: + return onSpace(ttext) + case NUL: + return onNul() + case COMMENT: + return onComment() + case DOCTYPE: + return onDoctype() + case EOF: + return onEof() + } +} +const processStart = () => (foreignStart() ? startInForeign() : startOutside()) +const processEnd = () => (cur().ns !== HTML ? endInForeign() : endOutside()) + +// text from the tokenizer: the common modes take it whole; the rest see it as the tokenizer's runs of whitespace and +// other characters, which they treat apart +const chars = (input: string) => { + let text = input + if (skipNL) { + skipNL = false + if (text.charCodeAt(0) === 10) { + text = text.slice(1) + if (text === '') return + } + } + const c = cur() + if (c.ns !== HTML && !integration(c)) { + insertText(text) + if (framesetOk && !allSpace(text)) framesetOk = false + return + } + switch (mode) { + case IN_BODY: + case IN_CAPTION: + case IN_CELL: + case IN_TEMPLATE: + reconstruct() + insertText(text) + if (framesetOk && !allSpace(text)) framesetOk = false + return + case TEXT: + case IN_SELECT: + case IN_SELECT_IN_TABLE: + insertText(text) + return + case IN_TABLE: + case IN_TABLE_BODY: + case IN_ROW: + charsInTable(text, !allSpace(text)) + return + case IN_TABLE_TEXT: + pending.push(text) + if (!pendingText && !allSpace(text)) pendingText = true + return + } + for (let i = 0; i < text.length;) { + const blank = space(text.charCodeAt(i)) + let j = i + 1 + while (j < text.length && space(text.charCodeAt(j)) === blank) j++ + if (blank) onSpace(text.slice(i, j)) + else onChars(text.slice(i, j)) + i = j + } +} +const onChars = (text: string) => { + tok = CHARS + ttext = text + if (inForeign()) { + insertText(text) + framesetOk = false + return + } + switch (mode) { + case INITIAL: + return initialAnything() + case BEFORE_HTML: + return beforeHtmlAnything() + case BEFORE_HEAD: + return beforeHeadAnything() + case IN_HEAD: + return inHeadAnything() + case IN_HEAD_NOSCRIPT: + return noscriptAnything() + case AFTER_HEAD: + return afterHeadAnything() + case IN_BODY: + case IN_CAPTION: + case IN_CELL: + case IN_TEMPLATE: + reconstruct() + insertText(text) + framesetOk = false + return + case TEXT: + case IN_SELECT: + case IN_SELECT_IN_TABLE: + return insertText(text) + case IN_TABLE: + case IN_TABLE_BODY: + case IN_ROW: + return charsInTable(text, true) + case IN_TABLE_TEXT: + pending.push(text) + pendingText = true + return + case IN_COLUMN_GROUP: + return columnGroupAnything() + case AFTER_BODY: + case AFTER_AFTER_BODY: + return afterBodyAnything() + } +} +const onSpace = (text: string) => { + tok = SPACE + ttext = text + if (inForeign()) return insertText(text) + switch (mode) { + case IN_HEAD: + case IN_HEAD_NOSCRIPT: + case AFTER_HEAD: + case TEXT: + case IN_COLUMN_GROUP: + case IN_SELECT: + case IN_SELECT_IN_TABLE: + case IN_FRAMESET: + case AFTER_FRAMESET: + return insertText(text) + case IN_BODY: + case IN_CAPTION: + case IN_CELL: + case IN_TEMPLATE: + case AFTER_BODY: + case AFTER_AFTER_BODY: + case AFTER_AFTER_FRAMESET: + reconstruct() + return insertText(text) + case IN_TABLE: + case IN_TABLE_BODY: + case IN_ROW: + return charsInTable(text, false) + case IN_TABLE_TEXT: + pending.push(text) + return + } +} +const onNul = () => { + tok = NUL + skipNL = false + if (inForeign()) return insertText('\uFFFD') + switch (mode) { + case INITIAL: + return initialAnything() + case BEFORE_HTML: + return beforeHtmlAnything() + case BEFORE_HEAD: + return beforeHeadAnything() + case IN_HEAD: + return inHeadAnything() + case IN_HEAD_NOSCRIPT: + return noscriptAnything() + case AFTER_HEAD: + return afterHeadAnything() + case IN_TABLE: + case IN_TABLE_BODY: + case IN_ROW: + if (FOSTERING[cur().id]) toTableText() + return + case IN_COLUMN_GROUP: + return columnGroupAnything() + case AFTER_BODY: + case AFTER_AFTER_BODY: + return afterBodyAnything() + } +} +const onComment = () => { + tok = COMMENT + skipNL = false + if (mode === IN_TABLE_TEXT && cur().ns === HTML) tableTextAnything() +} +let doctypeQuirks = false +const onDoctype = () => { + tok = DOCTYPE + skipNL = false + if (mode === INITIAL) { + quirks = doctypeQuirks + mode = BEFORE_HTML + } else if (mode === IN_TABLE_TEXT) tableTextAnything() +} +const onEof = () => { + tok = EOF + switch (mode) { + case INITIAL: + return initialAnything() + case BEFORE_HTML: + return beforeHtmlAnything() + case BEFORE_HEAD: + return beforeHeadAnything() + case IN_HEAD: + return inHeadAnything() + case IN_HEAD_NOSCRIPT: + return noscriptAnything() + case AFTER_HEAD: + return afterHeadAnything() + case IN_BODY: + case IN_TABLE: + case IN_CAPTION: + case IN_COLUMN_GROUP: + case IN_TABLE_BODY: + case IN_ROW: + case IN_CELL: + case IN_SELECT: + case IN_SELECT_IN_TABLE: + return eofInBody() + case TEXT: + pop() + mode = origMode + return onEof() + case IN_TABLE_TEXT: + return tableTextAnything() + case IN_TEMPLATE: + return eofInTemplate() + } +} +const eofInBody = () => { + if (tmplModes.length > 0) eofInTemplate() +} +const eofInTemplate = () => { + if (tmplCount === 0) return + popThrough(TEMPLATE) + clearToMarker() + tmplModes.pop() + resetMode() + onEof() +} + +// in body, for the modes that hand a token to it directly +const modeInBody = () => { + switch (tok) { + case START: + return startInBody() + case END: + return endInBody() + case CHARS: + reconstruct() + insertText(ttext) + framesetOk = false + return + case SPACE: + reconstruct() + return insertText(ttext) + case EOF: + return eofInBody() + } +} + +const startOutside = () => { + if (mode === IN_BODY) return startInBody() + switch (mode) { + case INITIAL: + return initialAnything() + case BEFORE_HTML: + if (tid === HTML_TAG) { + htmlEl = insertTok() + mode = BEFORE_HEAD + } else beforeHtmlAnything() + return + case BEFORE_HEAD: + if (tid === HTML_TAG) startInBody() + else if (tid === HEAD) { + headEl = insertTok() + mode = IN_HEAD + } else beforeHeadAnything() + return + case IN_HEAD: + return startInHead() + case IN_HEAD_NOSCRIPT: + return startInHeadNoscript() + case AFTER_HEAD: + return startAfterHead() + case IN_BODY: + return startInBody() + case IN_TABLE: + return startInTable() + case IN_TABLE_TEXT: + return tableTextAnything() + case IN_CAPTION: + return startInCaption() + case IN_COLUMN_GROUP: + return startInColumnGroup() + case IN_TABLE_BODY: + return startInTableBody() + case IN_ROW: + return startInRow() + case IN_CELL: + return startInCell() + case IN_SELECT: + return startInSelect() + case IN_SELECT_IN_TABLE: + return startInSelectInTable() + case IN_TEMPLATE: + return startInTemplate() + case AFTER_BODY: + case AFTER_AFTER_BODY: + if (tid === HTML_TAG) startInBody() + else afterBodyAnything() + return + case IN_FRAMESET: + if (tid === HTML_TAG) startInBody() + else if (tid === FRAMESET) insertTok() + else if (tid === FRAME) appendTok() + else if (tid === NOFRAMES) startInHead() + return + case AFTER_FRAMESET: + case AFTER_AFTER_FRAMESET: + if (tid === HTML_TAG) startInBody() + else if (tid === NOFRAMES) startInHead() + return + } +} +const endOutside = () => { + if (mode === IN_BODY) return endInBody() + switch (mode) { + case INITIAL: + return initialAnything() + case BEFORE_HTML: + if (tid === HTML_TAG || tid === HEAD || tid === BODY || tid === BR) beforeHtmlAnything() + return + case BEFORE_HEAD: + if (tid === HEAD || tid === BODY || tid === HTML_TAG || tid === BR) beforeHeadAnything() + return + case IN_HEAD: + if (tid === HEAD) { + pop() + mode = AFTER_HEAD + } else if (tid === BODY || tid === BR || tid === HTML_TAG) inHeadAnything() + else if (tid === TEMPLATE) templateEnd() + return + case IN_HEAD_NOSCRIPT: + if (tid === NOSCRIPT) { + pop() + mode = IN_HEAD + } else if (tid === BR) noscriptAnything() + return + case AFTER_HEAD: + if (tid === BODY || tid === HTML_TAG || tid === BR) afterHeadAnything() + else if (tid === TEMPLATE) templateEnd() + return + case IN_BODY: + return endInBody() + case TEXT: + pop() + mode = origMode + return + case IN_TABLE: + return endInTable() + case IN_TABLE_TEXT: + return tableTextAnything() + case IN_CAPTION: + return endInCaption() + case IN_COLUMN_GROUP: + return endInColumnGroup() + case IN_TABLE_BODY: + return endInTableBody() + case IN_ROW: + return endInRow() + case IN_CELL: + return endInCell() + case IN_SELECT: + return endInSelect() + case IN_SELECT_IN_TABLE: + return endInSelectInTable() + case IN_TEMPLATE: + if (tid === TEMPLATE) templateEnd() + return + case AFTER_BODY: + if (tid === HTML_TAG) mode = AFTER_AFTER_BODY + else afterBodyAnything() + return + case IN_FRAMESET: + if (tid === FRAMESET && !(stack.length === 1 && stack[0]!.id === HTML_TAG)) { + pop() + if (cur().id !== FRAMESET) mode = AFTER_FRAMESET + } + return + case AFTER_FRAMESET: + if (tid === HTML_TAG) mode = AFTER_AFTER_FRAMESET + return + case AFTER_AFTER_BODY: + return afterBodyAnything() + } +} + +// "anything else": each mode's way of making what the page left out, then reprocessing the token +const initialAnything = () => { + quirks = true + mode = BEFORE_HTML + dispatch() +} +const beforeHtmlAnything = () => { + htmlEl = make('html', HTML_TAG, HTML, '') + appendChild(doc, htmlEl) + push(htmlEl) + mode = BEFORE_HEAD + dispatch() +} +const beforeHeadAnything = () => { + headEl = insertFake('head', HEAD) + mode = IN_HEAD + dispatch() +} +const inHeadAnything = () => { + pop() + mode = AFTER_HEAD + dispatch() +} +const noscriptAnything = () => { + pop() + mode = IN_HEAD + dispatch() +} +const afterHeadAnything = () => { + const body = insertFake('body', BODY) + bodyEl ??= body + mode = IN_BODY + modeInBody() +} +const afterBodyAnything = () => { + mode = IN_BODY + modeInBody() +} +const columnGroupAnything = () => { + if (cur().id !== COLGROUP) return + pop() + mode = IN_TABLE + dispatch() +} + +const textParsing = (state: number) => { + insertTok() + tstate = state + rawTag = tag + origMode = mode + mode = TEXT +} +const templateEnd = () => { + if (tmplCount === 0) return + impliedEndsAll() + popThrough(TEMPLATE) + clearToMarker() + tmplModes.pop() + resetMode() +} + +const startInHead = (): void => { + switch (tid) { + case HTML_TAG: + return startInBody() + case BASE: + case BASEFONT: + case BGSOUND: + case LINK: + case META: + return appendTok() + case TITLE: + return textParsing(RCDATA) + case NOSCRIPT: + insertTok() + mode = IN_HEAD_NOSCRIPT + return + case NOFRAMES: + case STYLE: + return textParsing(RAWTEXT) + case SCRIPT: + return textParsing(SCRIPT_DATA) + case TEMPLATE: + insertTok() + afe.push(null) + framesetOk = false + mode = IN_TEMPLATE + tmplModes.push(IN_TEMPLATE) + return + case HEAD: + return + default: + return inHeadAnything() + } +} +const startInHeadNoscript = () => { + switch (tid) { + case HTML_TAG: + return startInBody() + case BASEFONT: + case BGSOUND: + case HEAD: + case LINK: + case META: + case NOFRAMES: + case STYLE: + return startInHead() + case NOSCRIPT: + return + default: + return noscriptAnything() + } +} +const startAfterHead = () => { + switch (tid) { + case HTML_TAG: + return startInBody() + case BODY: { + const body = insertTok() + bodyEl ??= body + framesetOk = false + mode = IN_BODY + return + } + case FRAMESET: + insertTok() + mode = IN_FRAMESET + return + case BASE: + case BASEFONT: + case BGSOUND: + case LINK: + case META: + case NOFRAMES: + case SCRIPT: + case STYLE: + case TEMPLATE: + case TITLE: + push(headEl!) + startInHead() + removeEl(headEl!) + return + case HEAD: + return + default: + return afterHeadAnything() + } +} + +// a later <html> or <body> adds the attributes the first one didn't have +const adopt = (el: El) => { + if (tattrs === '') return + const own = new Map(attrsOf(el)) + let added = false + for (const [name, value] of parseAttrs(tattrs)) + if (!own.has(name)) { + own.set(name, value) + added = true + } + if (!added) return + el.attrs = serialize(own) + el.map = own +} +const hiddenInput = () => + tattrs !== '' && parseAttrs(tattrs).get('type')?.toLowerCase() === 'hidden' + +// most start tags in body are only inserted (the switch's default), or are blocks that close a p first; most end +// tags are blocks, or the generic kind. they skip the long switches +const PLAIN_START = set( + 'span label sub sup var ruby noscript canvas audio video annotation-xml desc malignmark mglyph mi mn mo ms mtext', +) +const BLOCK_START = set( + 'p dl ol ul div dir nav main menu aside center figure footer header hgroup dialog details address article search ' + + 'section summary fieldset blockquote figcaption', +) +const BLOCK_END = set( + 'dl ul ol dir div nav pre main menu aside button center figure footer header hgroup dialog address article details ' + + 'search section summary listing fieldset blockquote figcaption', +) +const SWITCH_END = set( + 'a b i s u em tt big code font nobr small strike strong p li dd dt h1 h2 h3 h4 h5 h6 br body html form applet ' + + 'object marquee template', +) +const startInBody = (): void => { + if (tid === 0 || PLAIN_START[tid]) { + reconstruct() + insertTok() + return + } + if (BLOCK_START[tid]) { + if (pInButtonScope()) closeP() + insertTok() + return + } + switch (tid) { + case I: + case S: + case B: + case U: + case EM: + case TT: + case BIG: + case CODE: + case FONT: + case SMALL: + case STRIKE: + case STRONG: + reconstruct() + afePush(insertTok()) + return + case A: { + const entry = afeByTag('a') + if (entry) { + adoption() + removeEl(entry.el) + afeRemove(entry) + } + reconstruct() + afePush(insertTok()) + return + } + case H1: + case H2: + case H3: + case H4: + case H5: + case H6: + if (pInButtonScope()) closeP() + if (HEADINGS[cur().id]) pop() + insertTok() + return + case P: + case DL: + case OL: + case UL: + case DIV: + case DIR: + case NAV: + case MAIN: + case MENU: + case ASIDE: + case CENTER: + case FIGURE: + case FOOTER: + case HEADER: + case HGROUP: + case DIALOG: + case DETAILS: + case ADDRESS: + case ARTICLE: + case SEARCH: + case SECTION: + case SUMMARY: + case FIELDSET: + case BLOCKQUOTE: + case FIGCAPTION: + if (pInButtonScope()) closeP() + insertTok() + return + case LI: + case DD: + case DT: + framesetOk = false + for (let i = stack.length - 1; i >= 0; i--) { + const el = stack[i]! + const id = el.id + if ((tid === LI && id === LI) || ((tid === DD || tid === DT) && (id === DD || id === DT))) { + impliedEndsBut(id) + popThrough(id) + break + } + if (id !== ADDRESS && id !== DIV && id !== P && special(el)) break + } + if (pInButtonScope()) closeP() + insertTok() + return + case BR: + case IMG: + case WBR: + case AREA: + case EMBED: + case KEYGEN: + reconstruct() + appendTok() + framesetOk = false + return + case HR: + if (pInButtonScope()) closeP() + appendTok() + framesetOk = false + return + case RB: + case RTC: + if (inScope(RUBY)) impliedEnds() + insertTok() + return + case RT: + case RP: + if (inScope(RUBY)) impliedEndsBut(RTC) + insertTok() + return + case PRE: + case LISTING: + if (pInButtonScope()) closeP() + insertTok() + skipNL = true + framesetOk = false + return + case XMP: + if (pInButtonScope()) closeP() + reconstruct() + framesetOk = false + return textParsing(RAWTEXT) + case SVG_TAG: + reconstruct() + if (tself) attach(make(tag, tid, SVG, tattrs)) + else insert(tag, tid, SVG, tattrs) + return + case HTML_TAG: + if (tmplCount === 0) adopt(stack[0]!) + return + case BASE: + case LINK: + case META: + case STYLE: + case TITLE: + case SCRIPT: + case BGSOUND: + case BASEFONT: + case TEMPLATE: + return startInHead() + case BODY: { + const body = stack.length > 1 && stack[1]!.id === BODY ? stack[1]! : null + if (body && tmplCount === 0) { + framesetOk = false + adopt(body) + } + return + } + case FORM: { + const inTemplate = tmplCount > 0 + if (!formEl || inTemplate) { + if (pInButtonScope()) closeP() + const el = insertTok() + if (!inTemplate) formEl = el + } + return + } + case NOBR: + reconstruct() + if (inScope(NOBR)) { + adoption() + reconstruct() + } + afePush(insertTok()) + return + case MATH_TAG: { + reconstruct() + const attrs = tattrs === '' ? '' : mathAttrs(tattrs) + if (tself) attach(make(tag, tid, MATH, attrs)) + else insert(tag, tid, MATH, attrs) + return + } + case TABLE: + if (!quirks && pInButtonScope()) closeP() + insertTok() + framesetOk = false + mode = IN_TABLE + return + case INPUT: + reconstruct() + appendTok() + if (!hiddenInput()) framesetOk = false + return + case PARAM: + case TRACK: + case SOURCE: + return appendTok() + case IMAGE: + tag = 'img' + tid = IMG + reconstruct() + appendTok() + framesetOk = false + return + case BUTTON: + if (inScope(BUTTON)) { + impliedEnds() + popThrough(BUTTON) + } + reconstruct() + insertTok() + framesetOk = false + return + case APPLET: + case OBJECT: + case MARQUEE: + reconstruct() + insertTok() + afe.push(null) + framesetOk = false + return + case IFRAME: + framesetOk = false + return textParsing(RAWTEXT) + case SELECT: + reconstruct() + insertTok() + framesetOk = false + mode = + mode === IN_TABLE || + mode === IN_CAPTION || + mode === IN_TABLE_BODY || + mode === IN_ROW || + mode === IN_CELL + ? IN_SELECT_IN_TABLE + : IN_SELECT + return + case OPTION: + case OPTGROUP: + if (cur().id === OPTION) pop() + reconstruct() + insertTok() + return + case NOEMBED: + case NOFRAMES: + return textParsing(RAWTEXT) + case FRAMESET: { + const body = stack.length > 1 && stack[1]!.id === BODY ? stack[1]! : null + if (framesetOk && body) { + detach(body) + bodyGone = true + shortenTo(1) + tmplCount = 0 + insertTok() + mode = IN_FRAMESET + } + return + } + case TEXTAREA: + insertTok() + skipNL = true + tstate = RCDATA + rawTag = tag + origMode = mode + framesetOk = false + mode = TEXT + return + case PLAINTEXT: + if (pInButtonScope()) closeP() + insertTok() + tstate = PLAIN + return + case COL: + case TH: + case TD: + case TR: + case HEAD: + case FRAME: + case TBODY: + case TFOOT: + case THEAD: + case CAPTION: + case COLGROUP: + return + default: + // noscript too: with scripting off it is an ordinary element + reconstruct() + insertTok() + } +} + +const genericEndInBody = () => { + for (let i = stack.length - 1; i > 0; i--) { + const el = stack[i]! + if (tid === el.id && (tid !== 0 || el.tag === tag)) { + impliedEndsBut(tid) + if (stack.length - 1 >= i) shortenTo(i) + return + } + if (special(el)) return + } +} +const endInBody = () => { + if (BLOCK_END[tid]) { + if (inScope(tid)) { + impliedEnds() + popThrough(tid) + } + return + } + if (!SWITCH_END[tid]) return genericEndInBody() + switch (tid) { + case A: + case B: + case I: + case S: + case U: + case EM: + case TT: + case BIG: + case CODE: + case FONT: + case NOBR: + case SMALL: + case STRIKE: + case STRONG: + return adoption() + case P: + if (!pInButtonScope()) insertFake('p', P) + return closeP() + case DL: + case UL: + case OL: + case DIR: + case DIV: + case NAV: + case PRE: + case MAIN: + case MENU: + case ASIDE: + case BUTTON: + case CENTER: + case FIGURE: + case FOOTER: + case HEADER: + case HGROUP: + case DIALOG: + case ADDRESS: + case ARTICLE: + case DETAILS: + case SEARCH: + case SECTION: + case SUMMARY: + case LISTING: + case FIELDSET: + case BLOCKQUOTE: + case FIGCAPTION: + if (inScope(tid)) { + impliedEnds() + popThrough(tid) + } + return + case LI: + if (inScopeOf(LI, LIST_SCOPE)) { + impliedEndsBut(LI) + popThrough(LI) + } + return + case DD: + case DT: + if (inScope(tid)) { + impliedEndsBut(tid) + popThrough(tid) + } + return + case H1: + case H2: + case H3: + case H4: + case H5: + case H6: + if (headingInScope()) { + impliedEnds() + popThroughOf(HEADINGS) + } + return + case BR: + reconstruct() + insertFake('br', BR) + pop() + framesetOk = false + return + case BODY: + if (inScope(BODY)) mode = AFTER_BODY + return + case HTML_TAG: + if (inScope(BODY)) { + mode = AFTER_BODY + endOutside() + } + return + case FORM: { + const inTemplate = tmplCount > 0 + const el = formEl + if (!inTemplate) formEl = null + if ((el || inTemplate) && inScope(FORM)) { + impliedEnds() + if (inTemplate) popThrough(FORM) + else if (el) removeEl(el) + } + return + } + case APPLET: + case OBJECT: + case MARQUEE: + if (inScope(tid)) { + impliedEnds() + popThrough(tid) + clearToMarker() + } + return + case TEMPLATE: + return templateEnd() + default: + return genericEndInBody() + } +} + +// tables + +const tokenInTable = () => { + const saved = foster + foster = true + modeInBody() + foster = saved +} +const toTableText = () => { + pending = [] + pendingText = false + origMode = mode + mode = IN_TABLE_TEXT +} +const charsInTable = (text: string, nonSpace: boolean) => { + if (FOSTERING[cur().id]) { + toTableText() + pending.push(text) + pendingText = nonSpace + return + } + const saved = foster + foster = true + reconstruct() + insertText(text) + if (nonSpace) framesetOk = false + foster = saved +} +// the table's pending text goes in (fostered out of the table if any of it isn't whitespace), then the token goes on +const tableTextAnything = () => { + const list = pending + pending = [] + if (pendingText) { + const saved = foster + foster = true + for (const text of list) { + reconstruct() + insertText(text) + } + framesetOk = false + foster = saved + } else for (const text of list) insertText(text) + mode = origMode + dispatch() +} + +const startInTable = (): void => { + switch (tid) { + case TD: + case TH: + case TR: + clearBackTo(TABLE_CONTEXT) + insertFake('tbody', TBODY) + mode = IN_TABLE_BODY + return startInTableBody() + case STYLE: + case SCRIPT: + case TEMPLATE: + return startInHead() + case COL: + clearBackTo(TABLE_CONTEXT) + insertFake('colgroup', COLGROUP) + mode = IN_COLUMN_GROUP + return startInColumnGroup() + case FORM: + if (!formEl && tmplCount === 0) { + formEl = insertTok() + pop() + } + return + case TABLE: + if (inTableScope(TABLE)) { + popThrough(TABLE) + resetMode() + processStart() + } + return + case TBODY: + case TFOOT: + case THEAD: + clearBackTo(TABLE_CONTEXT) + insertTok() + mode = IN_TABLE_BODY + return + case INPUT: + if (hiddenInput()) appendTok() + else tokenInTable() + return + case CAPTION: + clearBackTo(TABLE_CONTEXT) + afe.push(null) + insertTok() + mode = IN_CAPTION + return + case COLGROUP: + clearBackTo(TABLE_CONTEXT) + insertTok() + mode = IN_COLUMN_GROUP + return + default: + return tokenInTable() + } +} +const endInTable = () => { + switch (tid) { + case TABLE: + if (inTableScope(TABLE)) { + popThrough(TABLE) + resetMode() + } + return + case TEMPLATE: + return templateEnd() + case BODY: + case CAPTION: + case COL: + case COLGROUP: + case HTML_TAG: + case TBODY: + case TD: + case TFOOT: + case TH: + case THEAD: + case TR: + return + default: + return tokenInTable() + } +} +const startInCaption = () => { + if (!TABLE_VOID[tid]) return startInBody() + if (!inTableScope(CAPTION)) return + impliedEnds() + popThrough(CAPTION) + clearToMarker() + mode = IN_TABLE + startInTable() +} +const endInCaption = () => { + switch (tid) { + case CAPTION: + case TABLE: + if (inTableScope(CAPTION)) { + impliedEnds() + popThrough(CAPTION) + clearToMarker() + mode = IN_TABLE + if (tid === TABLE) endInTable() + } + return + case BODY: + case COL: + case COLGROUP: + case HTML_TAG: + case TBODY: + case TD: + case TFOOT: + case TH: + case THEAD: + case TR: + return + default: + return endInBody() + } +} +const startInColumnGroup = () => { + if (tid === HTML_TAG) startInBody() + else if (tid === COL) appendTok() + else if (tid === TEMPLATE) startInHead() + else columnGroupAnything() +} +const endInColumnGroup = () => { + if (tid === COLGROUP) { + if (cur().id === COLGROUP) { + pop() + mode = IN_TABLE + } + } else if (tid === TEMPLATE) templateEnd() + else if (tid !== COL) columnGroupAnything() +} +const startInTableBody = (): void => { + switch (tid) { + case TR: + clearBackTo(TABLE_BODY_CONTEXT) + insertTok() + mode = IN_ROW + return + case TH: + case TD: + clearBackTo(TABLE_BODY_CONTEXT) + insertFake('tr', TR) + mode = IN_ROW + return startInRow() + case CAPTION: + case COL: + case COLGROUP: + case TBODY: + case TFOOT: + case THEAD: + if (tableBodyInTableScope()) { + clearBackTo(TABLE_BODY_CONTEXT) + pop() + mode = IN_TABLE + startInTable() + } + return + default: + return startInTable() + } +} +const endInTableBody = () => { + switch (tid) { + case TBODY: + case TFOOT: + case THEAD: + if (inTableScope(tid)) { + clearBackTo(TABLE_BODY_CONTEXT) + pop() + mode = IN_TABLE + } + return + case TABLE: + if (tableBodyInTableScope()) { + clearBackTo(TABLE_BODY_CONTEXT) + pop() + mode = IN_TABLE + endInTable() + } + return + case BODY: + case CAPTION: + case COL: + case COLGROUP: + case HTML_TAG: + case TD: + case TH: + case TR: + return + default: + return endInTable() + } +} +const startInRow = (): void => { + switch (tid) { + case TH: + case TD: + clearBackTo(TABLE_ROW_CONTEXT) + insertTok() + mode = IN_CELL + afe.push(null) + return + case CAPTION: + case COL: + case COLGROUP: + case TBODY: + case TFOOT: + case THEAD: + case TR: + if (inTableScope(TR)) { + clearBackTo(TABLE_ROW_CONTEXT) + pop() + mode = IN_TABLE_BODY + startInTableBody() + } + return + default: + return startInTable() + } +} +const endInRow = () => { + switch (tid) { + case TR: + if (inTableScope(TR)) { + clearBackTo(TABLE_ROW_CONTEXT) + pop() + mode = IN_TABLE_BODY + } + return + case TABLE: + if (inTableScope(TR)) { + clearBackTo(TABLE_ROW_CONTEXT) + pop() + mode = IN_TABLE_BODY + endInTableBody() + } + return + case TBODY: + case TFOOT: + case THEAD: + if (inTableScope(tid) || inTableScope(TR)) { + clearBackTo(TABLE_ROW_CONTEXT) + pop() + mode = IN_TABLE_BODY + endInTableBody() + } + return + case BODY: + case CAPTION: + case COL: + case COLGROUP: + case HTML_TAG: + case TD: + case TH: + return + default: + return endInTable() + } +} +const closeCell = () => { + impliedEnds() + popThroughOf(CELLS) + clearToMarker() + mode = IN_ROW +} +const startInCell = () => { + if (!TABLE_VOID[tid]) return startInBody() + if (inTableScope(TD) || inTableScope(TH)) { + closeCell() + startInRow() + } +} +const endInCell = () => { + switch (tid) { + case TD: + case TH: + if (inTableScope(tid)) { + impliedEnds() + popThrough(tid) + clearToMarker() + mode = IN_ROW + } + return + case TABLE: + case TBODY: + case TFOOT: + case THEAD: + case TR: + if (inTableScope(tid)) { + closeCell() + endInRow() + } + return + case BODY: + case CAPTION: + case COL: + case COLGROUP: + case HTML_TAG: + return + default: + return endInBody() + } +} + +// select and template + +const startInSelect = () => { + switch (tid) { + case HTML_TAG: + return startInBody() + case OPTION: + if (cur().id === OPTION) pop() + insertTok() + return + case OPTGROUP: + if (cur().id === OPTION) pop() + if (cur().id === OPTGROUP) pop() + insertTok() + return + case HR: + if (cur().id === OPTION) pop() + if (cur().id === OPTGROUP) pop() + appendTok() + return + case INPUT: + case KEYGEN: + case TEXTAREA: + case SELECT: + if (inSelectScope(SELECT)) { + popThrough(SELECT) + resetMode() + if (tid !== SELECT) processStart() + } + return + case SCRIPT: + case TEMPLATE: + return startInHead() + } +} +const endInSelect = () => { + switch (tid) { + case OPTGROUP: + if (stack.length > 1 && cur().id === OPTION && stack[stack.length - 2]!.id === OPTGROUP) pop() + if (cur().id === OPTGROUP) pop() + return + case OPTION: + if (cur().id === OPTION) pop() + return + case SELECT: + if (inSelectScope(SELECT)) { + popThrough(SELECT) + resetMode() + } + return + case TEMPLATE: + return templateEnd() + } +} +const SELECT_TABLE = set('caption table tbody tfoot thead tr td th') +const startInSelectInTable = () => { + if (!SELECT_TABLE[tid]) return startInSelect() + popThrough(SELECT) + resetMode() + processStart() +} +const endInSelectInTable = () => { + if (!SELECT_TABLE[tid]) return endInSelect() + if (!inTableScope(tid)) return + popThrough(SELECT) + resetMode() + skipNL = false + processEnd() +} +const startInTemplate = () => { + let next: number + switch (tid) { + case BASE: + case BASEFONT: + case BGSOUND: + case LINK: + case META: + case NOFRAMES: + case SCRIPT: + case STYLE: + case TEMPLATE: + case TITLE: + return startInHead() + case CAPTION: + case COLGROUP: + case TBODY: + case TFOOT: + case THEAD: + next = IN_TABLE + break + case COL: + next = IN_COLUMN_GROUP + break + case TR: + next = IN_TABLE_BODY + break + case TD: + case TH: + next = IN_ROW + break + default: + next = IN_BODY + } + tmplModes[tmplModes.length - 1] = next + mode = next + if (next === IN_TABLE) startInTable() + else if (next === IN_COLUMN_GROUP) startInColumnGroup() + else if (next === IN_TABLE_BODY) startInTableBody() + else if (next === IN_ROW) startInRow() + else startInBody() +} + +// tokenizer + +// what the tag states stop at: 1 whitespace, 2 '/', 4 '>', 8 '='; 16 what a tag name folds (ascii upper case, and a +// nul, which is U+FFFD) +const STOPS = new Uint8Array(65536) +STOPS[32] = STOPS[10] = STOPS[9] = STOPS[12] = 1 +STOPS[47] = 2 +STOPS[62] = 4 +STOPS[61] = 8 +for (let c = 65; c <= 90; c++) STOPS[c] = 16 +STOPS[0] = 16 +// tag names in a small direct-mapped cache: a page uses a few dozen names, read again without a slice or a hash +const NAME_CACHE: string[] = Array.from({ length: 256 }, () => '') +const ID_CACHE = new Int32Array(256) +// a tag's name from `from` (a letter) to whitespace, '/' or '>': sets tag and tid, and returns where it ends +const readName = (from: number) => { + const h = html + const length = n + const stops = STOPS + let i = from + 1 + let fold = 0 + for (; i < length; i++) { + const stop = stops[h.charCodeAt(i)]! + if (stop & 7) break + fold |= stop + } + const first = h.charCodeAt(from) + if (fold & 16 || first <= 90) { + tag = lowerAscii(h.slice(from, i)) + tid = IDS.get(tag) ?? 0 + return i + } + const size = i - from + const key = (first * 7 + size * 31 + h.charCodeAt(i - 1)) & 255 + const cached = NAME_CACHE[key]! + if (cached.length === size && h.startsWith(cached, from)) { + tag = cached + tid = ID_CACHE[key]! + return i + } + tid = IDS.get(h.slice(from, i)) ?? 0 + // a known name is the table's own string; the page's slices are not kept past the parse + tag = tid ? NAMES[tid - 1]! : h.slice(from, i) + NAME_CACHE[key] = tag + ID_CACHE[key] = tid + return i +} +// the attribute states from just after a tag's name to its '>', which only a quoted value can hold: where the tag +// ends (after the '>'), or -1 when the page ends first (and the tag is dropped). sets tself, attrsEnd, and named to +// whether any attribute started +let attrsEnd = 0 +let named = false +const tagEnd = (from: number): number => { + const h = html + const length = n + const stops = STOPS + named = false + let i = from + let c = h.charCodeAt(i) + for (;;) { + // before a name + while (stops[c] === 1) c = h.charCodeAt(++i) + if (c === 62) { + attrsEnd = i + tself = false + return i + 1 + } + if (c === 47) { + // a '/' right before the '>' self-closes; anything else is read again as before a name + c = h.charCodeAt(++i) + if (c === 62) { + attrsEnd = i + tself = true + return i + 1 + } + continue + } + if (i >= length) return -1 + // a name, whose first character may be '=' + named = true + c = h.charCodeAt(++i) + while (i < length && (stops[c]! & 15) === 0) c = h.charCodeAt(++i) + if (i >= length) return -1 + while (stops[c] === 1) c = h.charCodeAt(++i) + // no '=': what follows reads the same as before a name + if (c !== 61) continue + c = h.charCodeAt(++i) + while (stops[c] === 1) c = h.charCodeAt(++i) + if (c === 34 || c === 39) { + const close = h.indexOf(c === 34 ? '"' : "'", i + 1) + if (close < 0) return -1 + i = close + 1 + c = h.charCodeAt(i) + continue + } + if (c === 62) continue + while ((stops[c]! & 5) === 0) { + if (i >= length) return -1 + c = h.charCodeAt(++i) + } + } +} + +// a nul is rare, and indexOf is slow to look for one in a two-byte string (and can't stop at the text's end): by +// hand, over the page itself +const hasNul = (from: number, to: number) => { + const h = html + for (let i = from; i < to; i++) if (h.charCodeAt(i) === 0) return true + return false +} +// text in the data state: references decoded, and nuls (rare) handed on one by one +const dataText = (from: number, to: number) => { + if (to <= from) return + // inside svg text goes nowhere, and only could say the page has content (framesetOk) + if (current.rec === 0 && !framesetOk && !integration(current)) return + let text = html.slice(from, to) + if (amp < from) amp = html.indexOf('&', from) >>> 0 + if (amp < to) text = decode(text) + if ( + (to - from > 24 ? text.indexOf('\0') >= 0 : hasNul(from, to)) && + !(current.rec === 0 && !framesetOk) + ) { + // a run of nuls is one token, as the tokenizer emits them (in foreign content, one U+FFFD for the run) + for (let i = 0; i < text.length;) { + let j = i + if (text.charCodeAt(i) === 0) { + while (text.charCodeAt(j) === 0) j++ + onNul() + } else { + while (j < text.length && text.charCodeAt(j) !== 0) j++ + chars(text.slice(i, j)) + } + i = j + } + return + } + chars(text) +} +// text in raw text, rcdata, script data and plaintext: nuls are U+FFFD +const rawText = (from: number, to: number, refs: boolean) => { + if (to <= from) return + // nothing reads a dropped element's text + if (cur().rec < 2) return + let text = html.slice(from, to) + if (refs) text = decode(text) + if (text.indexOf('\0') >= 0) text = text.replaceAll('\0', '\uFFFD') + chars(text) +} + +const emitStart = (from: number, to: number) => { + tattrs = named ? html.slice(from, to) : '' + tok = START + skipNL = false + processStart() +} +const emitEnd = () => { + tok = END + skipNL = false + processEnd() +} + +// the end of a raw text element's text: where its end tag's '<' is, or -1 +const matches = (at: number, name: string) => { + for (let k = 0; k < name.length; k++) + if ((html.charCodeAt(at + k) | 32) !== name.charCodeAt(k)) return false + const c = html.charCodeAt(at + name.length) + return c === 32 || c === 62 || c === 47 || c === 10 || c === 9 || c === 12 +} +const rawEnd = (from: number) => { + for (let at = html.indexOf('</', from); at >= 0; at = html.indexOf('</', at + 2)) + if (matches(at + 2, rawTag)) return at + return -1 +} +// a script ends at its first </script unless a <!-- comes first: then the script data escaped states decide +const scriptEnd = (from: number) => { + let i = from + for (;;) { + const end = rawEnd(i) + if (commentOpen < i) commentOpen = html.indexOf('<!--', i) >>> 0 + if (commentOpen >= n || (end >= 0 && commentOpen > end)) return end + i = commentOpen + 4 + // escaped: 1, its dash 2, dash dash 3; double escaped: 4, 5, 6 + let st = 3 + for (; i < n; i++) { + const c = html.charCodeAt(i) + if (st <= 3) { + if (c === 45) st = st === 1 ? 2 : 3 + else if (c === 60) { + if (html.charCodeAt(i + 1) === 47) { + if (matches(i + 2, 'script')) return i + i++ + } else if (matches(i + 1, 'script')) { + i += 7 + st = 4 + continue + } + st = 1 + } else if (c === 62 && st === 3) break + else st = 1 + } else if (c === 45) st = st === 4 ? 5 : 6 + else if (c === 60) { + if (html.charCodeAt(i + 1) === 47 && matches(i + 2, 'script')) { + i += 8 + st = 1 + continue + } + st = 4 + } else if (c === 62 && st === 6) break + else st = 4 + } + if (i >= n) return -1 + // back in plain script data after the '>' + i++ + } +} + +// a doctype's text between '<!doctype' and its '>': whether it puts the page in quirks mode +const QUIRKS_PREFIXES = ( + '+//silmaril//dtd html pro v0r11 19970101//|-//as//dtd html 3.0 aswedit + extensions//|' + + '-//advasoft ltd//dtd html 3.0 aswedit + extensions//|-//ietf//dtd html 2.0 level 1//|' + + '-//ietf//dtd html 2.0 level 2//|-//ietf//dtd html 2.0 strict level 1//|-//ietf//dtd html 2.0 strict level 2//|' + + '-//ietf//dtd html 2.0 strict//|-//ietf//dtd html 2.0//|-//ietf//dtd html 2.1e//|-//ietf//dtd html 3.0//|' + + '-//ietf//dtd html 3.2 final//|-//ietf//dtd html 3.2//|-//ietf//dtd html 3//|-//ietf//dtd html level 0//|' + + '-//ietf//dtd html level 1//|-//ietf//dtd html level 2//|-//ietf//dtd html level 3//|' + + '-//ietf//dtd html strict level 0//|-//ietf//dtd html strict level 1//|-//ietf//dtd html strict level 2//|' + + '-//ietf//dtd html strict level 3//|-//ietf//dtd html strict//|-//ietf//dtd html//|' + + '-//metrius//dtd metrius presentational//|-//microsoft//dtd internet explorer 2.0 html strict//|' + + '-//microsoft//dtd internet explorer 2.0 html//|-//microsoft//dtd internet explorer 2.0 tables//|' + + '-//microsoft//dtd internet explorer 3.0 html strict//|-//microsoft//dtd internet explorer 3.0 html//|' + + '-//microsoft//dtd internet explorer 3.0 tables//|-//netscape comm. corp.//dtd html//|' + + "-//netscape comm. corp.//dtd strict html//|-//o'reilly and associates//dtd html 2.0//|" + + "-//o'reilly and associates//dtd html extended 1.0//|-//o'reilly and associates//dtd html extended relaxed 1.0//|" + + '-//sq//dtd html 2.0 hotmetal + extensions//|' + + '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//|' + + '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//|-//spyglass//dtd html 2.0 extended//|' + + '-//sun microsystems corp.//dtd hotjava html//|-//sun microsystems corp.//dtd hotjava strict html//|' + + '-//w3c//dtd html 3 1995-03-24//|-//w3c//dtd html 3.2 draft//|-//w3c//dtd html 3.2 final//|-//w3c//dtd html 3.2//|' + + '-//w3c//dtd html 3.2s draft//|-//w3c//dtd html 4.0 frameset//|-//w3c//dtd html 4.0 transitional//|' + + '-//w3c//dtd html experimental 19960712//|-//w3c//dtd html experimental 970421//|-//w3c//dtd w3 html//|' + + '-//w3o//dtd w3 html 3.0//|-//webtechs//dtd mozilla html 2.0//|-//webtechs//dtd mozilla html//' +).split('|') +const QUIRKS_NO_SYSTEM = [ + ...QUIRKS_PREFIXES, + '-//w3c//dtd html 4.01 frameset//', + '-//w3c//dtd html 4.01 transitional//', +] +const QUIRKS_IDS = new Set([ + '-//w3o//dtd w3 html strict 3.0//en//', + '-/w3c/dtd html 4.0 transitional/en', + 'html', +]) +const quirksOf = (name: string, publicId: string | null, systemId: string | null) => { + if (name !== 'html') return true + if ( + systemId !== null && + systemId.toLowerCase() === 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd' + ) + return true + if (publicId === null) return false + const id = publicId.toLowerCase() + if (QUIRKS_IDS.has(id)) return true + return (systemId === null ? QUIRKS_NO_SYSTEM : QUIRKS_PREFIXES).some((prefix) => + id.startsWith(prefix), + ) +} +const doctypeIsQuirks = (text: string, eof: boolean) => { + const length = text.length + let i = 0 + const skip = () => { + while (i < length && space(text.charCodeAt(i))) i++ + } + skip() + if (i >= length) return true + const start = i + while (i < length && !space(text.charCodeAt(i))) i++ + const name = lowerAscii(text.slice(start, i)) + skip() + if (i >= length) return eof || quirksOf(name, null, null) + const keyword = text.slice(i, i + 6).toLowerCase() + if (keyword !== 'public' && keyword !== 'system') return true + i += 6 + // a quoted identifier; null when what follows isn't one (the doctype is then bogus and forces quirks) + const id = () => { + skip() + const q = text.charCodeAt(i) + if (q !== 34 && q !== 39) return null + const close = text.indexOf(q === 34 ? '"' : "'", i + 1) + if (close < 0) return null + const value = text.slice(i + 1, close).replaceAll('\0', '\uFFFD') + i = close + 1 + return value + } + let publicId: string | null = null + let systemId: string | null + if (keyword === 'public') { + publicId = id() + if (publicId === null) return true + skip() + if (i >= length) return eof || quirksOf(name, publicId, null) + systemId = id() + if (systemId === null) return true + } else { + systemId = id() + if (systemId === null) return true + } + skip() + // anything after the system identifier makes a bogus doctype, but one that keeps what it read + if (i >= length && eof) return true + return quirksOf(name, publicId, systemId) +} + +// after '<!': a comment, the doctype, cdata (in foreign content) or a bogus comment. where it ends +const markup = (i: number) => { + if (html.charCodeAt(i) === 45 && html.charCodeAt(i + 1) === 45) { + onComment() + return commentEnd(i + 2) + } + if (html.slice(i, i + 7).toLowerCase() === 'doctype') { + const close = html.indexOf('>', i + 7) + doctypeQuirks = doctypeIsQuirks(html.slice(i + 7, close < 0 ? n : close), close < 0) + onDoctype() + return close < 0 ? n : close + 1 + } + if (html.startsWith('[CDATA[', i) && inForeign()) { + const close = html.indexOf(']]>', i + 7) + let text = html.slice(i + 7, close < 0 ? n : close) + if (text.indexOf('\0') >= 0) text = text.replace(/\0+/g, '\uFFFD') + if (text) chars(text) + return close < 0 ? n : close + 3 + } + onComment() + return bogusEnd(i) +} +const bogusEnd = (i: number) => { + const close = html.indexOf('>', i) + return close < 0 ? n : close + 1 +} +// a comment from just after '<!--': <!--> and <!---> end at once, then the first --> or --!> +const commentEnd = (i: number) => { + if (html.charCodeAt(i) === 62) return i + 1 + if (html.charCodeAt(i) === 45 && html.charCodeAt(i + 1) === 62) return i + 2 + for (let at = html.indexOf('--', i); at >= 0; at = html.indexOf('--', at + 1)) { + const c = html.charCodeAt(at + 2) + if (c === 62) return at + 3 + if (c === 33 && html.charCodeAt(at + 3) === 62) return at + 4 + } + return n +} + +const tokenize = () => { + const h = html + const length = n + let pos = 0 + // where the text not yet handed on starts: a '<' that starts nothing is text, and joins it + let from = 0 + while (pos < length) { + if (tstate !== DATA) { + if (tstate === PLAIN) { + rawText(pos, length, false) + return + } + const at = tstate === SCRIPT_DATA ? scriptEnd(pos) : rawEnd(pos) + rawText(pos, at < 0 ? length : at, tstate === RCDATA) + if (at < 0) return + const end = tagEnd(at + 2 + rawTag.length) + if (end < 0) return + tstate = DATA + tag = rawTag + tid = IDS.get(rawTag) ?? 0 + emitEnd() + pos = from = end + continue + } + // the next '<' is often a few characters on: by hand that far, then indexOf + let lt = pos + const stop = pos + 8 < length ? pos + 8 : length + while (lt < stop && h.charCodeAt(lt) !== 60) lt++ + if (lt === stop) lt = h.indexOf('<', lt) + if (lt < 0) break + const c = h.charCodeAt(lt + 1) + if (alpha(c)) { + const to = readName(lt + 1) + const end = tagEnd(to) + dataText(from, lt) + if (end < 0) return + emitStart(to, attrsEnd) + pos = from = end + } else if (c === 47) { + const next = h.charCodeAt(lt + 2) + if (alpha(next)) { + // an end tag mostly closes the current node: its name read against that one, without a scan + const open = current.tag + let to = lt + 2 + open.length + const after = h.charCodeAt(to) + if ( + current.ns !== SVG && + (after === 62 || + after === 32 || + after === 47 || + after === 10 || + after === 9 || + after === 12) && + h.startsWith(open, lt + 2) + ) { + tag = open + tid = current.id + } else to = readName(lt + 2) + const end = tagEnd(to) + dataText(from, lt) + if (end < 0) return + emitEnd() + pos = from = end + } else if (next === 62) { + // </> is nothing at all + dataText(from, lt) + pos = from = lt + 3 + } else if (lt + 2 >= length) pos = length + else { + dataText(from, lt) + onComment() + pos = from = bogusEnd(lt + 2) + } + } else if (c === 33) { + dataText(from, lt) + pos = from = markup(lt + 2) + } else if (c === 63) { + dataText(from, lt) + onComment() + pos = from = bogusEnd(lt + 1) + } else pos = lt + 1 + } + if (tstate === DATA) dataText(from, length) +} + +// the Head, read from the elements watched as they were made: where each ended up, by the oracle's rules +// an html template's content is a fragment of its own, outside the element's text +const textOf = (el: El): string => { + let out = '' + for (const kid of el.kids) + if (typeof kid === 'string') out += kid + else if ((kid as El).id !== TEMPLATE || (kid as El).ns !== HTML) out += textOf(kid as El) + return out +} +// where an element is in tree order: its child indexes from the root. inside svg nothing is kept, so an element there +// is where its nearest kept ancestor is (and after it, in the order made, which inside svg is tree order) +const position = (el: El) => { + const path: number[] = [] + for (let x = el, up = el.up; up; x = up, up = up.up) { + const at = up.kids.lastIndexOf(x) + if (at < 0) path.length = 0 + else path.push(at) + } + return path.toReversed() +} +const treeOrder = (a: number[], b: number[]) => { + for (let i = 0; i < a.length && i < b.length; i++) if (a[i] !== b[i]) return a[i]! - b[i]! + return a.length - b.length +} +const readHead = (): Head => { + const head: Head = { meta: new Map(), jsonLd: [] } + let headTitle: string | undefined + let anyTitle: string | undefined + // made in tree order, unless something was inserted before or moved + let order = watched + if (reordered) { + const places = new Map(watched.map((el) => [el, position(el)])) + order = watched.toSorted((a, b) => treeOrder(places.get(a)!, places.get(b)!)) + } + for (const el of order) { + // in the document (not in a template's content, or a body a frameset threw out), and in what + let inHead = false + let inSvg = false + let top: El = el + let inside = true + for (let up = el.up; up; top = up, up = up.up) { + if (up.id === TEMPLATE && up.ns === HTML) inside = false + if (up.tag === 'head') inHead = true + else if (up.tag === 'svg') inSvg = true + } + if (!inside || top !== doc) continue + if (el.tag === 'title') { + if (inSvg) continue + if (inHead) headTitle ??= textOf(el) + anyTitle ??= textOf(el) + } else if (el.tag === 'link') { + if (inHead && attr(el, 'rel') === 'canonical') head.canonical ??= attr(el, 'href') + } else if (el.tag === 'html') head.lang ??= attr(el, 'lang') || undefined + else if (el.tag === 'meta') { + for (const kind of ['name', 'property']) { + const value = attr(el, kind) + const key = `${kind} ${value}` + if (value !== undefined && !head.meta.has(key)) + head.meta.set(key, attr(el, 'content') ?? '') + } + } else if (el.tag === 'script') { + const value = textOf(el).trim() + if (value) head.jsonLd.push(value) + } + } + head.title = (headTitle ?? anyTitle)?.trim() || undefined + return head +} + +export const parse = (input: string): Document => { + html = input.indexOf('\r') < 0 ? input : input.replace(/\r\n?/g, '\n') + n = html.length + tstate = DATA + rawTag = '' + doc = make('#root', 0, HTML, '') + stack = [] + current = doc + pCount = 0 + tmplCount = 0 + afe = [] + tmplModes = [] + mode = INITIAL + origMode = INITIAL + quirks = false + framesetOk = true + foster = false + skipNL = false + headEl = formEl = htmlEl = bodyEl = null + bodyGone = false + pending = [] + pendingText = false + watched = [] + pruned = [] + reordered = false + tok = 0 + // found when first needed + amp = -1 + commentOpen = -1 + tokenize() + onEof() + const head = readHead() + // the dropped elements leave the tree, and the text either side of one is one text + for (const el of pruned) { + const kids: Node[] = [] + for (const kid of el.kids) + if (typeof kid === 'string') { + if (typeof kids[kids.length - 1] === 'string') kids[kids.length - 1] += kid + else kids.push(kid) + } else if (!DROP[(kid as El).id]) kids.push(kid) + el.kids = kids + } + const root = bodyEl && !bodyGone ? bodyEl : doc + root.tag = '#root' + root.up = null + const document: Document = { root, head } + // let the page go: the tree holds slices of it, not the parse's state + html = tag = tattrs = ttext = '' + NAME_CACHE.fill('') + stack = [] + afe = [] + watched = [] + pruned = [] + pending = [] + current = doc = headEl = formEl = htmlEl = bodyEl = null as unknown as El + return document +} diff --git a/packages/md-core/src/types.ts b/packages/md-core/src/types.ts new file mode 100644 index 0000000..ae183a0 --- /dev/null +++ b/packages/md-core/src/types.ts @@ -0,0 +1,71 @@ +// the contract between the parser (parse.ts) and the emitter (emit.ts). both sides are written against this file, so +// change it only with the other side in hand + +// a text node is its string, already entity-decoded, whitespace as written (the emitter collapses it; <pre> keeps it) +export type Node = Element | string + +export interface Element { + // lowercase tag name; the root is '#root' + tag: string + // the tag's attributes exactly as written, from after the tag name to before the closing '>' ('' when none). read + // them with attr(), which parses on first use: most elements' attributes are never read + attrs: string + kids: Node[] + up: Element | null + // attr()'s cache + map?: Map<string, string> | undefined +} + +// what the page's <head> says, read during the one scan; the head's elements are not in the tree +export interface Head { + // the first <title> in the head, else the first <title> anywhere outside an <svg>; trimmed + title?: string | undefined + // <html lang> + lang?: string | undefined + // <link rel="canonical"> in the head: its href as written + canonical?: string | undefined + // <meta> anywhere, first one wins: keyed 'name <name>' and 'property <property>' for each of the two it has, value + // its content (decoded; '' without one) + meta: Map<string, string> + // each non-empty <script type="application/ld+json">, trimmed, in page order + jsonLd: string[] +} + +export interface Document { + // children are the <body>'s children (or, without a body, the page's own) + root: Element + head: Head +} + +// what the parser never builds, with everything inside: never content, whatever the page says. the same set as +// @affordances/md's ALWAYS_DROP; comments and the doctype are dropped too +export const NEVER = new Set([ + 'script', + 'style', + 'noscript', + 'template', + 'svg', + 'canvas', + 'iframe', + 'link', + 'meta', + 'head', + 'object', + 'embed', + 'audio', + 'video', + 'source', +]) + +export type Options = { + // base for absolutizing links and images, usually the page's url + url?: string + // 'auto': <main> (or role=main), else the body minus its chrome; 'none': the whole body + extract?: 'auto' | 'none' + frontmatter?: boolean + jsonLd?: boolean + // another url for a link once it's absolute; undefined keeps it. not called for images or #fragment links + link?: (url: URL) => string | undefined +} + +export type Result = { markdown: string; title?: string; url?: string; tokens: number } diff --git a/packages/md-core/test/emit-pages.ts b/packages/md-core/test/emit-pages.ts new file mode 100644 index 0000000..b527e15 --- /dev/null +++ b/packages/md-core/test/emit-pages.ts @@ -0,0 +1,62 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs' + +// the pages emit is measured on: the benchmark corpus (real pages, cached by bench/fetch.ts, maybe absent) and +// @affordances/md's fixtures, each with the url it's converted against +export type Page = { name: string; html: string; url: string; corpus: boolean } + +const corpusDir = new URL('../bench/corpus/', import.meta.url) +const fixturesDir = new URL('../../md/test/fixtures/', import.meta.url) + +export const corpusPages = (): Page[] => { + const cache = new URL('.cache/', corpusDir) + if (!existsSync(cache)) return [] + const urls = readFileSync(new URL('urls.txt', corpusDir), 'utf8') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')) + return urls.flatMap((url) => { + const file = new URL(url.replace(/[^a-zA-Z0-9]/g, '_') + '.html', cache) + if (!existsSync(file)) return [] + const { hostname, pathname } = new URL(url) + const name = `${hostname.split('.').at(-2)}/${pathname.split('/').filter(Boolean).at(-1) ?? ''}` + return [{ name, html: readFileSync(file, 'utf8'), url, corpus: true }] + }) +} + +export const fixturePages = (): Page[] => + readdirSync(fixturesDir) + .filter((file) => file.endsWith('.html')) + .toSorted() + .map((file) => ({ + name: file.replace(/\.html$/, ''), + html: readFileSync(new URL(file, fixturesDir), 'utf8'), + url: 'https://shop.test/page', + corpus: false, + })) + +// the longest common subsequence of two line lists, as a count: how many of the reference's lines appear in order +export const common = (a: string[], b: string[]) => { + // lines as numbers, so the table compares ints + const ids = new Map<string, number>() + const id = (line: string) => { + let n = ids.get(line) + if (n === undefined) ids.set(line, (n = ids.size)) + return n + } + const x = a.map(id) + const y = b.map(id) + let prev = new Uint32Array(y.length + 1) + let next = new Uint32Array(y.length + 1) + for (let i = 1; i <= x.length; i++) { + for (let j = 1; j <= y.length; j++) + next[j] = x[i - 1] === y[j - 1] ? prev[j - 1]! + 1 : Math.max(prev[j]!, next[j - 1]!) + ;[prev, next] = [next, prev] + } + return prev[y.length]! +} + +export const similarity = (reference: string, ours: string) => { + if (reference === ours) return 1 + const a = reference.split('\n') + return common(a, ours.split('\n')) / a.length +} diff --git a/packages/md-core/test/emit-parity.ts b/packages/md-core/test/emit-parity.ts new file mode 100644 index 0000000..b786e23 --- /dev/null +++ b/packages/md-core/test/emit-parity.ts @@ -0,0 +1,110 @@ +// parity of emit(oracle(html)) with @affordances/md's htmlToMarkdown, per page. run with node: +// node test/emit-parity.ts every page: exact, or the share of the reference's lines reproduced in order +// node test/emit-parity.ts <name> one page's first differing hunks +// node test/emit-parity.ts --time emit-only time for the corpus (median of runs, warm) +import { writeFileSync } from 'node:fs' +import { htmlToMarkdown } from '@affordances/md' +import { emit } from '../src/emit.ts' +import type { Document } from '../src/types.ts' +import { oracle } from './support/oracle.ts' +import { corpusPages, fixturePages, similarity } from './emit-pages.ts' + +// the first differing hunks, as a unified-ish listing +const hunks = (reference: string, ours: string, count = 6) => { + const a = reference.split('\n') + const b = ours.split('\n') + const out: string[] = [] + let i = 0 + let j = 0 + while (i < a.length && j < b.length && out.length < count * 12) { + if (a[i] === b[j]) { + i++ + j++ + continue + } + // resync: the nearest pair of equal lines ahead + let best: [number, number] | undefined + for (let d = 1; d < 400 && !best; d++) + for (let k = 0; k <= d; k++) + if (a[i + k] !== undefined && a[i + k] === b[j + d - k] && a[i + k] !== '') { + best = [i + k, j + d - k] + break + } + const [ni, nj] = best ?? [a.length, b.length] + out.push(`@@ ref ${i + 1} / ours ${j + 1}`) + for (let k = Math.max(0, i - 1); k < i; k++) out.push(` ${a[k]}`) + for (let k = i; k < Math.min(ni, i + 8); k++) out.push(`- ${a[k]}`) + for (let k = j; k < Math.min(nj, j + 8); k++) out.push(`+ ${b[k]}`) + i = ni + j = nj + } + return out.join('\n') +} + +const median = (values: number[]) => values.toSorted((a, b) => a - b)[values.length >> 1]! +const args = process.argv.slice(2) +const parser = async (): Promise<(html: string) => Document> => + ((await import('../src/parse.ts')) as { parse: (html: string) => Document }).parse +const pages = [...corpusPages(), ...fixturePages()] +if (args[0] === '--time') { + // emit alone, over documents built once; --runs n, and per page with --pages + // --parser: documents from src/parse.ts (while it's being written, it may not load), else the oracle's + const build = args.includes('--parser') ? await parser() : oracle + const real = corpusPages() + let corpus = real.map((page) => ({ page, doc: build(page.html) })) + const count = Number(args[args.indexOf('--runs') + 1]) || 30 + // --cold: fresh documents for every run (built outside the timing), so nothing emit caches on one is reused + const cold = args.includes('--cold') + const runs: number[] = [] + const pageTimes = corpus.map(() => [] as number[]) + for (let run = 0; run < count; run++) { + if (cold && run) corpus = real.map((page) => ({ page, doc: build(page.html) })) + let total = 0 + corpus.forEach(({ page, doc }, i) => { + const at = performance.now() + emit(doc, { url: page.url }) + const took = performance.now() - at + pageTimes[i]!.push(took) + total += took + }) + runs.push(total) + } + if (args.includes('--pages')) + corpus.forEach(({ page }, i) => + console.log(`${median(pageTimes[i]!).toFixed(2).padStart(7)} ms ${page.name}`), + ) + console.log( + `emit, corpus total: median ${median(runs).toFixed(2)} ms, min ${Math.min(...runs).toFixed(2)} ms`, + ) +} else if (args[0]) { + const page = pages.find((p) => p.name === args[0] || p.name.includes(args[0]!)) + if (!page) throw new Error(`no page ${args[0]}`) + const reference = htmlToMarkdown(page.html, { url: page.url }).markdown + const ours = emit(oracle(page.html), { url: page.url }).markdown + // --write <dir>: both outputs, for a diff tool + if (args[1] === '--write' && args[2]) { + writeFileSync(`${args[2]}/ref.md`, reference) + writeFileSync(`${args[2]}/ours.md`, ours) + } + console.log(reference === ours ? 'exact' : hunks(reference, ours, Number(args[1]) || 6)) +} else { + let exact = 0 + let fixtures = 0 + for (const page of pages) { + const reference = htmlToMarkdown(page.html, { url: page.url }).markdown + const ours = emit(oracle(page.html), { url: page.url }).markdown + if (!page.corpus) fixtures++ + if (reference === ours) exact++ + // a page that isn't exact never reads 100%, even with every reference line in place + const share = + reference === ours + ? 'exact ' + : `${Math.min(99.9, similarity(reference, ours) * 100) + .toFixed(1) + .padStart(5)}%` + if (page.corpus || reference !== ours) console.log(`${share} ${page.name}`) + } + console.log( + `${exact}/${pages.length} exact (${pages.length - fixtures} corpus pages, ${fixtures} fixtures)`, + ) +} diff --git a/packages/md-core/test/emit-phases.ts b/packages/md-core/test/emit-phases.ts new file mode 100644 index 0000000..61854d4 --- /dev/null +++ b/packages/md-core/test/emit-phases.ts @@ -0,0 +1,38 @@ +// where emit's time goes, phase by phase, over the corpus: node test/emit-phases.ts +import { convertRoot, startConvert } from '../src/emit-convert.ts' +import { toMarkdown } from '../src/emit-markdown.ts' +import { begin, findMain, made, setPage } from '../src/emit-prune.ts' +import type { Document } from '../src/types.ts' +import { oracle } from './support/oracle.ts' +import { corpusPages } from './emit-pages.ts' + +// --parser: documents from src/parse.ts, else the oracle's +const build = process.argv.includes('--parser') + ? ((await import('../src/parse.ts')) as { parse: (html: string) => Document }).parse + : oracle +const corpus = corpusPages().map((page) => ({ page, doc: build(page.html) })) +// per phase, the fastest whole-corpus run: other work on the machine only ever adds time +const best = { main: Infinity, convert: Infinity, markdown: Infinity } +const runs = Number(process.argv[2]) || 100 +for (let run = 0; run < runs; run++) { + const totals = { main: 0, convert: 0, markdown: 0 } + for (const { page, doc } of corpus) { + let at = performance.now() + begin(false) + setPage(doc.root) + const main = findMain(doc.root) + if (!main) begin(true) + totals.main += performance.now() - at + at = performance.now() + startConvert({ url: page.url }, page.url) + const root = convertRoot(main ? made(doc.root, [main], '#root') : doc.root) + totals.convert += performance.now() - at + at = performance.now() + toMarkdown(root) + totals.markdown += performance.now() - at + } + for (const phase of ['main', 'convert', 'markdown'] as const) + best[phase] = Math.min(best[phase], totals[phase]) +} +for (const [phase, total] of Object.entries(best)) + console.log(`${phase.padEnd(9)} ${total.toFixed(2)} ms`) diff --git a/packages/md-core/test/emit.test.ts b/packages/md-core/test/emit.test.ts new file mode 100644 index 0000000..e7852f6 --- /dev/null +++ b/packages/md-core/test/emit.test.ts @@ -0,0 +1,313 @@ +import { htmlToMarkdown } from '@affordances/md' +import { describe, expect, test } from 'vitest' +import { emit } from '../src/emit.ts' +import type { Options, Result } from '../src/types.ts' +import { corpusPages, fixturePages, type Page, similarity } from './emit-pages.ts' +import { oracle } from './support/oracle.ts' + +// emit's result for a page, and @affordances/md's for the same page: the target is the same bytes (and title, url +// and token count). a page is a body's content, or a whole document +const url = 'https://shop.test/page' +const document = (html: string) => (/<html|<body|<head/i.test(html) ? html : `<body>${html}</body>`) +const result = ({ markdown, title, url: link, tokens }: Result) => ({ + markdown, + title, + url: link, + tokens, +}) +const ours = (html: string, options: Options = {}) => + result(emit(oracle(document(html)), { url, ...options })) +const theirs = (html: string, options: Options = {}) => + result(htmlToMarkdown(document(html), { url, ...options })) + +describe('blocks', () => { + test.each([ + '<h1>Title</h1><h2>Two</h2><h3>Three</h3><h6>Six</h6>', + '<p>one</p><p>two</p><hr><p>three</p>', + '<h1>a<br>b</h1><h2>c<br>d</h2><h3>e<br>f</h3>', + '<h2></h2><p></p><p><br></p><p><br>x<br></p>', + '<blockquote><p>quoted</p><blockquote><p>nested</p></blockquote></blockquote>', + '<blockquote>loose <b>text</b><ul><li>item</li></ul></blockquote>', + '<div>text<div>block</div>more</div>', + '<section><article><p>deep</p></article></section><aside>side</aside>', + '<p>E = mc<sup>2</sup> and H<sub>2</sub>O</p><div>x<sup>1</sup>y</div>', + '<p>a <q>quoted</q> b <q><em>em</em></q></p>', + '<p>long<wbr>word</p>', + '<center>old</center><font>font</font><big>big</big>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('lists', () => { + test.each([ + '<ul><li>a</li><li>b<ul><li>c</li><li>d</li></ul></li><li>e</li></ul>', + '<ol><li>one</li><li>two</li></ol><ol start="3"><li>three</li></ol><ol start="0"><li>z</li></ol>', + '<ol start="x"><li>a</li></ol><ol start="10"><li>ten</li><li>eleven</li></ol>', + '<ul><li><p>loose</p></li><li><p>items</p></li></ul>', + '<ul><li><div>a</div><ul><li>b</li></ul></li><li>c</li></ul>', + '<ul><li><input type="checkbox" checked> done</li><li><input type="checkbox"> todo</li><li><p><input type="checkbox"> in p</p></li></ul>', + '<ul><li>a</li><ul><li>nested directly</li></ul><li>b</li></ul>', + '<ul><li></li><li>after empty</li></ul>', + '<p>lead</p><ul><li>a</li></ul><ul><li>second list</li></ul><ol><li>third</li></ol>', + '<ul><li><hr></li><li>x</li></ul>', + '<ul><li><pre><code>code\n block</code></pre></li><li>b</li></ul>', + '<ul><li><blockquote>q</blockquote></li></ul>', + '<ol><li><ul><li><ul><li></li></ul></li></ul></li></ol>', + '<dt>stray term</dt><dd>stray definition</dd>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('inline', () => { + test.each([ + '<p>Orders <strong>ship</strong> in <em>two</em> to <b>three</b> <i>days</i>, <del>free</del> <s>x</s> <code>flat</code>.</p>', + '<p>foo<em>bar</em>baz <strong>a</strong><strong>b</strong> <em> spaced </em></p>', + '<p><em>*</em> <strong>**</strong> <em>_</em> <b><i>both</i></b> <i><b>both</b></i></p>', + '<p><em>a<em>b</em>c</em> <del>a<del>b</del>c</del> <strong>x <em>y</em> z</strong></p>', + '<p>a<mark>m</mark><u>u</u><ins>i</ins><small>s</small><kbd>Ctrl</kbd><samp>out</samp><var>v</var><tt>t</tt></p>', + '<p>code with <code>`ticks`</code> and <code>``double``</code> and <code> spaced </code> and <code>a|b</code></p>', + '<p>a<br>b<br><br>c</p><p>line<br> after</p>', + '<p><abbr title="x">ab</abbr> <time>noon</time> <cite>c</cite> <dfn>d</dfn> <span>s</span></p>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('escapes', () => { + test.each([ + '<p>*star* _under_ snake_case_name __dunder__ 2*3*4</p>', + '<p>[brackets] and ![bang] and (parens) and a](b</p>', + '<p>1. not a list</p><p>2) nor this</p><p>- dash</p><p>+ plus</p><p>* star</p><p># hash</p><p>> quote</p>', + '<p>= equals</p><p>~ tilde ~~strike~~</p><p>| pipe | x</p><p>`tick</p><p><div> and <3</p>', + '<p>&amp; &copy; &#38; A & B</p>', + '<p>back\\slash \\* \\_ and a\\</p>', + '<p>www.example.com and https://example.com and me@example.com</p>', + '<h2>www.example.com https://example.com me@example.com</h2>', + '<h2>Ends with #</h2><h3># starts</h3><h2> </h2>', + '<p>tab\there</p><p> lead and trail </p>', + '<p>emoji 😀 and ünïcödé and 中文</p>', + '<p>100% sure: 3 < 4 > 2, a_b_c, *a*b</p>', + '<p>text <a href="/x">link</a>! and ![<a href="/y">img</a></p>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('links and images', () => { + test.each([ + '<p><a href="/rel">relative</a> <a href="../up">up</a> <a href="?q=1&b=2">query</a> <a href="#frag">frag</a></p>', + '<p><a href="https://example.com">https://example.com</a> <a href="mailto:me@x.test">me@x.test</a></p>', + '<p><a href="https://example.com/a b">space</a> <a href="https://example.com/(paren)">paren</a> <a href="/a?b=(c)">p2</a></p>', + '<p><a href="/t" title="A "title"">titled</a> <a href="javascript:alert(1)">js</a> <a href="#">top</a> <a href="">none</a></p>', + '<p><a href="tel:+1">call</a> <a href="ftp://x.test">ftp</a> <a href="//cdn.test/x">proto</a> <a href="HTTPS://X.TEST/A">upper</a></p>', + '<h2 id="s"><a href="#s">Section</a></h2><h3><a href="/other">Elsewhere</a></h3>', + '<p><a href="/a"><img src="/i.png" alt="pic"></a> <a href="/b" aria-label="Label"><svg></svg></a> <a href="/c"></a></p>', + '<p><a href="/a" title="T"><span></span></a> <a href="/same">x</a> <a href="/same">x</a> <a href="/same">y</a></p>', + '<div><a href="/block"><div>block one</div><div>block two</div></a></div>', + '<p><img src="/a.png" alt="described"> <img src="/b.png" alt=""> <img src="/c.png"> <img alt="no src"> <img src="data:x" alt="data"></p>', + '<p><img src="/a.png" alt="with title" title="T"> <img src="https://cdn.test/x y.png" alt="space"></p>', + '<p><a href="/x">[x]: y</a></p>', + '<p><a href="https://x.test/%7Efoo">tilde</a> <a href="https://x.test:443/p">port</a> <a href="https://x.test/./a/../b">dots</a></p>', + '<p><a href="/path#x">hash</a> <a href="https://x.test">bare</a> <a href="https://x.test?q">q</a> <a href="http://127.1/">ip</a></p>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('code', () => { + test.each([ + '<pre><code class="language-ts">const a = 1\n</code></pre>', + '<pre><code>no language\n\n\n</code></pre>', + '<pre data-language="py"><code>print(1)</code></pre><pre class="language-rb"><code>puts 1</code></pre>', + '<pre><code class="language-js">a ``` b</code></pre>', + '<pre><div>line one</div><div>line two</div></pre>', + '<pre>a<br>b</pre><pre><span> indented</span>\n<span>next</span></pre>', + '<figure><figcaption>route.ts</figcaption><pre><code class="language-ts">x</code></pre></figure>', + '<figure><pre><code class="language-ts">x</code></pre><figcaption>after</figcaption></figure>', + '<div data-title="file.js"><pre><code class="language-js">y</code></pre></div>', + '<pre data-title="t.ts"><code class="language-ts">z</code></pre>', + '<listing>old\n code</listing><xmp>raw <b>x</b></xmp>', + '<pre><code class="language-a b">two classes</code></pre>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('tables', () => { + test.each([ + '<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>', + '<table><tr><td>headless</td><td>row</td></tr><tr><td>x</td><td>y</td></tr></table>', + '<table><tr><th>first row th</th></tr><tr><td>x</td></tr></table>', + '<table><tr><td>a</td><th>mixed</th></tr><tr><th>late</th><td>b</td></tr></table>', + '<table><tr><th colspan="2">wide</th></tr><tr><td>a</td><td>b</td></tr></table>', + '<table><tr><th>a</th><th>b</th></tr><tr><td rowspan="2">tall</td><td>1</td></tr><tr><td>2</td></tr></table>', + '<table><tr><th align="right">r</th><th align="center">c</th><th align="left">l</th></tr><tr><td>1</td><td>2</td><td>3</td></tr></table>', + '<table><tr><th>h</th></tr><tr><td><p>para one</p><p>para two</p></td></tr></table>', + '<table><tr><th>h</th></tr><tr><td><div>1,542</div><div>1,533</div></td></tr></table>', + '<table><tr><th>h</th></tr><tr><td>a | b <code>c|d</code></td></tr></table>', + '<table><tr><th>h</th></tr><tr><td><table><tr><td>in</td><td>ner</td></tr></table></td></tr></table>', + '<table><tr><th>Status</th></tr><tr><td></td></tr></table><p>after skeleton</p>', + '<table><tr><td></td></tr></table><table><caption>only caption</caption></table>', + '<table><tr><th><button>Sort</button></th></tr><tr><td>v</td></tr></table>', + '<table><tr><th>h</th></tr><tr><td>a<br>b</td></tr></table>', + '<table><tr><td>uneven</td></tr><tr><td>a</td><td>b</td><td>c</td></tr></table>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('details and definitions', () => { + test.each([ + '<details><summary>Returns</summary><p>Within 30 days.</p></details>', + '<details><p>no summary</p></details><details><summary><b>bold</b> sum</summary>text</details>', + '<dl><dt>Carrier</dt><dd>Post</dd><dt>Insured</dt><dd>Yes</dd></dl>', + '<dl><dt>A</dt><dt>B</dt><dd>both</dd><div><dt>C</dt><dd>wrapped</dd></div></dl>', + '<dl><dt>T</dt><dd><p>para</p><ul><li>list</li></ul>tail</dd><dd>no term</dd></dl>', + '<dl><dt></dt><dd>empty term</dd></dl>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('whitespace', () => { + test.each([ + '<p> many spaces\n\nand\tlines </p>', + '<p>a <span> b </span> c</p><p><span>x</span> <span>y</span></p>', + '<div> <span>inline</span> <div>block</div> after </div>', + '<p>nbsp  kept </p>', + '<p>before <img src="/i.png" alt="img"> after</p><p>x <input> y</p>', + '<p><span>un</span><em>believ</em><span>able</span></p>', + '<p>a<button>b</button>c <select><option>o</option></select> d</p>', + '<td>stray cell</td><nobr>no wrap</nobr>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('spacing', () => { + test.each([ + '<p><span>express</span><span>5.3.0</span> <span>$</span><span>48</span></p>', + '<p><a href="/a">a</a><a href="/b">b</a> <span><a href="/c">c</a></span><span><a href="/d">d</a></span></p>', + '<div style="display:flex">configure<span>vlt</span></div><div class="md:flex">x<span>y</span></div>', + '<p><span class="block">yarn (zpm)</span><span class="block">6.0.0</span> <span style="display: block">5/6</span><span>fixtures</span></p>', + '<p><span>H</span><span>e</span><span>l</span><span>l</span><span>o</span></p>', + '<p><a href="/u"><img src="/a.png" alt="Ann"></a><a href="/u"><img src="/a.png" alt="Ann"></a> <a href="/u">x</a></p>', + '<pre><code><span>no</span><span>space</span></code></pre><p><code><span>a</span><span>b</span></code></p>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('hidden', () => { + test.each([ + '<p>shown</p><p hidden>hidden</p><p aria-hidden="true">aria</p><p aria-hidden="false">kept</p>', + '<p style="display:none">none</p><p style="visibility: hidden">vis</p><p style="content-visibility:hidden">cv</p><p style="opacity:0">kept</p>', + '<p style="DISPLAY : NONE !important">caps</p><p style="display:/* c */none">comment</p><p style="d\\69splay:none">escape</p>', + '<p style="visibility:collapse">collapse</p><p style="color:red">red kept</p>', + '<div contenteditable>typed</div><div contenteditable="false">kept</div><div role="textbox">box</div>', + '<p>a</p><div data-affordances-md="skip">skipped</div><p hidden data-affordances-md="show">shown for agents</p>', + '<p>x<span hidden>gone</span>y</p>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +describe('extract', () => { + test.each([ + '<header><nav><a href="/">Home</a></nav></header><main><h1>Main</h1><p>content</p></main><footer>foot</footer>', + '<div role="main"><p>role main</p></div><nav>nav</nav>', + '<div role="main"><p>role</p></div><main><p>real main wins</p></main>', + '<main><p>first</p></main><main><p>second</p></main>', + '<div hidden><main><p>hidden main</p></main></div><p>body</p>', + '<header>banner</header><div role="navigation">nav role</div><p>body only</p><aside>aside</aside><footer>f</footer>', + '<div aria-hidden="true">x</div><div role="complementary">c</div><section><nav>inner nav</nav><p>kept</p></section>', + 'just text, no blocks <b>at all</b>', + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) +}) + +const whole = (head: string, body: string) => + `<html lang="en"><head>${head}</head><body>${body}</body></html>` +describe('the head', () => { + test.each([ + whole('<title>Shipping notes', '

no h1

'), + whole('Shipping notes', '

Shipping notes

body

'), + whole('Cart · Acme', '

Cart

'), + whole('Acme | Cart', '

Cart

'), + whole('Cart: details', '

Cart

'), + whole('Other', '

Heading https://x.test

'), + whole( + '', + '

T

How orders leave.

next

', + ), + whole('', '

OG

'), + whole( + '', + '

x

', + ), + whole('', '

x

'), + whole('', '

x

'), + whole( + '', + '

x

', + ), + whole('', '

x

'), + whole(' Spaced title ', '

a
b

'), + ])('%s', (html) => expect(ours(html)).toEqual(theirs(html))) + + test('without frontmatter or json-ld', () => { + const html = whole( + 'T', + '

d

', + ) + expect(ours(html, { frontmatter: false })).toEqual(theirs(html, { frontmatter: false })) + expect(ours(html, { jsonLd: false })).toEqual(theirs(html, { jsonLd: false })) + }) +}) + +// a link hook: every page's twin, but one +const link = (target: URL) => (target.pathname === '/skip' ? undefined : `${target.href}.md`) +describe('options', () => { + test('extract none keeps the chrome', () => { + const html = '

main

' + expect(ours(html, { extract: 'none' })).toEqual(theirs(html, { extract: 'none' })) + }) + test('the link hook relinks links, never images or fragments', () => { + const html = + '

a f i s

' + expect(ours(html, { link })).toEqual(theirs(html, { link })) + }) + test('without a url, links stay as written', () => { + const html = '

a i

' + expect(ours(html, { url: undefined })).toEqual(theirs(html, { url: undefined })) + }) +}) + +// @affordances/md's own fixtures, each against its output (not the .md beside it, which the working tree may change +// before the package is built again) +const fixtures = fixturePages() +// known differences, all from what emit doesn't do yet, each with the share of its reference lines emit reproduces in +// order: markers and slots (: main, text), the form summary, shown tab panels, streamed suspense +// boundaries. a page that gets closer should raise its floor; one that gets exact moves out of the list +const KNOWN = new Map([ + ['disclosure-fumadocs-tabs', 0.76], + ['disclosure-radix-tabs', 0.76], + ['form', 0.58], + ['form-labels', 0.53], + ['form-values', 0.33], + ['main-markers', 0.99], + ['markers', 0.66], + ['package-page', 0.93], + ['settings-form', 0.56], + ['streamed-instructions', 0.68], + ['streamed-next16.3', 0.46], + ['streamed-product', 0.86], + ['streamed-react19', 0.46], +]) +const markdownOf = (page: Page) => ({ + ours: emit(oracle(page.html), { url: page.url }).markdown, + reference: htmlToMarkdown(page.html, { url: page.url }).markdown, +}) +describe('fixtures', () => { + test.each( + fixtures.filter((page) => !KNOWN.has(page.name)).map((page) => [page.name, page] as const), + )('%s', (_, page) => { + const { ours: written, reference } = markdownOf(page) + expect(written).toBe(reference) + }) + test.each( + fixtures.filter((page) => KNOWN.has(page.name)).map((page) => [page.name, page] as const), + )('%s, a known difference', (_, page) => { + const { ours: written, reference } = markdownOf(page) + expect(written).not.toBe(reference) + expect(similarity(reference, written)).toBeGreaterThanOrEqual(KNOWN.get(page.name)!) + }) +}) + +// the benchmark corpus, when it's been fetched: byte for byte, every page +const corpus = corpusPages() +describe.skipIf(!corpus.length)('corpus parity', () => { + test.each(corpus.map((page) => [page.name, page] as const))('%s', (_, page) => { + const { ours: written, reference } = markdownOf(page) + expect(written).toBe(reference) + }) +}) diff --git a/packages/md-core/test/parse-entities-gen.ts b/packages/md-core/test/parse-entities-gen.ts new file mode 100644 index 0000000..045f5b3 --- /dev/null +++ b/packages/md-core/test/parse-entities-gen.ts @@ -0,0 +1,62 @@ +// writes src/entities-table.ts: every named character reference html knows, read out of the decode tree that parse5 +// itself decodes with (the entities package, parse5's dependency), so the table is the oracle's by construction. run +// with `node test/parse-entities-gen.ts` from the package, then `oxfmt src/entities-table.ts` +import { writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' + +const require = createRequire(import.meta.resolve('parse5')) +const entities = (await import(require.resolve('entities/decode'))) as { + EntityDecoder: new ( + tree: Uint16Array, + emit: (cp: number) => void, + ) => { + startEntity(mode: number): void + write(input: string, offset: number): number + end(): number + } + htmlDecodeTree: Uint16Array +} +const LEGACY = 0 +const STRICT = 1 + +let out = '' +const decoder = new entities.EntityDecoder(entities.htmlDecodeTree, (cp) => { + out += String.fromCodePoint(cp) +}) +// -1: the name so far could still become a reference; >0: it is one (the count includes the '&') +const run = (mode: number, text: string, end: boolean) => { + out = '' + decoder.startEntity(mode) + let consumed = decoder.write(text, 0) + if (consumed < 0 && end) consumed = decoder.end() + return { consumed, value: out } +} + +const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' +const table: [string, string][] = [] +const walk = (prefix: string) => { + for (const char of ALNUM) { + const name = prefix + char + if (run(STRICT, name, false).consumed !== -1) continue + const full = run(STRICT, `${name};`, false) + if (full.consumed === name.length + 2) table.push([`${name};`, full.value]) + const legacy = run(LEGACY, name, true) + if (legacy.consumed === name.length + 1) table.push([name, legacy.value]) + walk(name) + } +} +walk('') +table.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) +const strict = table.filter(([name]) => name.endsWith(';')).length +// the html spec's table: 2125 names with ';' and 106 legacy ones without +if (strict !== 2125 || table.length - strict !== 106) + throw new Error(`unexpected table: ${strict} with ';', ${table.length - strict} without`) + +const body = table.map(([name, value]) => ` ${JSON.stringify(name)}: ${JSON.stringify(value)},`) +writeFileSync( + new URL('../src/entities-table.ts', import.meta.url), + `// generated by test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones +// (decoded without a ';') also under their bare name. do not edit +export const ENTITIES: Record = {\n${body.join('\n')}\n}\n`, +) +console.log(`wrote ${table.length} names`) diff --git a/packages/md-core/test/parse-fuzz.ts b/packages/md-core/test/parse-fuzz.ts new file mode 100644 index 0000000..ce5c46d --- /dev/null +++ b/packages/md-core/test/parse-fuzz.ts @@ -0,0 +1,224 @@ +// generated html for the differential fuzz: small pages that pile up the constructs a parser gets wrong (raw text and +// its end tags, comments and their odd endings, quotes and '>' in attributes, references, misnesting, tables, foreign +// content, implied tags), seeded so a failure can be replayed + +// where this parser knowingly differs from the oracle, on what the generator can make: a generated page one of these +// matches is left out of the fuzz, and the reason stays here to be seen. none at present: the differences known (see +// the report) are on pages this generator doesn't make +export const KNOWN: { why: string; matches: (html: string) => boolean }[] = [] + +// pages parse5 7.3 throws on: an end tag that empties its stack of open elements (popUntilTagNamePopped pops +// everything when the tag isn't there, then text goes into nothing). browsers don't, so the oracle can't speak to +// them; the fuzz counts and skips them, and checks this parser still parses them +export const ORACLE_THROWS = ['
>'] + +// mulberry32: small, fast, and the same everywhere +export const random = (seed: number) => { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +const TAGS = ( + 'p div span b i u s em strong code a font nobr big small tt strike li ul ol dl dt dd h1 h2 h3 pre listing ' + + 'table caption colgroup col tbody thead tfoot tr td th select option optgroup form button label input textarea ' + + 'title script style xmp iframe noembed noframes noscript template svg math mi mo mtext annotation-xml desc ' + + 'foreignObject path g html head body br img hr wbr image keygen object applet marquee canvas video audio source ' + + 'meta link base rt rp rb rtc ruby section article header footer nav main aside blockquote figure figcaption ' + + 'details summary dialog address center fieldset menu dir search hgroup frameset frame param track embed area ' + + 'sub sup var my-element x' +).split(' ') +const RARE_TAGS = ['plaintext'] +const ATTRS = [ + 'class', + 'id', + 'href', + 'type', + 'color', + 'face', + 'size', + 'encoding', + 'lang', + 'rel', + 'name', + 'content', + 'property', + 'xlink:href', + 'XLINK:href', + 'definitionurl', + 'title', + 'data-x', + 'CLASS', +] +const VALUES = [ + 'x', + 'hidden', + 'HIDDEN', + 'canonical', + 'text/html', + 'application/ld+json', + 'a b', + '>', + 'a>b', + '"', + "'", + '&', + '¬it;', + '¬', + '&=', + '&x', + '&', + '€', + '�', + '', + '/', + 'red', + 'en', + 'og:title', +] +const WORDS = [ + 'a', + 'text', + ' ', + '\n', + ' \n ', + '\t', + '&', + '<b>', + '¬it;', + '¬', + '©', + '€', + '–', + '�', + '�', + '�', + 'A', + ' ', + ' ', + '&#;', + '&#x;', + '&', + '&;', + '&zz;', + '<', + '< b', + '>', + '"', + "'", + '=', + '\r\n', + '\r', + '\0', + ' ', + '©', + '', + '', +] +const COMMENTS = [ + '', + '', + '', + '', + '', + '', + '', + '', + '', + ''", + '\0', +] + +// a few tags that interact a lot, for the denser half of the pages: formatting misnested across blocks, tables and +// what gets fostered out of them, select, and foreign content with its integration points and breakouts +const DENSE = ( + 'a b i nobr font p div li dd table caption tr td th tbody colgroup col select option optgroup svg math mi ' + + 'annotation-xml desc foreignObject title template button form h1 pre textarea script style noscript object br' +).split(' ') + +export const generate = (seed: number) => { + const next = random(seed) + const dense = next() < 0.5 + const pick = (list: readonly T[]) => list[Math.floor(next() * list.length)]! + const chance = (p: number) => next() < p + const attrs = () => { + let out = '' + const count = chance(0.5) ? 0 : Math.floor(next() * 4) + for (let i = 0; i < count; i++) { + out += pick([' ', '\n', ' ', '/', ' /']) + out += pick(ATTRS) + if (chance(0.8)) { + out += pick(['=', ' = ', '=']) + const value = pick(VALUES) + const q = next() + if (q < 0.45) out += `"${value.replaceAll('"', '"')}"` + else if (q < 0.8) out += `'${value.replaceAll("'", ''')}'` + else out += value.replace(/[\s"'>]/g, '') || 'v' + } + } + if (chance(0.1)) out += '/' + return out + } + const parts: string[] = chance(0.3) ? [''] : [] + const length = 1 + Math.floor(next() * (dense ? 80 : 40)) + for (let i = 0; i < length; i++) { + const r = next() + if (r < 0.3) parts.push(pick(WORDS)) + else if (r < 0.62) { + const tag = chance(0.003) ? pick(RARE_TAGS) : pick(dense && chance(0.8) ? DENSE : TAGS) + const name = chance(0.1) ? tag.toUpperCase() : tag + parts.push(`<${name}${attrs()}>`) + // raw text content right after its element + if (/^(script|style|title|textarea|xmp|iframe|noembed|noframes)$/.test(tag) && chance(0.7)) { + const bits = 1 + Math.floor(next() * 5) + for (let b = 0; b < bits; b++) parts.push(pick(RAW_BITS)) + if (chance(0.8)) parts.push(``) + } + } else if (r < 0.9) + parts.push(``) + else parts.push(pick(COMMENTS)) + } + // sometimes a page ends inside a tag or an attribute + if (chance(0.03)) + parts.push(pick(['">y', + 'a</title', + '<title>never closed <p>', + '<textarea>\nfirst newline dropped</textarea>', + '<textarea>\n\nonly one dropped</textarea>', + '<textarea><!-- not a comment --></textarea>', + '<textarea>a\0b</textarea>', + '<p><textarea><b></textarea>', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('rawtext: style, xmp, iframe, noembed, noframes', () => { + test.each([ + '<style>p { color: red } </p> <b></style>after', + '<xmp><b>&</b></xmp>', + '<p>a<xmp>b</xmp>', + '<iframe><p>x</p></iframe>after', + '<noembed><b>x</b></noembed>after', + '<noframes><b>x</b></noframes>after', + '<style></styl></style >x', + '<style>\0</style>', + // noscript isn't raw text with scripting off: its content is parsed + '<noscript><b>x</b></noscript>after', + '<head><noscript><link rel=x><b>y</b></noscript></head>', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('script data and its escapes', () => { + test.each([ + '<script>if (a < b) document.write("</div>")</script>after', + '<script>var s = "</scr" + "ipt>"</script>after', + '<script>a</script >b', + '<script>a</SCRIPT>b', + '<script>a</scriptx>still script</script>b', + '<script><!-- <script> </script> still --></script>after', + '<script><!-- </script>after', + '<script><!--></script>after', + '<script><!---></script>after', + '<script><!-- a --></script>after', + '<script><!-- <script></script> --> </script>after', + '<script><!-- <SCRIPT>x</SCRIPT> -- > --></script>after', + '<script><!-- <scripts></script>after', + '<script><!-- -- <script --></script>after', + '<script>\0</script>', + '<script>never closed <p>x', + '<script>a</script', + '<script type="application/ld+json">{"a": "</p>"}</script>', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('plaintext', () => { + test.each(['<plaintext><b>x</b></plaintext>&', '<p>a<plaintext>b'])('%j', (html) => + expect(difference(html)).toBeUndefined(), + ) +}) + +describe('comments and bogus comments', () => { + test.each([ + 'a<!-- c -->b', + 'a<!---->b', + 'a<!-->b', + 'a<!--->b', + 'a<!-- c --!>b', + 'a<!-- c --!x -->b', + 'a<!-- c -- d -->b', + 'a<!-- <!-- nested --> -->b', + 'a<!-- c ---->b', + 'a<!--', + 'a<!-- never closed <p>x', + 'a<?php echo "<b>"; ?>b', + 'a</ x>b', + 'a</3>b', + 'a</>b', + 'a<!x>b', + 'a<!>b', + 'a<![CDATA[ c ]]>b', + 'a</', + 'a<', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('cdata only in foreign content', () => { + test.each([ + '<svg><![CDATA[ <b> ]]></svg>after', + '<math><mi>x</mi><![CDATA[ a<b ]]></math>', + '<math><![CDATA[ a\0\0b ]]></math>', + '<math><![CDATA[ never closed', + '<div><![CDATA[ <b>x</b> ]]></div>', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('doctypes and quirks', () => { + test.each([ + // a p doesn't close for a table in quirks mode + '<!DOCTYPE html><p><table><tr><td>x</table>', + '<p><table><tr><td>x</table>', + '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><p><table></table>', + '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><p><table></table>', + '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "x"><p><table></table>', + '<!DOCTYPE html SYSTEM "about:legacy-compat"><p><table></table>', + '<!DOCTYPE html SYSTEM "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"><p><table></table>', + '<!doctype HTML><p><table></table>', + '<!DOCTYPEhtml><p><table></table>', + '<!DOCTYPE><p><table></table>', + '<!DOCTYPE foo><p><table></table>', + '<!DOCTYPE html "x"><p><table></table>', + '<!DOCTYPE html PUBLIC><p><table></table>', + '<!DOCTYPE html PUBLIC "html"><p><table></table>', + '<!DOCTYPE html PUBLIC "x" junk><p><table></table>', + '<!DOCTYPE html SYSTEM "x" junk><p><table></table>', + '<!DOCTYPE html PUBLIC "x>"><p><table></table>', + 'x<!DOCTYPE html><p><table></table>', + '<!DOCTYPE html', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('tags and attributes', () => { + test.each([ + '<a href="x>y" title=\'a>b\'>z</a>', + '<a href=x>y</a>', + "<a b'c'>x</a>", + '<a b"c">x</a>', + "<a b='>'c>x</a>", + '<a =b>x</a>', + '<a ==b>x</a>', + '<a b= c>x</a>', + '<a b =c d>x</a>', + '<a b="1"c="2">x</a>', + '<a b=x/>y</a>', + '<a/b/c>x</a>', + '<a b=>x</a>', + '<a href="&¬it;¬=&=x&x">x</a>', + "<a href='€�&'>x</a>", + '<a HREF="X" Class=y>x</a>', + '<a b=1 b=2 B=3>x</a>', + '<a b="\0">x</a>', + '<a\0b c>x</a>', + '<DIV>upper</DiV>', + '<div\n\tclass="a"\fid=b>x</div>', + '<div class="a\r\nb">x</div>', + '<my-element data-x="1">x</my-element>', + '<div >no attributes</div>', + '<br/><br /><img src=x/><hr/>', + '<div/>not self-closing</div>', + '<a href="never closed>x', + '<div', + '<div class', + '</div foo="bar">x', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('void elements and implied end tags', () => { + test.each([ + '<p>a<p>b<div>c</div><p>d', + '<p>a<h1>b</h1><p>c<ul><li>d</ul>', + '<p>a<table></table>', + '<p>a<hr>b', + '<p>a<pre>\nb</pre>', + '<pre>\n\nx</pre><listing>\nx</listing>', + '<pre> x</pre>', + '<pre><!---->\nx</pre>', + '<ul><li>a<li>b<ul><li>c</ul><li>d</ul>', + '<li>a<div><li>b</div>', + '<dl><dt>a<dd>b<dt>c<dd>d</dl>', + '<select><option>a<option>b<optgroup><option>c<optgroup>d</select>', + '<h1>a<h2>b</h2>c</h1>', + '<h1>a</h2>b', + '<ruby>a<rb>b<rt>c<rp>d<rtc>e<rt>f</ruby>', + '<button>a<button>b</button>', + '<form><form>x</form></form>', + '<form>a</form>b</form>c', + '<nobr>a<nobr>b</nobr>', + '<a>a<a>b</a>c', + '<a href=1>a<div>b<a href=2>c</a></div>', + '<br>a<input>b<img>c<wbr>d<embed>e<keygen>f<area>g', + '<image src=x>', + '<p>a</p></p>b', + '</p>x', + '</br>x', + '</div>x', + '<div>a</span>b</div>', + '<p><b>x</p>y', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('misnested formatting: the adoption agency', () => { + test.each([ + '<b>1<p>2</b>3</p>', + '<b>1<i>2</b>3</i>4', + '<a href=x>1<p>2</a>3', + '<b><b><b><b>x</b></b></b></b>', + '<b>1<div>2<i>3</div>4</b>5', + '<b id=1><b id=1><b id=1><b id=1>x', + '<b><b><b><b><p>x</b>y', + '<b>a<table><tr><td>b</b>c</td></tr></table>d', + '<b><noscript><p>x</b>y', + '<b><object><p>x</b>y</object>', + '<i><b><p>x</i>y', + '<em><strong><code><s><u><p>x</em>y', + '<b>a</b></b>b', + '<b>x<p>y<b>z', + '<font color=red>a<p>b</font>c', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('tables and foster parenting', () => { + test.each([ + '<table><tr><td>a</td></tr></table>', + '<table><td>a<td>b<tr><td>c</table>', + '<table>text<tr><td>x</table>', + '<table> <tr> <td>x</td> </tr> </table>', + '<table><b>x</b><tr><td>y</table>', + '<table><div>x</div></table>', + '<table><caption>c<td>x</table>', + '<table><colgroup><col><col></colgroup><tbody><tr><th>h</th></tr></tbody></table>', + '<table><col><tr><td>x</table>', + '<table><thead><tr><td>a<tbody><tr><td>b<tfoot><tr><td>c</table>', + '<table><tr><td>a<table><tr><td>b</table>c</table>', + '<table><table>x</table>', + '<table><input type=hidden><input type=text>x</table>', + '<table><form><tr><td>x</form></table>', + '<table><script>a</script><style>b</style><tr><td>x</table>', + '<table><select><option>a</table>b', + '<table><tr><td><select><option>a<td>b</table>', + '<table><tr>a<!-- c -->b<td>x</table>', + '<table><tr><td>a</tr></td>b</table>', + '<table></tbody></tr></td>x</table>', + '<td>outside</td>', + '<table><tr><td>x</table></td>y', + '<table><caption>a<p>b</caption>c</table>', + '<p>a<table><tr><td>b</p>c</td></tr></table>', + '<table>�<tr><td>x\0y</table>', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('select', () => { + test.each([ + '<select><option>a</option><b>bold?</b>text</select>', + '<select><input>x', + '<select><textarea>x</textarea>', + '<select><select>x', + '<select><script>a</script><option>b</select>', + '<select><hr><option>a</select>', + '<select><optgroup><option>a</optgroup>b</select>', + '<select>\0x</select>', + ])('%j', (html) => expect(difference(html)).toBeUndefined()) +}) + +describe('html, head and body', () => { + test.each([ + '', + ' ', + 'x', + '<html>', + '<head>', + '<body>', + '<html><head><title>tb', + 'beforexafter', + ' x ', + 't

body text', + 'x', + 'betweenx', + ' after headx', + 'x', + '

x', + 'abc', + 'a

b', + 'a

b', + 'a \n', + '

x', + '

x

', + '