@uxfront/site-checks 0.1.0 → 0.1.1

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/lib/site.js CHANGED
@@ -2,14 +2,14 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { join, sep } from "node:path";
3
3
 
4
4
  import {
5
- countH1,
6
- decoder,
7
- escapeRegExp,
8
- jsonLdBodies,
9
- jsonLdNodes,
10
- scoped,
11
- tags,
12
- titleTexts,
5
+ countH1,
6
+ decoder,
7
+ escapeRegExp,
8
+ jsonLdBodies,
9
+ jsonLdNodes,
10
+ scoped,
11
+ tags,
12
+ titleTexts,
13
13
  } from "./html.js";
14
14
 
15
15
  /** @import { CheckedPage, IndexSource, ParseProfile, PathPattern, Scope, SitemapEntry } from "../index.js" */
@@ -29,137 +29,140 @@ import {
29
29
  * @implements {CheckedPage}
30
30
  */
31
31
  export class Page {
32
- /** @type {Map<string, unknown>} */
33
- #cache = new Map();
34
-
35
- /**
36
- * @param {{ loc: string, path: string, file: string, html: string, profile: Profile, decode: (text: string) => string }} input
37
- */
38
- constructor({ loc, path, file, html, profile, decode }) {
39
- this.loc = loc;
40
- this.path = path;
41
- this.file = file;
42
- this.html = html;
43
- this.profile = profile;
44
- this.decode = decode;
45
- }
46
-
47
- /**
48
- * @template T
49
- * @param {string} key
50
- * @param {() => T} read
51
- * @returns {T}
52
- */
53
- #once(key, read) {
54
- if (!this.#cache.has(key)) this.#cache.set(key, read());
55
- return /** @type {T} */ (this.#cache.get(key));
56
- }
57
-
58
- /** Every tag of this name in a scope, the profile's by default. @param {string} name @param {Scope} [scope] */
59
- tags(name, scope = this.profile.scope) {
60
- return this.#once(`tags:${scope}:${name}`, () =>
61
- tags(scoped(this.html, scope), name, this.profile, this.decode),
62
- );
63
- }
64
-
65
- /** Every tag of this name in the whole document. @param {string} name */
66
- documentTags(name) {
67
- return this.tags(name, "document");
68
- }
69
-
70
- /** A value as the profile reads it, trimmed when `trimValues` says so. @param {string} value */
71
- #value(value) {
72
- return this.profile.trimValues ? value.trim() : value;
73
- }
74
-
75
- /**
76
- * The `content` of every `<meta>` whose key is `key`. With `property-first`, a tag's key is its
77
- * `property`, or else its `name`, and a tag with no `content` is left out.
78
- * @param {string} key
79
- * @param {Scope} [scope]
80
- */
81
- meta(key, scope) {
82
- const metas = this.tags("meta", scope);
83
- const found =
84
- this.profile.metaKey === "property-first"
85
- ? metas.filter((tag) => (tag.property ?? tag.name) === key && tag.content !== undefined)
86
- : metas.filter((tag) => tag.name === key || tag.property === key);
87
- return found.map((tag) => this.#value(tag.content ?? ""));
88
- }
89
-
90
- /** The first value of a `<meta>`, or `undefined`. @param {string} key */
91
- first(key) {
92
- return this.meta(key)[0];
93
- }
94
-
95
- /** Whether a `<meta>` is set, to something other than spaces. @param {string} key */
96
- has(key) {
97
- return Boolean(this.first(key)?.trim());
98
- }
99
-
100
- get titles() {
101
- return this.#once("titles", () => {
102
- const { titleScope, trimTitle } = this.profile;
103
- return titleTexts(scoped(this.html, titleScope), this.profile).map((title) =>
104
- trimTitle === "none"
105
- ? this.decode(title)
106
- : trimTitle === "before-decode"
107
- ? this.decode(title.trim())
108
- : this.decode(title).trim(),
109
- );
110
- });
111
- }
112
-
113
- get lang() {
114
- const lang = this.documentTags("html")[0]?.lang;
115
- return lang === undefined ? undefined : this.#value(lang);
116
- }
117
-
118
- get h1() {
119
- return this.#once("h1", () => countH1(this.html, this.profile));
120
- }
121
-
122
- /**
123
- * The `href` of each canonical link: `exact` takes `rel="canonical"`, `exact-any-case` the same
124
- * in any case, and `token` a `rel` with `canonical` among its words. With `requireHref`, a link
125
- * with no `href` doesn't count.
126
- * @param {"token" | "exact" | "exact-any-case"} rel
127
- * @param {boolean} [requireHref]
128
- */
129
- canonicals(rel, requireHref = false) {
130
- return this.tags("link")
131
- .filter((tag) =>
132
- rel === "token"
133
- ? (tag.rel ?? "").toLowerCase().split(/\s+/).includes("canonical")
134
- : rel === "exact-any-case"
135
- ? tag.rel?.toLowerCase() === "canonical"
136
- : tag.rel === "canonical",
137
- )
138
- .filter((tag) => !requireHref || tag.href !== undefined)
139
- .map((tag) => tag.href ?? "");
140
- }
141
-
142
- /** Each JSON-LD block, parsed, or the reason it doesn't parse. */
143
- get blocks() {
144
- return this.#once("blocks", () =>
145
- jsonLdBodies(this.html, this.profile, this.decode).map((body) => {
146
- try {
147
- return { ok: true, value: /** @type {unknown} */ (JSON.parse(body)) };
148
- } catch (error) {
149
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
150
- }
151
- }),
152
- );
153
- }
154
-
155
- get nodes() {
156
- return this.#once("nodes", () =>
157
- jsonLdNodes(
158
- this.blocks.flatMap((block) => (block.ok ? [block.value] : [])),
159
- this.profile.nodes,
160
- ),
161
- );
162
- }
32
+ /** @type {Map<string, unknown>} */
33
+ #cache = new Map();
34
+
35
+ /**
36
+ * @param {{ loc: string, path: string, file: string, html: string, profile: Profile, decode: (text: string) => string }} input
37
+ */
38
+ constructor({ loc, path, file, html, profile, decode }) {
39
+ this.loc = loc;
40
+ this.path = path;
41
+ this.file = file;
42
+ this.html = html;
43
+ this.profile = profile;
44
+ this.decode = decode;
45
+ }
46
+
47
+ /**
48
+ * @template T
49
+ * @param {string} key
50
+ * @param {() => T} read
51
+ * @returns {T}
52
+ */
53
+ #once(key, read) {
54
+ if (!this.#cache.has(key)) {
55
+ this.#cache.set(key, read());
56
+ }
57
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- each key has one reader and one T
58
+ return /** @type {T} */ (this.#cache.get(key));
59
+ }
60
+
61
+ /** Every tag of this name in a scope, the profile's by default. @param {string} name @param {Scope} [scope] */
62
+ tags(name, scope = this.profile.scope) {
63
+ return this.#once(`tags:${scope}:${name}`, () =>
64
+ tags(scoped(this.html, scope), name, this.profile, this.decode),
65
+ );
66
+ }
67
+
68
+ /** Every tag of this name in the whole document. @param {string} name */
69
+ documentTags(name) {
70
+ return this.tags(name, "document");
71
+ }
72
+
73
+ /** A value as the profile reads it, trimmed when `trimValues` says so. @param {string} value */
74
+ #value(value) {
75
+ return this.profile.trimValues ? value.trim() : value;
76
+ }
77
+
78
+ /**
79
+ * The `content` of every `<meta>` whose key is `key`. With `property-first`, a tag's key is its
80
+ * `property`, or else its `name`, and a tag with no `content` is left out.
81
+ * @param {string} key
82
+ * @param {Scope} [scope]
83
+ */
84
+ meta(key, scope) {
85
+ const metas = this.tags("meta", scope);
86
+ const found =
87
+ this.profile.metaKey === "property-first"
88
+ ? metas.filter((tag) => (tag.property ?? tag.name) === key && tag.content !== undefined)
89
+ : metas.filter((tag) => tag.name === key || tag.property === key);
90
+ return found.map((tag) => this.#value(tag.content ?? ""));
91
+ }
92
+
93
+ /** The first value of a `<meta>`, or `undefined`. @param {string} key */
94
+ first(key) {
95
+ return this.meta(key)[0];
96
+ }
97
+
98
+ /** Whether a `<meta>` is set, to something other than spaces. @param {string} key */
99
+ has(key) {
100
+ return Boolean(this.first(key)?.trim());
101
+ }
102
+
103
+ get titles() {
104
+ return this.#once("titles", () => {
105
+ const { titleScope, trimTitle } = this.profile;
106
+ return titleTexts(scoped(this.html, titleScope), this.profile).map((title) =>
107
+ trimTitle === "none"
108
+ ? this.decode(title)
109
+ : trimTitle === "before-decode"
110
+ ? this.decode(title.trim())
111
+ : this.decode(title).trim(),
112
+ );
113
+ });
114
+ }
115
+
116
+ get lang() {
117
+ const lang = this.documentTags("html")[0]?.lang;
118
+ return lang === undefined ? undefined : this.#value(lang);
119
+ }
120
+
121
+ get h1() {
122
+ return this.#once("h1", () => countH1(this.html, this.profile));
123
+ }
124
+
125
+ /**
126
+ * The `href` of each canonical link: `exact` takes `rel="canonical"`, `exact-any-case` the same
127
+ * in any case, and `token` a `rel` with `canonical` among its words. With `requireHref`, a link
128
+ * with no `href` doesn't count.
129
+ * @param {"token" | "exact" | "exact-any-case"} rel
130
+ * @param {boolean} [requireHref]
131
+ */
132
+ canonicals(rel, requireHref = false) {
133
+ return this.tags("link")
134
+ .filter((tag) =>
135
+ rel === "token"
136
+ ? (tag.rel ?? "").toLowerCase().split(/\s+/).includes("canonical")
137
+ : rel === "exact-any-case"
138
+ ? tag.rel?.toLowerCase() === "canonical"
139
+ : tag.rel === "canonical",
140
+ )
141
+ .filter((tag) => !requireHref || tag.href !== undefined)
142
+ .map((tag) => tag.href ?? "");
143
+ }
144
+
145
+ /** Each JSON-LD block, parsed, or the reason it doesn't parse. */
146
+ get blocks() {
147
+ return this.#once("blocks", () =>
148
+ jsonLdBodies(this.html, this.profile, this.decode).map((body) => {
149
+ try {
150
+ return { ok: true, value: /** @type {unknown} */ (JSON.parse(body)) };
151
+ } catch (error) {
152
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
153
+ }
154
+ }),
155
+ );
156
+ }
157
+
158
+ get nodes() {
159
+ return this.#once("nodes", () =>
160
+ jsonLdNodes(
161
+ this.blocks.flatMap((block) => (block.ok ? [block.value] : [])),
162
+ this.profile.nodes,
163
+ ),
164
+ );
165
+ }
163
166
  }
164
167
 
165
168
  /**
@@ -168,321 +171,345 @@ export class Page {
168
171
  * @param {readonly PathPattern[]} patterns
169
172
  */
170
173
  export const inScope = (path, patterns) =>
171
- patterns.some((pattern) =>
172
- pattern.endsWith("*") ? path.startsWith(pattern.slice(0, -1)) : path === pattern,
173
- );
174
+ patterns.some((pattern) =>
175
+ pattern.endsWith("*") ? path.startsWith(pattern.slice(0, -1)) : path === pattern,
176
+ );
174
177
 
175
178
  /**
176
179
  * Everything the rules read about a built site, each file read once.
177
180
  */
178
181
  export class Site {
179
- /** @type {Map<string, string | undefined>} */
180
- #files = new Map();
181
- /** @type {string[] | undefined} */
182
- #html;
183
-
184
- /**
185
- * @param {{ site: string, dist: string, profile: Profile, paths: PathMode, now: Date }} input
186
- */
187
- constructor({ site, dist, profile, paths, now }) {
188
- this.site = site.replace(/\/+$/, "");
189
- this.host = new URL(this.site).host;
190
- this.dist = dist;
191
- this.profile = profile;
192
- this.paths = paths;
193
- this.now = now;
194
- this.decode = decoder(profile);
195
- }
196
-
197
- /** A file in `dist` as text, or `undefined`. @param {string} file */
198
- read(file) {
199
- if (!this.#files.has(file)) {
200
- const path = join(this.dist, file);
201
- let text;
202
- try {
203
- text = statSync(path).isFile() ? readFileSync(path, "utf8") : undefined;
204
- } catch {
205
- text = undefined;
206
- }
207
- this.#files.set(file, text);
208
- }
209
- return this.#files.get(file);
210
- }
211
-
212
- /** @param {string} file */
213
- exists(file) {
214
- return existsSync(join(this.dist, file));
215
- }
216
-
217
- /** The length of a text in the profile's units. @param {string} text */
218
- length(text) {
219
- if (this.profile.count === "utf-16") return text.length;
220
- // A surrogate pair is one code point in two UTF-16 units.
221
- return text.length - (text.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)?.length ?? 0);
222
- }
223
-
224
- /** Every HTML file in `dist`, with `/` between folders, in order. */
225
- get htmlFiles() {
226
- this.#html ??= readdirSync(this.dist, { recursive: true, encoding: "utf8" })
227
- .map((file) => file.split(sep).join("/"))
228
- .filter((file) => file.endsWith(".html") && isFile(join(this.dist, file)))
229
- .toSorted();
230
- return this.#html;
231
- }
232
-
233
- /** The path a file is served at, as the `paths` mode says. @param {string} file */
234
- served(file) {
235
- if (this.paths === "exact-slash") {
236
- if (file === "index.html") return "/";
237
- if (file.endsWith("/index.html")) return `/${file.slice(0, -"index.html".length)}`;
238
- return `/${file.slice(0, -".html".length)}`;
239
- }
240
- return `/${file}`.replace(/(?:\/index)?\.html$/, "") || "/";
241
- }
242
-
243
- get #byPath() {
244
- /** @type {Map<string, string>} */
245
- const map = new Map();
246
- for (const file of this.htmlFiles) {
247
- const path = this.served(file);
248
- // A `.html` file wins over a folder's `index.html` at the same path.
249
- if (!map.has(path) || !file.endsWith("/index.html")) map.set(path, file);
250
- }
251
- return map;
252
- }
253
-
254
- /** @type {Map<string, string> | undefined} */
255
- #paths;
256
-
257
- /** The file a site path is served from, or `undefined`. @param {string} path */
258
- resolve(path) {
259
- if (this.paths === "lookup") {
260
- const trimmed = path.replace(/^\/+|\/+$/g, "");
261
- const file = !trimmed
262
- ? "index.html"
263
- : path.endsWith("/") || this.read(`${trimmed}.html`) === undefined
264
- ? `${trimmed}/index.html`
265
- : `${trimmed}.html`;
266
- return this.read(file) === undefined ? undefined : file;
267
- }
268
- this.#paths ??= this.#byPath;
269
- return this.#paths.get(path);
270
- }
271
-
272
- /** @type {{ exists: boolean, entries: Entry[] } | undefined} */
273
- #sitemap;
274
-
275
- get sitemap() {
276
- if (!this.#sitemap) {
277
- const xml = this.read("sitemap.xml");
278
- /** @param {string | undefined} text */
279
- const trim = (text) => (this.profile.trimSitemap ? text?.trim() : text);
280
- const entries = [...(xml ?? "").matchAll(/<url>([\s\S]*?)<\/url>/g)].map(([, body = ""]) => {
281
- const raw = body.match(/<loc>([^<]*)<\/loc>/)?.[1];
282
- let loc = trim(raw) ?? "";
283
- let error;
284
- try {
285
- loc = this.decode(loc);
286
- } catch (thrown) {
287
- error = thrown instanceof Error ? thrown.message : String(thrown);
288
- }
289
- let url;
290
- try {
291
- url = loc ? new URL(loc) : undefined;
292
- } catch {
293
- url = undefined;
294
- }
295
- return {
296
- loc,
297
- lastmod: trim(body.match(/<lastmod>([^<]*)<\/lastmod>/)?.[1]),
298
- url,
299
- hasLoc: raw !== undefined && Boolean(loc),
300
- ...(error === undefined ? {} : { error }),
301
- };
302
- });
303
- this.#sitemap = { exists: xml !== undefined, entries };
304
- }
305
- return this.#sitemap;
306
- }
307
-
308
- /** The decoded `<loc>` values. */
309
- get locs() {
310
- return new Set(this.sitemap.entries.map((entry) => entry.loc));
311
- }
312
-
313
- /**
314
- * A page read through the profile.
315
- * @param {string} loc @param {string} path @param {string} file
316
- */
317
- page(loc, path, file) {
318
- return new Page({
319
- loc,
320
- path,
321
- file,
322
- html: this.read(file) ?? "",
323
- profile: this.profile,
324
- decode: this.decode,
325
- });
326
- }
327
-
328
- /** @type {HeaderRule[] | undefined} */
329
- #headers;
330
-
331
- /** The rules of `_headers`, each a pattern and its headers, with lower-case names. */
332
- get headers() {
333
- if (!this.#headers) {
334
- const text = this.read("_headers") ?? "";
335
- /** @type {HeaderRule[]} */
336
- const rules = [];
337
- if (this.profile.headersParser === "blocks") {
338
- // A rule is everything from one unindented line to the next, trimmed. A `#` line is a
339
- // rule of its own, and a line that still ends in `\r` doesn't read as a header.
340
- for (const block of text.split(/\n(?=\S)/)) {
341
- const [pattern = "", ...lines] = block.trim().split("\n");
342
- rules.push({
343
- pattern,
344
- headers: lines.flatMap((line) => {
345
- const [, name, value = ""] = line.match(/^\s+([^:]+):\s*(.*)$/) ?? [];
346
- return name ? [/** @type {[string, string]} */ ([name.toLowerCase(), value])] : [];
347
- }),
348
- });
349
- }
350
- this.#headers = rules;
351
- return rules;
352
- }
353
- for (const line of text.split("\n")) {
354
- if (!line.trim() || line.trim().startsWith("#")) continue;
355
- if (!/^\s/.test(line)) {
356
- rules.push({ pattern: line.trim(), headers: [] });
357
- continue;
358
- }
359
- const at = line.indexOf(":");
360
- if (at > 0 && line.slice(0, at).trim()) {
361
- rules
362
- .at(-1)
363
- ?.headers.push([line.slice(0, at).trim().toLowerCase(), line.slice(at + 1).trim()]);
364
- }
365
- }
366
- this.#headers = rules;
367
- }
368
- return this.#headers;
369
- }
370
-
371
- /**
372
- * The headers `_headers` gives a URL, as Cloudflare matches it: a rule's pattern is a path, or
373
- * a URL with a host, where `*` matches anything and a `:placeholder` anything but `.` in a host
374
- * or `/` in a path. A request gets the headers of every rule it matches.
375
- * @param {string} url
376
- * @returns {[name: string, value: string][]}
377
- */
378
- headersFor(url) {
379
- let host, pathname;
380
- try {
381
- ({ host, pathname } = new URL(url, this.site));
382
- } catch {
383
- return [];
384
- }
385
- return this.headers.flatMap(({ pattern, headers }) => {
386
- const match = cloudflarePattern(pattern).exec(
387
- pattern.startsWith("https://") ? `${host}${pathname}` : pathname,
388
- );
389
- if (!match) return [];
390
- /** @param {string} value */
391
- const fill = (value) =>
392
- value.replace(
393
- /:([A-Za-z]\w*)/g,
394
- (placeholder, /** @type {string} */ name) => match.groups?.[name] ?? placeholder,
395
- );
396
- return headers.map(([name, value]) => /** @type {[string, string]} */ ([name, fill(value)]));
397
- });
398
- }
399
-
400
- /** The sources of `_redirects` rules. */
401
- get redirected() {
402
- return new Set(
403
- (this.read("_redirects") ?? "")
404
- .split("\n")
405
- .map((line) => line.trim().split(/\s+/)[0] ?? "")
406
- .filter((source) => source && !source.startsWith("#")),
407
- );
408
- }
409
-
410
- /**
411
- * The first source that takes a page out of the index, or `undefined`.
412
- * @param {readonly IndexSource[]} sources
413
- * @param {{ file: string, path: string, host: string }} at
414
- */
415
- outOfIndex(sources, { file, path, host }) {
416
- for (const source of sources) {
417
- const found = this.#outBy(source, file, path, host);
418
- if (found) return found;
419
- }
420
- return undefined;
421
- }
422
-
423
- /**
424
- * @param {IndexSource} source @param {string} file @param {string} path @param {string} host
425
- * @returns {string | undefined}
426
- */
427
- #outBy(source, file, path, host) {
428
- switch (source.type) {
429
- case "files":
430
- return source.files.includes(file) ? `it's ${file}` : undefined;
431
- case "under": {
432
- const folder = source.paths.find((prefix) => file.startsWith(prefix));
433
- return folder ? `it's under ${folder}` : undefined;
434
- }
435
- case "redirects":
436
- return this.redirected.has(path) ? "_redirects sends it elsewhere" : undefined;
437
- case "refresh": {
438
- const page = this.page("", path, file);
439
- return page
440
- .documentTags("meta")
441
- .some((tag) => tag["http-equiv"]?.toLowerCase() === "refresh")
442
- ? "it's a meta refresh"
443
- : undefined;
444
- }
445
- case "meta": {
446
- const page = this.page("", path, file);
447
- const test = valueTest(source.values, source.word, source.caseSensitive);
448
- const scope = source.scope ?? this.profile.scope;
449
- // With `property`, a tag is found as the profile finds any `<meta>`, by its `name` or its
450
- // `property`. Without, by its `name` alone.
451
- const contents = source.property
452
- ? source.names.flatMap((name) => page.meta(name, scope))
453
- : page
454
- .tags("meta", scope)
455
- .filter((meta) => {
456
- const name = source.anyCaseNames ? meta.name?.toLowerCase() : meta.name;
457
- return name !== undefined && source.names.includes(name);
458
- })
459
- .map((meta) => meta.content ?? "");
460
- const hit = contents.find((content) => test(content));
461
- return hit === undefined ? undefined : `a robots <meta> says "${hit}"`;
462
- }
463
- case "headers": {
464
- const test = valueTest(source.values, source.word, false);
465
- for (const { pattern, headers } of this.headers) {
466
- // Host rules end in `/*` and would match every path, so `ignore` reads path rules alone.
467
- if (source.hosts === "ignore" && !pattern.startsWith("/")) continue;
468
- const target =
469
- source.hosts === "match" && pattern.startsWith("https://") ? `${host}${path}` : path;
470
- const regexp =
471
- source.hosts === "drop" ? droppedHostPattern(pattern) : cloudflarePattern(pattern);
472
- if (!regexp.test(target)) continue;
473
- const values = headers
474
- .filter(([name]) => name === "x-robots-tag")
475
- .map(([, value]) => value);
476
- // A parser that keeps one value per header name keeps the last.
477
- const read = source.hosts === "drop" ? values.slice(-1) : values;
478
- const tag = read.find((value) => test(value));
479
- if (tag !== undefined) return `_headers ${pattern} sends X-Robots-Tag: ${tag}`;
480
- }
481
- return undefined;
482
- }
483
- }
484
- return undefined;
485
- }
182
+ /** @type {Map<string, string | undefined>} */
183
+ #files = new Map();
184
+ /** @type {string[] | undefined} */
185
+ #html;
186
+
187
+ /**
188
+ * @param {{ site: string, dist: string, profile: Profile, paths: PathMode, now: Date }} input
189
+ */
190
+ constructor({ site, dist, profile, paths, now }) {
191
+ this.site = site.replace(/\/+$/, "");
192
+ this.host = new URL(this.site).host;
193
+ this.dist = dist;
194
+ this.profile = profile;
195
+ this.paths = paths;
196
+ this.now = now;
197
+ this.decode = decoder(profile);
198
+ }
199
+
200
+ /** A file in `dist` as text, or `undefined`. @param {string} file */
201
+ read(file) {
202
+ if (!this.#files.has(file)) {
203
+ const path = join(this.dist, file);
204
+ let text;
205
+ try {
206
+ text = statSync(path).isFile() ? readFileSync(path, "utf8") : undefined;
207
+ } catch {
208
+ text = undefined;
209
+ }
210
+ this.#files.set(file, text);
211
+ }
212
+ return this.#files.get(file);
213
+ }
214
+
215
+ /** @param {string} file */
216
+ exists(file) {
217
+ return existsSync(join(this.dist, file));
218
+ }
219
+
220
+ /** The length of a text in the profile's units. @param {string} text */
221
+ length(text) {
222
+ if (this.profile.count === "utf-16") {
223
+ return text.length;
224
+ }
225
+ // A surrogate pair is one code point in two UTF-16 units.
226
+ return text.length - (text.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)?.length ?? 0);
227
+ }
228
+
229
+ /** Every HTML file in `dist`, with `/` between folders, in order. */
230
+ get htmlFiles() {
231
+ this.#html ??= readdirSync(this.dist, { recursive: true, encoding: "utf8" })
232
+ .map((file) => file.split(sep).join("/"))
233
+ .filter((file) => file.endsWith(".html") && isFile(join(this.dist, file)))
234
+ .toSorted();
235
+ return this.#html;
236
+ }
237
+
238
+ /** The path a file is served at, as the `paths` mode says. @param {string} file */
239
+ served(file) {
240
+ if (this.paths === "exact-slash") {
241
+ if (file === "index.html") {
242
+ return "/";
243
+ }
244
+ if (file.endsWith("/index.html")) {
245
+ return `/${file.slice(0, -"index.html".length)}`;
246
+ }
247
+ return `/${file.slice(0, -".html".length)}`;
248
+ }
249
+ return `/${file}`.replace(/(?:\/index)?\.html$/, "") || "/";
250
+ }
251
+
252
+ get #byPath() {
253
+ /** @type {Map<string, string>} */
254
+ const map = new Map();
255
+ for (const file of this.htmlFiles) {
256
+ const path = this.served(file);
257
+ // A `.html` file wins over a folder's `index.html` at the same path.
258
+ if (!map.has(path) || !file.endsWith("/index.html")) {
259
+ map.set(path, file);
260
+ }
261
+ }
262
+ return map;
263
+ }
264
+
265
+ /** @type {Map<string, string> | undefined} */
266
+ #paths;
267
+
268
+ /** The file a site path is served from, or `undefined`. @param {string} path */
269
+ resolve(path) {
270
+ if (this.paths === "lookup") {
271
+ const trimmed = path.replaceAll(/^\/+|\/+$/g, "");
272
+ const file = !trimmed
273
+ ? "index.html"
274
+ : path.endsWith("/") || this.read(`${trimmed}.html`) === undefined
275
+ ? `${trimmed}/index.html`
276
+ : `${trimmed}.html`;
277
+ return this.read(file) === undefined ? undefined : file;
278
+ }
279
+ this.#paths ??= this.#byPath;
280
+ return this.#paths.get(path);
281
+ }
282
+
283
+ /** @type {{ exists: boolean, entries: Entry[] } | undefined} */
284
+ #sitemap;
285
+
286
+ get sitemap() {
287
+ if (!this.#sitemap) {
288
+ const xml = this.read("sitemap.xml");
289
+ /** @param {string | undefined} text */
290
+ const trim = (text) => (this.profile.trimSitemap ? text?.trim() : text);
291
+ const entries = [...(xml ?? "").matchAll(/<url>([\s\S]*?)<\/url>/g)].map(([, body = ""]) => {
292
+ const raw = body.match(/<loc>([^<]*)<\/loc>/)?.[1];
293
+ let loc = trim(raw) ?? "";
294
+ let decodeError;
295
+ try {
296
+ loc = this.decode(loc);
297
+ } catch (error) {
298
+ decodeError = error instanceof Error ? error.message : String(error);
299
+ }
300
+ let url;
301
+ try {
302
+ url = loc ? new URL(loc) : undefined;
303
+ } catch {
304
+ url = undefined;
305
+ }
306
+ /** @type {Entry} */
307
+ const entry = {
308
+ loc,
309
+ lastmod: trim(body.match(/<lastmod>([^<]*)<\/lastmod>/)?.[1]),
310
+ url,
311
+ hasLoc: raw !== undefined && Boolean(loc),
312
+ };
313
+ if (decodeError !== undefined) {
314
+ entry.error = decodeError;
315
+ }
316
+ return entry;
317
+ });
318
+ this.#sitemap = { exists: xml !== undefined, entries };
319
+ }
320
+ return this.#sitemap;
321
+ }
322
+
323
+ /** The decoded `<loc>` values. */
324
+ get locs() {
325
+ return new Set(this.sitemap.entries.map((entry) => entry.loc));
326
+ }
327
+
328
+ /**
329
+ * A page read through the profile.
330
+ * @param {string} loc @param {string} path @param {string} file
331
+ */
332
+ page(loc, path, file) {
333
+ return new Page({
334
+ loc,
335
+ path,
336
+ file,
337
+ html: this.read(file) ?? "",
338
+ profile: this.profile,
339
+ decode: this.decode,
340
+ });
341
+ }
342
+
343
+ /** @type {HeaderRule[] | undefined} */
344
+ #headers;
345
+
346
+ /** The rules of `_headers`, each a pattern and its headers, with lower-case names. */
347
+ get headers() {
348
+ if (!this.#headers) {
349
+ const text = this.read("_headers") ?? "";
350
+ /** @type {HeaderRule[]} */
351
+ const rules = [];
352
+ if (this.profile.headersParser === "blocks") {
353
+ // A rule is everything from one unindented line to the next, trimmed. A `#` line is a
354
+ // rule of its own, and a line that still ends in `\r` doesn't read as a header.
355
+ for (const block of text.split(/\n(?=\S)/)) {
356
+ const [pattern = "", ...lines] = block.trim().split("\n");
357
+ rules.push({
358
+ pattern,
359
+ headers: lines.flatMap((line) => {
360
+ const [, name, value = ""] = line.match(/^\s+([^:]+):\s*(.*)$/) ?? [];
361
+ return name ? [/** @type {[string, string]} */ ([name.toLowerCase(), value])] : [];
362
+ }),
363
+ });
364
+ }
365
+ this.#headers = rules;
366
+ return rules;
367
+ }
368
+ for (const line of text.split("\n")) {
369
+ if (!line.trim() || line.trim().startsWith("#")) {
370
+ continue;
371
+ }
372
+ if (!/^\s/.test(line)) {
373
+ rules.push({ pattern: line.trim(), headers: [] });
374
+ continue;
375
+ }
376
+ const at = line.indexOf(":");
377
+ if (at > 0 && line.slice(0, at).trim()) {
378
+ rules
379
+ .at(-1)
380
+ ?.headers.push([line.slice(0, at).trim().toLowerCase(), line.slice(at + 1).trim()]);
381
+ }
382
+ }
383
+ this.#headers = rules;
384
+ }
385
+ return this.#headers;
386
+ }
387
+
388
+ /**
389
+ * The headers `_headers` gives a URL, as Cloudflare matches it: a rule's pattern is a path, or
390
+ * a URL with a host, where `*` matches anything and a `:placeholder` anything but `.` in a host
391
+ * or `/` in a path. A request gets the headers of every rule it matches.
392
+ * @param {string} url
393
+ * @returns {[name: string, value: string][]}
394
+ */
395
+ headersFor(url) {
396
+ let host, pathname;
397
+ try {
398
+ ({ host, pathname } = new URL(url, this.site));
399
+ } catch {
400
+ return [];
401
+ }
402
+ return this.headers.flatMap(({ pattern, headers }) => {
403
+ const match = cloudflarePattern(pattern).exec(
404
+ pattern.startsWith("https://") ? `${host}${pathname}` : pathname,
405
+ );
406
+ if (!match) {
407
+ return [];
408
+ }
409
+ /** @param {string} value */
410
+ const fill = (value) =>
411
+ value.replaceAll(
412
+ /:([A-Za-z]\w*)/g,
413
+ (placeholder, /** @type {string} */ name) => match.groups?.[name] ?? placeholder,
414
+ );
415
+ return headers.map(([name, value]) => /** @type {[string, string]} */ ([name, fill(value)]));
416
+ });
417
+ }
418
+
419
+ /** The sources of `_redirects` rules. */
420
+ get redirected() {
421
+ return new Set(
422
+ (this.read("_redirects") ?? "")
423
+ .split("\n")
424
+ .map((line) => line.trim().split(/\s+/)[0] ?? "")
425
+ .filter((source) => source && !source.startsWith("#")),
426
+ );
427
+ }
428
+
429
+ /**
430
+ * The first source that takes a page out of the index, or `undefined`.
431
+ * @param {readonly IndexSource[]} sources
432
+ * @param {{ file: string, path: string, host: string }} at
433
+ */
434
+ outOfIndex(sources, { file, path, host }) {
435
+ for (const source of sources) {
436
+ const found = this.#outBy(source, file, path, host);
437
+ if (found) {
438
+ return found;
439
+ }
440
+ }
441
+ return undefined;
442
+ }
443
+
444
+ /**
445
+ * @param {IndexSource} source @param {string} file @param {string} path @param {string} host
446
+ * @returns {string | undefined}
447
+ */
448
+ #outBy(source, file, path, host) {
449
+ switch (source.type) {
450
+ case "files":
451
+ return source.files.includes(file) ? `it's ${file}` : undefined;
452
+ case "under": {
453
+ const folder = source.paths.find((prefix) => file.startsWith(prefix));
454
+ return folder ? `it's under ${folder}` : undefined;
455
+ }
456
+ case "redirects":
457
+ return this.redirected.has(path) ? "_redirects sends it elsewhere" : undefined;
458
+ case "refresh": {
459
+ const page = this.page("", path, file);
460
+ return page
461
+ .documentTags("meta")
462
+ .some((tag) => tag["http-equiv"]?.toLowerCase() === "refresh")
463
+ ? "it's a meta refresh"
464
+ : undefined;
465
+ }
466
+ case "meta": {
467
+ const page = this.page("", path, file);
468
+ const test = valueTest(source.values, source.word, source.caseSensitive);
469
+ const scope = source.scope ?? this.profile.scope;
470
+ // With `property`, a tag is found as the profile finds any `<meta>`, by its `name` or its
471
+ // `property`. Without, by its `name` alone.
472
+ const contents = source.property
473
+ ? source.names.flatMap((name) => page.meta(name, scope))
474
+ : page
475
+ .tags("meta", scope)
476
+ .filter((meta) => {
477
+ const name = source.anyCaseNames ? meta.name?.toLowerCase() : meta.name;
478
+ return name !== undefined && source.names.includes(name);
479
+ })
480
+ .map((meta) => meta.content ?? "");
481
+ const hit = contents.find((content) => test(content));
482
+ return hit === undefined ? undefined : `a robots <meta> says "${hit}"`;
483
+ }
484
+ case "headers": {
485
+ const test = valueTest(source.values, source.word, false);
486
+ for (const { pattern, headers } of this.headers) {
487
+ // Host rules end in `/*` and would match every path, so `ignore` reads path rules alone.
488
+ if (source.hosts === "ignore" && !pattern.startsWith("/")) {
489
+ continue;
490
+ }
491
+ const target =
492
+ source.hosts === "match" && pattern.startsWith("https://") ? `${host}${path}` : path;
493
+ const regexp =
494
+ source.hosts === "drop" ? droppedHostPattern(pattern) : cloudflarePattern(pattern);
495
+ if (!regexp.test(target)) {
496
+ continue;
497
+ }
498
+ const values = headers
499
+ .filter(([name]) => name === "x-robots-tag")
500
+ .map(([, value]) => value);
501
+ // A parser that keeps one value per header name keeps the last.
502
+ const read = source.hosts === "drop" ? values.slice(-1) : values;
503
+ const tag = read.find((value) => test(value));
504
+ if (tag !== undefined) {
505
+ return `_headers ${pattern} sends X-Robots-Tag: ${tag}`;
506
+ }
507
+ }
508
+ return undefined;
509
+ }
510
+ }
511
+ return undefined;
512
+ }
486
513
  }
487
514
 
488
515
  /**
@@ -491,58 +518,64 @@ export class Site {
491
518
  * @param {boolean | undefined} caseSensitive
492
519
  */
493
520
  function valueTest(values = ["noindex"], word = false, caseSensitive = false) {
494
- const alternatives = values.map(escapeRegExp).join("|");
495
- const regexp = new RegExp(
496
- word ? `\\b(?:${alternatives})\\b` : alternatives,
497
- caseSensitive ? "" : "i",
498
- );
499
- return (/** @type {string} */ value) => regexp.test(value);
521
+ const alternatives = values.map(escapeRegExp).join("|");
522
+ const regexp = new RegExp(
523
+ word ? `\\b(?:${alternatives})\\b` : alternatives,
524
+ caseSensitive ? "" : "i",
525
+ );
526
+ return (/** @type {string} */ value) => regexp.test(value);
500
527
  }
501
528
 
502
529
  /** @type {Map<string, RegExp>} */
503
530
  const patterns = new Map();
504
531
 
532
+ /**
533
+ * One part of a `_headers` pattern as a regular expression: `*` is a named splat, and `:name` a
534
+ * named group that stops at any of the delimiters.
535
+ * @param {string} text
536
+ * @param {string} delimiters
537
+ */
538
+ const segment = (text, delimiters) =>
539
+ text
540
+ .split(/(\*|:[A-Za-z]\w*)/)
541
+ .map((part, index) =>
542
+ part === "*"
543
+ ? "(?<splat>.*)"
544
+ : index % 2
545
+ ? `(?<${part.slice(1)}>[^${delimiters}]+)`
546
+ : escapeRegExp(part),
547
+ )
548
+ .join("");
549
+
505
550
  /**
506
551
  * A `_headers` pattern as Cloudflare matches it: `https://host/path` against `host/path`, a path
507
552
  * against the path. `*` is a splat, and `:name` a placeholder that stops at `.` in a host or `/`.
508
553
  * @param {string} pattern
509
554
  */
510
555
  function cloudflarePattern(pattern) {
511
- let regexp = patterns.get(pattern);
512
- if (!regexp) {
513
- /** @param {string} text @param {string} delimiters */
514
- const segment = (text, delimiters) =>
515
- text
516
- .split(/(\*|:[A-Za-z]\w*)/)
517
- .map((part, index) =>
518
- part === "*"
519
- ? "(?<splat>.*)"
520
- : index % 2
521
- ? `(?<${part.slice(1)}>[^${delimiters}]+)`
522
- : escapeRegExp(part),
523
- )
524
- .join("");
525
- const [, host, path] = pattern.match(/^https:\/\/([^/]+)(\/.*)$/) ?? [];
526
- let source;
527
- try {
528
- source =
529
- host !== undefined && path !== undefined
530
- ? `^${segment(host, "./")}${segment(path, "/")}$`
531
- : `^${segment(pattern, "/")}$`;
532
- regexp = new RegExp(source);
533
- } catch {
534
- // Two placeholders with one name can't both be groups: match them without names.
535
- regexp = new RegExp(
536
- `^${pattern
537
- .replace(/^https:\/\//, "")
538
- .split(/(\*|:[A-Za-z]\w*)/)
539
- .map((part, index) => (part === "*" ? ".*" : index % 2 ? "[^/]+" : escapeRegExp(part)))
540
- .join("")}$`,
541
- );
542
- }
543
- patterns.set(pattern, regexp);
544
- }
545
- return regexp;
556
+ let regexp = patterns.get(pattern);
557
+ if (!regexp) {
558
+ const [, host, path] = pattern.match(/^https:\/\/([^/]+)(\/.*)$/) ?? [];
559
+ let source;
560
+ try {
561
+ source =
562
+ host !== undefined && path !== undefined
563
+ ? `^${segment(host, "./")}${segment(path, "/")}$`
564
+ : `^${segment(pattern, "/")}$`;
565
+ regexp = new RegExp(source);
566
+ } catch {
567
+ // Two placeholders with one name can't both be groups: match them without names.
568
+ regexp = new RegExp(
569
+ `^${pattern
570
+ .replace(/^https:\/\//, "")
571
+ .split(/(\*|:[A-Za-z]\w*)/)
572
+ .map((part, index) => (part === "*" ? ".*" : index % 2 ? "[^/]+" : escapeRegExp(part)))
573
+ .join("")}$`,
574
+ );
575
+ }
576
+ patterns.set(pattern, regexp);
577
+ }
578
+ return regexp;
546
579
  }
547
580
 
548
581
  /**
@@ -550,19 +583,19 @@ function cloudflarePattern(pattern) {
550
583
  * @param {string} pattern
551
584
  */
552
585
  function droppedHostPattern(pattern) {
553
- const source = pattern
554
- .replace(/^https?:\/\/[^/]+/, "")
555
- .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
556
- .replace(/\*/g, ".*")
557
- .replace(/:\w+/g, "[^/]+");
558
- return new RegExp(`^${source}$`);
586
+ const source = pattern
587
+ .replace(/^https?:\/\/[^/]+/, "")
588
+ .replaceAll(/[.+?^${}()|[\]\\]/g, String.raw`\$&`)
589
+ .replaceAll("*", ".*")
590
+ .replaceAll(/:\w+/g, "[^/]+");
591
+ return new RegExp(`^${source}$`);
559
592
  }
560
593
 
561
594
  /** Whether a path is a file, and not a folder or a link to nothing. @param {string} path */
562
595
  export function isFile(path) {
563
- try {
564
- return statSync(path).isFile();
565
- } catch {
566
- return false;
567
- }
596
+ try {
597
+ return statSync(path).isFile();
598
+ } catch {
599
+ return false;
600
+ }
568
601
  }