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

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,467 @@
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 { treeToDogsbayMd } from "@dogsbay/format-dogsbay-md/browser";
13
+ import { htmlToTree } from "../convert.js";
14
+ /** A link to a page, held until every page is converted: `dogsbay-page:<key>#<fragment>`. */
15
+ const PAGE = "dogsbay-page:";
16
+ /**
17
+ * Which book the start page leads to, and its pages: read from the start page alone.
18
+ * Throws when the page is not one of the site's content pages or the book is unknown.
19
+ */
20
+ export function planBook(opts) {
21
+ return plan(opts).plan;
22
+ }
23
+ function plan(opts) {
24
+ const { adapter } = opts;
25
+ const $start = load(opts.start.html);
26
+ const startInfo = readStart(adapter, $start, opts.start);
27
+ if (adapter.contentsUrl && !opts.contents)
28
+ throw new Error(`${adapter.name}: the site's contents page is needed (importBook fetches it)`);
29
+ const contents = readContents(adapter, $start, startInfo, opts.contents);
30
+ const all = contents.flatMap(flatten);
31
+ // The start page's key in the contents: by its address (or an alias of it), the address
32
+ // asked for, else its title when only one entry has it (a page that does not name its file)
33
+ const asked = opts.start.requestedUrl ? safeKey(adapter, opts.start.requestedUrl) : null;
34
+ let startKey = inContents(all, startInfo.key) ?? inContents(all, asked);
35
+ if (!startKey) {
36
+ const title = $start(startInfo.root).find("h1").first().text().replace(/\s+/g, " ").trim();
37
+ startKey = uniqueByTitle(all, title) ?? startInfo.key;
38
+ }
39
+ const want = opts.book ? bookKey(adapter, contents, all, opts.book) : startKey;
40
+ const found = findBook(contents, want);
41
+ if (!found)
42
+ 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)"));
43
+ const { section: bookSection } = found;
44
+ let book = found.book;
45
+ let section = bookSection;
46
+ if (opts.scope === "section" || opts.scope === "page") {
47
+ const path = pathTo(found.book, want) ?? [found.book];
48
+ const self = path[path.length - 1];
49
+ const part = opts.scope === "page" ? { ...self, children: [] } : [...path].reverse().find((e) => e.children.length) ?? found.book;
50
+ // The part's book is its section: what it is part of
51
+ if (part !== found.book)
52
+ section = found.book.title;
53
+ book = part;
54
+ }
55
+ // Reading order, each page once (an entry may point at a section of a page already listed)
56
+ const seen = new Set();
57
+ const order = flatten(book).filter((e) => e.key && !seen.has(e.key) && seen.add(e.key));
58
+ const result = {
59
+ title: book.title,
60
+ section,
61
+ // A book entry may have no page of its own: its first page stands for it
62
+ key: book.key ?? order[0]?.key ?? startKey,
63
+ pages: order.map((e) => ({ key: e.key, title: e.title, url: adapter.urlOf(e.key) })),
64
+ };
65
+ return { plan: result, $start, startInfo, startKey, book, section, order };
66
+ }
67
+ /** The start page's facts: from its address, else from the address asked for. */
68
+ function readStart(adapter, $start, start) {
69
+ const info = adapter.readPage($start, start.url) ?? (start.requestedUrl ? adapter.readPage($start, start.requestedUrl) : null);
70
+ if (!info)
71
+ throw new Error(`${adapter.name}: the start page is not a content page of this site`);
72
+ return info;
73
+ }
74
+ function readContents(adapter, $start, info, contents) {
75
+ return adapter.readContents?.(contents ? load(contents.html) : $start, info, contents?.html) ?? [];
76
+ }
77
+ /** The key the contents know a page by: the key itself, or the page an alias names. */
78
+ function inContents(all, key) {
79
+ if (!key)
80
+ return null;
81
+ if (all.some((e) => e.key === key))
82
+ return key;
83
+ return all.find((e) => e.key && e.aliases?.includes(key))?.key ?? null;
84
+ }
85
+ function safeKey(adapter, url) {
86
+ try {
87
+ return adapter.keyOf(new URL(url));
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
93
+ /**
94
+ * What `book` names: a key, a page's address, a slug (last path segment), else a title when
95
+ * one book has it, else one entry anywhere ("Getting started" is a book and a nested topic).
96
+ */
97
+ function bookKey(adapter, contents, all, book) {
98
+ const own = inContents(all, book);
99
+ if (own)
100
+ return own;
101
+ if (/^https?:\/\//i.test(book)) {
102
+ const k = inContents(all, safeKey(adapter, book));
103
+ if (k)
104
+ return k;
105
+ }
106
+ return keyBySlug(contents, book) ?? uniqueByTitle(contents, book) ?? uniqueByTitle(all, book) ?? book;
107
+ }
108
+ function uniqueByTitle(all, title) {
109
+ const t = title.replace(/\s+/g, " ").trim();
110
+ if (!t)
111
+ return null;
112
+ const keys = new Set(all.filter((e) => e.key && e.title === t).map((e) => e.key));
113
+ return keys.size === 1 ? [...keys][0] : null;
114
+ }
115
+ /** The entries from `root` down to the one whose key is `key`. */
116
+ function pathTo(root, key) {
117
+ if (root.key === key)
118
+ return [root];
119
+ for (const c of root.children) {
120
+ const p = pathTo(c, key);
121
+ if (p)
122
+ return [root, ...p];
123
+ }
124
+ return null;
125
+ }
126
+ export async function importBook(opts) {
127
+ const { adapter } = opts;
128
+ const delay = opts.delayMs ?? adapter.delayMs;
129
+ // A site whose pages do not carry its contents: fetch the page that does, first
130
+ if (adapter.contentsUrl && !opts.contents) {
131
+ const url = adapter.contentsUrl(readStart(adapter, load(opts.start.html), opts.start));
132
+ if (!url)
133
+ throw new Error(`${adapter.name}: the start page does not say where the site's contents are`);
134
+ if (delay > 0)
135
+ await sleep(delay, opts.signal);
136
+ const html = await opts.fetch(url, "contents", opts.signal).catch(() => null);
137
+ if (!html)
138
+ throw new Error(`${adapter.name}: the site's contents (${url}) could not be had`);
139
+ opts = { ...opts, contents: { html, url } };
140
+ }
141
+ const { plan: planned, $start, startInfo, startKey, book, section, order } = plan(opts);
142
+ // File names: the book's first page is index.md; two pages never share a name
143
+ const files = new Map();
144
+ const taken = new Set();
145
+ for (const e of order) {
146
+ const key = e.key;
147
+ let name = key === planned.key ? "index.md" : adapter.fileOf(key);
148
+ if (key !== planned.key)
149
+ for (let i = 2; taken.has(name) || name === "index.md"; i++)
150
+ name = adapter.fileOf(key).replace(/(\.md)?$/, `-${i}.md`);
151
+ taken.add(name);
152
+ files.set(key, name);
153
+ }
154
+ const fileOf = (key) => files.get(key);
155
+ // 1. Fetch and convert, one page at a time (each page's DOM is dropped once converted).
156
+ // Links to pages are held as placeholders until every page is in.
157
+ const converted = new Map();
158
+ const missing = [];
159
+ const convert = (key, $, info) => {
160
+ const links = { internal: 0, site: 0, external: 0, anchorsDropped: 0 };
161
+ const base = new URL(info.url);
162
+ const r = htmlToTree($, {
163
+ profile: adapter.profile,
164
+ root: info.root,
165
+ resolveHref: (href) => {
166
+ if (href.startsWith("#"))
167
+ return `${PAGE}${key}#${decode(href.slice(1))}`;
168
+ let u;
169
+ try {
170
+ u = new URL(href, base);
171
+ }
172
+ catch {
173
+ return href;
174
+ }
175
+ const target = adapter.keyOf(u);
176
+ if (!target) {
177
+ links.external++;
178
+ return u.href;
179
+ }
180
+ return `${PAGE}${target}${u.hash ? `#${decode(u.hash.slice(1))}` : ""}`;
181
+ },
182
+ onImage: ({ src }) => {
183
+ try {
184
+ return new URL(src, base).href;
185
+ }
186
+ catch {
187
+ return src;
188
+ }
189
+ },
190
+ // Kept SVGs (syntax diagrams): assets/<page>-diagram-1.svg, beside the flat pages
191
+ assetPath: (name) => `assets/${fileOf(key).replace(/\.md$/, "")}-${name}`,
192
+ });
193
+ 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 });
194
+ };
195
+ for (const [index, e] of order.entries()) {
196
+ const key = e.key;
197
+ // The start page as read, unless the adapter fetches content from elsewhere (fetchUrlOf)
198
+ if (key === startKey && !adapter.fetchUrlOf) {
199
+ // Found by title or slug: its links resolve against its own address, not the one it was read at
200
+ convert(key, $start, key === startInfo.key ? startInfo : { ...startInfo, key, url: adapter.urlOf(key) });
201
+ }
202
+ else {
203
+ if (opts.signal?.aborted)
204
+ throw new Error("cancelled");
205
+ // Every fetch waits, the first too: the start page was just fetched by the caller
206
+ if (delay > 0)
207
+ await sleep(delay, opts.signal);
208
+ const html = await opts.fetch(adapter.fetchUrlOf?.(key) ?? adapter.urlOf(key), key, opts.signal).catch(() => null);
209
+ if (opts.signal?.aborted)
210
+ throw new Error("cancelled");
211
+ const $ = html ? load(html) : null;
212
+ const info = $ ? adapter.readPage($, adapter.urlOf(key)) : null;
213
+ if ($ && info)
214
+ convert(key, $, info);
215
+ else
216
+ missing.push(key);
217
+ }
218
+ opts.onPage?.({ key, title: e.title, index, total: order.length, ok: converted.has(key) });
219
+ }
220
+ // 3. Images on the site's own host, saved in the book (one fetch per image, however many pages show it)
221
+ const binaries = {};
222
+ const imagesMissing = [];
223
+ if (opts.fetchBytes) {
224
+ const origin = new URL(adapter.urlOf(planned.key)).origin;
225
+ const wanted = new Map();
226
+ for (const page of converted.values())
227
+ walkInline(page.tree, (n) => {
228
+ if (n.type !== "image" || wanted.has(n.src))
229
+ return;
230
+ let u;
231
+ try {
232
+ u = new URL(n.src);
233
+ }
234
+ catch {
235
+ return;
236
+ }
237
+ if (u.origin === origin)
238
+ wanted.set(n.src, null);
239
+ });
240
+ // Not the name of a kept SVG (a syntax diagram)
241
+ const names = new Set([...converted.values()].flatMap((p) => p.assets.map((a) => a.path.replace(/^assets\//, "").toLowerCase())));
242
+ let index = 0;
243
+ for (const url of wanted.keys()) {
244
+ if (opts.signal?.aborted)
245
+ throw new Error("cancelled");
246
+ if (delay > 0)
247
+ await sleep(delay, opts.signal);
248
+ const bytes = await opts.fetchBytes(url, opts.signal).catch(() => null);
249
+ if (opts.signal?.aborted)
250
+ throw new Error("cancelled");
251
+ // A file the site can serve by its extension only: an image of a kind not known keeps its URL
252
+ const kind = bytes && (sniff(bytes) ?? knownExtension(url));
253
+ if (bytes && kind) {
254
+ const path = assetName(url, names, kind);
255
+ binaries[`content/${path}`] = bytes;
256
+ wanted.set(url, path);
257
+ }
258
+ else if (!bytes)
259
+ imagesMissing.push(url);
260
+ opts.onImage?.({ url, index: index++, total: wanted.size, ok: !!bytes });
261
+ }
262
+ for (const page of converted.values())
263
+ walkInline(page.tree, (n) => {
264
+ if (n.type === "image")
265
+ n.src = wanted.get(n.src) ?? n.src;
266
+ });
267
+ }
268
+ // 4. Links between pages
269
+ for (const [key, page] of converted) {
270
+ rewriteLinks(page.tree, (href) => {
271
+ if (!href.startsWith(PAGE))
272
+ return href;
273
+ const [target, ...rest] = href.slice(PAGE.length).split("#");
274
+ const fragment = rest.join("#");
275
+ const there = converted.get(target);
276
+ if (!there) {
277
+ page.links.site++;
278
+ return adapter.urlOf(target) + (fragment ? `#${encodeURIComponent(fragment)}` : "");
279
+ }
280
+ page.links.internal++;
281
+ // A fragment with no anchor in the Markdown (a topic's id that is not a heading's) lands on the page
282
+ const keep = fragment && there.anchored.has(fragment);
283
+ if (fragment && !keep)
284
+ page.links.anchorsDropped++;
285
+ if (target === key)
286
+ return keep ? `#${fragment}` : fileOf(key);
287
+ return fileOf(target) + (keep ? `#${fragment}` : "");
288
+ });
289
+ }
290
+ // 5. Files
291
+ const out = {};
292
+ const pages = [];
293
+ for (const [key, page] of converted) {
294
+ // The summary is the page's own first paragraph too: written into front matter as well, so the
295
+ // build's llms.txt, search and link previews (and an agent reading the folder) need not guess it
296
+ const frontmatter = { title: page.title, ...(page.description ? { description: page.description } : {}), type: page.type, source: page.info.url, ...(page.info.updated ? { updated: page.info.updated } : {}) };
297
+ out[`content/${fileOf(key)}`] = treeToDogsbayMd(page.tree, { frontmatter }).replace(/\n*$/, "\n");
298
+ for (const a of page.assets)
299
+ out[`content/${a.path}`] = a.content;
300
+ pages.push({ key, file: fileOf(key), title: page.title, type: page.type, links: page.links, fidelity: page.fidelity });
301
+ }
302
+ out["content/nav.yml"] = navYaml(book, (k) => converted.has(k), fileOf);
303
+ out["content/index.md"] ??= `---\ntitle: ${JSON.stringify(book.title)}\n---\n`;
304
+ // The site's name, description and the line under the name: `site.*`, where the builds read them
305
+ const meta = startInfo.meta;
306
+ const product = meta.product ? productName(meta.product) : "";
307
+ const tagline = [product, meta.version].filter(Boolean).join(" ");
308
+ const descr = [tagline, section].filter(Boolean).join(": ");
309
+ out["dogsbay.config.yml"] = [
310
+ "schemaVersion: 1",
311
+ "site:",
312
+ ` name: ${JSON.stringify(book.title)}`,
313
+ ...(descr ? [` description: ${JSON.stringify(descr)}`] : []),
314
+ ...(tagline ? [` tagline: ${JSON.stringify(tagline)}`] : []),
315
+ "",
316
+ `# Imported from ${adapter.urlOf(planned.key)} with @dogsbay/format-html (${adapter.name}).`,
317
+ ...(adapter.licence ? [`# ${adapter.licence.notice}`, `# Licence: ${adapter.licence.url}`] : []),
318
+ "",
319
+ ].join("\n");
320
+ return {
321
+ title: book.title,
322
+ key: planned.key,
323
+ startKey,
324
+ section,
325
+ files: out,
326
+ binaries,
327
+ imagesMissing,
328
+ pages,
329
+ missing,
330
+ differs: pages.filter((p) => p.fidelity.differs.length).map((p) => p.key),
331
+ };
332
+ }
333
+ /** The top-level contents entry (a "book") that holds `key`, and its section. */
334
+ export function findBook(contents, key) {
335
+ const has = (e) => e.key === key || e.children.some(has);
336
+ for (const top of contents) {
337
+ // Sections (no page of their own) hold books; a site without sections lists books directly
338
+ if (top.key === null) {
339
+ for (const book of top.children)
340
+ if (has(book))
341
+ return { book, section: top.title };
342
+ }
343
+ else if (has(top))
344
+ return { book: top };
345
+ }
346
+ return null;
347
+ }
348
+ /**
349
+ * nav.yml for a book: an entry with children is a group whose first item is its own
350
+ * page. Entries with no converted page under them are left out; a page is listed once.
351
+ */
352
+ export function navYaml(book, have, fileOf) {
353
+ const q = (s) => JSON.stringify(s);
354
+ const listed = new Set();
355
+ // An entry is a group only when something new is listed under it; an entry that
356
+ // lists nothing (a section of a page already listed) is left out
357
+ const walk = (e, depth) => {
358
+ const pad = " ".repeat(depth);
359
+ const file = e.key && have(e.key) && !listed.has(e.key) ? fileOf(e.key) : null;
360
+ if (file)
361
+ listed.add(e.key);
362
+ const under = e.children.flatMap((c) => walk(c, depth + 2));
363
+ if (!under.length)
364
+ return file ? [`${pad}- ${q(e.title)}: ${file}`] : [];
365
+ return [`${pad}- ${q(e.title)}:`, ...(file ? [`${pad} - ${file}`] : []), ...under];
366
+ };
367
+ return walk(book, 0).join("\n") + "\n";
368
+ }
369
+ /** A product's URL segment as a name: `red_hat_ansible_automation_platform` → "Red Hat Ansible Automation Platform". */
370
+ export function productName(segment) {
371
+ return segment
372
+ .split(/[_-]+/)
373
+ .filter(Boolean)
374
+ .map((w) => (/^[a-z]/.test(w) ? w[0].toUpperCase() + w.slice(1) : w))
375
+ .join(" ");
376
+ }
377
+ function keyBySlug(contents, slug) {
378
+ return contents.flatMap(flatten).find((e) => e.key?.split("/").pop() === slug)?.key ?? undefined;
379
+ }
380
+ function flatten(e) {
381
+ return [e, ...e.children.flatMap(flatten)];
382
+ }
383
+ function entryTitle(order, key) {
384
+ return order.find((e) => e.key === key)?.title ?? key;
385
+ }
386
+ function rewriteLinks(tree, fn) {
387
+ walkInline(tree, (n) => { if (n.type === "link")
388
+ n.href = fn(n.href); });
389
+ }
390
+ /** Every inline node of a tree, a link's content too. */
391
+ function walkInline(tree, fn) {
392
+ const inl = (ns) => {
393
+ for (const n of ns ?? []) {
394
+ fn(n);
395
+ if ("children" in n && Array.isArray(n.children))
396
+ inl(n.children);
397
+ }
398
+ };
399
+ const rec = (ns) => {
400
+ for (const n of ns) {
401
+ inl(n.inline);
402
+ if (n.children)
403
+ rec(n.children);
404
+ }
405
+ };
406
+ rec(tree);
407
+ }
408
+ /**
409
+ * An image's file in the book: `assets/<its file name>`, made unique (`-2`) when two images share a
410
+ * name, with the extension of what the bytes are (IBM serves JPEGs named .png): the site's server
411
+ * and the PDF go by the extension.
412
+ */
413
+ function assetName(url, taken, kind) {
414
+ const last = decode(new URL(url).pathname.split("/").pop() || "image");
415
+ const clean = last.replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/^\.+/, "") || "image";
416
+ const dot = clean.lastIndexOf(".");
417
+ const [stem, given] = dot > 0 ? [clean.slice(0, dot), clean.slice(dot)] : [clean, ""];
418
+ const same = kind === ".jpg" ? /^\.jpe?g$/i.test(given) : given.toLowerCase() === kind;
419
+ const ext = same ? given : kind;
420
+ let name = stem + ext;
421
+ for (let i = 2; taken.has(name.toLowerCase()); i++)
422
+ name = `${stem}-${i}${ext}`;
423
+ taken.add(name.toLowerCase());
424
+ return `assets/${name}`;
425
+ }
426
+ const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico"]);
427
+ /** The URL's own extension, when it is an image's that sites serve: else undefined. */
428
+ function knownExtension(url) {
429
+ const m = /\.[a-z0-9]+$/i.exec(new URL(url).pathname)?.[0].toLowerCase();
430
+ return m && IMAGE_EXTENSIONS.has(m) ? (m === ".jpeg" ? ".jpg" : m) : undefined;
431
+ }
432
+ /** What an image's bytes are, by their first bytes: its extension, or undefined when not known. */
433
+ function sniff(b) {
434
+ const at = (i, ...v) => v.every((x, j) => b[i + j] === x);
435
+ if (at(0, 0x89, 0x50, 0x4e, 0x47))
436
+ return ".png";
437
+ if (at(0, 0xff, 0xd8, 0xff))
438
+ return ".jpg";
439
+ if (at(0, 0x47, 0x49, 0x46, 0x38))
440
+ return ".gif";
441
+ if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50))
442
+ return ".webp";
443
+ if (at(4, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66))
444
+ return ".avif";
445
+ const head = new TextDecoder().decode(b.subarray(0, 256)).trimStart();
446
+ if (/^(<\?xml[^>]*>\s*)?(<!--[^]*?-->\s*)*<svg\b/i.test(head))
447
+ return ".svg";
448
+ return undefined;
449
+ }
450
+ function decode(s) {
451
+ try {
452
+ return decodeURIComponent(s);
453
+ }
454
+ catch {
455
+ return s;
456
+ }
457
+ }
458
+ /** Wait, or stop at once when the signal fires (a cancel during a long wait). */
459
+ function sleep(ms, signal) {
460
+ return new Promise((resolve, reject) => {
461
+ if (signal?.aborted)
462
+ return reject(new Error("cancelled"));
463
+ const t = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(); }, ms);
464
+ const stop = () => { clearTimeout(t); reject(new Error("cancelled")); };
465
+ signal?.addEventListener("abort", stop, { once: true });
466
+ });
467
+ }
@@ -0,0 +1,2 @@
1
+ import type { SiteAdapter } from "./types.js";
2
+ export declare const ibm: SiteAdapter;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * IBM Documentation (www.ibm.com/docs). A topic's address answers a browser with IBM's app (no
3
+ * content in the page: it loads it) and other clients with the topic as DITA-OT HTML. Either
4
+ * way this adapter reads what IBM's app reads, from IBM's API, so the CLI and the extension
5
+ * fetch the same things:
6
+ *
7
+ * - the product's contents, `/docs/api/v1/toc/<product path>?lang=<lang>`: JSON, each entry
8
+ * with its file (`href`) and the name its `?topic=` address uses (`topicId`);
9
+ * - each topic, `/docs/api/v1/content/<file>?parsebody=true&lang=<lang>`: the DITA-OT article.
10
+ *
11
+ * A topic's key is its file path, `<lang>/<product code>[_<version>]/…/<topic>.html`: what links
12
+ * between topics use. Its address, `/docs/<key>`, redirects to the `?topic=<name>` address the
13
+ * page names as canonical; the contents say which file each name is (`aliases`).
14
+ *
15
+ * IBM's content is © IBM, not openly licensed: imports are for the reader's own use.
16
+ */
17
+ import { load } from "cheerio";
18
+ const ORIGIN = "https://www.ibm.com";
19
+ /**
20
+ * /docs/<lang>/<code>[_<version>]/…/<topic>.htm(l): a topic by its file. The code is IBM's
21
+ * product id in capitals, with the version (`SSEPGG_11.5.0`, Db2) or without (`SSAVQO`,
22
+ * watsonx Orchestrate).
23
+ */
24
+ const FILE_PATH = /^[A-Z][A-Z0-9]{2,}(?:_[^/]+)?\/.+\.html?$/;
25
+ const FILE = /^\/docs\/([a-z]{2}(?:-[a-z]{2})?)\/([A-Z][A-Z0-9]{2,}(?:_[^/]+)?\/.+\.html?)$/;
26
+ /**
27
+ * /docs/<lang>/<product…>/<version>: a product's root, two or more lower-case segments:
28
+ * `db2/11.5.x`, `watsonx/watson-orchestrate/base`.
29
+ */
30
+ const PRODUCT = /^\/docs\/([a-z]{2}(?:-[a-z]{2})?)\/((?:[a-z0-9][^/]*\/)+[a-z0-9][^/]*)\/?$/;
31
+ const HOSTS = new Set(["www.ibm.com", "ibm.com"]);
32
+ /** IBM's page data names the topic's file: `contentProducer: 'IBM Documentation 1.0 - SSAVQO/about/doc_landing.html'`. */
33
+ const PRODUCER = /contentProducer\s*:\s*['"][^'"]*? - ([A-Z][A-Z0-9]{2,}(?:_[^/'"]+)?\/[^'"\s]+\.html?)['"]/;
34
+ const LANG = /^[a-z]{2}(?:-[a-z]{2})?$/;
35
+ export const ibm = {
36
+ name: "ibm",
37
+ profile: "dita-ot-html5",
38
+ delayMs: 1500,
39
+ matches: ["https://www.ibm.com/docs/*"],
40
+ licence: {
41
+ name: "© IBM Corporation (not openly licensed)",
42
+ url: "https://www.ibm.com/legal",
43
+ notice: "IBM documentation is © IBM Corporation and is not openly licensed: keep this import for your own use and do not republish it.",
44
+ },
45
+ // A topic: as IBM's app (a browser), or as plain HTML (other clients). Not a product's
46
+ // landing page or search: no topic there.
47
+ detect($, url) {
48
+ const u = pageUrl($, url);
49
+ if (!u || !HOSTS.has(u.hostname) || !u.pathname.startsWith("/docs/"))
50
+ return false;
51
+ // On a copy: readPage prepares the page in place
52
+ return !!ibm.readPage(load($.html()), u.href);
53
+ },
54
+ readPage($, url) {
55
+ const u = pageUrl($, url);
56
+ if (!u)
57
+ return null;
58
+ let key = ibm.keyOf(u);
59
+ if (!key)
60
+ return null;
61
+ // The page's product, version and language: from its canonical ?topic= address
62
+ const canonical = $('link[rel="canonical"]').attr("href");
63
+ const c = canonical ? safeUrl(canonical) : null;
64
+ const pm = (c && PRODUCT.exec(c.pathname)) || PRODUCT.exec(u.pathname);
65
+ const lang = pm?.[1] ?? key.split("/")[0];
66
+ // IBM's app names the topic's file in its page data: the key, when the address only has a name
67
+ const file = $("script").toArray().map((s) => PRODUCER.exec($(s).text())?.[1]).find(Boolean);
68
+ // Only when the page names the topic it is at (the canonical's ?topic= is the address's): an
69
+ // app's page data can be the first page loaded's
70
+ const sameTopic = !c || c.searchParams.get("topic") === u.searchParams.get("topic");
71
+ if (file && sameTopic && key.includes("?topic="))
72
+ key = `${lang}/${file}`;
73
+ const article = $("main article").length ? "main article" : "article";
74
+ // Neither a topic nor IBM's app showing one (a product's landing page, search)
75
+ if (!$(article).length && !file && !key.includes("?topic="))
76
+ return null;
77
+ const product = ($('meta[property="og:title"]').attr("content") ?? "").split(" | ").slice(1).join(" | ").trim();
78
+ const version = pm ? pm[2].split("/").pop() : "";
79
+ const meta = { lang };
80
+ // "Db2 for Linux, UNIX and Windows 11.5.x": the name without the version, which is its own fact
81
+ // The version as IBM writes it in the title ("Base"), not as the address has it ("base")
82
+ const named = !!version && product.toLowerCase().endsWith(` ${version.toLowerCase()}`);
83
+ if (product)
84
+ meta.product = named ? product.slice(0, -version.length - 1) : product;
85
+ if (version)
86
+ meta.version = named ? product.slice(-version.length) : version;
87
+ if (pm)
88
+ meta.productPath = pm[2];
89
+ $(`${article} script, ${article} style`).remove();
90
+ // "Last Updated: 2026-08-14", IBM's line in the article: the page's date, not its content
91
+ const stamp = $(`${article} #lastModifiedDate`);
92
+ const updated = /\d{4}-\d{2}-\d{2}/.exec(stamp.text())?.[0];
93
+ stamp.remove();
94
+ return { key, url: ibm.urlOf(key), root: article, meta, ...(updated ? { updated } : {}) };
95
+ },
96
+ contentsUrl: (page) => page.meta.productPath ? `${ORIGIN}/docs/api/v1/toc/${page.meta.productPath}?lang=${page.meta.lang ?? "en"}` : undefined,
97
+ // The contents API: { toc: { label, href, topicId, topics: [...] } }, the product at the top
98
+ // and its books under it; hrefs relative to /docs/<lang>/. A file listed twice has `?pos=2`.
99
+ readContents(_$, page, source) {
100
+ let toc;
101
+ try {
102
+ toc = source ? JSON.parse(source).toc : undefined;
103
+ }
104
+ catch {
105
+ return [];
106
+ }
107
+ if (!toc)
108
+ return [];
109
+ const lang = page.meta.lang ?? "en";
110
+ const base = `${ORIGIN}/docs/${lang}/`;
111
+ const product = page.meta.productPath;
112
+ const entry = (t) => {
113
+ const u = t.href ? safeUrl(t.href, base) : null;
114
+ const key = u ? ibm.keyOf(u) : null;
115
+ return {
116
+ title: (t.label ?? "").replace(/\s+/g, " ").trim(),
117
+ key,
118
+ ...(key && product && t.topicId ? { aliases: [`${lang}/${product}?topic=${t.topicId}`] } : {}),
119
+ children: (t.topics ?? []).map(entry),
120
+ };
121
+ };
122
+ return (toc.topics ?? []).map(entry);
123
+ },
124
+ keyOf(u) {
125
+ if (!HOSTS.has(u.hostname))
126
+ return null;
127
+ const f = FILE.exec(u.pathname);
128
+ if (f)
129
+ return `${f[1]}/${f[2]}`;
130
+ // /docs/<lang>/<product>/<version>?topic=<file path or name>
131
+ const p = PRODUCT.exec(u.pathname);
132
+ const topic = u.searchParams.get("topic");
133
+ if (!p || !topic)
134
+ return null;
135
+ if (FILE_PATH.test(topic))
136
+ return `${p[1]}/${topic}`;
137
+ return `${p[1]}/${p[2]}?topic=${topic}`;
138
+ },
139
+ // A topic's content, as IBM's app fetches it
140
+ fetchUrlOf(key) {
141
+ const [lang, ...rest] = key.split("/");
142
+ const file = rest.join("/");
143
+ if (!LANG.test(lang) || !FILE_PATH.test(file))
144
+ return ibm.urlOf(key);
145
+ return `${ORIGIN}/docs/api/v1/content/${encodeURIComponent(file)}?parsebody=true&lang=${lang}`;
146
+ },
147
+ urlOf: (key) => `${ORIGIN}/docs/${key}`,
148
+ // The topic's file name (`r0002034.html` → r0002034.md); a slug key gives the slug
149
+ fileOf: (key) => {
150
+ const last = key.includes("?topic=") ? key.split("?topic=")[1] : key.split("/").pop();
151
+ return `${last.replace(/\.html?$/, "").replace(/[^\p{L}\p{N}._-]/gu, "_") || "page"}.md`;
152
+ },
153
+ };
154
+ /** The page's URL: the one it was fetched from, else its canonical link. */
155
+ function pageUrl($, url) {
156
+ if (url)
157
+ return safeUrl(url);
158
+ const canonical = $('link[rel="canonical"]').attr("href");
159
+ return canonical ? safeUrl(canonical) : null;
160
+ }
161
+ function safeUrl(href, base) {
162
+ try {
163
+ return new URL(href, base);
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @dogsbay/format-html/site: whole books from documentation sites, through site
3
+ * adapters. Never fetches; the caller passes its fetch to importBook.
4
+ */
5
+ import type { CheerioAPI } from "cheerio";
6
+ import { ibm } from "./ibm.js";
7
+ import { redhat } from "./redhat.js";
8
+ import type { SiteAdapter } from "./types.js";
9
+ export declare const SITES: SiteAdapter[];
10
+ export declare function siteByName(name: string): SiteAdapter | undefined;
11
+ export declare function detectSite($: CheerioAPI, url?: string): SiteAdapter | undefined;
12
+ export { redhat, ibm };
13
+ /** Every adapter's pages, as extension match patterns. */
14
+ export declare const SITE_MATCHES: string[];
15
+ export { importBook, planBook, findBook, navYaml } from "./book.js";
16
+ export type { ImportBookOptions, ImportBookResult, PageReport, BookPlan } from "./book.js";
17
+ export type { SiteAdapter, SitePageInfo, ContentsEntry } from "./types.js";
@@ -0,0 +1,13 @@
1
+ import { ibm } from "./ibm.js";
2
+ import { redhat } from "./redhat.js";
3
+ export const SITES = [redhat, ibm];
4
+ export function siteByName(name) {
5
+ return SITES.find((s) => s.name === name);
6
+ }
7
+ export function detectSite($, url) {
8
+ return SITES.find((s) => s.detect($, url));
9
+ }
10
+ export { redhat, ibm };
11
+ /** Every adapter's pages, as extension match patterns. */
12
+ export const SITE_MATCHES = [...new Set(SITES.flatMap((s) => s.matches))];
13
+ export { importBook, planBook, findBook, navYaml } from "./book.js";
@@ -0,0 +1,2 @@
1
+ import type { SiteAdapter } from "./types.js";
2
+ export declare const redhat: SiteAdapter;