@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,168 @@
1
+ /**
2
+ * Inline DITA elements whose text is code. `cmd` is not one: in a task,
3
+ * `<span class="ph cmd">` is the step's instruction, a sentence.
4
+ */
5
+ const CODE_CLASSES = ["codeph", "cmdname", "filepath", "userinput", "systemoutput", "parmname", "varname", "option", "synph", "msgph", "apiname"];
6
+ /** DITA note types to callout types. Types without a callout of their own keep their label as the title. */
7
+ const NOTE_TYPES = {
8
+ note: "note", tip: "tip", important: "important", warning: "warning", caution: "caution", danger: "danger",
9
+ attention: "important", notice: "important", remember: "note", restriction: "warning", fastpath: "tip", trouble: "tip", other: "note",
10
+ };
11
+ /** What a DITA-OT related-links block holds: child links, link lists, "Related …" groups. */
12
+ const RELATED_LINKS = ".ullinks, .ulchildlink, .olchildlink, .relinfo, .linklist, .linklistwithchild, .relconcepts, .reltasks, .relref";
13
+ const TOPIC_TYPES = [
14
+ [/\bconbody\b/, "concept"],
15
+ [/\btaskbody\b/, "task"],
16
+ [/\b(refbody|reference)\b/, "reference"],
17
+ [/\bglossbody\b/, "glossentry"],
18
+ [/\btroublebody\b/, "troubleshooting"],
19
+ ];
20
+ export const ditaOtHtml5 = {
21
+ name: "dita-ot-html5",
22
+ detect($) {
23
+ if (/DITA-OT/i.test($('meta[name="generator"]').attr("content") ?? ""))
24
+ return true;
25
+ return $("div.body").filter((_, e) => /\b(con|task|ref|gloss|trouble)body\b/.test(e.attribs?.class ?? "")).length > 0
26
+ || $("h1.topictitle1").length > 0;
27
+ },
28
+ root($) {
29
+ // The outermost topic: the one whose title is the h1. An <article> holds it, its body and
30
+ // its nested topics; where the outermost topic has no <article> of its own (Cisco's chapter
31
+ // pages: h1, body, then the nested topics' <article>s side by side), the h1's parent does.
32
+ // Up from the h1 to the first element that also holds the topic's body: not a title
33
+ // wrapper (<header>) and never the whole <body> (old XHTML builds: the list below).
34
+ const h1 = $("h1.topictitle1").first();
35
+ if (h1.length) {
36
+ const article = h1.closest("article");
37
+ if (article.length)
38
+ return article;
39
+ for (let el = h1.parent(); el.length && !el.is("body, html"); el = el.parent()) {
40
+ if (el.children(".body").length)
41
+ return el;
42
+ }
43
+ }
44
+ for (const sel of ["article", "main", "div.body", "body"]) {
45
+ const r = $(sel).first();
46
+ if (r.length)
47
+ return r;
48
+ }
49
+ return undefined;
50
+ },
51
+ normalize($, root) {
52
+ // Related links (child topics with their short descriptions, "Related tasks", "Related
53
+ // information"): DITA-OT puts them in a <nav>, which the core skips as site chrome, but
54
+ // the reader sees them as part of the topic. Kept, as a block. The parent / previous /
55
+ // next links (familylinks) are navigation the site's own pager gives: dropped.
56
+ // Builds differ in the wrapper: `nav.related-links` (DITA-OT 3/4 HTML5), or a plain <nav>
57
+ // (inside an <aside> on IBM Docs) holding the lists by their classes.
58
+ root.find(".familylinks").remove();
59
+ root.find("nav").each((_, el) => {
60
+ const nav = $(el);
61
+ if (!nav.is(".related-links") && !nav.find(RELATED_LINKS).length)
62
+ return;
63
+ el.name = "div";
64
+ delete el.attribs.role;
65
+ });
66
+ // DITA-OT gives each title a generated id for aria-labelledby (`ariaid-title1`; IBM's
67
+ // `<topic id>__title__1`). It is never a link target; dropped, so the topic's own id
68
+ // becomes the title's anchor.
69
+ root.find("h1, h2, h3, h4, h5, h6").each((_, el) => {
70
+ const h = el;
71
+ if (/^ariaid-title\d+$|__title__\d+$/.test(h.attribs?.id ?? ""))
72
+ delete h.attribs.id;
73
+ });
74
+ // A topic's title keeps the topic's id as its anchor, as DITA links point at topics. Where
75
+ // the build gave the title an id of its own derived from the topic's (Cisco: `<topic>__<title>`),
76
+ // that id goes, so the container's id anchors the heading and in-page links land.
77
+ // The dropped id stays on an empty marker in the title, so the report lists it as
78
+ // unanchored and a link to it still lands on the page.
79
+ root.find("article[id], div.topic[id], section.topic[id]").addBack("[id]").each((_, el) => {
80
+ const id = el.attribs.id;
81
+ const title = $(el).children("h1, h2, h3, h4, h5, h6").first();
82
+ const own = title.attr("id");
83
+ if (own?.startsWith(`${id}__`)) {
84
+ title.removeAttr("id");
85
+ title.prepend($("<span>").attr("id", own));
86
+ }
87
+ });
88
+ // WebHelp's (Oxygen) "Edit online" link in the topic: the publisher's chrome. Only that
89
+ // link: `edit-link` can also be an author's outputclass on content.
90
+ root.find(".edit-link").filter((_, el) => {
91
+ const e = $(el);
92
+ return e.find('a[title="Edit this document"]').length > 0 || e.text().trim() === "Edit online";
93
+ }).remove();
94
+ // Syntax diagrams (the DITA-OT syntax-diagram plugin, IBM's reference pages): the diagram
95
+ // is an inline SVG, kept as a file. Two spacer images with the accessibility links ("Read
96
+ // syntax diagram", "Skip visual syntax diagram") go; the text version the first one
97
+ // points at (longdesc) stays as a link, the diagram for readers who cannot see it.
98
+ root.find(".syntaxdiagram").each((_, el) => {
99
+ const d = $(el);
100
+ if (d.parents(".syntaxdiagram").length)
101
+ return;
102
+ const longdesc = d.find("img[longdesc]").first().attr("longdesc");
103
+ d.find("img").filter((_, i) => /syntax diagram/i.test(i.attribs?.alt ?? "")).each((_, i) => {
104
+ const p = $(i).parent();
105
+ $(i).remove();
106
+ if (p.is("a") && !p.text().trim() && !p.find("img").length)
107
+ p.remove();
108
+ });
109
+ d.find('a[name="skip"], a[id="skip"]').filter((_, a) => !$(a).text().trim()).remove();
110
+ d.find("svg").filter((_, s) => !$(s).parents("svg").length).attr("data-dogsbay-keep", "Syntax diagram");
111
+ if (longdesc)
112
+ d.append($("<p>").append($("<a>").attr("href", longdesc).text("Syntax diagram as text")));
113
+ });
114
+ // Notes → callouts, with the generated label ("Note:") removed
115
+ root.find("div.note, aside.note, section.note").each((_, el) => {
116
+ const e = $(el);
117
+ const cls = e.attr("class") ?? "";
118
+ const named = /\bnote_(\w+)\b/.exec(cls)?.[1] ?? /\b(tip|important|warning|caution|danger|attention|notice|remember|restriction|fastpath|trouble|other)\b/.exec(cls)?.[1] ?? "note";
119
+ const type = NOTE_TYPES[named] ?? "note";
120
+ e.attr("data-callout", type);
121
+ let label = e.children("span, div").filter((_, c) => /\b(note__title|notetitle|\w+title)\b/.test(c.attribs?.class ?? "")).first();
122
+ // Inside a site's own wrappers (IBM Docs: Carbon's notification divs), not a nested note's
123
+ if (!label.length)
124
+ label = e.find("span.note__title, span.notetitle").filter((_, c) => $(c).parents("div.note, aside.note, section.note").first().is(el)).first();
125
+ const text = label.text().replace(/[:\s]+$/, "").trim();
126
+ if (label.length)
127
+ label.remove();
128
+ if (text && text.toLowerCase() !== type)
129
+ e.attr("data-callout-title", text);
130
+ else if (!text && named !== type)
131
+ e.attr("data-callout-title", named[0].toUpperCase() + named.slice(1));
132
+ });
133
+ // Code phrases → <code>
134
+ root.find(CODE_CLASSES.map((c) => `span.${c}`).join(",")).each((_, el) => {
135
+ el.name = "code";
136
+ });
137
+ // Lists drawn with <div>s (unordered steps: div.ul.steps-unordered > div.li.step)
138
+ root.find("div").each((_, el) => {
139
+ const d = el;
140
+ const tokens = (d.attribs?.class ?? "").split(/\s+/);
141
+ if (tokens.includes("ul") || tokens.includes("steps-unordered"))
142
+ d.name = "ul";
143
+ else if (tokens.includes("ol"))
144
+ d.name = "ol";
145
+ else if (tokens.includes("li") || tokens.includes("step") || tokens.includes("substep")) {
146
+ // Only an item when its parent is (or became) a list
147
+ const parent = $(el).parent().get(0);
148
+ const pt = (parent?.attribs?.class ?? "").split(/\s+/);
149
+ if (parent && (["ul", "ol"].includes(parent.name ?? "") || pt.includes("ul") || pt.includes("ol") || pt.includes("steps-unordered")))
150
+ d.name = "li";
151
+ }
152
+ });
153
+ },
154
+ // The topic's short description: written by its author as the one-line summary. The first is the
155
+ // page's own (a nested topic's comes after it).
156
+ description($, root) {
157
+ const text = root.find("p.shortdesc, div.shortdesc").first().text().replace(/\s+/g, " ").trim();
158
+ return text || undefined;
159
+ },
160
+ topicType($, root) {
161
+ const body = root.is("div.body") ? root : root.find("div.body").first();
162
+ const cls = body.attr("class") ?? "";
163
+ for (const [re, type] of TOPIC_TYPES)
164
+ if (re.test(cls))
165
+ return type;
166
+ return body.length ? "topic" : undefined;
167
+ },
168
+ };
@@ -0,0 +1,3 @@
1
+ import type { Profile } from "./types.js";
2
+ /** Any HTML: the core alone. The root is the page's main content when it is marked. */
3
+ export declare const generic: Profile;
@@ -0,0 +1,18 @@
1
+ /** Any HTML: the core alone. The root is the page's main content when it is marked. */
2
+ export const generic = {
3
+ name: "generic",
4
+ detect: () => true,
5
+ root($) {
6
+ for (const sel of ["main", "[role=main]", "article", "body"]) {
7
+ const r = $(sel).first();
8
+ if (r.length)
9
+ return r;
10
+ }
11
+ return undefined;
12
+ },
13
+ normalize() { },
14
+ description($) {
15
+ const text = ($('meta[name="description"]').attr("content") ?? $('meta[property="og:description"]').attr("content") ?? "").replace(/\s+/g, " ").trim();
16
+ return text || undefined;
17
+ },
18
+ };
@@ -0,0 +1,11 @@
1
+ import type { CheerioAPI } from "cheerio";
2
+ import { broadcomTechdocs } from "./broadcom-techdocs.js";
3
+ import { ditaOtHtml5 } from "./dita-ot-html5.js";
4
+ import { generic } from "./generic.js";
5
+ import type { Profile } from "./types.js";
6
+ /** Detection order: the most specific first; generic matches anything. */
7
+ export declare const PROFILES: Profile[];
8
+ export declare function profileByName(name: string): Profile | undefined;
9
+ export declare function detectProfile($: CheerioAPI): Profile;
10
+ export { broadcomTechdocs, ditaOtHtml5, generic };
11
+ export type { Profile };
@@ -0,0 +1,12 @@
1
+ import { broadcomTechdocs } from "./broadcom-techdocs.js";
2
+ import { ditaOtHtml5 } from "./dita-ot-html5.js";
3
+ import { generic } from "./generic.js";
4
+ /** Detection order: the most specific first; generic matches anything. */
5
+ export const PROFILES = [broadcomTechdocs, ditaOtHtml5, generic];
6
+ export function profileByName(name) {
7
+ return PROFILES.find((p) => p.name === name);
8
+ }
9
+ export function detectProfile($) {
10
+ return PROFILES.find((p) => p.detect($)) ?? generic;
11
+ }
12
+ export { broadcomTechdocs, ditaOtHtml5, generic };
@@ -0,0 +1,20 @@
1
+ import type { CheerioAPI, Cheerio } from "cheerio";
2
+ import type { DomNode } from "../dom.js";
3
+ /**
4
+ * A generator profile: what one publishing tool (DITA-OT, Asciidoctor, Sphinx…)
5
+ * leaves in its HTML, rewritten to the plain HTML the core reads. Profiles change
6
+ * the document in place; they never fetch and never drop content the reader sees.
7
+ */
8
+ export interface Profile {
9
+ name: string;
10
+ /** Does this document look like this generator's output? */
11
+ detect($: CheerioAPI): boolean;
12
+ /** The content root when the caller names none. */
13
+ root($: CheerioAPI): Cheerio<DomNode & any> | undefined;
14
+ /** Rewrite the generator's vocabulary under root to plain HTML. */
15
+ normalize($: CheerioAPI, root: Cheerio<DomNode & any>): void;
16
+ /** The page's one-line summary, when the generator marks one (DITA's short description). Plain text. */
17
+ description?($: CheerioAPI, root: Cheerio<DomNode & any>): string | undefined;
18
+ /** The page's topic type (concept, task, reference…), when the generator says. */
19
+ topicType?($: CheerioAPI, root: Cheerio<DomNode & any>): string | undefined;
20
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,127 @@
1
+ import type { FidelityReport } from "../core/fidelity.js";
2
+ import type { ContentsEntry, SiteAdapter } from "./types.js";
3
+ export interface ImportBookOptions {
4
+ adapter: SiteAdapter;
5
+ /**
6
+ * The page the reader is on (or the first saved page): its HTML, and its URL when known.
7
+ * `requestedUrl`: the address asked for, when a redirect changed it (IBM's file address
8
+ * names the topic; the `?topic=` address it redirects to does not).
9
+ */
10
+ start: {
11
+ html: string;
12
+ url?: string;
13
+ requestedUrl?: string;
14
+ };
15
+ /**
16
+ * The site's contents (HTML, or JSON), for adapters whose pages do not carry them
17
+ * (`contentsUrl`). importBook fetches them when not given; planBook needs them.
18
+ */
19
+ contents?: {
20
+ html: string;
21
+ url?: string;
22
+ };
23
+ /** HTML of a page, or null when it cannot be had. */
24
+ fetch: (url: string, key: string, signal?: AbortSignal) => Promise<string | null>;
25
+ /**
26
+ * An image's bytes, or null when it cannot be had (or is not an image). When given, the pages'
27
+ * images on the site's own host are saved in the book (`content/assets/`, in `binaries`) and
28
+ * the pages point at them; an image that cannot be had, or of a kind not known (neither its
29
+ * bytes nor its URL say png, jpg, gif, webp, avif, svg or ico), keeps its URL. Without it,
30
+ * every image keeps its URL on the site.
31
+ */
32
+ fetchBytes?: (url: string, signal?: AbortSignal) => Promise<Uint8Array | null>;
33
+ /**
34
+ * The book: a page key, a page's last path segment (its slug), or an entry's title when
35
+ * only one entry has it; the book is the top-level contents entry holding that page.
36
+ * Default: the start page.
37
+ */
38
+ book?: string;
39
+ /**
40
+ * How much of the book: all of it (default); `section`, the smallest contents entry with
41
+ * pages under it that holds the page (the entry itself when it has some); `page`, the page.
42
+ */
43
+ scope?: "book" | "section" | "page";
44
+ /** Override the adapter's delay between fetches (ms). */
45
+ delayMs?: number;
46
+ /** Progress: called once per page, after its fetch. */
47
+ onPage?: (entry: {
48
+ key: string;
49
+ title: string;
50
+ index: number;
51
+ total: number;
52
+ ok: boolean;
53
+ }) => void;
54
+ /** Progress: called once per image, after its fetch (`fetchBytes`). */
55
+ onImage?: (image: {
56
+ url: string;
57
+ index: number;
58
+ total: number;
59
+ ok: boolean;
60
+ }) => void;
61
+ /** Stop between fetches when this says so (a cancel button). */
62
+ signal?: AbortSignal;
63
+ }
64
+ export interface PageReport {
65
+ key: string;
66
+ file: string;
67
+ title: string;
68
+ type: string;
69
+ links: {
70
+ internal: number;
71
+ site: number;
72
+ external: number;
73
+ anchorsDropped: number;
74
+ };
75
+ fidelity: FidelityReport;
76
+ }
77
+ export interface ImportBookResult {
78
+ title: string;
79
+ /** The book's first page (its index.md). */
80
+ key: string;
81
+ /** The start page's key. */
82
+ startKey: string;
83
+ /** The contents section the book sits in ("Install", "Use"…). */
84
+ section?: string;
85
+ /** Project files by path: content/*.md, content/nav.yml, dogsbay.config.yml. */
86
+ files: Record<string, string>;
87
+ /** The images saved in the book, by path (content/assets/…): with `fetchBytes`. */
88
+ binaries: Record<string, Uint8Array>;
89
+ /** Images on the site's host that could not be had: their URLs, kept in the pages. */
90
+ imagesMissing: string[];
91
+ pages: PageReport[];
92
+ /** Keys of contents entries that could not be fetched or read. */
93
+ missing: string[];
94
+ /** Pages whose source and output counts differ. */
95
+ differs: string[];
96
+ }
97
+ /** A book as planned from its start page, before anything is fetched. */
98
+ export interface BookPlan {
99
+ title: string;
100
+ section?: string;
101
+ /** The book's pages in reading order, each once. */
102
+ pages: Array<{
103
+ key: string;
104
+ title: string;
105
+ url: string;
106
+ }>;
107
+ /** The book's first page. */
108
+ key: string;
109
+ }
110
+ /**
111
+ * Which book the start page leads to, and its pages: read from the start page alone.
112
+ * Throws when the page is not one of the site's content pages or the book is unknown.
113
+ */
114
+ export declare function planBook(opts: Pick<ImportBookOptions, "adapter" | "start" | "book" | "scope" | "contents">): BookPlan;
115
+ export declare function importBook(opts: ImportBookOptions): Promise<ImportBookResult>;
116
+ /** The top-level contents entry (a "book") that holds `key`, and its section. */
117
+ export declare function findBook(contents: ContentsEntry[], key: string): {
118
+ book: ContentsEntry;
119
+ section?: string;
120
+ } | null;
121
+ /**
122
+ * nav.yml for a book: an entry with children is a group whose first item is its own
123
+ * page. Entries with no converted page under them are left out; a page is listed once.
124
+ */
125
+ export declare function navYaml(book: ContentsEntry, have: (key: string) => boolean, fileOf: (key: string) => string): string;
126
+ /** A product's URL segment as a name: `red_hat_ansible_automation_platform` → "Red Hat Ansible Automation Platform". */
127
+ export declare function productName(segment: string): string;