@dogsbay/format-html 0.2.0-beta.179 → 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/dist/core/fidelity.js +4 -0
- package/dist/core/inline.js +17 -1
- package/dist/site/book.d.ts +32 -5
- package/dist/site/book.js +239 -60
- package/dist/site/gitbook.d.ts +74 -0
- package/dist/site/gitbook.js +730 -0
- package/dist/site/index.d.ts +9 -4
- package/dist/site/index.js +11 -4
- package/dist/site/next-data.d.ts +25 -0
- package/dist/site/next-data.js +136 -0
- package/dist/site/sniff.d.ts +38 -0
- package/dist/site/sniff.js +57 -0
- package/dist/site/types.d.ts +50 -0
- package/package.json +8 -3
package/dist/core/fidelity.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DATA_DIRECTIVES } from "@dogsbay/format-dogsbay-md/browser";
|
|
1
2
|
import { tagOf } from "../dom.js";
|
|
2
3
|
import { isSkipped } from "./blocks.js";
|
|
3
4
|
const zero = () => ({ headings: 0, codeBlocks: 0, tables: 0, listItems: 0, images: 0, callouts: 0, links: 0 });
|
|
@@ -92,6 +93,9 @@ export function countTree(tree) {
|
|
|
92
93
|
c.callouts++;
|
|
93
94
|
break;
|
|
94
95
|
}
|
|
96
|
+
// A block that links (a card) is a link; a data directive's `href` names a field of its file's rows
|
|
97
|
+
if (typeof n.props?.href === "string" && n.props.href && !DATA_DIRECTIVES.includes(n.type))
|
|
98
|
+
c.links++;
|
|
95
99
|
inl(n.inline);
|
|
96
100
|
rec(n.children ?? []);
|
|
97
101
|
}
|
package/dist/core/inline.js
CHANGED
|
@@ -49,7 +49,9 @@ function walk(nodes, ann, out, opts) {
|
|
|
49
49
|
const href = fixed ?? (raw ? (opts.resolveHref ? opts.resolveHref(raw, n) : raw) : undefined);
|
|
50
50
|
const merged = merge(kids);
|
|
51
51
|
const children = trimEdges(merged);
|
|
52
|
-
|
|
52
|
+
// A link that runs something is its text (the page is someone else's): every writer
|
|
53
|
+
// checks hrefs too, but the tree is handed on (2026-11-19)
|
|
54
|
+
if (!href || !children.length || !safeLink(href)) {
|
|
53
55
|
out.push(...kids);
|
|
54
56
|
break;
|
|
55
57
|
}
|
|
@@ -70,6 +72,8 @@ function walk(nodes, ann, out, opts) {
|
|
|
70
72
|
// `data-resolved-src`: the converter already placed the image (an SVG kept as a file)
|
|
71
73
|
const fixedSrc = attribs["data-resolved-src"];
|
|
72
74
|
const src = fixedSrc ?? (opts.onImage ? opts.onImage({ src: raw, alt, attribs }) : raw);
|
|
75
|
+
if (!safeLink(src, true))
|
|
76
|
+
break;
|
|
73
77
|
const img = { type: "image", src };
|
|
74
78
|
if (alt)
|
|
75
79
|
img.alt = alt;
|
|
@@ -147,3 +151,15 @@ export function trimEdges(nodes) {
|
|
|
147
151
|
a[a.length - 1] = { ...last, text: last.text.replace(/\s+$/, "") };
|
|
148
152
|
return a;
|
|
149
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* A link or image source that runs nothing: not `javascript:`/`vbscript:` (spaces and control
|
|
156
|
+
* characters inside the scheme ignored, as browsers do), and `data:` only for an image's image.
|
|
157
|
+
*/
|
|
158
|
+
function safeLink(href, image = false) {
|
|
159
|
+
const h = href.replace(/[\u0000-\u0020]/g, "").toLowerCase();
|
|
160
|
+
if (h.startsWith("javascript:") || h.startsWith("vbscript:"))
|
|
161
|
+
return false;
|
|
162
|
+
if (h.startsWith("data:"))
|
|
163
|
+
return image && h.startsWith("data:image/") && !h.startsWith("data:image/svg");
|
|
164
|
+
return true;
|
|
165
|
+
}
|
package/dist/site/book.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type FidelityReport } from "../core/fidelity.js";
|
|
2
2
|
import type { ContentsEntry, SiteAdapter } from "./types.js";
|
|
3
3
|
export interface ImportBookOptions {
|
|
4
4
|
adapter: SiteAdapter;
|
|
@@ -20,7 +20,7 @@ export interface ImportBookOptions {
|
|
|
20
20
|
html: string;
|
|
21
21
|
url?: string;
|
|
22
22
|
};
|
|
23
|
-
/** HTML
|
|
23
|
+
/** A page's HTML (or its text, for an adapter with `readText`), or null when it cannot be had. */
|
|
24
24
|
fetch: (url: string, key: string, signal?: AbortSignal) => Promise<string | null>;
|
|
25
25
|
/**
|
|
26
26
|
* An image's bytes, or null when it cannot be had (or is not an image). When given, the pages'
|
|
@@ -38,9 +38,11 @@ export interface ImportBookOptions {
|
|
|
38
38
|
book?: string;
|
|
39
39
|
/**
|
|
40
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
|
|
41
|
+
* pages under it that holds the page (the entry itself when it has some); `page`, the page;
|
|
42
|
+
* a number, the entry that many levels below the book on the way to the page (0: the book),
|
|
43
|
+
* as `planScopes` lists them.
|
|
42
44
|
*/
|
|
43
|
-
scope?: "book" | "section" | "page";
|
|
45
|
+
scope?: "book" | "section" | "page" | number;
|
|
44
46
|
/** Override the adapter's delay between fetches (ms). */
|
|
45
47
|
delayMs?: number;
|
|
46
48
|
/** Progress: called once per page, after its fetch. */
|
|
@@ -82,7 +84,7 @@ export interface ImportBookResult {
|
|
|
82
84
|
startKey: string;
|
|
83
85
|
/** The contents section the book sits in ("Install", "Use"…). */
|
|
84
86
|
section?: string;
|
|
85
|
-
/** Project files by path: content/*.md, content/nav.yml, dogsbay.config.yml. */
|
|
87
|
+
/** Project files by path: content/*.md, content/nav.yml, dogsbay.config.yml, and data/*.json (records integration blocks held). */
|
|
86
88
|
files: Record<string, string>;
|
|
87
89
|
/** The images saved in the book, by path (content/assets/…): with `fetchBytes`. */
|
|
88
90
|
binaries: Record<string, Uint8Array>;
|
|
@@ -112,6 +114,30 @@ export interface BookPlan {
|
|
|
112
114
|
* Throws when the page is not one of the site's content pages or the book is unknown.
|
|
113
115
|
*/
|
|
114
116
|
export declare function planBook(opts: Pick<ImportBookOptions, "adapter" | "start" | "book" | "scope" | "contents">): BookPlan;
|
|
117
|
+
type PlanOptions = Pick<ImportBookOptions, "adapter" | "start" | "book" | "scope" | "contents">;
|
|
118
|
+
/** One choice of how much to save, from the page up to its book. */
|
|
119
|
+
export interface ScopeRung {
|
|
120
|
+
/** What to pass as `scope`. */
|
|
121
|
+
scope: "page" | number;
|
|
122
|
+
/** `section`: the smallest part with pages under it (the default); `chapter`: a larger one. */
|
|
123
|
+
kind: "page" | "section" | "chapter" | "book";
|
|
124
|
+
title: string;
|
|
125
|
+
/** Pages it holds, each once. */
|
|
126
|
+
pages: number;
|
|
127
|
+
}
|
|
128
|
+
export interface ScopePlan {
|
|
129
|
+
/** Where the page is: the book's section (when the site has them), the book, …, the page. */
|
|
130
|
+
trail: string[];
|
|
131
|
+
/** From the page up to the whole book; a part with the same pages as a smaller one is left out. */
|
|
132
|
+
rungs: ScopeRung[];
|
|
133
|
+
/** The rung chosen when the reader does not choose: the section. */
|
|
134
|
+
defaultIndex: number;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The parts of the book the start page sits in, smallest first, read from the contents
|
|
138
|
+
* alone (nothing is fetched): each rung's `scope` given to importBook saves that part.
|
|
139
|
+
*/
|
|
140
|
+
export declare function planScopes(opts: Omit<PlanOptions, "scope">): ScopePlan;
|
|
115
141
|
export declare function importBook(opts: ImportBookOptions): Promise<ImportBookResult>;
|
|
116
142
|
/** The top-level contents entry (a "book") that holds `key`, and its section. */
|
|
117
143
|
export declare function findBook(contents: ContentsEntry[], key: string): {
|
|
@@ -125,3 +151,4 @@ export declare function findBook(contents: ContentsEntry[], key: string): {
|
|
|
125
151
|
export declare function navYaml(book: ContentsEntry, have: (key: string) => boolean, fileOf: (key: string) => string): string;
|
|
126
152
|
/** A product's URL segment as a name: `red_hat_ansible_automation_platform` → "Red Hat Ansible Automation Platform". */
|
|
127
153
|
export declare function productName(segment: string): string;
|
|
154
|
+
export {};
|
package/dist/site/book.js
CHANGED
|
@@ -9,10 +9,13 @@
|
|
|
9
9
|
* to a page that could not be had points at the live site, not at a missing file.
|
|
10
10
|
*/
|
|
11
11
|
import { load } from "cheerio";
|
|
12
|
-
import { treeToDogsbayMd } from "@dogsbay/format-dogsbay-md/browser";
|
|
12
|
+
import { DATA_DIRECTIVES, headingIds, inertTemplateSyntax, treeToDogsbayMd } from "@dogsbay/format-dogsbay-md/browser";
|
|
13
13
|
import { htmlToTree } from "../convert.js";
|
|
14
|
+
import { compare, countTree } from "../core/fidelity.js";
|
|
14
15
|
/** A link to a page, held until every page is converted: `dogsbay-page:<key>#<fragment>`. */
|
|
15
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]+)*$/;
|
|
16
19
|
/**
|
|
17
20
|
* Which book the start page leads to, and its pages: read from the start page alone.
|
|
18
21
|
* Throws when the page is not one of the site's content pages or the book is unknown.
|
|
@@ -43,10 +46,12 @@ function plan(opts) {
|
|
|
43
46
|
const { section: bookSection } = found;
|
|
44
47
|
let book = found.book;
|
|
45
48
|
let section = bookSection;
|
|
46
|
-
if (opts.scope === "section" || opts.scope === "page") {
|
|
49
|
+
if (opts.scope === "section" || opts.scope === "page" || typeof opts.scope === "number") {
|
|
47
50
|
const path = pathTo(found.book, want) ?? [found.book];
|
|
48
51
|
const self = path[path.length - 1];
|
|
49
|
-
const part = opts.scope === "page" ? { ...self, children: [] }
|
|
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;
|
|
50
55
|
// The part's book is its section: what it is part of
|
|
51
56
|
if (part !== found.book)
|
|
52
57
|
section = found.book.title;
|
|
@@ -62,7 +67,54 @@ function plan(opts) {
|
|
|
62
67
|
key: book.key ?? order[0]?.key ?? startKey,
|
|
63
68
|
pages: order.map((e) => ({ key: e.key, title: e.title, url: adapter.urlOf(e.key) })),
|
|
64
69
|
};
|
|
65
|
-
|
|
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
|
+
};
|
|
66
118
|
}
|
|
67
119
|
/** The start page's facts: from its address, else from the address asked for. */
|
|
68
120
|
function readStart(adapter, $start, start) {
|
|
@@ -138,7 +190,7 @@ export async function importBook(opts) {
|
|
|
138
190
|
throw new Error(`${adapter.name}: the site's contents (${url}) could not be had`);
|
|
139
191
|
opts = { ...opts, contents: { html, url } };
|
|
140
192
|
}
|
|
141
|
-
const { plan: planned, $start, startInfo, startKey, book, section, order } = plan(opts);
|
|
193
|
+
const { plan: planned, $start, startInfo, startKey, book, section, order, aliasOf, fetchUrls } = plan(opts);
|
|
142
194
|
// File names: the book's first page is index.md; two pages never share a name
|
|
143
195
|
const files = new Map();
|
|
144
196
|
const taken = new Set();
|
|
@@ -156,46 +208,91 @@ export async function importBook(opts) {
|
|
|
156
208
|
// Links to pages are held as placeholders until every page is in.
|
|
157
209
|
const converted = new Map();
|
|
158
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
|
+
};
|
|
159
242
|
const convert = (key, $, info) => {
|
|
160
243
|
const links = { internal: 0, site: 0, external: 0, anchorsDropped: 0 };
|
|
161
244
|
const base = new URL(info.url);
|
|
162
245
|
const r = htmlToTree($, {
|
|
163
246
|
profile: adapter.profile,
|
|
164
247
|
root: info.root,
|
|
165
|
-
resolveHref: (
|
|
166
|
-
|
|
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
|
-
},
|
|
248
|
+
resolveHref: resolver(key, base, links),
|
|
249
|
+
onImage: ({ src }) => absolute(base)(src),
|
|
190
250
|
// Kept SVGs (syntax diagrams): assets/<page>-diagram-1.svg, beside the flat pages
|
|
191
251
|
assetPath: (name) => `assets/${fileOf(key).replace(/\.md$/, "")}-${name}`,
|
|
192
252
|
});
|
|
193
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 });
|
|
194
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
|
+
};
|
|
195
292
|
for (const [index, e] of order.entries()) {
|
|
196
293
|
const key = e.key;
|
|
197
294
|
// The start page as read, unless the adapter fetches content from elsewhere (fetchUrlOf)
|
|
198
|
-
if (key === startKey && !adapter.fetchUrlOf) {
|
|
295
|
+
if (key === startKey && !adapter.fetchUrlOf && !adapter.readText) {
|
|
199
296
|
// Found by title or slug: its links resolve against its own address, not the one it was read at
|
|
200
297
|
convert(key, $start, key === startInfo.key ? startInfo : { ...startInfo, key, url: adapter.urlOf(key) });
|
|
201
298
|
}
|
|
@@ -205,15 +302,44 @@ export async function importBook(opts) {
|
|
|
205
302
|
// Every fetch waits, the first too: the start page was just fetched by the caller
|
|
206
303
|
if (delay > 0)
|
|
207
304
|
await sleep(delay, opts.signal);
|
|
208
|
-
const
|
|
305
|
+
const body = await opts.fetch(fetchUrls.get(key) ?? adapter.fetchUrlOf?.(key) ?? adapter.urlOf(key), key, opts.signal).catch(() => null);
|
|
209
306
|
if (opts.signal?.aborted)
|
|
210
307
|
throw new Error("cancelled");
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
+
}
|
|
217
343
|
}
|
|
218
344
|
opts.onPage?.({ key, title: e.title, index, total: order.length, ok: converted.has(key) });
|
|
219
345
|
}
|
|
@@ -234,7 +360,7 @@ export async function importBook(opts) {
|
|
|
234
360
|
catch {
|
|
235
361
|
return;
|
|
236
362
|
}
|
|
237
|
-
if (u.origin === origin)
|
|
363
|
+
if (u.origin === origin || adapter.imageHost?.(u))
|
|
238
364
|
wanted.set(n.src, null);
|
|
239
365
|
});
|
|
240
366
|
// Not the name of a kept SVG (a syntax diagram)
|
|
@@ -266,26 +392,57 @@ export async function importBook(opts) {
|
|
|
266
392
|
});
|
|
267
393
|
}
|
|
268
394
|
// 4. Links between pages
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
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++;
|
|
279
431
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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
|
+
}
|
|
289
446
|
}
|
|
290
447
|
// 5. Files
|
|
291
448
|
const out = {};
|
|
@@ -294,11 +451,17 @@ export async function importBook(opts) {
|
|
|
294
451
|
// The summary is the page's own first paragraph too: written into front matter as well, so the
|
|
295
452
|
// build's llms.txt, search and link previews (and an agent reading the folder) need not guess it
|
|
296
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 } : {}) };
|
|
297
|
-
|
|
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 });
|
|
298
459
|
for (const a of page.assets)
|
|
299
460
|
out[`content/${a.path}`] = a.content;
|
|
300
461
|
pages.push({ key, file: fileOf(key), title: page.title, type: page.type, links: page.links, fidelity: page.fidelity });
|
|
301
462
|
}
|
|
463
|
+
for (const [name, file] of dataFiles)
|
|
464
|
+
out[`data/${name}.json`] = `${JSON.stringify(file.rows, null, 2)}\n`;
|
|
302
465
|
out["content/nav.yml"] = navYaml(book, (k) => converted.has(k), fileOf);
|
|
303
466
|
out["content/index.md"] ??= `---\ntitle: ${JSON.stringify(book.title)}\n---\n`;
|
|
304
467
|
// The site's name, description and the line under the name: `site.*`, where the builds read them
|
|
@@ -312,6 +475,9 @@ export async function importBook(opts) {
|
|
|
312
475
|
` name: ${JSON.stringify(book.title)}`,
|
|
313
476
|
...(descr ? [` description: ${JSON.stringify(descr)}`] : []),
|
|
314
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",
|
|
315
481
|
"",
|
|
316
482
|
`# Imported from ${adapter.urlOf(planned.key)} with @dogsbay/format-html (${adapter.name}).`,
|
|
317
483
|
...(adapter.licence ? [`# ${adapter.licence.notice}`, `# Licence: ${adapter.licence.url}`] : []),
|
|
@@ -383,9 +549,21 @@ function flatten(e) {
|
|
|
383
549
|
function entryTitle(order, key) {
|
|
384
550
|
return order.find((e) => e.key === key)?.title ?? key;
|
|
385
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);
|
|
386
554
|
function rewriteLinks(tree, fn) {
|
|
387
555
|
walkInline(tree, (n) => { if (n.type === "link")
|
|
388
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);
|
|
389
567
|
}
|
|
390
568
|
/** Every inline node of a tree, a link's content too. */
|
|
391
569
|
function walkInline(tree, fn) {
|
|
@@ -411,7 +589,8 @@ function walkInline(tree, fn) {
|
|
|
411
589
|
* and the PDF go by the extension.
|
|
412
590
|
*/
|
|
413
591
|
function assetName(url, taken, kind) {
|
|
414
|
-
|
|
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";
|
|
415
594
|
const clean = last.replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/^\.+/, "") || "image";
|
|
416
595
|
const dot = clean.lastIndexOf(".");
|
|
417
596
|
const [stem, given] = dot > 0 ? [clean.slice(0, dot), clean.slice(dot)] : [clean, ""];
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitBook published sites, on any domain (developer.harness.io, gitbook.com/docs). One book
|
|
3
|
+
* is one GitBook **space** (owner, 2026-11-18): the space the reader is on.
|
|
4
|
+
*
|
|
5
|
+
* Measured 2026-11-18 (plans/import-extension-sniffing.md, docs-dev/format-html.md):
|
|
6
|
+
* - Pages are read from their `.md`, not their HTML: the `.md` is GitBook's document written
|
|
7
|
+
* out again, every tag and word of the Git Sync source (checked against GitbookIO/public-docs),
|
|
8
|
+
* which @dogsbay/format-gitbook translates. The HTML lacks Mermaid source, code languages and
|
|
9
|
+
* the API pages' OpenAPI specs, and streams half its content (Next.js `$RC` moves).
|
|
10
|
+
* - The contents come from the start page's own data: Next.js puts the sidebar's whole tree
|
|
11
|
+
* (`"pages":[…]`: id, title, href, pathnames, groups with `descendants`) in the page's
|
|
12
|
+
* `self.__next_f.push(…)` scripts; the server's HTML draws only part of it. `llms.txt` is flat
|
|
13
|
+
* (one `##` per site section, spaces mixed) and not used.
|
|
14
|
+
* - A space's first page has two pathnames (`""` and its slug): its `.md` is `<space>/<slug>.md`;
|
|
15
|
+
* `<space>.md` is a "Page Not Found" Markdown page with status 200 (a soft 404).
|
|
16
|
+
* - Each `.md` starts with a "For the complete documentation index" banner and ends with an
|
|
17
|
+
* appended `# Agent Instructions` section: both are GitBook's, not the page's.
|
|
18
|
+
* - Card links are `{% content-ref url="/pages/<id>" %}`: the id is in the tree, kept as an alias.
|
|
19
|
+
* - Images are on `<n>-files.gitbook.io`, which answers any origin (`Access-Control-Allow-Origin: *`);
|
|
20
|
+
* GitBook's own `/~gitbook/image` proxy needs a signature we cannot make.
|
|
21
|
+
*
|
|
22
|
+
* Detected by `<meta name="generator" content="GitBook …">`; `bind` makes the adapter of the
|
|
23
|
+
* page's site and space. Reads, never fetches.
|
|
24
|
+
*/
|
|
25
|
+
import { type CheerioAPI } from "cheerio";
|
|
26
|
+
import { type PageIntegration } from "@dogsbay/format-gitbook";
|
|
27
|
+
import type { Counts } from "../core/fidelity.js";
|
|
28
|
+
import type { SiteAdapter, TextPage } from "./types.js";
|
|
29
|
+
/** One entry of GitBook's page tree, as its page data writes it. */
|
|
30
|
+
interface GbPage {
|
|
31
|
+
id: string;
|
|
32
|
+
title: string;
|
|
33
|
+
href?: string;
|
|
34
|
+
pathnames?: string[];
|
|
35
|
+
type: string;
|
|
36
|
+
descendants?: GbPage[];
|
|
37
|
+
}
|
|
38
|
+
/** What a GitBook page's data says about its space. */
|
|
39
|
+
export interface GitbookData {
|
|
40
|
+
pages: GbPage[];
|
|
41
|
+
/** The space's title (the book's). */
|
|
42
|
+
title?: string;
|
|
43
|
+
/** The space's published address (`https://site/space/`). */
|
|
44
|
+
published?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The space's page tree and facts, from the page's Next.js data (`self.__next_f.push([1,"…"])`
|
|
48
|
+
* scripts, each a JSON string; together one stream). Null when the page has none.
|
|
49
|
+
*/
|
|
50
|
+
export declare function gitbookData($: CheerioAPI): GitbookData | null;
|
|
51
|
+
/** The adapter of one GitBook site and space, from a page of it. */
|
|
52
|
+
export declare function gitbookSite(origin: string, data: GitbookData): SiteAdapter;
|
|
53
|
+
/** The adapter every GitBook site gets bound from: detects, then `bind`s to the page's site. */
|
|
54
|
+
export declare const gitbook: SiteAdapter;
|
|
55
|
+
/**
|
|
56
|
+
* The integration blocks a published GitBook page's data holds (plans/gitbook-integrations.md):
|
|
57
|
+
* each object with `renderContext.integrationName` and `initialInput`, its input props and its
|
|
58
|
+
* ContentKit element (`initialOutput.element`), references resolved. In the data's order, which
|
|
59
|
+
* is not the page's: format-gitbook matches them by props.
|
|
60
|
+
*/
|
|
61
|
+
export declare function gitbookIntegrations($: CheerioAPI): PageIntegration[];
|
|
62
|
+
/**
|
|
63
|
+
* A page's `.md` as a tree, or null when it is GitBook's "Page Not Found". With its published
|
|
64
|
+
* page's integration blocks (`gitbookIntegrations`), its own are filled from them.
|
|
65
|
+
*/
|
|
66
|
+
export declare function readGitbookText(text: string, pageIntegrations?: PageIntegration[]): TextPage | null;
|
|
67
|
+
/**
|
|
68
|
+
* What a GitBook page's text holds, counted from the text (outside code), for the fidelity
|
|
69
|
+
* report: headings, code blocks, tables, list items, images, callouts (hints), links. Every scan
|
|
70
|
+
* is linear (the text is someone else's: a backtracking pattern over `<a href="x" ` repeated took
|
|
71
|
+
* minutes, review 2026-11-18).
|
|
72
|
+
*/
|
|
73
|
+
export declare function countGitbook(text: string): Counts;
|
|
74
|
+
export {};
|