@dogsbay/format-html 0.0.0-stage → 0.2.0-beta.180

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @dogsbay/format-html
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ HTML to Dogsbay's `TreeNode[]`, for importing published documentation sites.
4
+
5
+ ```ts
6
+ import { htmlToTree } from "@dogsbay/format-html";
7
+
8
+ const { tree, title, topicType, ids, fidelity } = htmlToTree(html, {
9
+ // optional: "dita-ot-html5" | "broadcom-techdocs" | "generic" | a Profile; detected when left out
10
+ profile: "dita-ot-html5",
11
+ // optional: CSS selector of the content; else the profile's root
12
+ root: "article",
13
+ // optional: selectors to remove first (a site's chrome)
14
+ remove: ["nav.breadcrumbs"],
15
+ resolveHref: (href, el) => href, // return undefined to keep only the text
16
+ onImage: ({ src, alt, attribs }) => src,
17
+ assetPath: (name) => `assets/${name}`, // where a kept SVG's file goes; without it none is kept
18
+ });
19
+ // assets: [{ name: "diagram-1.svg", path, type: "image/svg+xml", content }]
20
+ ```
21
+
22
+ - **Core**: plain semantic HTML (headings, paragraphs, lists, tables, code, figures,
23
+ definition lists, block quotes, details, YouTube embeds) to the tree, in the shapes the
24
+ dogsbay-md parser makes, so `treeToDogsbayMd` writes them back. Empty list items and
25
+ empty sections are kept. Containers are unwrapped; a container's id becomes its first
26
+ heading's anchor.
27
+ - **Profiles**: a publishing tool's HTML vocabulary rewritten to plain HTML.
28
+ `dita-ot-html5` (Fluid Topics, docs.redhat.com, IBM Docs, Oxygen WebHelp, Paligo…):
29
+ notes to callouts, code phrases to code, steps drawn with `<div>`s to lists, nested
30
+ topics read whole, topic type from the body class, related and child links kept (in
31
+ `nav.related-links` or IBM's `<aside><nav>`), syntax diagrams' SVG kept as files.
32
+ `broadcom-techdocs` (techdocs.broadcom.com: VMware, Symantec, CA): DITA rendered by Adobe
33
+ Experience Manager, rewritten into DITA-OT's shapes (inline `<div>` wrappers removed,
34
+ `h1.title`, notes typed by `data-label`, child links listed with their descriptions,
35
+ section titles anchored by the section's id), then the DITA-OT profile.
36
+ `generic`: the core alone.
37
+ - **SVG as files**: a profile marks an `<svg>` that is content (`data-dogsbay-keep="alt"`);
38
+ `htmlToTree` returns it in `assets` (scripts, foreign objects, event handlers and links
39
+ out removed) and the tree points at it.
40
+ - **Fidelity report**: headings, code blocks, tables, list items, images (inline SVG
41
+ included), callouts and links counted in the source and in the tree; links inside a
42
+ skipped `<nav>` count in the source, so a dropped link list shows. `fidelity.differs` names what does not match.
43
+ - **Ids**: `ids.anchored` became heading anchors; `ids.unanchored` have no place in
44
+ Markdown, so a link to `page#id` should land on the page.
45
+
46
+ Whole books (or parts: `scope: "section" | "page"`) from a site, through a site adapter (`redhat`, `ibm`):
47
+
48
+ ```ts
49
+ import { importBook, redhat } from "@dogsbay/format-html/site";
50
+
51
+ const book = await importBook({
52
+ adapter: redhat,
53
+ start: { html, url }, // the page the reader is on
54
+ fetch: async (url) => (await fetch(url)).text(),
55
+ });
56
+ // book.files: content/*.md, content/nav.yml, dogsbay.config.yml
57
+ ```
58
+
59
+ It never fetches: give it HTML from anywhere (a browser extension, saved pages, Node's
60
+ `fetch`, a Worker). Runs in Node and in the browser (cheerio).
@@ -0,0 +1,56 @@
1
+ /**
2
+ * One HTML page to TreeNode[]: pick the profile, find the content root, let the
3
+ * profile rewrite its vocabulary, walk, and compare source with output.
4
+ */
5
+ import { type CheerioAPI } from "cheerio";
6
+ import type { TreeNode } from "@dogsbay/types";
7
+ import { type BlockOptions } from "./core/blocks.js";
8
+ import { type FidelityReport } from "./core/fidelity.js";
9
+ import { type Profile } from "./profiles/index.js";
10
+ export interface HtmlToTreeOptions extends BlockOptions {
11
+ /** A profile or its name. Detected when not given. */
12
+ profile?: Profile | string;
13
+ /** CSS selector of the content root (first match). Else the profile's root. */
14
+ root?: string;
15
+ /** Selectors removed from the root before anything else (a site's chrome). */
16
+ remove?: string[];
17
+ /**
18
+ * Where a kept SVG's file goes, as the image's src in the Markdown (`diagram-1.svg` →
19
+ * `assets/page-diagram-1.svg`). Without it no SVG is kept: a caller that writes no files
20
+ * (Fluid Topics) gets no image pointing at a file nobody wrote.
21
+ */
22
+ assetPath?: (name: string) => string;
23
+ }
24
+ /** A file the page needs beside its Markdown: an inline SVG the profile kept (a syntax diagram). */
25
+ export interface PageAsset {
26
+ /** `diagram-<n>.svg`, unique within the page. */
27
+ name: string;
28
+ /** Where the Markdown points at it (`assetPath(name)`). */
29
+ path: string;
30
+ type: "image/svg+xml";
31
+ content: string;
32
+ }
33
+ export interface HtmlToTreeResult {
34
+ tree: TreeNode[];
35
+ /** The first h1 under the root, else in the document. */
36
+ title?: string;
37
+ /** The page's one-line summary, when the profile finds one (DITA's short description, else the meta description). */
38
+ description?: string;
39
+ /** concept, task, reference… when the profile can tell; else "topic". */
40
+ topicType: string;
41
+ profile: string;
42
+ ids: {
43
+ /** Ids that became heading anchors: a link to page#id still lands. */
44
+ anchored: string[];
45
+ /** Ids the Markdown has no place for: a link to page#id lands on the page. */
46
+ unanchored: string[];
47
+ };
48
+ fidelity: FidelityReport;
49
+ /** Files the Markdown points at (kept SVGs). */
50
+ assets: PageAsset[];
51
+ }
52
+ /**
53
+ * Convert HTML (a string, or a cheerio document the caller has already prepared)
54
+ * to a tree. A cheerio document passed in is changed in place.
55
+ */
56
+ export declare function htmlToTree(input: string | CheerioAPI, opts?: HtmlToTreeOptions): HtmlToTreeResult;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * One HTML page to TreeNode[]: pick the profile, find the content root, let the
3
+ * profile rewrite its vocabulary, walk, and compare source with output.
4
+ */
5
+ import { load } from "cheerio";
6
+ import { blocksFrom, newLedger } from "./core/blocks.js";
7
+ import { compare, countSource, countTree } from "./core/fidelity.js";
8
+ import { detectProfile, profileByName } from "./profiles/index.js";
9
+ /**
10
+ * Convert HTML (a string, or a cheerio document the caller has already prepared)
11
+ * to a tree. A cheerio document passed in is changed in place.
12
+ */
13
+ export function htmlToTree(input, opts = {}) {
14
+ const $ = typeof input === "string" ? load(input) : input;
15
+ const profile = typeof opts.profile === "string" ? profileByName(opts.profile) : opts.profile;
16
+ if (typeof opts.profile === "string" && !profile)
17
+ throw new Error(`format-html: no profile named "${opts.profile}"`);
18
+ const p = profile ?? detectProfile($);
19
+ const root = opts.root ? $(opts.root).first() : p.root($);
20
+ const empty = { anchored: [], unanchored: [] };
21
+ if (!root || !root.length) {
22
+ const zero = countTree([]);
23
+ return { tree: [], topicType: "topic", profile: p.name, ids: empty, fidelity: compare(zero, zero), assets: [] };
24
+ }
25
+ if (opts.remove?.length)
26
+ root.find(opts.remove.join(",")).remove();
27
+ p.normalize($, root);
28
+ const assets = keepSvgs($, root, opts.assetPath);
29
+ const rootNode = root.get(0);
30
+ const title = root.find("h1").first().text().replace(/\s+/g, " ").trim() || $("h1").first().text().replace(/\s+/g, " ").trim() || undefined;
31
+ const topicType = p.topicType?.($, root) ?? "topic";
32
+ const description = p.description?.($, root);
33
+ const ledger = newLedger();
34
+ const tree = blocksFrom(rootNode.children ?? [], opts, ledger, rootNode.attribs?.id);
35
+ const fidelity = compare(countSource(rootNode.children ?? []), countTree(tree));
36
+ for (const id of ledger.anchored)
37
+ ledger.unanchored.delete(id);
38
+ return {
39
+ tree,
40
+ title,
41
+ ...(description ? { description } : {}),
42
+ topicType,
43
+ profile: p.name,
44
+ ids: { anchored: [...ledger.anchored], unanchored: [...ledger.unanchored] },
45
+ fidelity,
46
+ assets,
47
+ };
48
+ }
49
+ const SVG_NS = "http://www.w3.org/2000/svg";
50
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
51
+ /** Elements removed from a kept SVG: what runs, embeds or animates attributes. */
52
+ const DROP_IN_SVG = new Set(["script", "foreignobject", "iframe", "object", "embed", "set", "animate", "animatemotion", "animatetransform", "discard", "handler", "listener"]);
53
+ /**
54
+ * Each `<svg data-dogsbay-keep>` (a profile marks the ones that are content, such as syntax
55
+ * diagrams) becomes a file and an image pointing at it. The SVG comes from someone else's
56
+ * site: scripts, foreign objects, event handlers and links out are removed, and as an
57
+ * <img> it could not run them anyway.
58
+ */
59
+ function keepSvgs($, root, assetPath) {
60
+ const out = [];
61
+ // The outermost marked SVGs only: an inner one goes with its parent's file
62
+ const marked = root.find("svg[data-dogsbay-keep]").filter((_, el) => !$(el).parents("svg").length);
63
+ // Without a place for the files (a caller that writes no assets), the SVG stays as it was:
64
+ // skipped by the walk, and the report counts it as a lost image
65
+ if (!assetPath) {
66
+ root.find("svg[data-dogsbay-keep]").removeAttr("data-dogsbay-keep");
67
+ return out;
68
+ }
69
+ marked.each((_, el) => {
70
+ const svg = $(el);
71
+ const alt = svg.attr("data-dogsbay-keep") || svg.attr("aria-label") || svg.children("title").first().text().trim() || "Diagram";
72
+ svg.find("[data-dogsbay-keep]").addBack().removeAttr("data-dogsbay-keep");
73
+ // By name, lower-cased: the parser keeps SVG's camel case (foreignObject), selectors do not
74
+ // match it. Animations go too: <set>/<animate> can give a link a javascript: href.
75
+ svg.find("*").filter((_, n) => DROP_IN_SVG.has((n.name ?? "").toLowerCase())).remove();
76
+ // Styles stay (the diagrams draw with them), without anything fetched from elsewhere
77
+ svg.find("*").filter((_, n) => (n.name ?? "").toLowerCase() === "style").each((_, st) => {
78
+ const css = $(st).text().replace(/@import[^;]*;?/gi, "").replace(/url\(\s*(['"]?)(?!#)[^)]*\1\s*\)/gi, "none");
79
+ $(st).text(css);
80
+ });
81
+ for (const node of [el, ...svg.find("*").toArray()]) {
82
+ const prefixes = node["x-attribsPrefix"] ?? {};
83
+ const attribs = {};
84
+ for (const [name, v] of Object.entries(node.attribs ?? {})) {
85
+ if (/^on/i.test(name) || (/(^|:)href$/i.test(name) && !v.trim().startsWith("#")) || /^contentscripttype$/i.test(name))
86
+ continue;
87
+ if (/^style$/i.test(name) && /url\(\s*['"]?(?!#)/i.test(v))
88
+ continue;
89
+ // The parser keeps a namespaced attribute's prefix aside (xlink:href → href); a
90
+ // standalone file needs it back, for renderers that know only SVG 1.1
91
+ const prefix = prefixes[name];
92
+ attribs[prefix ? `${prefix}:${name}` : name] = v;
93
+ }
94
+ node.attribs = attribs;
95
+ delete node["x-attribsPrefix"];
96
+ delete node["x-attribsNamespace"];
97
+ }
98
+ if (!svg.attr("xmlns"))
99
+ svg.attr("xmlns", SVG_NS);
100
+ if (/\sxlink:/.test($.xml(el)) && !svg.attr("xmlns:xlink"))
101
+ svg.attr("xmlns:xlink", XLINK_NS);
102
+ const name = `diagram-${out.length + 1}.svg`;
103
+ const path = assetPath(name);
104
+ out.push({ name, path, type: "image/svg+xml", content: $.xml(el) + "\n" });
105
+ svg.replaceWith($("<img>").attr({ src: name, alt, "data-resolved-src": path }));
106
+ });
107
+ return out;
108
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Semantic HTML (a node list) to TreeNode[], in the shapes the dogsbay-md parser
3
+ * produces and its serializer reads: text on the node (`heading.inline`,
4
+ * `paragraph.inline`, `list-item.inline`, `td.inline`), callouts with `props.type`,
5
+ * code with its text in `html` and `props.code`.
6
+ *
7
+ * Plain HTML only. Generator profiles rewrite their vocabulary first; the one
8
+ * convention of our own is `<aside data-callout="type">` for a callout.
9
+ *
10
+ * Rules:
11
+ * - Keep what the source has. An empty list item stays an empty item; an empty
12
+ * section keeps its heading.
13
+ * - Containers (div, section, article, main, custom elements) are unwrapped. A
14
+ * container's id moves to its first heading, so links to it still land.
15
+ */
16
+ import type { TreeNode } from "@dogsbay/types";
17
+ import { type DomNode } from "../dom.js";
18
+ import { trimEdges, type InlineOptions } from "./inline.js";
19
+ export interface BlockOptions extends InlineOptions {
20
+ /**
21
+ * Give headings the ids the source has (their own, or their container's), as
22
+ * `props.slug`. Default true. False leaves headings without ids (the serializer's
23
+ * reader makes anchors from the text) and records every id as unanchored: for a
24
+ * site whose links land on pages, never on sections.
25
+ */
26
+ headingIds?: boolean;
27
+ }
28
+ /** Ids the walk saw: those given to a heading, and those it had nowhere to put. */
29
+ export interface IdLedger {
30
+ anchored: Set<string>;
31
+ unanchored: Set<string>;
32
+ }
33
+ export declare const isSkipped: (n: DomNode) => boolean;
34
+ /**
35
+ * Block or inline: a tag we do not know is a block when it holds a block. A callout
36
+ * (`data-callout`) is a block whatever its tag. Cached per node: the walk asks again
37
+ * at every level it unwraps.
38
+ */
39
+ export declare function isBlock(n: DomNode): boolean;
40
+ export declare function newLedger(): IdLedger;
41
+ /** Convert a node list to blocks. */
42
+ export declare function blocksFrom(nodes: DomNode[], opts?: BlockOptions, ids?: IdLedger, containerId?: string): TreeNode[];
43
+ /**
44
+ * A caption is inline Markdown (dogsbay-md); a <caption>'s text is plain, so the
45
+ * characters Markdown would read as formatting are escaped.
46
+ */
47
+ export declare const escapeCaption: (text: string) => string;
48
+ /** The video id of a YouTube embed, watch or short URL. */
49
+ export declare function youtubeIdFromUrl(url: string): string | undefined;
50
+ export { trimEdges };
@@ -0,0 +1,372 @@
1
+ import { classOf, elements, rawText, tagOf, textContent } from "../dom.js";
2
+ import { inlineFrom, trimEdges } from "./inline.js";
3
+ /** Tags that are always blocks. */
4
+ const BLOCK_TAGS = new Set([
5
+ "p", "ul", "ol", "dl", "table", "pre", "div", "section", "article", "aside", "main", "header", "footer",
6
+ "figure", "blockquote", "details", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "address", "center", "form",
7
+ "fieldset", "iframe", "video", "audio", "menu",
8
+ ]);
9
+ /** Tags that are always inline. */
10
+ const INLINE_TAGS = new Set([
11
+ "a", "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "dfn", "del", "em", "i", "img", "ins", "kbd",
12
+ "label", "mark", "q", "s", "samp", "small", "span", "strike", "strong", "sub", "sup", "time", "tt", "u", "var", "wbr",
13
+ ]);
14
+ /** Never content. */
15
+ const SKIP_TAGS = new Set(["script", "style", "noscript", "template", "button", "nav", "head", "link", "meta", "svg", "input", "select", "textarea"]);
16
+ export const isSkipped = (n) => SKIP_TAGS.has(tagOf(n)) || n.attribs?.hidden !== undefined || n.attribs?.["aria-hidden"] === "true";
17
+ const blockCache = new WeakMap();
18
+ /**
19
+ * Block or inline: a tag we do not know is a block when it holds a block. A callout
20
+ * (`data-callout`) is a block whatever its tag. Cached per node: the walk asks again
21
+ * at every level it unwraps.
22
+ */
23
+ export function isBlock(n) {
24
+ const name = tagOf(n);
25
+ if (BLOCK_TAGS.has(name) || isCallout(n))
26
+ return true;
27
+ if (INLINE_TAGS.has(name))
28
+ return false;
29
+ let b = blockCache.get(n);
30
+ if (b === undefined) {
31
+ b = elements(n).some((c) => !isSkipped(c) && isBlock(c));
32
+ blockCache.set(n, b);
33
+ }
34
+ return b;
35
+ }
36
+ const HEADING = /^h([1-6])$/;
37
+ export function newLedger() {
38
+ return { anchored: new Set(), unanchored: new Set() };
39
+ }
40
+ /** Convert a node list to blocks. */
41
+ export function blocksFrom(nodes, opts = {}, ids = newLedger(), containerId) {
42
+ return new Walker(opts, ids).blocks(nodes, containerId);
43
+ }
44
+ class Walker {
45
+ opts;
46
+ ids;
47
+ constructor(opts, ids) {
48
+ this.opts = opts;
49
+ this.ids = ids;
50
+ }
51
+ /**
52
+ * `pendingId`: the id of the container these nodes came from. It goes to the
53
+ * first heading, if a heading comes before any other content; else it is
54
+ * recorded as having no anchor.
55
+ */
56
+ blocks(nodes, pendingId) {
57
+ const out = [];
58
+ let run = [];
59
+ let pending = pendingId;
60
+ const lose = () => {
61
+ if (pending) {
62
+ this.ids.unanchored.add(pending);
63
+ pending = undefined;
64
+ }
65
+ };
66
+ const flush = () => {
67
+ if (!run.length)
68
+ return;
69
+ const inline = inlineFrom(run, this.opts);
70
+ this.collectInlineIds(run);
71
+ run = [];
72
+ if (inline.length) {
73
+ lose();
74
+ out.push({ type: "paragraph", inline });
75
+ }
76
+ };
77
+ for (const n of nodes) {
78
+ if (n.type === "text") {
79
+ run.push(n);
80
+ continue;
81
+ }
82
+ if (n.type !== "tag" || isSkipped(n))
83
+ continue;
84
+ const name = tagOf(n);
85
+ if (name === "iframe") {
86
+ const id = youtubeIdFromUrl(n.attribs?.src ?? "");
87
+ if (id) {
88
+ flush();
89
+ const title = (n.attribs?.title ?? "").trim();
90
+ out.push({ type: "youtube", props: title ? { id, title } : { id } });
91
+ }
92
+ continue;
93
+ }
94
+ if (!isBlock(n)) {
95
+ run.push(n);
96
+ continue;
97
+ }
98
+ flush();
99
+ const hm = HEADING.exec(name);
100
+ if (hm) {
101
+ const own = n.attribs?.id || leadingAnchorId(n);
102
+ if (own)
103
+ lose();
104
+ const slug = own || pending;
105
+ pending = undefined;
106
+ out.push(this.heading(n, Number(hm[1]), slug));
107
+ continue;
108
+ }
109
+ if (isCallout(n)) {
110
+ lose();
111
+ this.recordId(n);
112
+ out.push(this.callout(n));
113
+ continue;
114
+ }
115
+ if (isContainer(name)) {
116
+ // Unwrap; the container's id goes down to its first heading
117
+ const id = n.attribs?.id;
118
+ if (id)
119
+ lose();
120
+ const pass = id || pending;
121
+ pending = undefined;
122
+ out.push(...this.blocks(n.children ?? [], pass));
123
+ continue;
124
+ }
125
+ lose();
126
+ this.recordId(n);
127
+ out.push(...this.block(n, name));
128
+ }
129
+ flush();
130
+ lose();
131
+ return out;
132
+ }
133
+ heading(n, level, slug) {
134
+ const node = { type: "heading", props: { level }, inline: inlineFrom(n.children, this.opts).map(noBreak) };
135
+ if (slug && this.opts.headingIds === false)
136
+ this.ids.unanchored.add(slug);
137
+ else if (slug) {
138
+ node.props.slug = slug;
139
+ this.ids.anchored.add(slug);
140
+ }
141
+ this.collectInlineIds(n.children ?? [], slug);
142
+ return node;
143
+ }
144
+ block(n, name) {
145
+ switch (name) {
146
+ case "p": {
147
+ // A <p> holding a block (invalid HTML, but parsers keep it in some fragments)
148
+ if (elements(n).some((c) => !isSkipped(c) && isBlock(c)))
149
+ return this.blocks(n.children ?? []);
150
+ const inline = inlineFrom(n.children, this.opts);
151
+ this.collectInlineIds(n.children ?? []);
152
+ return inline.length ? [{ type: "paragraph", inline }] : [];
153
+ }
154
+ case "ul":
155
+ case "ol":
156
+ case "menu":
157
+ return [this.list(n, name === "ol")];
158
+ case "dl":
159
+ return [this.deflist(n)];
160
+ case "pre":
161
+ return [codeBlock(n)];
162
+ case "table":
163
+ return [this.table(n)];
164
+ case "blockquote":
165
+ return [{ type: "blockquote", children: this.blocks(n.children ?? []) }];
166
+ case "hr":
167
+ return [{ type: "hr" }];
168
+ case "figure":
169
+ return this.figure(n);
170
+ case "details": {
171
+ const summary = elements(n).find((c) => tagOf(c) === "summary");
172
+ const body = this.blocks((n.children ?? []).filter((c) => c !== summary));
173
+ const node = { type: "details", children: body };
174
+ const title = summary ? textContent(summary) : "";
175
+ if (title)
176
+ node.props = { summary: title };
177
+ return [node];
178
+ }
179
+ default:
180
+ // video, audio, form, fieldset, address, center: their content
181
+ return this.blocks(n.children ?? []);
182
+ }
183
+ }
184
+ callout(n) {
185
+ const type = (n.attribs?.["data-callout"] || "note").toLowerCase();
186
+ const props = { type };
187
+ const title = n.attribs?.["data-callout-title"];
188
+ if (title)
189
+ props.title = title;
190
+ return { type: "callout", props, children: this.blocks(n.children ?? []) };
191
+ }
192
+ /**
193
+ * A list. Every <li> is an item, empty or not. The item's leading text (or its
194
+ * first paragraph) is the item's own text; what follows are its blocks.
195
+ */
196
+ list(n, ordered) {
197
+ const items = elements(n)
198
+ .filter((c) => tagOf(c) === "li")
199
+ .map((li) => {
200
+ this.recordId(li);
201
+ const blocks = this.blocks(li.children ?? []);
202
+ const item = { type: "list-item" };
203
+ if (blocks[0]?.type === "paragraph") {
204
+ item.inline = blocks.shift().inline;
205
+ }
206
+ item.children = blocks;
207
+ if (!item.inline && !blocks.length)
208
+ item.children = [];
209
+ else if (!blocks.length)
210
+ delete item.children;
211
+ return item;
212
+ });
213
+ const node = { type: ordered ? "ordered-list" : "unordered-list", children: items };
214
+ const start = Number(n.attribs?.start);
215
+ if (ordered && Number.isInteger(start) && start !== 1)
216
+ node.props = { start };
217
+ return node;
218
+ }
219
+ deflist(n) {
220
+ const children = [];
221
+ const scan = (nodes) => {
222
+ for (const c of nodes) {
223
+ const t = tagOf(c);
224
+ if (t === "dt") {
225
+ this.recordId(c);
226
+ children.push({ type: "dt", inline: inlineFrom(c.children, this.opts).map(noBreak) });
227
+ }
228
+ else if (t === "dd")
229
+ children.push({ type: "dd", children: this.blocks(c.children ?? []) });
230
+ else if (t === "div")
231
+ scan(c.children ?? []); // HTML5 allows <div> groups of dt/dd
232
+ }
233
+ };
234
+ scan(n.children ?? []);
235
+ return { type: "deflist", children };
236
+ }
237
+ table(t) {
238
+ const children = [];
239
+ const caption = elements(t).find((c) => tagOf(c) === "caption");
240
+ const head = [];
241
+ const body = [];
242
+ for (const c of elements(t)) {
243
+ const name = tagOf(c);
244
+ if (name === "thead")
245
+ head.push(...elements(c).filter((r) => tagOf(r) === "tr"));
246
+ else if (name === "tbody" || name === "tfoot")
247
+ body.push(...elements(c).filter((r) => tagOf(r) === "tr"));
248
+ else if (name === "tr")
249
+ body.push(c);
250
+ }
251
+ // No <thead>, but a first row of <th> only: that row is the header
252
+ if (!head.length && body.length) {
253
+ const cells = elements(body[0]).filter((c) => /^t[hd]$/.test(tagOf(c)));
254
+ if (cells.length && cells.every((c) => tagOf(c) === "th"))
255
+ head.push(body.shift());
256
+ }
257
+ const rows = (trs, cellType) => trs.map((tr) => ({
258
+ type: "tr",
259
+ children: elements(tr)
260
+ .filter((c) => /^t[hd]$/.test(tagOf(c)))
261
+ .map((cell) => {
262
+ const node = { type: cellType };
263
+ if ((cell.children ?? []).some((c) => c.type === "tag" && !isSkipped(c) && isBlock(c))) {
264
+ node.children = this.blocks(cell.children ?? []);
265
+ }
266
+ else {
267
+ node.inline = inlineFrom(cell.children, this.opts);
268
+ this.collectInlineIds(cell.children ?? []);
269
+ }
270
+ const spans = cellSpans(cell);
271
+ if (spans)
272
+ node.props = spans;
273
+ return node;
274
+ }),
275
+ }));
276
+ if (head.length)
277
+ children.push({ type: "thead", children: rows(head, "th") });
278
+ if (body.length)
279
+ children.push({ type: "tbody", children: rows(body, "td") });
280
+ const node = { type: "table", children };
281
+ const cap = caption ? textContent(caption) : "";
282
+ if (cap)
283
+ node.props = { caption: escapeCaption(cap) };
284
+ return node;
285
+ }
286
+ figure(n) {
287
+ const cap = elements(n).find((c) => tagOf(c) === "figcaption");
288
+ const body = this.blocks((n.children ?? []).filter((c) => c !== cap));
289
+ const caption = cap ? textContent(cap) : "";
290
+ if (!caption)
291
+ return body;
292
+ return [{ type: "figure", props: { caption: escapeCaption(caption) }, children: body }];
293
+ }
294
+ /** An id on a block that is not a heading or container: it has no anchor in Markdown. */
295
+ recordId(n) {
296
+ const id = n.attribs?.id;
297
+ if (id && !this.ids.anchored.has(id))
298
+ this.ids.unanchored.add(id);
299
+ }
300
+ /** Ids on inline elements (`<a id>`, `<span id>`) inside a run. */
301
+ collectInlineIds(nodes, except) {
302
+ const rec = (ns) => {
303
+ for (const c of ns) {
304
+ if (c.type !== "tag")
305
+ continue;
306
+ const id = c.attribs?.id || (tagOf(c) === "a" ? c.attribs?.name : undefined);
307
+ if (id && id !== except && !this.ids.anchored.has(id))
308
+ this.ids.unanchored.add(id);
309
+ rec(c.children ?? []);
310
+ }
311
+ };
312
+ rec(nodes);
313
+ }
314
+ }
315
+ const CONTAINER_TAGS = new Set(["div", "section", "article", "main", "header", "footer", "aside"]);
316
+ function isContainer(name) {
317
+ return CONTAINER_TAGS.has(name) || (!BLOCK_TAGS.has(name) && !INLINE_TAGS.has(name));
318
+ }
319
+ function isCallout(n) {
320
+ return n.attribs?.["data-callout"] !== undefined;
321
+ }
322
+ /** `<h2><a id="x"></a>Title</h2>`: an empty anchor at the start of a heading names it. */
323
+ function leadingAnchorId(h) {
324
+ for (const c of h.children ?? []) {
325
+ if (c.type === "text" && !(c.data ?? "").trim())
326
+ continue;
327
+ if (tagOf(c) === "a" && !c.attribs?.href && !textContent(c))
328
+ return c.attribs?.id || c.attribs?.name;
329
+ return undefined;
330
+ }
331
+ return undefined;
332
+ }
333
+ /** A heading is one line: a break inside it is a space. */
334
+ function noBreak(n) {
335
+ return n.type === "break" ? { type: "text", text: " " } : n;
336
+ }
337
+ function codeBlock(pre) {
338
+ const code = elements(pre).length === 1 && tagOf(elements(pre)[0]) === "code" ? elements(pre)[0] : undefined;
339
+ const language = langFrom(classOf(pre)) ?? (code ? langFrom(classOf(code)) : undefined) ?? pre.attribs?.["data-lang"] ?? code?.attribs?.["data-lang"];
340
+ // A leading newline after <pre> is not content (HTML drops it); trailing whitespace neither
341
+ const text = rawText(pre).replace(/^\r?\n/, "").replace(/\s+$/, "");
342
+ return { type: "code", html: text, props: { code: text, ...(language ? { language } : {}) } };
343
+ }
344
+ function langFrom(cls) {
345
+ const m = /\b(?:language|lang)-([\w+#.-]+)/.exec(cls);
346
+ return m ? m[1] : undefined;
347
+ }
348
+ function cellSpans(cell) {
349
+ const cs = parseInt(cell.attribs?.colspan ?? "", 10);
350
+ const rs = parseInt(cell.attribs?.rowspan ?? "", 10);
351
+ const props = {};
352
+ if (Number.isFinite(cs) && cs > 1)
353
+ props.colspan = cs;
354
+ if (Number.isFinite(rs) && rs > 1)
355
+ props.rowspan = rs;
356
+ return Object.keys(props).length ? props : undefined;
357
+ }
358
+ /**
359
+ * A caption is inline Markdown (dogsbay-md); a <caption>'s text is plain, so the
360
+ * characters Markdown would read as formatting are escaped.
361
+ */
362
+ export const escapeCaption = (text) => text
363
+ .replace(/\\/g, "\\\\")
364
+ .replace(/([*`\[\]])/g, "\\$1")
365
+ .replace(/<(?=[A-Za-z/!?])/g, "\\<")
366
+ .replace(/_/g, (m, i, s) => (i === 0 || /\W/.test(s[i - 1]) || i === s.length - 1 || /\W/.test(s[i + 1]) ? "\\_" : m));
367
+ /** The video id of a YouTube embed, watch or short URL. */
368
+ export function youtubeIdFromUrl(url) {
369
+ const m = url.match(/(?:youtube(?:-nocookie)?\.com\/embed\/|youtu\.be\/|youtube\.com\/watch\?(?:[^"]*&)?v=)([\w-]{6,})/);
370
+ return m?.[1];
371
+ }
372
+ export { trimEdges };