@hamzaahmadaslam/schema-truth 0.0.0-stage → 1.0.0

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/src/fetch.mjs ADDED
@@ -0,0 +1,338 @@
1
+ // Fetches the pages named on the command line, and nothing else. Every hop (the URL given, then each redirect, at
2
+ // most 3) is checked before a connection is made: http or https only, and every address the host name resolves to
3
+ // must be public. The connection then goes only to those checked addresses, so a second DNS answer cannot swap in a
4
+ // private one. One time limit covers the whole page (10 s by default), the body stops at 2 MB, and the User-Agent
5
+ // names the tool.
6
+ import dns from "node:dns";
7
+ import http from "node:http";
8
+ import https from "node:https";
9
+ import net from "node:net";
10
+ import { Writable } from "node:stream";
11
+ import { pipeline } from "node:stream/promises";
12
+ import zlib from "node:zlib";
13
+
14
+ export const MAX_BYTES = 2 * 1024 * 1024;
15
+ export const MAX_REDIRECTS = 3;
16
+ export const DEFAULT_TIMEOUT_MS = 10_000;
17
+
18
+ /** A page that could not be fetched. The message is written for the person running the tool. */
19
+ export class FetchError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = "FetchError";
23
+ }
24
+ }
25
+
26
+ function ipv4ToNumber(ip) {
27
+ const [a, b, c, d] = ip.split(".").map(Number);
28
+ return ((a << 24) >>> 0) + (b << 16) + (c << 8) + d;
29
+ }
30
+
31
+ /** Special-purpose IPv4 ranges (IANA registry, RFC 6890 and later). The single cloud metadata addresses come first. */
32
+ const V4_RANGES = [
33
+ ["169.254.169.254/32", "metadata"], // AWS, Google Cloud, Azure and others
34
+ ["169.254.170.2/32", "metadata"], // AWS container credentials
35
+ ["100.100.100.200/32", "metadata"], // Alibaba Cloud
36
+ ["192.0.0.192/32", "metadata"], // Oracle Cloud
37
+ ["0.0.0.0/8", "unspecified"],
38
+ ["10.0.0.0/8", "private"],
39
+ ["100.64.0.0/10", "private"], // shared address space (carrier-grade NAT)
40
+ ["127.0.0.0/8", "loopback"],
41
+ ["169.254.0.0/16", "link-local"],
42
+ ["172.16.0.0/12", "private"],
43
+ ["192.0.0.0/24", "reserved"],
44
+ ["192.0.2.0/24", "reserved"], // documentation
45
+ ["192.88.99.0/24", "reserved"],
46
+ ["192.168.0.0/16", "private"],
47
+ ["198.18.0.0/15", "reserved"], // benchmarking
48
+ ["198.51.100.0/24", "reserved"], // documentation
49
+ ["203.0.113.0/24", "reserved"], // documentation
50
+ ["224.0.0.0/4", "multicast"],
51
+ ["240.0.0.0/4", "reserved"], // includes the broadcast address
52
+ ].map(([cidr, reason]) => {
53
+ const [base, bits] = cidr.split("/");
54
+ const mask = (~0 << (32 - Number(bits))) >>> 0;
55
+ return { base: (ipv4ToNumber(base) & mask) >>> 0, mask, reason };
56
+ });
57
+
58
+ function ipv4Reason(ip) {
59
+ const n = ipv4ToNumber(ip);
60
+ return V4_RANGES.find(({ base, mask }) => ((n & mask) >>> 0) === base)?.reason ?? null;
61
+ }
62
+
63
+ /** An IPv6 address as eight 16-bit numbers, or null. Handles "::", a zone ("%eth0") and a dotted IPv4 tail. */
64
+ function ipv6Groups(ip) {
65
+ let text = ip.toLowerCase().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
66
+ const tailStart = text.lastIndexOf(":") + 1;
67
+ const tail = text.slice(tailStart);
68
+ if (tail.includes(".")) {
69
+ if (!net.isIPv4(tail)) return null;
70
+ const n = ipv4ToNumber(tail);
71
+ text = `${text.slice(0, tailStart)}${(n >>> 16).toString(16)}:${(n & 0xffff).toString(16)}`;
72
+ }
73
+ const halves = text.split("::");
74
+ if (halves.length > 2) return null;
75
+ const head = halves[0] ? halves[0].split(":") : [];
76
+ const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
77
+ const fill = 8 - head.length - rest.length;
78
+ if (halves.length === 2 ? fill < 1 : fill !== 0) return null;
79
+ const groups = [...head, ...Array(halves.length === 2 ? fill : 0).fill("0"), ...rest];
80
+ if (groups.some((group) => !/^[0-9a-f]{1,4}$/.test(group))) return null;
81
+ return groups.map((group) => parseInt(group, 16));
82
+ }
83
+
84
+ function ipv6Reason(ip) {
85
+ const g = ipv6Groups(ip);
86
+ if (!g) return "invalid";
87
+ const zeros = (from, to) => g.slice(from, to).every((group) => group === 0);
88
+ const embedded = () => `${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`;
89
+ if (zeros(0, 8)) return "unspecified";
90
+ if (zeros(0, 7) && g[7] === 1) return "loopback";
91
+ if (zeros(0, 5) && g[5] === 0xffff) return ipv4Reason(embedded()); // IPv4-mapped
92
+ if (zeros(0, 6)) return "reserved"; // IPv4-compatible, deprecated
93
+ if (g[0] === 0x64 && g[1] === 0xff9b && zeros(2, 6)) return ipv4Reason(embedded()); // NAT64 (RFC 6052)
94
+ if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 1) return "private"; // local-use NAT64
95
+ if (g[0] === 0x100 && zeros(1, 4)) return "reserved"; // discard-only
96
+ if (g[0] === 0xfd00 && g[1] === 0x0ec2 && zeros(2, 7) && g[7] === 0x254) return "metadata"; // AWS, fd00:ec2::254
97
+ if ((g[0] & 0xfe00) === 0xfc00) return "private"; // unique local
98
+ if ((g[0] & 0xffc0) === 0xfe80) return "link-local";
99
+ if ((g[0] & 0xffc0) === 0xfec0) return "private"; // site-local, deprecated
100
+ if ((g[0] & 0xff00) === 0xff00) return "multicast";
101
+ if (g[0] === 0x2001 && g[1] === 0x0db8) return "reserved"; // documentation
102
+ if (g[0] === 0x3fff && g[1] < 0x1000) return "reserved"; // documentation
103
+ if (g[0] === 0x2001 && g[1] < 0x0200) return "reserved"; // protocol assignments, including Teredo
104
+ if (g[0] === 0x2002) return "reserved"; // 6to4
105
+ if ((g[0] & 0xe000) !== 0x2000) return "reserved"; // outside global unicast 2000::/3
106
+ return null;
107
+ }
108
+
109
+ /**
110
+ * Why an address must not be fetched ("loopback", "private", "link-local", "metadata", "unspecified", "multicast",
111
+ * "reserved" or "invalid"), or null for a public address.
112
+ */
113
+ export function blockedReason(address) {
114
+ const ip = String(address).replace(/^\[|\]$/g, "");
115
+ const bare = ip.replace(/%.*$/, "");
116
+ if (net.isIPv4(bare)) return ipv4Reason(bare);
117
+ if (net.isIPv6(bare)) return ipv6Reason(ip);
118
+ return "invalid";
119
+ }
120
+
121
+ const REASON_TEXT = {
122
+ loopback: "a loopback address",
123
+ private: "a private network address",
124
+ "link-local": "a link-local address",
125
+ metadata: "a cloud metadata address",
126
+ unspecified: "an unspecified address",
127
+ multicast: "a multicast address",
128
+ reserved: "a reserved address",
129
+ invalid: "an address that cannot be checked",
130
+ };
131
+
132
+ /** Parses a URL the tool may fetch: http or https only. */
133
+ export function parseHttpUrl(text) {
134
+ let url;
135
+ try {
136
+ url = new URL(text);
137
+ } catch {
138
+ throw new FetchError("not a valid URL");
139
+ }
140
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
141
+ throw new FetchError(`only http and https URLs are fetched, not ${url.protocol.slice(0, -1)}`);
142
+ }
143
+ url.hash = "";
144
+ return url;
145
+ }
146
+
147
+ const defaultResolve = (hostname) => dns.promises.lookup(hostname, { all: true });
148
+
149
+ /** Rejects when `signal` aborts, so a DNS lookup cannot outlast the time limit. */
150
+ function withSignal(promise, signal) {
151
+ if (signal.aborted) return Promise.reject(signal.reason);
152
+ return new Promise((resolve, reject) => {
153
+ const onAbort = () => reject(signal.reason);
154
+ signal.addEventListener("abort", onAbort, { once: true });
155
+ promise.then(
156
+ (value) => {
157
+ signal.removeEventListener("abort", onAbort);
158
+ resolve(value);
159
+ },
160
+ (error) => {
161
+ signal.removeEventListener("abort", onAbort);
162
+ reject(error);
163
+ },
164
+ );
165
+ });
166
+ }
167
+
168
+ /** The addresses for a URL's host, each one checked. An IP address in the URL is checked as it is. */
169
+ async function checkedAddresses(url, resolve, signal) {
170
+ const host = url.hostname.replace(/^\[|\]$/g, "");
171
+ let addresses;
172
+ if (net.isIP(host)) {
173
+ addresses = [{ address: host, family: net.isIP(host) }];
174
+ } else {
175
+ try {
176
+ addresses = await withSignal(Promise.resolve(resolve(host)), signal);
177
+ } catch (error) {
178
+ if (signal.aborted) throw error;
179
+ throw new FetchError(`could not resolve the host name ${host} (${error?.code ?? error?.message ?? error})`);
180
+ }
181
+ if (!Array.isArray(addresses) || !addresses.length) throw new FetchError(`could not resolve the host name ${host}`);
182
+ }
183
+ for (const { address } of addresses) {
184
+ const reason = blockedReason(address);
185
+ if (reason) {
186
+ const where = address === host ? host : `${host} resolves to ${address}, which`;
187
+ throw new FetchError(`refused: ${where} is ${REASON_TEXT[reason]}`);
188
+ }
189
+ }
190
+ return addresses.map(({ address }) => ({ address, family: net.isIP(address) }));
191
+ }
192
+
193
+ /** A dns.lookup stand-in for the connection: it answers only with the addresses already checked. */
194
+ export function pinnedLookup(addresses) {
195
+ return (hostname, options, callback) => {
196
+ if (typeof options === "function") {
197
+ callback = options;
198
+ options = {};
199
+ }
200
+ const family = options?.family === "IPv4" ? 4 : options?.family === "IPv6" ? 6 : options?.family;
201
+ const wanted = family === 4 || family === 6 ? addresses.filter((entry) => entry.family === family) : addresses;
202
+ if (!wanted.length) {
203
+ const error = new Error(`no checked address for ${hostname}`);
204
+ error.code = "ENOTFOUND";
205
+ return process.nextTick(callback, error);
206
+ }
207
+ if (options?.all) process.nextTick(callback, null, wanted.map((entry) => ({ ...entry })));
208
+ else process.nextTick(callback, null, wanted[0].address, wanted[0].family);
209
+ };
210
+ }
211
+
212
+ /** One GET with Node's http or https client, connecting through `lookup`. Resolves with the response stream. */
213
+ function nodeTransport(url, { headers, lookup, signal }) {
214
+ const client = url.protocol === "https:" ? https : http;
215
+ return new Promise((resolve, reject) => {
216
+ const request = client.request(url, { method: "GET", headers, lookup, agent: false, signal }, resolve);
217
+ request.on("error", reject);
218
+ request.end();
219
+ });
220
+ }
221
+
222
+ const DECODERS = {
223
+ identity: null,
224
+ gzip: () => zlib.createGunzip(),
225
+ "x-gzip": () => zlib.createGunzip(),
226
+ deflate: () => zlib.createInflate(),
227
+ br: () => zlib.createBrotliDecompress(),
228
+ };
229
+ /** A byte count for messages: "1000 bytes", "512 KB", "2 MB". */
230
+ function size(bytes) {
231
+ if (bytes < 1024) return `${bytes} bytes`;
232
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
233
+ return `${Math.round((bytes / 1024 / 1024) * 10) / 10} MB`;
234
+ }
235
+
236
+ async function readBody(response, maxBytes, signal) {
237
+ const encoding = String(response.headers["content-encoding"] ?? "identity").trim().toLowerCase() || "identity";
238
+ if (!Object.hasOwn(DECODERS, encoding)) {
239
+ response.destroy();
240
+ throw new FetchError(`the page uses a content encoding this tool cannot read (${encoding})`);
241
+ }
242
+ const chunks = [];
243
+ let received = 0;
244
+ const collect = new Writable({
245
+ write(chunk, _encoding, done) {
246
+ received += chunk.length;
247
+ if (received > maxBytes) return done(new FetchError(`the page is larger than ${size(maxBytes)}`));
248
+ chunks.push(chunk);
249
+ done();
250
+ },
251
+ });
252
+ const decoder = DECODERS[encoding]?.();
253
+ try {
254
+ await pipeline(...(decoder ? [response, decoder, collect] : [response, collect]), { signal });
255
+ } catch (error) {
256
+ if (error instanceof FetchError || signal.aborted) throw error;
257
+ if (decoder && /^(Z_|ERR_BROTLI|ERR__)/.test(String(error?.code))) throw new FetchError(`the page could not be decompressed (${encoding})`);
258
+ throw error;
259
+ }
260
+ return Buffer.concat(chunks);
261
+ }
262
+
263
+ const NETWORK_ERRORS = {
264
+ ECONNREFUSED: "the connection was refused",
265
+ ECONNRESET: "the connection was reset",
266
+ ETIMEDOUT: "the connection timed out",
267
+ EHOSTUNREACH: "the host could not be reached",
268
+ ENETUNREACH: "the network could not be reached",
269
+ EPROTO: "the TLS connection failed",
270
+ };
271
+
272
+ function describeError(error) {
273
+ const code = error?.code;
274
+ if (NETWORK_ERRORS[code]) return NETWORK_ERRORS[code];
275
+ if (/CERT|SELF_SIGNED|ALTNAME|TLS|SSL/.test(String(code))) return `the TLS certificate was not accepted (${code})`;
276
+ return code ? `${error.message} (${code})` : String(error?.message ?? error);
277
+ }
278
+
279
+ /**
280
+ * Fetches one page. Returns { url, contentType, body } where `url` is the address after redirects and `body` a
281
+ * Buffer, or throws a FetchError with a plain message. `resolve` (host name to [{ address, family }]) and
282
+ * `transport` (one GET) are injectable, so tests run without DNS or a network.
283
+ */
284
+ export async function fetchPage(input, options = {}) {
285
+ const {
286
+ timeoutMs = DEFAULT_TIMEOUT_MS,
287
+ maxBytes = MAX_BYTES,
288
+ maxRedirects = MAX_REDIRECTS,
289
+ userAgent = "schema-truth",
290
+ resolve = defaultResolve,
291
+ transport = nodeTransport,
292
+ } = options;
293
+ const signal = AbortSignal.timeout(timeoutMs);
294
+ const headers = {
295
+ "user-agent": userAgent,
296
+ accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1",
297
+ "accept-encoding": "gzip, deflate, br",
298
+ };
299
+ let url = parseHttpUrl(input);
300
+ try {
301
+ for (let redirects = 0; ; redirects++) {
302
+ const addresses = await checkedAddresses(url, resolve, signal);
303
+ const response = await transport(url, { headers, lookup: pinnedLookup(addresses), signal });
304
+ const status = response.statusCode;
305
+ const location = response.headers.location;
306
+ if (status >= 300 && status < 400 && location) {
307
+ response.destroy();
308
+ if (redirects >= maxRedirects) throw new FetchError(`stopped after ${maxRedirects} redirects`);
309
+ let next;
310
+ try {
311
+ next = new URL(location, url);
312
+ } catch {
313
+ throw new FetchError("the server redirected to an address that is not a valid URL");
314
+ }
315
+ url = parseHttpUrl(next.href);
316
+ continue;
317
+ }
318
+ if (status < 200 || status >= 300) {
319
+ response.destroy();
320
+ throw new FetchError(`the server answered HTTP ${status}`);
321
+ }
322
+ const contentType = String(response.headers["content-type"] ?? "");
323
+ if (contentType && !/^\s*(?:text\/html|application\/xhtml\+xml)\s*(?:;|$)/i.test(contentType)) {
324
+ response.destroy();
325
+ throw new FetchError(`not an HTML page (${contentType.split(";")[0].trim()})`);
326
+ }
327
+ if (Number(response.headers["content-length"]) > maxBytes) {
328
+ response.destroy();
329
+ throw new FetchError(`the page is larger than ${size(maxBytes)}`);
330
+ }
331
+ return { url: url.href, contentType, body: await readBody(response, maxBytes, signal) };
332
+ }
333
+ } catch (error) {
334
+ if (error instanceof FetchError) throw error;
335
+ if (signal.aborted) throw new FetchError(`timed out after ${timeoutMs / 1000} s`);
336
+ throw new FetchError(describeError(error));
337
+ }
338
+ }
package/src/html.mjs ADDED
@@ -0,0 +1,337 @@
1
+ // Reads HTML in code: the JSON-LD blocks, and the text a visitor sees. Nothing on the page runs: scripts are not
2
+ // executed and stylesheets are not loaded, so only HTML attributes and inline styles can hide an element.
3
+
4
+ const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
5
+
6
+ /** Elements whose content is raw text that ends only at the matching end tag. None of it is text a visitor reads. */
7
+ const RAW_TEXT = new Set(["script", "style", "title", "textarea", "iframe", "noembed", "noframes", "noscript", "xmp"]);
8
+
9
+ /** Elements whose content is never shown as page text: inert templates, media fallbacks, drawings. */
10
+ const NOT_SHOWN = new Set(["template", "svg", "object", "canvas", "audio", "video", "datalist"]);
11
+
12
+ /** Elements that start a new line of text. */
13
+ const BLOCK = new Set([
14
+ "address", "article", "aside", "blockquote", "caption", "center", "dd", "details", "dialog", "dir", "div", "dl",
15
+ "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup",
16
+ "hr", "legend", "li", "main", "menu", "nav", "ol", "optgroup", "option", "p", "pre", "search", "section", "summary",
17
+ "table", "tbody", "tfoot", "thead", "tr", "ul",
18
+ ]);
19
+ const CELL = new Set(["td", "th"]);
20
+
21
+ /** Opening one of these closes an open <p>, as browsers do. */
22
+ const CLOSES_P = new Set([
23
+ "address", "article", "aside", "blockquote", "center", "dd", "details", "dialog", "dir", "div", "dl", "dt",
24
+ "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr",
25
+ "li", "main", "menu", "nav", "ol", "p", "pre", "search", "section", "summary", "table", "ul", "xmp",
26
+ ]);
27
+ const SCOPE = new Set(["button", "table", "td", "th", "caption", "template", "object", "marquee", "applet", "svg", "math"]);
28
+ const HEADINGS = new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
29
+
30
+ /** For elements whose end tag is optional: which open elements a new one closes, and where the search stops. */
31
+ const IMPLIED = {
32
+ li: { closes: ["li"], stops: ["ul", "ol", "menu", ...SCOPE] },
33
+ dt: { closes: ["dt", "dd"], stops: ["dl", ...SCOPE] },
34
+ dd: { closes: ["dt", "dd"], stops: ["dl", ...SCOPE] },
35
+ tr: { closes: ["tr"], stops: ["table"] },
36
+ td: { closes: ["td", "th"], stops: ["tr", "table"] },
37
+ th: { closes: ["td", "th"], stops: ["tr", "table"] },
38
+ thead: { closes: ["thead", "tbody", "tfoot"], stops: ["table"] },
39
+ tbody: { closes: ["thead", "tbody", "tfoot"], stops: ["table"] },
40
+ tfoot: { closes: ["thead", "tbody", "tfoot"], stops: ["table"] },
41
+ option: { closes: ["option"], stops: ["select", "datalist", "optgroup"] },
42
+ optgroup: { closes: ["option", "optgroup"], stops: ["select", "datalist"] },
43
+ };
44
+
45
+ // Named character references: the HTML 4 set (Latin-1, symbols, punctuation) and a few HTML5 ones seen in prices
46
+ // and ratings. Anything else is left as written.
47
+ const LATIN1 =
48
+ "nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute " +
49
+ "micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig " +
50
+ "Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash " +
51
+ "Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc " +
52
+ "euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml " +
53
+ "yacute thorn yuml";
54
+ const NAMED = {
55
+ quot: 34, amp: 38, apos: 39, lt: 60, gt: 62, OElig: 338, oelig: 339, Scaron: 352, scaron: 353, Yuml: 376,
56
+ fnof: 402, circ: 710, tilde: 732, ensp: 8194, emsp: 8195, thinsp: 8201, zwnj: 8204, zwj: 8205, lrm: 8206,
57
+ rlm: 8207, ndash: 8211, mdash: 8212, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221,
58
+ bdquo: 8222, dagger: 8224, Dagger: 8225, bull: 8226, hellip: 8230, permil: 8240, prime: 8242, Prime: 8243,
59
+ lsaquo: 8249, rsaquo: 8250, euro: 8364, trade: 8482, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595,
60
+ minus: 8722, infin: 8734, ne: 8800, le: 8804, ge: 8805, starf: 9733, star: 9734, check: 10003, half: 189,
61
+ };
62
+ LATIN1.split(" ").forEach((name, i) => (NAMED[name] = 160 + i));
63
+
64
+ /** What browsers show for numeric references 128 to 159, which old pages use for Windows-1252 characters. */
65
+ const WINDOWS_1252 = {
66
+ 128: 8364, 130: 8218, 131: 402, 132: 8222, 133: 8230, 134: 8224, 135: 8225, 136: 710, 137: 8240, 138: 352,
67
+ 139: 8249, 140: 338, 142: 381, 145: 8216, 146: 8217, 147: 8220, 148: 8221, 149: 8226, 150: 8211, 151: 8212,
68
+ 152: 732, 153: 8482, 154: 353, 155: 8250, 156: 339, 158: 382, 159: 376,
69
+ };
70
+
71
+ function codePoint(n) {
72
+ if (WINDOWS_1252[n]) return String.fromCodePoint(WINDOWS_1252[n]);
73
+ if (n === 0 || n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return "�";
74
+ return String.fromCodePoint(n);
75
+ }
76
+
77
+ /** Decodes character references such as &amp;, &#8364; and &#x20AC;. Unknown names are left as they are. */
78
+ export function decodeEntities(text) {
79
+ if (!text.includes("&")) return text;
80
+ return text.replace(/&(?:#(\d{1,7});?|#[xX]([0-9a-fA-F]{1,6});?|([a-zA-Z][a-zA-Z0-9]{1,31});)/g, (match, dec, hex, name) => {
81
+ if (dec !== undefined) return codePoint(Number(dec));
82
+ if (hex !== undefined) return codePoint(parseInt(hex, 16));
83
+ return Object.hasOwn(NAMED, name) ? String.fromCodePoint(NAMED[name]) : match;
84
+ });
85
+ }
86
+
87
+ const isSpace = (code) => code === 32 || code === 9 || code === 10 || code === 12 || code === 13;
88
+ const isLetter = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
89
+
90
+ /**
91
+ * Reads one tag starting at `lt` (the "<"). Returns { end, name, closing, attrs } or null when the "<" does not
92
+ * start a tag, in which case it is plain text. Attribute names are lower-cased and values decoded.
93
+ */
94
+ function readTag(html, lt) {
95
+ let i = lt + 1;
96
+ const closing = html.charCodeAt(i) === 47; // "/"
97
+ if (closing) i++;
98
+ if (!isLetter(html.charCodeAt(i))) return null;
99
+ const nameStart = i;
100
+ while (i < html.length && !isSpace(html.charCodeAt(i)) && html[i] !== "/" && html[i] !== ">") i++;
101
+ const name = html.slice(nameStart, i).toLowerCase();
102
+ const attrs = {};
103
+ while (i < html.length) {
104
+ const c = html[i];
105
+ if (c === ">") return { end: i + 1, name, closing, attrs };
106
+ if (c === "/" || isSpace(html.charCodeAt(i))) {
107
+ i++;
108
+ continue;
109
+ }
110
+ const attrStart = i;
111
+ while (i < html.length && !isSpace(html.charCodeAt(i)) && !"/>=".includes(html[i])) i++;
112
+ if (i === attrStart) {
113
+ i++; // a stray "="
114
+ continue;
115
+ }
116
+ const attrName = html.slice(attrStart, i).toLowerCase();
117
+ while (isSpace(html.charCodeAt(i))) i++;
118
+ let value = "";
119
+ if (html[i] === "=") {
120
+ i++;
121
+ while (isSpace(html.charCodeAt(i))) i++;
122
+ const quote = html[i];
123
+ if (quote === '"' || quote === "'") {
124
+ const close = html.indexOf(quote, i + 1);
125
+ if (close === -1) return { end: html.length, name, closing, attrs };
126
+ value = html.slice(i + 1, close);
127
+ i = close + 1;
128
+ } else {
129
+ const valueStart = i;
130
+ while (i < html.length && !isSpace(html.charCodeAt(i)) && html[i] !== ">") i++;
131
+ value = html.slice(valueStart, i);
132
+ }
133
+ }
134
+ if (!Object.hasOwn(attrs, attrName)) attrs[attrName] = decodeEntities(value);
135
+ }
136
+ return { end: html.length, name, closing, attrs };
137
+ }
138
+
139
+ /** Whether an element and everything inside it is kept out of the visible text. */
140
+ function hides(name, attrs) {
141
+ if (NOT_SHOWN.has(name)) return true;
142
+ if (name === "dialog" && !Object.hasOwn(attrs, "open")) return true;
143
+ if (Object.hasOwn(attrs, "hidden") && attrs.hidden.trim().toLowerCase() !== "until-found") return true;
144
+ const style = attrs.style ?? "";
145
+ return /(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*(?:hidden|collapse))\s*(?:!\s*important\s*)?(?:;|$)/i.test(style);
146
+ }
147
+
148
+ const JSON_LD_TYPE = /^\s*application\/ld\+json\s*(?:;.*)?$/i;
149
+
150
+ /**
151
+ * Reads an HTML document. Returns { text, blocks }: the text a visitor sees, one line per block of the page (table
152
+ * cells joined with " | ", image alt text as "[image: ...]"), and every <script type="application/ld+json"> as
153
+ * { index, line, raw }, where `line` is the line of the file where the script's content starts.
154
+ */
155
+ export function parseHtml(html) {
156
+ const pieces = [];
157
+ const blocks = [];
158
+ const stack = [];
159
+ let hidden = 0;
160
+ let scanned = 0;
161
+ let line = 1;
162
+ const lineAt = (offset) => {
163
+ for (; scanned < offset; scanned++) if (html.charCodeAt(scanned) === 10) line++;
164
+ return line;
165
+ };
166
+ const emit = (text) => {
167
+ if (!hidden) pieces.push(text);
168
+ };
169
+ const pop = () => {
170
+ const top = stack.pop();
171
+ if (top.hidden) hidden--;
172
+ if (top.block) emit("\n");
173
+ };
174
+ const popThrough = (index) => {
175
+ while (stack.length > index) pop();
176
+ };
177
+ const find = (names, stops) => {
178
+ for (let k = stack.length - 1; k >= 0; k--) {
179
+ if (names.includes(stack[k].name)) return k;
180
+ if (stops.includes(stack[k].name)) return -1;
181
+ }
182
+ return -1;
183
+ };
184
+
185
+ const open = (name, attrs) => {
186
+ if (name === "html" || name === "head" || name === "body") return;
187
+ if (CLOSES_P.has(name)) {
188
+ const p = find(["p"], [...SCOPE]);
189
+ if (p >= 0) popThrough(p);
190
+ }
191
+ if (HEADINGS.has(name) && HEADINGS.has(stack.at(-1)?.name)) pop();
192
+ const rule = IMPLIED[name];
193
+ if (rule) {
194
+ const k = find(rule.closes, rule.stops);
195
+ if (k >= 0) popThrough(k);
196
+ }
197
+ if (VOID.has(name)) {
198
+ if (name === "br" || name === "hr") emit("\n");
199
+ else if (name === "img" && attrs.alt?.trim() && !hides(name, attrs)) emit(` [image: ${attrs.alt.trim()}] `);
200
+ return;
201
+ }
202
+ const isHidden = hides(name, attrs);
203
+ const block = BLOCK.has(name);
204
+ if (block) emit("\n");
205
+ if (CELL.has(name)) emit("\u0001");
206
+ stack.push({ name, hidden: isHidden, block });
207
+ if (isHidden) hidden++;
208
+ };
209
+
210
+ const close = (name) => {
211
+ if (name === "br") return emit("\n");
212
+ const k = stack.findLastIndex((entry) => entry.name === name);
213
+ if (k >= 0) popThrough(k);
214
+ else if (name === "p") emit("\n");
215
+ };
216
+
217
+ let i = 0;
218
+ while (i < html.length) {
219
+ const lt = html.indexOf("<", i);
220
+ if (lt === -1) {
221
+ emit(decodeEntities(html.slice(i)));
222
+ break;
223
+ }
224
+ if (lt > i) emit(decodeEntities(html.slice(i, lt)));
225
+ if (html.startsWith("<!--", lt)) {
226
+ const end = html.indexOf("-->", lt + 4);
227
+ i = end === -1 ? html.length : end + 3;
228
+ continue;
229
+ }
230
+ if (html[lt + 1] === "!" || html[lt + 1] === "?") {
231
+ const end = html.indexOf(">", lt + 2);
232
+ i = end === -1 ? html.length : end + 1;
233
+ continue;
234
+ }
235
+ const tag = readTag(html, lt);
236
+ if (!tag) {
237
+ emit("<");
238
+ i = lt + 1;
239
+ continue;
240
+ }
241
+ i = tag.end;
242
+ if (tag.closing) {
243
+ close(tag.name);
244
+ continue;
245
+ }
246
+ if (RAW_TEXT.has(tag.name)) {
247
+ const endTag = new RegExp(`</${tag.name}(?=[\\s/>])`, "ig");
248
+ endTag.lastIndex = i;
249
+ const found = endTag.exec(html);
250
+ const contentEnd = found ? found.index : html.length;
251
+ if (tag.name === "script" && JSON_LD_TYPE.test(tag.attrs.type ?? "")) {
252
+ blocks.push({ index: blocks.length + 1, line: lineAt(i), raw: html.slice(i, contentEnd) });
253
+ }
254
+ const gt = found ? html.indexOf(">", contentEnd) : -1;
255
+ i = gt === -1 ? html.length : gt + 1;
256
+ continue;
257
+ }
258
+ open(tag.name, tag.attrs);
259
+ }
260
+
261
+ const text = pieces
262
+ .join("")
263
+ .split("\n")
264
+ .map((row) =>
265
+ row
266
+ .split("\u0001")
267
+ .map((cell) => cell.replace(/\s+/g, " ").trim())
268
+ .filter(Boolean)
269
+ .join(" | "),
270
+ )
271
+ .filter(Boolean)
272
+ .join("\n");
273
+ return { text, blocks };
274
+ }
275
+
276
+ /** The text of an HTML fragment (a FAQ answer, say) on one line. */
277
+ export function fragmentText(fragment) {
278
+ if (!fragment.includes("<")) return decodeEntities(fragment).replace(/\s+/g, " ").trim();
279
+ return parseHtml(fragment).text.replace(/\s*\n\s*/g, " ").trim();
280
+ }
281
+
282
+ /** Strips what pages wrap JSON-LD in (HTML comments, CDATA markers, a trailing semicolon) around the JSON itself. */
283
+ function unwrap(raw) {
284
+ let text = raw.replace(/^\uFEFF/, "").trim();
285
+ let before;
286
+ do {
287
+ before = text;
288
+ text = text
289
+ .replace(/^<!--/, "")
290
+ .replace(/-->$/, "")
291
+ .replace(/^(?:\/\/[^\S\n]*)?<!\[CDATA\[/, "")
292
+ .replace(/(?:\/\/[^\S\n]*)?\]\]>$/, "")
293
+ .replace(/;$/, "")
294
+ .trim();
295
+ } while (text !== before);
296
+ return text;
297
+ }
298
+
299
+ /**
300
+ * Parses the JSON-LD blocks found by parseHtml. Each comes back as { index, line, data }, or as
301
+ * { index, line, error } with error "empty" or "invalid" when there is nothing to parse or it is not valid JSON.
302
+ */
303
+ export function readJsonLd(blocks) {
304
+ return blocks.map(({ index, line, raw }) => {
305
+ const text = unwrap(raw);
306
+ if (!text) return { index, line, error: "empty" };
307
+ try {
308
+ return { index, line, data: JSON.parse(text) };
309
+ } catch {
310
+ return { index, line, error: "invalid" };
311
+ }
312
+ });
313
+ }
314
+
315
+ /** The charset named in a Content-Type header or in a <meta> tag near the top of the page, if any. */
316
+ function declaredCharset(bytes, contentType) {
317
+ const fromHeader = /charset\s*=\s*["']?\s*([\w.:-]+)/i.exec(contentType ?? "");
318
+ if (fromHeader) return fromHeader[1];
319
+ const head = Buffer.from(bytes.subarray(0, 4096)).toString("latin1");
320
+ const fromMeta = /<meta[^>]*?charset\s*=\s*["']?\s*([\w.:-]+)/i.exec(head);
321
+ if (!fromMeta) return null;
322
+ // A page that could be read as ASCII to find this tag cannot be UTF-16, whatever the tag says.
323
+ return /^utf-?16/i.test(fromMeta[1]) ? "utf-8" : fromMeta[1];
324
+ }
325
+
326
+ /** Bytes to text: a byte order mark first, then the Content-Type charset, then a <meta> charset, else UTF-8. */
327
+ export function decodeHtml(bytes, contentType = "") {
328
+ if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) return new TextDecoder("utf-8").decode(bytes);
329
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(bytes);
330
+ if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(bytes);
331
+ const label = declaredCharset(bytes, contentType) ?? "utf-8";
332
+ try {
333
+ return new TextDecoder(label).decode(bytes);
334
+ } catch {
335
+ return new TextDecoder("utf-8").decode(bytes);
336
+ }
337
+ }