@dogsbay/site-files 0.2.0-beta.176 → 0.2.0-beta.178

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/index.d.ts CHANGED
@@ -26,3 +26,4 @@ export * from "./facets.js";
26
26
  export * from "./blog-order.js";
27
27
  export * from "./nav-sections.js";
28
28
  export * from "./unlisted.js";
29
+ export * from "./link-summary.js";
package/dist/index.js CHANGED
@@ -26,3 +26,4 @@ export * from "./facets.js";
26
26
  export * from "./blog-order.js";
27
27
  export * from "./nav-sections.js";
28
28
  export * from "./unlisted.js";
29
+ export * from "./link-summary.js";
@@ -0,0 +1,33 @@
1
+ /**
2
+ * A link's summary: what a page (or a place on it) is about, read from the page's built HTML, for
3
+ * a link preview card (upstream item 25 of dogsbay-playground; plans/link-previews.md).
4
+ *
5
+ * One function for every host: `@dogsbay/elements/link-previews` (the reader's card on an Astro
6
+ * site, and dogsbay-ssg's), the playground's preview and editor, the IDE. Same input, same card.
7
+ *
8
+ * TEXT ONLY: the page's HTML is read, never returned, so nothing in it can run or load in the
9
+ * card. No DOM: a linear scanner (no backtracking pattern over the page), so it runs in a worker
10
+ * and on pages built from someone else's repository.
11
+ *
12
+ * - No `#id`: the page's title (its `<h1>`, else `<title>`) and the first paragraph of its content
13
+ * (`article.docs-prose`, else `<main>`, else the page).
14
+ * - `#id` on a heading: its text as the label, and the first paragraph of its section.
15
+ * - `#id` on anything else (a figure, a table, a callout: a link target): its caption or title as
16
+ * the label, and the first paragraph inside it.
17
+ * - An `#id` the page lacks: undefined, so a host can say the link goes nowhere.
18
+ * - A redirect page (`<meta http-equiv="refresh">` naming a URL, as Astro's stubs and dogsbay-ssg's redirect
19
+ * entries are built): undefined. Its title is the old page's; the reader would land elsewhere.
20
+ */
21
+ export interface LinkSummary {
22
+ /** The page's title. */
23
+ title: string;
24
+ /** The heading's text, or the target's caption or title; absent for the page itself. */
25
+ label?: string;
26
+ /** About `EXCERPT_LENGTH` characters of the first paragraph, cut on a word; may be empty. */
27
+ excerpt: string;
28
+ /** What the link names: the page, a heading on it, or another target (a figure, a table). */
29
+ kind: "page" | "heading" | "target";
30
+ }
31
+ /** An excerpt is cut near this many characters, on a word. */
32
+ export declare const EXCERPT_LENGTH = 200;
33
+ export declare function linkSummary(html: string, id?: string): LinkSummary | undefined;
@@ -0,0 +1,321 @@
1
+ /**
2
+ * A link's summary: what a page (or a place on it) is about, read from the page's built HTML, for
3
+ * a link preview card (upstream item 25 of dogsbay-playground; plans/link-previews.md).
4
+ *
5
+ * One function for every host: `@dogsbay/elements/link-previews` (the reader's card on an Astro
6
+ * site, and dogsbay-ssg's), the playground's preview and editor, the IDE. Same input, same card.
7
+ *
8
+ * TEXT ONLY: the page's HTML is read, never returned, so nothing in it can run or load in the
9
+ * card. No DOM: a linear scanner (no backtracking pattern over the page), so it runs in a worker
10
+ * and on pages built from someone else's repository.
11
+ *
12
+ * - No `#id`: the page's title (its `<h1>`, else `<title>`) and the first paragraph of its content
13
+ * (`article.docs-prose`, else `<main>`, else the page).
14
+ * - `#id` on a heading: its text as the label, and the first paragraph of its section.
15
+ * - `#id` on anything else (a figure, a table, a callout: a link target): its caption or title as
16
+ * the label, and the first paragraph inside it.
17
+ * - An `#id` the page lacks: undefined, so a host can say the link goes nowhere.
18
+ * - A redirect page (`<meta http-equiv="refresh">` naming a URL, as Astro's stubs and dogsbay-ssg's redirect
19
+ * entries are built): undefined. Its title is the old page's; the reader would land elsewhere.
20
+ */
21
+ /** An excerpt is cut near this many characters, on a word. */
22
+ export const EXCERPT_LENGTH = 200;
23
+ const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
24
+ /** Elements whose content is not markup: skipped (or read as text, `title`). */
25
+ const RAW = new Set(["script", "style", "textarea", "title", "noscript", "template", "xmp"]);
26
+ /** Opening one of these ends an open `<p>` (as a browser does). */
27
+ const CLOSES_P = new Set([
28
+ "address", "article", "aside", "blockquote", "details", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form",
29
+ "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "main", "nav", "ol", "p", "pre", "section", "table", "ul",
30
+ ]);
31
+ /** Containers whose paragraphs are not the page's own text (chrome, asides, captions, tables). */
32
+ const NOT_PROSE = new Set(["nav", "aside", "header", "footer", "figure", "table", "details", "blockquote", "form", "button", "svg", "math", "dialog"]);
33
+ /** Never read as text: hidden decoration (a heading's ¶ link), embedded pictures. */
34
+ const NO_TEXT = new Set(["svg", "math", "button", "select", "img"]);
35
+ const ENTITIES = Object.assign(Object.create(null), {
36
+ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", hellip: "…", mdash: "—", ndash: "–", lsquo: "‘",
37
+ rsquo: "’", ldquo: "“", rdquo: "”", laquo: "«", raquo: "»", copy: "©", reg: "®", trade: "™", middot: "·", times: "×",
38
+ para: "¶", sect: "§", deg: "°", rarr: "→", larr: "←", bull: "•", shy: "",
39
+ });
40
+ function decode(s) {
41
+ if (!s.includes("&"))
42
+ return s;
43
+ return s.replace(/&(#[xX][0-9a-fA-F]{1,6}|#\d{1,7}|[a-zA-Z]{2,8});/g, (m, e) => {
44
+ if (e[0] !== "#")
45
+ return ENTITIES[e] ?? ENTITIES[e.toLowerCase()] ?? m;
46
+ const n = e[1] === "x" || e[1] === "X" ? Number.parseInt(e.slice(2), 16) : Number.parseInt(e.slice(1), 10);
47
+ return n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : "�";
48
+ });
49
+ }
50
+ const isNameChar = (c) => c > " " && c !== ">" && c !== "/" && c !== "=" && c !== '"' && c !== "'";
51
+ /** The page as a tree of elements and text, in one pass over the HTML. */
52
+ function parse(html) {
53
+ const root = { tag: "#root", attrs: {}, children: [], start: 0, end: 0 };
54
+ const lower = html.toLowerCase();
55
+ let cur = root;
56
+ let i = 0;
57
+ let text = 0;
58
+ let order = 1;
59
+ /** How many of each tag are open: a close walks the stack only for a tag that is (linear overall). */
60
+ const open = new Map();
61
+ const flush = (end) => {
62
+ if (end > text)
63
+ cur.children.push(html.slice(text, end));
64
+ };
65
+ const pop = () => {
66
+ cur.end = order;
67
+ open.set(cur.tag, open.get(cur.tag) - 1);
68
+ cur = cur.parent;
69
+ };
70
+ const close = (tag) => {
71
+ if (!open.get(tag))
72
+ return;
73
+ while (cur !== root) {
74
+ const done = cur.tag === tag;
75
+ pop();
76
+ if (done)
77
+ return;
78
+ }
79
+ };
80
+ while (i < html.length) {
81
+ const lt = html.indexOf("<", i);
82
+ if (lt < 0)
83
+ break;
84
+ const next = html[lt + 1] ?? "";
85
+ if (html.startsWith("<!--", lt)) {
86
+ flush(lt);
87
+ // `<!-->` and `<!--->` are empty comments, as a browser reads them
88
+ const empty = html.startsWith("<!-->", lt) ? 5 : html.startsWith("<!--->", lt) ? 6 : 0;
89
+ const end = empty ? lt : html.indexOf("-->", lt + 4);
90
+ i = text = empty ? lt + empty : end < 0 ? html.length : end + 3;
91
+ continue;
92
+ }
93
+ if (next === "!" || next === "?") {
94
+ flush(lt);
95
+ const end = html.indexOf(">", lt);
96
+ i = text = end < 0 ? html.length : end + 1;
97
+ continue;
98
+ }
99
+ const closing = next === "/";
100
+ let j = lt + (closing ? 2 : 1);
101
+ if (!/[a-zA-Z]/.test(html[j] ?? "")) {
102
+ i = lt + 1;
103
+ continue;
104
+ }
105
+ const nameStart = j;
106
+ while (j < html.length && isNameChar(html[j]))
107
+ j++;
108
+ const tag = lower.slice(nameStart, j);
109
+ // Attributes, character by character: a quoted value may hold `>`
110
+ const attrs = {};
111
+ let self = false;
112
+ while (j < html.length && html[j] !== ">") {
113
+ const c = html[j];
114
+ if (c === "/") {
115
+ self = true;
116
+ j++;
117
+ continue;
118
+ }
119
+ if (c <= " ") {
120
+ j++;
121
+ continue;
122
+ }
123
+ self = false;
124
+ const a = j;
125
+ while (j < html.length && (isNameChar(html[j]) || html[j] === '"' || html[j] === "'") && html[j] !== "=")
126
+ j++;
127
+ const name = lower.slice(a, j);
128
+ while (j < html.length && html[j] <= " ")
129
+ j++;
130
+ let value = "";
131
+ if (html[j] === "=") {
132
+ j++;
133
+ while (j < html.length && html[j] <= " ")
134
+ j++;
135
+ const q = html[j];
136
+ if (q === '"' || q === "'") {
137
+ const end = html.indexOf(q, j + 1);
138
+ value = html.slice(j + 1, end < 0 ? html.length : end);
139
+ j = end < 0 ? html.length : end + 1;
140
+ }
141
+ else {
142
+ const v = j;
143
+ while (j < html.length && html[j] > " " && html[j] !== ">")
144
+ j++;
145
+ value = html.slice(v, j);
146
+ }
147
+ }
148
+ if (name && !(name in attrs))
149
+ attrs[name] = decode(value);
150
+ if (j === a)
151
+ j++;
152
+ }
153
+ if (j >= html.length) {
154
+ // A tag never closed: the rest is not text either
155
+ flush(lt);
156
+ text = html.length;
157
+ break;
158
+ }
159
+ flush(lt);
160
+ i = text = j + 1;
161
+ if (closing) {
162
+ close(tag);
163
+ continue;
164
+ }
165
+ if (CLOSES_P.has(tag))
166
+ close("p");
167
+ const el = { tag, attrs, children: [], parent: cur, start: order++, end: 0 };
168
+ el.excl = NOT_PROSE.has(tag) || hidden(el) || "data-pagefind-ignore" in attrs ? el : cur.excl;
169
+ cur.children.push(el);
170
+ if (RAW.has(tag)) {
171
+ const end = lower.indexOf(`</${tag}`, i);
172
+ const stop = end < 0 ? html.length : end;
173
+ if (tag === "title")
174
+ el.children.push(html.slice(i, stop));
175
+ const gt = end < 0 ? -1 : html.indexOf(">", end);
176
+ i = text = gt < 0 ? html.length : gt + 1;
177
+ el.end = order;
178
+ continue;
179
+ }
180
+ if (!VOID.has(tag) && !self) {
181
+ cur = el;
182
+ open.set(tag, (open.get(tag) ?? 0) + 1);
183
+ }
184
+ else
185
+ el.end = order;
186
+ }
187
+ flush(html.length);
188
+ while (cur !== root)
189
+ pop();
190
+ root.end = order;
191
+ return root;
192
+ }
193
+ /** Every element under `root`, in document order (iterative: nesting depth is the page's). */
194
+ function* elements(root) {
195
+ const stack = [...root.children].reverse();
196
+ while (stack.length) {
197
+ const n = stack.pop();
198
+ if (typeof n === "string")
199
+ continue;
200
+ yield n;
201
+ for (let k = n.children.length - 1; k >= 0; k--)
202
+ stack.push(n.children[k]);
203
+ }
204
+ }
205
+ const hidden = (e) => e.attrs["aria-hidden"] === "true" || "hidden" in e.attrs || e.tag === "template";
206
+ /** An element's text as a reader sees it: entities decoded, hidden parts left out, spaces collapsed. */
207
+ function textOf(el) {
208
+ let out = "";
209
+ const stack = [el];
210
+ while (stack.length) {
211
+ const n = stack.pop();
212
+ if (typeof n === "string") {
213
+ out += decode(n);
214
+ continue;
215
+ }
216
+ if (n !== el && (hidden(n) || NO_TEXT.has(n.tag) || n.tag === "script" || n.tag === "style"))
217
+ continue;
218
+ if (n.tag === "br")
219
+ out += " ";
220
+ for (let k = n.children.length - 1; k >= 0; k--)
221
+ stack.push(n.children[k]);
222
+ }
223
+ return out.replace(/[\s ]+/g, " ").trim();
224
+ }
225
+ /** Whether `a` is `b` or holds it. */
226
+ const holds = (a, b) => a.start <= b.start && b.end <= a.end;
227
+ /** Whether nothing between `el` and `top` (an aside, a figure, chrome, hidden) makes its text not the page's prose. */
228
+ function within(el, top) {
229
+ const x = el.parent?.excl;
230
+ return !x || holds(x, top);
231
+ }
232
+ const HEADING = /^h([1-6])$/;
233
+ /** A title or label is cut near this many characters (a page could hold a heading of any length). */
234
+ const NAME_LENGTH = 120;
235
+ /** Cut near `limit` on a word, with an ellipsis. */
236
+ function cut(text, limit = EXCERPT_LENGTH) {
237
+ if (text.length <= limit)
238
+ return text;
239
+ const slice = text.slice(0, limit);
240
+ const space = slice.lastIndexOf(" ");
241
+ return `${(space > limit * 0.6 ? slice.slice(0, space) : slice).replace(/[\s,;:.–—-]+$/, "")}…`;
242
+ }
243
+ const name = (text) => cut(text, NAME_LENGTH);
244
+ /** Blocks whose own text is the target's when it holds no paragraph (`{#id}` on a paragraph or an item). */
245
+ const TEXT_BLOCK = new Set(["p", "li", "dd", "dt", "td", "th", "blockquote", "figcaption", "caption", "summary", "pre"]);
246
+ /** The first paragraph with text in `els` that is the page's own prose (not in chrome, a table or an aside). */
247
+ function firstParagraph(els, top, stop) {
248
+ for (const e of els) {
249
+ if (stop?.(e))
250
+ break;
251
+ if (e.tag !== "p" || !within(e, top) || hidden(e))
252
+ continue;
253
+ const t = textOf(e);
254
+ if (t)
255
+ return cut(t);
256
+ }
257
+ return "";
258
+ }
259
+ function find(root, test) {
260
+ for (const e of elements(root))
261
+ if (test(e))
262
+ return e;
263
+ return undefined;
264
+ }
265
+ /** A target's own name: its caption, title, or first heading. */
266
+ function targetLabel(el) {
267
+ const own = el.attrs["data-title"] ?? el.attrs["aria-label"] ?? el.attrs.title;
268
+ if (own?.trim())
269
+ return name(own.replace(/\s+/g, " ").trim());
270
+ const named = find(el, (e) => e.tag === "figcaption" || e.tag === "caption" || e.tag === "summary" || "data-card-title" in e.attrs || "data-title" in e.attrs || HEADING.test(e.tag));
271
+ return named ? name(textOf(named)) : "";
272
+ }
273
+ /**
274
+ * The summary of a page (`html`, the whole built page) or of the place `id` names on it (the
275
+ * fragment of a link, decoded, without `#`); undefined when the page has no such id.
276
+ */
277
+ /** `<meta http-equiv="refresh" content="0; url=…">`: a refresh that goes elsewhere (one that only reloads is no redirect). */
278
+ const isRedirect = (e) => e.tag === "meta" && e.attrs["http-equiv"]?.trim().toLowerCase() === "refresh" && /[;,]\s*url\s*=/i.test(e.attrs.content ?? "");
279
+ export function linkSummary(html, id) {
280
+ const root = parse(html);
281
+ if (find(root, isRedirect))
282
+ return undefined;
283
+ const main = find(root, (e) => e.tag === "main") ?? root;
284
+ const content = find(main, (e) => e.tag === "article" && /(?:^|\s)docs-prose(?:\s|$)/.test(e.attrs.class ?? "")) ?? main;
285
+ const h1 = find(main, (e) => e.tag === "h1");
286
+ const titleEl = find(root, (e) => e.tag === "title");
287
+ const title = name((h1 && textOf(h1)) || (titleEl ? textOf(titleEl).split(" | ")[0].trim() : ""));
288
+ const fragment = id?.replace(/^#/, "");
289
+ if (!fragment || fragment === "top") {
290
+ // After the title when it is in the content (the reader has read it already)
291
+ const all = [...elements(content)];
292
+ const from = h1 ? all.indexOf(h1) + 1 : 0;
293
+ return { title, excerpt: firstParagraph(all.slice(Math.max(0, from)), content), kind: "page" };
294
+ }
295
+ const target = find(root, (e) => e.attrs.id === fragment);
296
+ if (!target)
297
+ return undefined;
298
+ const level = HEADING.exec(target.tag)?.[1];
299
+ if (level === "1")
300
+ return { title, excerpt: firstParagraph(elements(content), content), kind: "page" };
301
+ if (level) {
302
+ // The heading's section: what follows it in its own container, up to a heading of its level
303
+ // or higher (a heading inside a <details> ends with it)
304
+ const box = target.parent ?? root;
305
+ const all = [...elements(box)];
306
+ const after = all.slice(all.indexOf(target) + 1).filter((e) => !holds(target, e));
307
+ const top = holds(content, target) ? content : main;
308
+ return {
309
+ title,
310
+ label: name(textOf(target)),
311
+ excerpt: firstParagraph(after, top, (e) => {
312
+ const m = HEADING.exec(e.tag);
313
+ return !!m && Number(m[1]) <= Number(level);
314
+ }),
315
+ kind: "heading",
316
+ };
317
+ }
318
+ const inside = firstParagraph(elements(target), target);
319
+ const own = !inside && TEXT_BLOCK.has(target.tag) ? cut(textOf(target)) : "";
320
+ return { title, label: targetLabel(target), excerpt: inside || own, kind: "target" };
321
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dogsbay/site-files",
3
- "version": "0.2.0-beta.176",
3
+ "version": "0.2.0-beta.178",
4
4
  "description": "robots.txt, _headers, llms.txt, sitemaps, redirects and JSON-LD for docs sites; shared by the dogsbay Astro pipeline and dogsbay-ssg, Worker-safe",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -9,6 +9,10 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
+ },
13
+ "./link-summary": {
14
+ "types": "./dist/link-summary.d.ts",
15
+ "import": "./dist/link-summary.js"
12
16
  }
13
17
  },
14
18
  "files": [