@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.
@@ -0,0 +1,646 @@
1
+ /**
2
+ * A book (one top-level entry of a site's contents, with everything under it) as
3
+ * a Dogsbay project: content/*.md, content/nav.yml and dogsbay.config.yml.
4
+ *
5
+ * The fetch is the caller's: a browser extension's same-origin fetch in the
6
+ * reader's session, a folder of saved pages, Node's fetch on a site that allows
7
+ * it. Pages are fetched one at a time, `delayMs` before each fetch, and converted
8
+ * as they arrive; links between pages are settled once every page is in, so a link
9
+ * to a page that could not be had points at the live site, not at a missing file.
10
+ */
11
+ import { load } from "cheerio";
12
+ import { DATA_DIRECTIVES, headingIds, inertTemplateSyntax, treeToDogsbayMd } from "@dogsbay/format-dogsbay-md/browser";
13
+ import { htmlToTree } from "../convert.js";
14
+ import { compare, countTree } from "../core/fidelity.js";
15
+ /** A link to a page, held until every page is converted: `dogsbay-page:<key>#<fragment>`. */
16
+ const PAGE = "dogsbay-page:";
17
+ /** A data file's name: a stem and a hash, nothing a path could make more of. */
18
+ const DATA_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
19
+ /**
20
+ * Which book the start page leads to, and its pages: read from the start page alone.
21
+ * Throws when the page is not one of the site's content pages or the book is unknown.
22
+ */
23
+ export function planBook(opts) {
24
+ return plan(opts).plan;
25
+ }
26
+ function plan(opts) {
27
+ const { adapter } = opts;
28
+ const $start = load(opts.start.html);
29
+ const startInfo = readStart(adapter, $start, opts.start);
30
+ if (adapter.contentsUrl && !opts.contents)
31
+ throw new Error(`${adapter.name}: the site's contents page is needed (importBook fetches it)`);
32
+ const contents = readContents(adapter, $start, startInfo, opts.contents);
33
+ const all = contents.flatMap(flatten);
34
+ // The start page's key in the contents: by its address (or an alias of it), the address
35
+ // asked for, else its title when only one entry has it (a page that does not name its file)
36
+ const asked = opts.start.requestedUrl ? safeKey(adapter, opts.start.requestedUrl) : null;
37
+ let startKey = inContents(all, startInfo.key) ?? inContents(all, asked);
38
+ if (!startKey) {
39
+ const title = $start(startInfo.root).find("h1").first().text().replace(/\s+/g, " ").trim();
40
+ startKey = uniqueByTitle(all, title) ?? startInfo.key;
41
+ }
42
+ const want = opts.book ? bookKey(adapter, contents, all, opts.book) : startKey;
43
+ const found = findBook(contents, want);
44
+ if (!found)
45
+ throw new Error(`${adapter.name}: ${opts.book ?? startInfo.url} is not in the site's contents` + (opts.book ? "" : " (name its page or title with book)"));
46
+ const { section: bookSection } = found;
47
+ let book = found.book;
48
+ let section = bookSection;
49
+ if (opts.scope === "section" || opts.scope === "page" || typeof opts.scope === "number") {
50
+ const path = pathTo(found.book, want) ?? [found.book];
51
+ const self = path[path.length - 1];
52
+ const part = opts.scope === "page" ? { ...self, children: [] }
53
+ : typeof opts.scope === "number" ? path[Math.max(0, Math.min(Math.trunc(opts.scope), path.length - 1))]
54
+ : sectionOf(path) ?? found.book;
55
+ // The part's book is its section: what it is part of
56
+ if (part !== found.book)
57
+ section = found.book.title;
58
+ book = part;
59
+ }
60
+ // Reading order, each page once (an entry may point at a section of a page already listed)
61
+ const seen = new Set();
62
+ const order = flatten(book).filter((e) => e.key && !seen.has(e.key) && seen.add(e.key));
63
+ const result = {
64
+ title: book.title,
65
+ section,
66
+ // A book entry may have no page of its own: its first page stands for it
67
+ key: book.key ?? order[0]?.key ?? startKey,
68
+ pages: order.map((e) => ({ key: e.key, title: e.title, url: adapter.urlOf(e.key) })),
69
+ };
70
+ // Other names of a page (IBM's `?topic=`, GitBook's `/pages/<id>`): a link to one goes to the page
71
+ // A page's own key wins over another page's alias (GitBook's first page has its `.md` path as an
72
+ // alias, which a real page could have as its key)
73
+ const keys = new Set(all.filter((e) => e.key).map((e) => e.key));
74
+ const aliasOf = new Map();
75
+ for (const e of all)
76
+ if (e.key)
77
+ for (const a of e.aliases ?? [])
78
+ if (!keys.has(a) && !aliasOf.has(a))
79
+ aliasOf.set(a, e.key);
80
+ const fetchUrls = new Map(all.filter((e) => e.key && e.fetchUrl).map((e) => [e.key, e.fetchUrl]));
81
+ return { plan: result, $start, startInfo, startKey, book, section, order, aliasOf, fetchUrls, path: pathTo(found.book, want) ?? [found.book], whole: found };
82
+ }
83
+ /** The smallest entry on the path with pages under it: the default part to save. */
84
+ function sectionOf(path) {
85
+ return [...path].reverse().find((e) => e.children.length);
86
+ }
87
+ /**
88
+ * The parts of the book the start page sits in, smallest first, read from the contents
89
+ * alone (nothing is fetched): each rung's `scope` given to importBook saves that part.
90
+ */
91
+ export function planScopes(opts) {
92
+ const { path, whole } = plan({ ...opts, scope: undefined });
93
+ const count = (e) => new Set(flatten(e).filter((x) => x.key).map((x) => x.key)).size;
94
+ const self = path[path.length - 1];
95
+ const section = sectionOf(path) ?? whole.book;
96
+ const rungs = [{ scope: "page", kind: "page", title: self.title, pages: 1 }];
97
+ for (let i = path.length - 1; i >= 0; i--) {
98
+ const e = path[i];
99
+ if (i > 0 && !e.children.length)
100
+ continue;
101
+ const pages = count(e);
102
+ const kind = i === 0 ? "book" : e === section ? "section" : "chapter";
103
+ // A part holding no more than the one below it is the same choice
104
+ if (pages <= rungs[rungs.length - 1].pages && i > 0)
105
+ continue;
106
+ if (pages <= rungs[rungs.length - 1].pages)
107
+ rungs.pop();
108
+ rungs.push({ scope: i, kind, title: e.title, pages });
109
+ }
110
+ // The section's rung, or the one with its pages when it was the same choice as another
111
+ const want = count(section);
112
+ const at = rungs.findIndex((r) => r.pages >= want);
113
+ return {
114
+ trail: [...(whole.section ? [whole.section] : []), ...path.map((e) => e.title)],
115
+ rungs,
116
+ defaultIndex: at >= 0 ? at : rungs.length - 1,
117
+ };
118
+ }
119
+ /** The start page's facts: from its address, else from the address asked for. */
120
+ function readStart(adapter, $start, start) {
121
+ const info = adapter.readPage($start, start.url) ?? (start.requestedUrl ? adapter.readPage($start, start.requestedUrl) : null);
122
+ if (!info)
123
+ throw new Error(`${adapter.name}: the start page is not a content page of this site`);
124
+ return info;
125
+ }
126
+ function readContents(adapter, $start, info, contents) {
127
+ return adapter.readContents?.(contents ? load(contents.html) : $start, info, contents?.html) ?? [];
128
+ }
129
+ /** The key the contents know a page by: the key itself, or the page an alias names. */
130
+ function inContents(all, key) {
131
+ if (!key)
132
+ return null;
133
+ if (all.some((e) => e.key === key))
134
+ return key;
135
+ return all.find((e) => e.key && e.aliases?.includes(key))?.key ?? null;
136
+ }
137
+ function safeKey(adapter, url) {
138
+ try {
139
+ return adapter.keyOf(new URL(url));
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ }
145
+ /**
146
+ * What `book` names: a key, a page's address, a slug (last path segment), else a title when
147
+ * one book has it, else one entry anywhere ("Getting started" is a book and a nested topic).
148
+ */
149
+ function bookKey(adapter, contents, all, book) {
150
+ const own = inContents(all, book);
151
+ if (own)
152
+ return own;
153
+ if (/^https?:\/\//i.test(book)) {
154
+ const k = inContents(all, safeKey(adapter, book));
155
+ if (k)
156
+ return k;
157
+ }
158
+ return keyBySlug(contents, book) ?? uniqueByTitle(contents, book) ?? uniqueByTitle(all, book) ?? book;
159
+ }
160
+ function uniqueByTitle(all, title) {
161
+ const t = title.replace(/\s+/g, " ").trim();
162
+ if (!t)
163
+ return null;
164
+ const keys = new Set(all.filter((e) => e.key && e.title === t).map((e) => e.key));
165
+ return keys.size === 1 ? [...keys][0] : null;
166
+ }
167
+ /** The entries from `root` down to the one whose key is `key`. */
168
+ function pathTo(root, key) {
169
+ if (root.key === key)
170
+ return [root];
171
+ for (const c of root.children) {
172
+ const p = pathTo(c, key);
173
+ if (p)
174
+ return [root, ...p];
175
+ }
176
+ return null;
177
+ }
178
+ export async function importBook(opts) {
179
+ const { adapter } = opts;
180
+ const delay = opts.delayMs ?? adapter.delayMs;
181
+ // A site whose pages do not carry its contents: fetch the page that does, first
182
+ if (adapter.contentsUrl && !opts.contents) {
183
+ const url = adapter.contentsUrl(readStart(adapter, load(opts.start.html), opts.start));
184
+ if (!url)
185
+ throw new Error(`${adapter.name}: the start page does not say where the site's contents are`);
186
+ if (delay > 0)
187
+ await sleep(delay, opts.signal);
188
+ const html = await opts.fetch(url, "contents", opts.signal).catch(() => null);
189
+ if (!html)
190
+ throw new Error(`${adapter.name}: the site's contents (${url}) could not be had`);
191
+ opts = { ...opts, contents: { html, url } };
192
+ }
193
+ const { plan: planned, $start, startInfo, startKey, book, section, order, aliasOf, fetchUrls } = plan(opts);
194
+ // File names: the book's first page is index.md; two pages never share a name
195
+ const files = new Map();
196
+ const taken = new Set();
197
+ for (const e of order) {
198
+ const key = e.key;
199
+ let name = key === planned.key ? "index.md" : adapter.fileOf(key);
200
+ if (key !== planned.key)
201
+ for (let i = 2; taken.has(name) || name === "index.md"; i++)
202
+ name = adapter.fileOf(key).replace(/(\.md)?$/, `-${i}.md`);
203
+ taken.add(name);
204
+ files.set(key, name);
205
+ }
206
+ const fileOf = (key) => files.get(key);
207
+ // 1. Fetch and convert, one page at a time (each page's DOM is dropped once converted).
208
+ // Links to pages are held as placeholders until every page is in.
209
+ const converted = new Map();
210
+ const missing = [];
211
+ /** Data files (`data/<name>.json`) the pages' directives show, their links held as placeholders too. */
212
+ const dataFiles = new Map();
213
+ /** The data files each page shows: their links count in the page's report. */
214
+ const dataShown = new Map();
215
+ /** A link as a placeholder for a page of the site (by its key, an alias followed), else absolute. */
216
+ const resolver = (key, base, links) => (href) => {
217
+ if (href.startsWith("#"))
218
+ return `${PAGE}${key}#${decode(href.slice(1))}`;
219
+ let u;
220
+ try {
221
+ u = new URL(href, base);
222
+ }
223
+ catch {
224
+ return href;
225
+ }
226
+ const found = adapter.keyOf(u);
227
+ if (!found) {
228
+ links.external++;
229
+ return u.href;
230
+ }
231
+ const target = aliasOf.get(found) ?? found;
232
+ return `${PAGE}${target}${u.hash ? `#${decode(u.hash.slice(1))}` : ""}`;
233
+ };
234
+ const absolute = (base) => (src) => {
235
+ try {
236
+ return new URL(src, base).href;
237
+ }
238
+ catch {
239
+ return src;
240
+ }
241
+ };
242
+ const convert = (key, $, info) => {
243
+ const links = { internal: 0, site: 0, external: 0, anchorsDropped: 0 };
244
+ const base = new URL(info.url);
245
+ const r = htmlToTree($, {
246
+ profile: adapter.profile,
247
+ root: info.root,
248
+ resolveHref: resolver(key, base, links),
249
+ onImage: ({ src }) => absolute(base)(src),
250
+ // Kept SVGs (syntax diagrams): assets/<page>-diagram-1.svg, beside the flat pages
251
+ assetPath: (name) => `assets/${fileOf(key).replace(/\.md$/, "")}-${name}`,
252
+ });
253
+ converted.set(key, { tree: r.tree, title: r.title ?? entryTitle(order, key), description: r.description, type: r.topicType, anchored: new Set(r.ids.anchored), fidelity: r.fidelity, info, links, assets: r.assets });
254
+ };
255
+ // A page read from the site's own text: its links and images settled as the HTML's are
256
+ const convertText = (key, page) => {
257
+ const links = { internal: 0, site: 0, external: 0, anchorsDropped: 0 };
258
+ const url = adapter.urlOf(key);
259
+ const base = new URL(url);
260
+ const fidelity = compare(page.source, countTree(page.tree));
261
+ rewriteLinks(page.tree, resolver(key, base, links));
262
+ const abs = absolute(base);
263
+ walkInline(page.tree, (n) => { if (n.type === "image")
264
+ n.src = abs(n.src); });
265
+ const anchored = new Set([...headingIds(page.tree).values()].map((h) => h.id).filter(Boolean));
266
+ const info = { key, url, root: "", meta: startInfo.meta };
267
+ // Its data files: named by their content, so one already in is the same; links held as the page's are
268
+ const shows = [];
269
+ for (const [name, file] of Object.entries(page.data ?? {})) {
270
+ if (!DATA_NAME.test(name))
271
+ continue;
272
+ shows.push(name);
273
+ if (dataFiles.has(name))
274
+ continue;
275
+ const settle = resolver(key, base, { internal: 0, site: 0, external: 0, anchorsDropped: 0 });
276
+ const links = new Set(file.links);
277
+ dataFiles.set(name, {
278
+ links,
279
+ rows: file.rows.map((row) => {
280
+ const out = {};
281
+ for (const [k, v] of Object.entries(row))
282
+ if (k !== "__proto__")
283
+ out[k] = links.has(k) && typeof v === "string" && v ? settle(v) : v;
284
+ return out;
285
+ }),
286
+ });
287
+ }
288
+ if (shows.length)
289
+ dataShown.set(key, shows);
290
+ converted.set(key, { tree: page.tree, title: page.title ?? entryTitle(order, key), description: page.description, type: page.type ?? "topic", anchored, fidelity, info, links, assets: [] });
291
+ };
292
+ for (const [index, e] of order.entries()) {
293
+ const key = e.key;
294
+ // The start page as read, unless the adapter fetches content from elsewhere (fetchUrlOf)
295
+ if (key === startKey && !adapter.fetchUrlOf && !adapter.readText) {
296
+ // Found by title or slug: its links resolve against its own address, not the one it was read at
297
+ convert(key, $start, key === startInfo.key ? startInfo : { ...startInfo, key, url: adapter.urlOf(key) });
298
+ }
299
+ else {
300
+ if (opts.signal?.aborted)
301
+ throw new Error("cancelled");
302
+ // Every fetch waits, the first too: the start page was just fetched by the caller
303
+ if (delay > 0)
304
+ await sleep(delay, opts.signal);
305
+ const body = await opts.fetch(fetchUrls.get(key) ?? adapter.fetchUrlOf?.(key) ?? adapter.urlOf(key), key, opts.signal).catch(() => null);
306
+ if (opts.signal?.aborted)
307
+ throw new Error("cancelled");
308
+ if (adapter.readText) {
309
+ // Its HTML too when the text needs it: the start page's is in hand, another is fetched
310
+ let html;
311
+ if (body && adapter.pageFor?.(body)) {
312
+ if (key === startKey)
313
+ html = opts.start.html;
314
+ else {
315
+ if (delay > 0)
316
+ await sleep(delay, opts.signal);
317
+ html = (await opts.fetch(adapter.urlOf(key), key, opts.signal).catch(() => null)) ?? undefined;
318
+ if (opts.signal?.aborted)
319
+ throw new Error("cancelled");
320
+ }
321
+ }
322
+ // A page that cannot be read is missing, not the end of the book (someone else's text)
323
+ let page = null;
324
+ try {
325
+ page = body ? adapter.readText(body, { key, url: adapter.urlOf(key) }, html) : null;
326
+ }
327
+ catch {
328
+ page = null;
329
+ }
330
+ if (page)
331
+ convertText(key, page);
332
+ else
333
+ missing.push(key);
334
+ }
335
+ else {
336
+ const $ = body ? load(body) : null;
337
+ const info = $ ? adapter.readPage($, adapter.urlOf(key)) : null;
338
+ if ($ && info)
339
+ convert(key, $, info);
340
+ else
341
+ missing.push(key);
342
+ }
343
+ }
344
+ opts.onPage?.({ key, title: e.title, index, total: order.length, ok: converted.has(key) });
345
+ }
346
+ // 3. Images on the site's own host, saved in the book (one fetch per image, however many pages show it)
347
+ const binaries = {};
348
+ const imagesMissing = [];
349
+ if (opts.fetchBytes) {
350
+ const origin = new URL(adapter.urlOf(planned.key)).origin;
351
+ const wanted = new Map();
352
+ for (const page of converted.values())
353
+ walkInline(page.tree, (n) => {
354
+ if (n.type !== "image" || wanted.has(n.src))
355
+ return;
356
+ let u;
357
+ try {
358
+ u = new URL(n.src);
359
+ }
360
+ catch {
361
+ return;
362
+ }
363
+ if (u.origin === origin || adapter.imageHost?.(u))
364
+ wanted.set(n.src, null);
365
+ });
366
+ // Not the name of a kept SVG (a syntax diagram)
367
+ const names = new Set([...converted.values()].flatMap((p) => p.assets.map((a) => a.path.replace(/^assets\//, "").toLowerCase())));
368
+ let index = 0;
369
+ for (const url of wanted.keys()) {
370
+ if (opts.signal?.aborted)
371
+ throw new Error("cancelled");
372
+ if (delay > 0)
373
+ await sleep(delay, opts.signal);
374
+ const bytes = await opts.fetchBytes(url, opts.signal).catch(() => null);
375
+ if (opts.signal?.aborted)
376
+ throw new Error("cancelled");
377
+ // A file the site can serve by its extension only: an image of a kind not known keeps its URL
378
+ const kind = bytes && (sniff(bytes) ?? knownExtension(url));
379
+ if (bytes && kind) {
380
+ const path = assetName(url, names, kind);
381
+ binaries[`content/${path}`] = bytes;
382
+ wanted.set(url, path);
383
+ }
384
+ else if (!bytes)
385
+ imagesMissing.push(url);
386
+ opts.onImage?.({ url, index: index++, total: wanted.size, ok: !!bytes });
387
+ }
388
+ for (const page of converted.values())
389
+ walkInline(page.tree, (n) => {
390
+ if (n.type === "image")
391
+ n.src = wanted.get(n.src) ?? n.src;
392
+ });
393
+ }
394
+ // 4. Links between pages
395
+ /** A placeholder as a saved page's file (from `key`'s page), else the page on the live site. */
396
+ const settle = (href, key, counts) => {
397
+ if (!href.startsWith(PAGE))
398
+ return href;
399
+ const [target, ...rest] = href.slice(PAGE.length).split("#");
400
+ const fragment = rest.join("#");
401
+ const there = converted.get(target);
402
+ if (!there) {
403
+ counts.site++;
404
+ return adapter.urlOf(target) + (fragment ? `#${encodeURIComponent(fragment)}` : "");
405
+ }
406
+ counts.internal++;
407
+ // A fragment with no anchor in the Markdown (a topic's id that is not a heading's) lands on the page
408
+ const keep = fragment && there.anchored.has(fragment);
409
+ if (fragment && !keep)
410
+ counts.anchorsDropped++;
411
+ if (target === key)
412
+ return keep ? `#${fragment}` : fileOf(key);
413
+ return fileOf(target) + (keep ? `#${fragment}` : "");
414
+ };
415
+ for (const [key, page] of converted)
416
+ rewriteLinks(page.tree, (href) => settle(href, key, page.links));
417
+ // A data file's links, as a page's (its declared link fields only): every page is a file in
418
+ // content/, so a file name reads the same from each. They count in every page that shows the file.
419
+ const dataCounts = new Map();
420
+ for (const [name, file] of dataFiles) {
421
+ const counts = { internal: 0, site: 0, external: 0, anchorsDropped: 0 };
422
+ for (const row of file.rows) {
423
+ for (const k of file.links) {
424
+ const v = row[k];
425
+ if (typeof v !== "string")
426
+ continue;
427
+ if (v.startsWith(PAGE))
428
+ row[k] = settle(v, null, counts);
429
+ else
430
+ counts.external++;
431
+ }
432
+ }
433
+ dataCounts.set(name, counts);
434
+ }
435
+ for (const [key, names] of dataShown) {
436
+ const page = converted.get(key);
437
+ if (!page)
438
+ continue;
439
+ for (const name of names) {
440
+ const c = dataCounts.get(name);
441
+ page.links.internal += c.internal;
442
+ page.links.site += c.site;
443
+ page.links.external += c.external;
444
+ page.links.anchorsDropped += c.anchorsDropped;
445
+ }
446
+ }
447
+ // 5. Files
448
+ const out = {};
449
+ const pages = [];
450
+ for (const [key, page] of converted) {
451
+ // The summary is the page's own first paragraph too: written into front matter as well, so the
452
+ // build's llms.txt, search and link previews (and an agent reading the folder) need not guess it
453
+ const frontmatter = { title: page.title, ...(page.description ? { description: page.description } : {}), type: page.type, source: page.info.url, ...(page.info.updated ? { updated: page.info.updated } : {}) };
454
+ // Text the converter read is literal: a `{{`, `{%` or `{#` in it must not reach the build's
455
+ // template pass (the serializer writes prose template tags through; review 2026-11-19)
456
+ const md = treeToDogsbayMd(page.tree, { frontmatter }).replace(/\n*$/, "\n");
457
+ const fm = /^---\n[\s\S]*?\n---\n/.exec(md)?.[0] ?? "";
458
+ out[`content/${fileOf(key)}`] = fm + inertTemplateSyntax(md.slice(fm.length), { attributes: true });
459
+ for (const a of page.assets)
460
+ out[`content/${a.path}`] = a.content;
461
+ pages.push({ key, file: fileOf(key), title: page.title, type: page.type, links: page.links, fidelity: page.fidelity });
462
+ }
463
+ for (const [name, file] of dataFiles)
464
+ out[`data/${name}.json`] = `${JSON.stringify(file.rows, null, 2)}\n`;
465
+ out["content/nav.yml"] = navYaml(book, (k) => converted.has(k), fileOf);
466
+ out["content/index.md"] ??= `---\ntitle: ${JSON.stringify(book.title)}\n---\n`;
467
+ // The site's name, description and the line under the name: `site.*`, where the builds read them
468
+ const meta = startInfo.meta;
469
+ const product = meta.product ? productName(meta.product) : "";
470
+ const tagline = [product, meta.version].filter(Boolean).join(" ");
471
+ const descr = [tagline, section].filter(Boolean).join(": ");
472
+ out["dogsbay.config.yml"] = [
473
+ "schemaVersion: 1",
474
+ "site:",
475
+ ` name: ${JSON.stringify(book.title)}`,
476
+ ...(descr ? [` description: ${JSON.stringify(descr)}`] : []),
477
+ ...(tagline ? [` tagline: ${JSON.stringify(tagline)}`] : []),
478
+ // A card on hovering a link to another page or to a footnote (GitBook's annotations are
479
+ // footnotes, a popover on its site; docs/link-previews.md)
480
+ "linkPreviews: true",
481
+ "",
482
+ `# Imported from ${adapter.urlOf(planned.key)} with @dogsbay/format-html (${adapter.name}).`,
483
+ ...(adapter.licence ? [`# ${adapter.licence.notice}`, `# Licence: ${adapter.licence.url}`] : []),
484
+ "",
485
+ ].join("\n");
486
+ return {
487
+ title: book.title,
488
+ key: planned.key,
489
+ startKey,
490
+ section,
491
+ files: out,
492
+ binaries,
493
+ imagesMissing,
494
+ pages,
495
+ missing,
496
+ differs: pages.filter((p) => p.fidelity.differs.length).map((p) => p.key),
497
+ };
498
+ }
499
+ /** The top-level contents entry (a "book") that holds `key`, and its section. */
500
+ export function findBook(contents, key) {
501
+ const has = (e) => e.key === key || e.children.some(has);
502
+ for (const top of contents) {
503
+ // Sections (no page of their own) hold books; a site without sections lists books directly
504
+ if (top.key === null) {
505
+ for (const book of top.children)
506
+ if (has(book))
507
+ return { book, section: top.title };
508
+ }
509
+ else if (has(top))
510
+ return { book: top };
511
+ }
512
+ return null;
513
+ }
514
+ /**
515
+ * nav.yml for a book: an entry with children is a group whose first item is its own
516
+ * page. Entries with no converted page under them are left out; a page is listed once.
517
+ */
518
+ export function navYaml(book, have, fileOf) {
519
+ const q = (s) => JSON.stringify(s);
520
+ const listed = new Set();
521
+ // An entry is a group only when something new is listed under it; an entry that
522
+ // lists nothing (a section of a page already listed) is left out
523
+ const walk = (e, depth) => {
524
+ const pad = " ".repeat(depth);
525
+ const file = e.key && have(e.key) && !listed.has(e.key) ? fileOf(e.key) : null;
526
+ if (file)
527
+ listed.add(e.key);
528
+ const under = e.children.flatMap((c) => walk(c, depth + 2));
529
+ if (!under.length)
530
+ return file ? [`${pad}- ${q(e.title)}: ${file}`] : [];
531
+ return [`${pad}- ${q(e.title)}:`, ...(file ? [`${pad} - ${file}`] : []), ...under];
532
+ };
533
+ return walk(book, 0).join("\n") + "\n";
534
+ }
535
+ /** A product's URL segment as a name: `red_hat_ansible_automation_platform` → "Red Hat Ansible Automation Platform". */
536
+ export function productName(segment) {
537
+ return segment
538
+ .split(/[_-]+/)
539
+ .filter(Boolean)
540
+ .map((w) => (/^[a-z]/.test(w) ? w[0].toUpperCase() + w.slice(1) : w))
541
+ .join(" ");
542
+ }
543
+ function keyBySlug(contents, slug) {
544
+ return contents.flatMap(flatten).find((e) => e.key?.split("/").pop() === slug)?.key ?? undefined;
545
+ }
546
+ function flatten(e) {
547
+ return [e, ...e.children.flatMap(flatten)];
548
+ }
549
+ function entryTitle(order, key) {
550
+ return order.find((e) => e.key === key)?.title ?? key;
551
+ }
552
+ /** Every link's href: inline links, and blocks that link (a card's `href`). */
553
+ const isDataDirective = (n) => DATA_DIRECTIVES.includes(n.type);
554
+ function rewriteLinks(tree, fn) {
555
+ walkInline(tree, (n) => { if (n.type === "link")
556
+ n.href = fn(n.href); });
557
+ const rec = (ns) => {
558
+ for (const n of ns) {
559
+ // A data directive's `href` names a field of its file's rows: its links are settled in the file
560
+ if (typeof n.props?.href === "string" && n.props.href && !isDataDirective(n))
561
+ n.props = { ...n.props, href: fn(n.props.href) };
562
+ if (n.children)
563
+ rec(n.children);
564
+ }
565
+ };
566
+ rec(tree);
567
+ }
568
+ /** Every inline node of a tree, a link's content too. */
569
+ function walkInline(tree, fn) {
570
+ const inl = (ns) => {
571
+ for (const n of ns ?? []) {
572
+ fn(n);
573
+ if ("children" in n && Array.isArray(n.children))
574
+ inl(n.children);
575
+ }
576
+ };
577
+ const rec = (ns) => {
578
+ for (const n of ns) {
579
+ inl(n.inline);
580
+ if (n.children)
581
+ rec(n.children);
582
+ }
583
+ };
584
+ rec(tree);
585
+ }
586
+ /**
587
+ * An image's file in the book: `assets/<its file name>`, made unique (`-2`) when two images share a
588
+ * name, with the extension of what the bytes are (IBM serves JPEGs named .png): the site's server
589
+ * and the PDF go by the extension.
590
+ */
591
+ function assetName(url, taken, kind) {
592
+ // Decoded first: a storage URL names its file with encoded slashes (GitBook: `o/spaces%2F…%2Fdiagram.png`)
593
+ const last = decode(new URL(url).pathname).split("/").pop() || "image";
594
+ const clean = last.replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/^\.+/, "") || "image";
595
+ const dot = clean.lastIndexOf(".");
596
+ const [stem, given] = dot > 0 ? [clean.slice(0, dot), clean.slice(dot)] : [clean, ""];
597
+ const same = kind === ".jpg" ? /^\.jpe?g$/i.test(given) : given.toLowerCase() === kind;
598
+ const ext = same ? given : kind;
599
+ let name = stem + ext;
600
+ for (let i = 2; taken.has(name.toLowerCase()); i++)
601
+ name = `${stem}-${i}${ext}`;
602
+ taken.add(name.toLowerCase());
603
+ return `assets/${name}`;
604
+ }
605
+ const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico"]);
606
+ /** The URL's own extension, when it is an image's that sites serve: else undefined. */
607
+ function knownExtension(url) {
608
+ const m = /\.[a-z0-9]+$/i.exec(new URL(url).pathname)?.[0].toLowerCase();
609
+ return m && IMAGE_EXTENSIONS.has(m) ? (m === ".jpeg" ? ".jpg" : m) : undefined;
610
+ }
611
+ /** What an image's bytes are, by their first bytes: its extension, or undefined when not known. */
612
+ function sniff(b) {
613
+ const at = (i, ...v) => v.every((x, j) => b[i + j] === x);
614
+ if (at(0, 0x89, 0x50, 0x4e, 0x47))
615
+ return ".png";
616
+ if (at(0, 0xff, 0xd8, 0xff))
617
+ return ".jpg";
618
+ if (at(0, 0x47, 0x49, 0x46, 0x38))
619
+ return ".gif";
620
+ if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50))
621
+ return ".webp";
622
+ if (at(4, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66))
623
+ return ".avif";
624
+ const head = new TextDecoder().decode(b.subarray(0, 256)).trimStart();
625
+ if (/^(<\?xml[^>]*>\s*)?(<!--[^]*?-->\s*)*<svg\b/i.test(head))
626
+ return ".svg";
627
+ return undefined;
628
+ }
629
+ function decode(s) {
630
+ try {
631
+ return decodeURIComponent(s);
632
+ }
633
+ catch {
634
+ return s;
635
+ }
636
+ }
637
+ /** Wait, or stop at once when the signal fires (a cancel during a long wait). */
638
+ function sleep(ms, signal) {
639
+ return new Promise((resolve, reject) => {
640
+ if (signal?.aborted)
641
+ return reject(new Error("cancelled"));
642
+ const t = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(); }, ms);
643
+ const stop = () => { clearTimeout(t); reject(new Error("cancelled")); };
644
+ signal?.addEventListener("abort", stop, { once: true });
645
+ });
646
+ }