@v-office/site-checks 0.4.2 → 0.5.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.
@@ -5,7 +5,7 @@ import { brotliCompressSync, constants } from "node:zlib";
5
5
  import os from "node:os";
6
6
  import { spawn } from "node:child_process";
7
7
  import { parseArgs } from "node:util";
8
- //#region src/jsComments.ts
8
+ // src/jsComments.ts
9
9
  /** One pass over JavaScript (or the script parts of a component): its comments, and the code with
10
10
  * them blanked. String and template literals are kept whole, so `//` in `"https://…"` or `/*` in
11
11
  * `'a /* b'` is no comment; `${…}` inside a template is code again, to its matching `}`. `'…'` and
@@ -55,60 +55,121 @@ const regexEnd = (text, start) => {
55
55
  }
56
56
  return start + 1;
57
57
  };
58
- /** Every comment in the text, in order, with its position. Everything else is code, as written. */
59
- const findComments = (text) => {
58
+ /** A tag's head: `<` and its name with any type arguments (`<Panel<string>`, `<Table<Row<Id>>`), or
59
+ * the `<` of a fragment `<>`. Consumed whole, so a type argument's `>` does not end the tag. */
60
+ const TAG_HEAD = /^<(?:(?=>)|[A-Za-z][\w.:-]*(?:<(?:[^<>]|<[^<>]*>)*>)?(?=[\s/>]))/;
61
+ /** A generic in a `.tsx` file (`<T,>`, `<T extends X>`): code, never a tag. */
62
+ const GENERIC = /^<[A-Za-z][\w.]*\s*(?:,|extends\b)/;
63
+ /** The length of the tag head at `at`, or 0 where none starts. */
64
+ const tagHead = (text, at) => {
65
+ const ahead = text.slice(at, at + 200);
66
+ return GENERIC.test(ahead) ? 0 : TAG_HEAD.exec(ahead)?.[0].length ?? 0;
67
+ };
68
+ /** Every comment in the text, in order, with its position. Everything else is code, as written.
69
+ * With `jsx`, JSX is followed as the TSX parser does: an element's children are text across any
70
+ * number of lines (`https://…` in them is no comment), its `{…}` are code, and an attribute's
71
+ * quoted value is a string. */
72
+ const findComments = (text, { jsx = false } = {}) => {
60
73
  const comments = [];
61
74
  let i = 0;
62
75
  const n = text.length;
63
- const templates = [];
76
+ const frames = [];
64
77
  let depth = 0;
78
+ /** A comment starting at `i`: recorded, and its end returned; else -1. */
79
+ const comment = () => {
80
+ if (text[i] !== "/") return -1;
81
+ let end;
82
+ if (text[i + 1] === "/") {
83
+ LINE_END.lastIndex = i;
84
+ end = LINE_END.exec(text)?.index ?? n;
85
+ } else if (text[i + 1] === "*") {
86
+ const close = text.indexOf("*/", i + 2);
87
+ end = close === -1 ? n : close + 2;
88
+ } else return -1;
89
+ comments.push({
90
+ start: i,
91
+ end,
92
+ text: text.slice(i, end)
93
+ });
94
+ return end;
95
+ };
96
+ /** A `{` (or `${`) of the innermost frame: code until its matching `}`. */
97
+ const openCode = (frame, width) => {
98
+ frame.code = depth;
99
+ depth += 1;
100
+ i += width;
101
+ };
65
102
  while (i < n) {
66
103
  const c = text[i];
67
- if (templates.length > 0 && templates.at(-1) === -1) {
104
+ const frame = frames.at(-1);
105
+ if (frame?.code === -1 && frame.kind === "template") {
68
106
  if (c === "\\") i += 2;
69
107
  else if (c === "`") {
70
- templates.pop();
108
+ frames.pop();
71
109
  i += 1;
72
- } else if (c === "$" && text[i + 1] === "{") {
73
- templates[templates.length - 1] = depth;
74
- depth += 1;
110
+ } else if (c === "$" && text[i + 1] === "{") openCode(frame, 2);
111
+ else i += 1;
112
+ continue;
113
+ }
114
+ if (frame?.code === -1 && frame.kind === "children") {
115
+ if (c === "{") openCode(frame, 1);
116
+ else if (c === "<") {
117
+ const closing = text[i + 1] === "/";
118
+ frames.push({
119
+ kind: closing ? "closing" : "tag",
120
+ code: -1
121
+ });
122
+ i += closing ? 2 : Math.max(1, tagHead(text, i));
123
+ } else i += 1;
124
+ continue;
125
+ }
126
+ if (frame?.code === -1) {
127
+ const end = comment();
128
+ if (end !== -1) i = end;
129
+ else if (c === "\"" || c === "'") {
130
+ const close = text.indexOf(c, i + 1);
131
+ i = close === -1 ? n : close + 1;
132
+ } else if (c === "{") openCode(frame, 1);
133
+ else if (c === "/" && text[i + 1] === ">") {
134
+ frames.pop();
75
135
  i += 2;
136
+ } else if (c === ">") {
137
+ frames.pop();
138
+ if (frame.kind === "tag") frames.push({
139
+ kind: "children",
140
+ code: -1
141
+ });
142
+ else if (frames.at(-1)?.kind === "children") frames.pop();
143
+ i += 1;
76
144
  } else i += 1;
77
145
  continue;
78
146
  }
79
- if (c === "\\") i += 2;
80
- else if (c === "/" && text[i + 1] === "/") {
81
- LINE_END.lastIndex = i;
82
- const end = LINE_END.exec(text)?.index ?? n;
83
- comments.push({
84
- start: i,
85
- end,
86
- text: text.slice(i, end)
87
- });
88
- i = end;
89
- } else if (c === "/" && text[i + 1] === "*") {
90
- const close = text.indexOf("*/", i + 2);
91
- const end = close === -1 ? n : close + 2;
92
- comments.push({
93
- start: i,
94
- end,
95
- text: text.slice(i, end)
96
- });
97
- i = end;
98
- } else if (c === "/" && startsRegex(text, i, comments)) i = regexEnd(text, i);
147
+ const end = comment();
148
+ if (end !== -1) i = end;
149
+ else if (c === "\\") i += 2;
150
+ else if (c === "/" && startsRegex(text, i, comments)) i = regexEnd(text, i);
99
151
  else if (c === "'" || c === "\"") {
100
152
  let j = i + 1;
101
153
  while (j < n && text[j] !== c && text[j] !== "\n") j += text[j] === "\\" ? 2 : 1;
102
154
  if (j < n && text[j] === c) j += 1;
103
155
  i = j;
104
156
  } else if (c === "`") {
105
- templates.push(-1);
157
+ frames.push({
158
+ kind: "template",
159
+ code: -1
160
+ });
106
161
  i += 1;
162
+ } else if (jsx && c === "<" && tagHead(text, i) > 0 && startsRegex(text, i, comments)) {
163
+ frames.push({
164
+ kind: "tag",
165
+ code: -1
166
+ });
167
+ i += tagHead(text, i);
107
168
  } else {
108
169
  if (c === "{") depth += 1;
109
170
  else if (c === "}") {
110
171
  depth -= 1;
111
- if (templates.length > 0 && templates.at(-1) === depth) templates[templates.length - 1] = -1;
172
+ if (frame?.code === depth) frame.code = -1;
112
173
  }
113
174
  i += 1;
114
175
  }
@@ -117,19 +178,18 @@ const findComments = (text) => {
117
178
  };
118
179
  /** The text with its comments blanked: a line comment becomes a space, a block comment a space
119
180
  * and its newlines. */
120
- const stripComments = (text) => {
181
+ const stripComments = (text, options = {}) => {
121
182
  let out = "";
122
183
  let from = 0;
123
- for (const { start, end, text: comment } of findComments(text)) {
184
+ for (const { start, end, text: comment } of findComments(text, options)) {
124
185
  out += `${text.slice(from, start)} ${"\n".repeat((comment.match(/\n/g) ?? []).length)}`;
125
186
  from = end;
126
187
  }
127
188
  return out + text.slice(from);
128
189
  };
129
190
  /** Every comment in the text, as written. */
130
- const jsComments = (text) => findComments(text).map((c) => c.text);
131
- //#endregion
132
- //#region src/astroConfig.ts
191
+ const jsComments = (text, options = {}) => findComments(text, options).map((c) => c.text);
192
+ // src/astroConfig.ts
133
193
  /** The Astro config files, in the order Astro itself looks for them. */
134
194
  const CONFIG_FILES = [
135
195
  "astro.config.mjs",
@@ -205,8 +265,42 @@ const readAstroConfig = (root) => {
205
265
  layoutKey: LAYOUT_KEYS.find((key) => mentions(text, key) > 0)
206
266
  };
207
267
  };
208
- //#endregion
209
- //#region src/checks/consentGate.ts
268
+ // src/sourceComments.ts
269
+ /** Files of code only, read by the string-aware JavaScript lexer: no text runs between their
270
+ * tokens, so a `//` outside a string always opens a comment. */
271
+ const CODE = /* @__PURE__ */ new Set([
272
+ ".ts",
273
+ ".js",
274
+ ".mjs",
275
+ ".cjs",
276
+ ".mts",
277
+ ".cts"
278
+ ]);
279
+ /** Files where JSX markup runs as text between the code: there `//` is text („https://…",
280
+ * „Strand // mehr"), while a quoted attribute value (`accept="image/*"`) is a string. The lexer
281
+ * follows the elements (`stripComments(…, { jsx: true })`). */
282
+ const JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
283
+ const blank = (text) => text.replace(/[^\n]/g, " ");
284
+ const htmlComments$1 = (text) => text.replace(/<!--[\s\S]*?-->/g, blank);
285
+ const inScripts = (text) => text.replace(/(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi, (_, open, code, close) => open + stripComments(code) + close);
286
+ /** A source file with its comments blanked, line breaks kept so a line number still points at
287
+ * its line, and nothing of what renders blanked with them:
288
+ * - code (`.ts`, `.js`, …): every comment, strings kept whole;
289
+ * - JSX (`.tsx`, `.jsx`): every comment, strings and attribute values kept whole, never a `//`
290
+ * in the markup's text;
291
+ * - Astro: its frontmatter and `<script>` blocks as code, the `{/* … *\/}` and `<!-- … -->` of its
292
+ * markup;
293
+ * - HTML: its `<script>` blocks as code and its `<!-- … -->`; MDX and Markdown: `{/* … *\/}` and
294
+ * `<!-- … -->`. JSON and YAML hold none. */
295
+ const blankSourceComments = (raw, extension) => {
296
+ if (CODE.has(extension)) return stripComments(raw);
297
+ if (JSX.has(extension)) return stripComments(htmlComments$1(raw), { jsx: true });
298
+ if (extension === ".astro") return htmlComments$1(inScripts(raw.replace(/^---\r?\n[\s\S]*?\r?\n---/, (frontmatter) => stripComments(frontmatter))).replace(/\{\s*\/\*[\s\S]*?\*\/\s*\}/g, blank));
299
+ if (extension === ".html") return htmlComments$1(inScripts(raw));
300
+ if (extension === ".mdx" || extension === ".md") return htmlComments$1(raw.replace(/\{\s*\/\*[\s\S]*?\*\/\s*\}/g, blank));
301
+ return raw;
302
+ };
303
+ // src/checks/consentGate.ts
210
304
  /** The consent kit's files in a site: its presence under `src/lib/consent/` is what makes the
211
305
  * check apply; the vendors the site enables and the fleet registry's review of them. */
212
306
  const KIT_DIR = "src/lib/consent/";
@@ -222,6 +316,53 @@ const hostOf = (url) => {
222
316
  return;
223
317
  }
224
318
  };
319
+ const LEAK_FIX = "Frame it with ConsentEmbed, or register the vendor so the kit injects it after consent; list a consent-free host in consentAllowedHosts.";
320
+ /** The project's sources by their project-relative path, or `null` without the consent kit. */
321
+ const kitSources = (ctx) => {
322
+ const sources = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts", ".json"]));
323
+ const byRel = new Map(sources.map((file) => [ctx.rel(file), file]));
324
+ return [...byRel.keys()].some((rel) => rel.startsWith(KIT_DIR)) ? byRel : null;
325
+ };
326
+ /** Each vendor the site enables, against the fleet registry's review. What cannot be read is a
327
+ * finding, never a pass: a list the check cannot read, or a registry that does not parse, would
328
+ * otherwise approve every vendor in it. */
329
+ const vendorFindings = (ctx, byRel) => {
330
+ const enabledFile = byRel.get(ENABLED_FILE);
331
+ const registryFile = byRel.get(REGISTRY_FILE);
332
+ if (!enabledFile || !registryFile) return [];
333
+ const enabled = stripComments(ctx.readSource(enabledFile)).match(/ENABLED_VENDOR_IDS\b[^=]*=\s*\[([^\]]*)\]/)?.[1];
334
+ const rest = enabled?.replace(/(["'`])[^"'`]*\1/g, "").replace(/[\s,]/g, "");
335
+ if (enabled === void 0 || rest) return [{
336
+ path: ENABLED_FILE,
337
+ message: "ENABLED_VENDOR_IDS is not an array literal of quoted ids, so the enabled vendors could not be checked against the consent registry. Write it as ENABLED_VENDOR_IDS = [\"…\", …]."
338
+ }];
339
+ const ids = [...enabled.matchAll(/["'`]([^"'`]+)["'`]/g)].map((m) => m[1]);
340
+ let registry;
341
+ try {
342
+ registry = JSON.parse(ctx.readSource(registryFile));
343
+ } catch (err) {
344
+ return [{
345
+ path: REGISTRY_FILE,
346
+ message: `The consent registry snapshot is not valid JSON (${err.message}), so the enabled vendors could not be checked. Restore it from the registry.`
347
+ }];
348
+ }
349
+ const vendors = registry?.vendors;
350
+ if (!Array.isArray(vendors)) return [{
351
+ path: REGISTRY_FILE,
352
+ message: "The consent registry snapshot has no vendors array, so the enabled vendors could not be checked. Restore it from the registry."
353
+ }];
354
+ const status = new Map(vendors.map((v) => [v?.id, v?.reviewStatus]));
355
+ const findings = [];
356
+ for (const id of ids) if (!status.has(id)) findings.push({
357
+ path: ENABLED_FILE,
358
+ message: `The enabled vendor "${id}" is not in the consent registry.`
359
+ });
360
+ else if (status.get(id) !== "approved") findings.push({
361
+ path: ENABLED_FILE,
362
+ message: `The enabled vendor "${id}" is "${String(status.get(id))}" in the consent registry, not approved.`
363
+ });
364
+ return findings;
365
+ };
225
366
  /** No third-party script or iframe loads outside the consent layer (the kit injects a vendor's
226
367
  * script after consent, so one in the HTML loads before it), and no vendor the site enables is
227
368
  * still unapproved in the fleet's consent registry. Skipped in a project without the kit. The
@@ -233,9 +374,8 @@ const consentGate = {
233
374
  severity: "error",
234
375
  stage: "dist",
235
376
  begin: (ctx) => {
236
- const sources = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts", ".json"]));
237
- const byRel = new Map(sources.map((file) => [ctx.rel(file), file]));
238
- if (![...byRel.keys()].some((rel) => rel.startsWith(KIT_DIR))) return null;
377
+ const byRel = kitSources(ctx);
378
+ if (!byRel) return null;
239
379
  const siteHost = ctx.config.site ? hostOf(ctx.config.site) : void 0;
240
380
  const allowed = new Set(ctx.options.consentAllowedHosts);
241
381
  const findings = [];
@@ -251,34 +391,70 @@ const consentGate = {
251
391
  if (el.closest(EMBED_TEMPLATE)) continue;
252
392
  findings.push({
253
393
  path: page.path,
254
- message: `A third-party <${el.tagName.toLowerCase()}> from ${host} loads before consent. Frame it with ConsentEmbed, or register the vendor so the kit injects it after consent; list a consent-free host in consentAllowedHosts.`
394
+ message: `A third-party <${el.tagName.toLowerCase()}> from ${host} loads before consent. ${LEAK_FIX}`
255
395
  });
256
396
  }
257
397
  },
258
- finish: () => {
259
- const enabledFile = byRel.get(ENABLED_FILE);
260
- const registryFile = byRel.get(REGISTRY_FILE);
261
- if (!enabledFile || !registryFile) return findings;
262
- const enabled = ctx.readSource(enabledFile).match(/ENABLED_VENDOR_IDS\b[^=]*=\s*\[([^\]]*)\]/);
263
- if (!enabled) return findings;
264
- const ids = [...enabled[1].matchAll(/["'`]([^"'`]+)["'`]/g)].map((m) => m[1]);
265
- const registry = JSON.parse(ctx.readSource(registryFile));
266
- const status = new Map((registry.vendors ?? []).map((v) => [v.id, v.reviewStatus]));
267
- for (const id of ids) if (!status.has(id)) findings.push({
268
- path: ENABLED_FILE,
269
- message: `The enabled vendor "${id}" is not in the consent registry.`
270
- });
271
- else if (status.get(id) !== "approved") findings.push({
272
- path: ENABLED_FILE,
273
- message: `The enabled vendor "${id}" is "${status.get(id)}" in the consent registry, not approved.`
274
- });
275
- return findings;
276
- }
398
+ finish: () => [...findings, ...vendorFindings(ctx, byRel)]
277
399
  };
278
400
  }
279
401
  };
280
- //#endregion
281
- //#region src/context.ts
402
+ /** The site's own markup, where an island rendered only in the browser (`client:only`) writes the
403
+ * tags the built HTML never shows. */
404
+ const MARKUP = /* @__PURE__ */ new Set([
405
+ ".astro",
406
+ ".tsx",
407
+ ".jsx",
408
+ ".html",
409
+ ".mdx"
410
+ ]);
411
+ /** The consent layer: the kit's components (ConsentEmbed's template frame, the gated loaders) and
412
+ * its library inject vendors after consent. */
413
+ const CONSENT_LAYER = ["src/components/consent/", KIT_DIR];
414
+ /** ConsentEmbed's click-to-load frame written out in a page: loaded after consent. */
415
+ const EMBED_TEMPLATE_SOURCE = /<template\b[^>]*\bdata-embed-content\b[^>]*>[\s\S]*?<\/template\s*>/gi;
416
+ /** A `<script>` or `<iframe>` whose `src` is an absolute or protocol-relative URL: quoted, or a
417
+ * string in a JSX expression. The tag may span lines. */
418
+ const VENDOR_TAG = /<(script|iframe)\b[^>]*?\ssrc\s*=\s*\{?\s*(["'`])\s*((?:https?:)?\/\/[^"'`\s>]+)/gi;
419
+ /** No third-party `<script src>` or `<iframe src>` in the site's own markup outside the consent
420
+ * layer: the dist stage sees only what the built HTML holds, and a component rendered in the
421
+ * browser (a `client:only` island, a video player in TSX) loads its vendor all the same. A tag in
422
+ * a comment renders nothing and is not read. The site's own host and `consentAllowedHosts` are
423
+ * allowed. Skipped without the kit, and without a known site host (a computed `site`, no
424
+ * `--site`): the site's own absolute URLs would read as third-party, as the dist half waits too. */
425
+ const consentGateSource = {
426
+ id: "consent-gate-source",
427
+ title: "Third-party resources in the site's markup wait for consent",
428
+ severity: "error",
429
+ stage: "src",
430
+ begin: (ctx) => {
431
+ const siteHost = ctx.config.site ? hostOf(ctx.config.site) : void 0;
432
+ if (!kitSources(ctx) || !siteHost) return null;
433
+ const allowed = new Set(ctx.options.consentAllowedHosts);
434
+ return { finish: () => {
435
+ const findings = [];
436
+ for (const file of ctx.sourceFiles(MARKUP)) {
437
+ const rel = ctx.rel(file);
438
+ if (CONSENT_LAYER.some((dir) => rel.startsWith(dir))) continue;
439
+ const blank = (block) => block.replace(/[^\n]/g, " ");
440
+ const text = blankSourceComments(ctx.readSource(file), path.extname(file).toLowerCase()).replace(EMBED_TEMPLATE_SOURCE, blank);
441
+ for (const match of text.matchAll(VENDOR_TAG)) {
442
+ const url = match[3];
443
+ const absolute = url.startsWith("//") ? `https:${url}` : url;
444
+ const host = hostOf(absolute) ?? absolute.replace(/^https?:\/\//i, "").split("/")[0];
445
+ if (host === siteHost || allowed.has(host)) continue;
446
+ const line = text.slice(0, match.index).split("\n").length;
447
+ findings.push({
448
+ path: rel,
449
+ message: `A third-party <${match[1].toLowerCase()}> from ${host} (line ${line}) loads before consent. ${LEAK_FIX}`
450
+ });
451
+ }
452
+ }
453
+ return findings;
454
+ } };
455
+ }
456
+ };
457
+ // src/context.ts
282
458
  const SKIPPED_TEXT_TAGS = /* @__PURE__ */ new Set([
283
459
  "SCRIPT",
284
460
  "STYLE",
@@ -289,13 +465,15 @@ const collectFiles = (dir, base = dir) => fs.readdirSync(dir, { withFileTypes: t
289
465
  const full = path.join(dir, entry.name);
290
466
  return entry.isDirectory() ? collectFiles(full, base) : [path.relative(base, full).split(path.sep).join("/")];
291
467
  });
468
+ /** The files under `dir`, `node_modules` left out: those with one of the extensions, or every
469
+ * file without any. */
292
470
  function* filesUnder(dir, extensions) {
293
471
  if (!fs.existsSync(dir)) return;
294
472
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
295
473
  const full = path.join(dir, entry.name);
296
474
  if (entry.isDirectory()) {
297
475
  if (entry.name !== "node_modules") yield* filesUnder(full, extensions);
298
- } else if (extensions.has(path.extname(entry.name).toLowerCase())) yield full;
476
+ } else if (!extensions || extensions.has(path.extname(entry.name).toLowerCase())) yield full;
299
477
  }
300
478
  }
301
479
  /** `about-us/index.html` → `/about-us/`, `imprint.html` → `/imprint`, `index.html` → `/`. */
@@ -434,12 +612,23 @@ const readPage = (ctx, file) => {
434
612
  comments: () => {
435
613
  if (comments === void 0) {
436
614
  comments = [];
437
- if (root) commentsOf(root, comments);
615
+ commentsOf(document, comments);
438
616
  }
439
617
  return comments;
440
618
  }
441
619
  };
442
620
  };
621
+ /** A status page (`/404`, `/500`, or one under a locale prefix, `/en/404/`): served for an error,
622
+ * never a page a search engine should list. */
623
+ const STATUS_PAGE = /(?:^|\/)(?:404|500)\/?$/;
624
+ /** A page a search engine may index and someone reads: not noindex, not a redirect stub, not a
625
+ * status page. The launch signal of every check that waits for the launch: before it, the
626
+ * preview's blanket robots meta makes every page noindex, while the 404 page often has none. */
627
+ const isIndexable = (page) => !page.redirect && !page.noindex && !STATUS_PAGE.test(page.url);
628
+ /** A rental's page: the rental blocks' fact row (`data-rental-stats`), or a site's own chip row
629
+ * (`data-rental-facts`) beside the owner's description. A listing's cards carry chip rows too, but
630
+ * no description, so they never make the listing a rental page. */
631
+ const isRentalPage = (document) => !!document.querySelector("[data-rental-stats]") || !!document.querySelector("[data-rental-facts]") && !!document.querySelector("[data-rental-description]");
443
632
  /** Elements that start a new line of text: their text never runs into the text beside them. */
444
633
  const BLOCK_TAGS = new Set("ADDRESS ARTICLE ASIDE BLOCKQUOTE BR DD DETAILS DIV DL DT FIGCAPTION FIGURE FOOTER H1 H2 H3 H4 H5 H6 HEADER HR LI MAIN NAV OL P PRE SECTION SUMMARY TABLE TD TH TR UL".split(" "));
445
634
  /** An element's readable text, whitespace collapsed: a space at every block boundary, so
@@ -506,8 +695,7 @@ const xmlText = (text) => text.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(amp|lt|gt|quot
506
695
  apos: "'"
507
696
  }[name.toLowerCase()] ?? entity;
508
697
  });
509
- //#endregion
510
- //#region src/exclude.ts
698
+ // src/exclude.ts
511
699
  const LOCALE = /^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i;
512
700
  /** The `:line` (and `:column`) a source finding's path ends with. */
513
701
  const LINE = /:\d+(?::\d+)?$/;
@@ -545,15 +733,14 @@ const assertKnownChecks = (exclude, ids) => {
545
733
  const unknown = Object.keys(exclude).filter((id) => !known.has(id));
546
734
  if (unknown.length > 0) throw new Error(`[site-checks] "exclude" names ${unknown.length === 1 ? "an unknown check" : "unknown checks"}: ${unknown.join(", ")}`);
547
735
  };
548
- //#endregion
549
- //#region src/checks/copy.ts
736
+ // src/checks/copy.ts
550
737
  /** Pages the copy checks read: not a redirect stub, not the 404 page, not an excluded path. An
551
738
  * entry covers the path and everything below it, with or without a locale prefix: `/impressum`
552
739
  * also covers `/de/impressum`. */
553
740
  const excluded = (page, paths) => page.redirect || page.path === "404.html" || paths.some((entry) => coversUrl(entry, page.url));
554
- const excerpt$2 = (text, max = 90) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
741
+ const excerpt$3 = (text, max = 90) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
555
742
  /** Quotes and whitespace removed, lower-cased: two renderings of one sentence compare equal. */
556
- const normalize$3 = (text) => text.toLowerCase().replace(/[„“”"‚’'«»]/g, "").replace(/\s+/g, " ").trim();
743
+ const normalize$2 = (text) => text.toLowerCase().replace(/[„“”"‚’'«»]/g, "").replace(/\s+/g, " ").trim();
557
744
  const SKIPPED = /* @__PURE__ */ new Set([
558
745
  "SCRIPT",
559
746
  "STYLE",
@@ -612,19 +799,20 @@ const sentencesOf = (blocks) => blocks.flatMap((block) => {
612
799
  const MIN_SENTENCE = 25;
613
800
  /** Wordings a recorded customer correction bans, found in the rendered text of a page. A warning:
614
801
  * the rendered text includes the feed's descriptions, and an owner's new wording must not stop the
615
- * nightly builds. */
802
+ * nightly builds. A ban scoped `"in": "src"` is the site's own text only: `banned-copy-src` reads
803
+ * it in `src/`, this check never. */
616
804
  const bannedCopy = {
617
805
  id: "banned-copy",
618
806
  title: "Wordings banned by a recorded correction",
619
807
  severity: "warning",
620
808
  stage: "dist",
621
809
  begin: (ctx) => {
622
- if (!ctx.hasDist || ctx.options.bannedCopy.length === 0) return null;
623
- const skip = [...ctx.options.copyExcludePaths, ...ctx.options.bannedCopyExcludePaths];
624
- const bans = ctx.options.bannedCopy.map((ban) => ({
810
+ const bans = ctx.options.bannedCopy.filter((ban) => ban.in !== "src").map((ban) => ({
625
811
  ...ban,
626
812
  re: new RegExp(ban.pattern, "g")
627
813
  }));
814
+ if (!ctx.hasDist || bans.length === 0) return null;
815
+ const skip = [...ctx.options.copyExcludePaths, ...ctx.options.bannedCopyExcludePaths];
628
816
  const findings = [];
629
817
  return {
630
818
  visit: (page) => {
@@ -632,7 +820,7 @@ const bannedCopy = {
632
820
  const text = blockText(page.document.body);
633
821
  for (const ban of bans) for (const match of text.matchAll(ban.re)) if (match[0]) findings.push({
634
822
  path: page.path,
635
- message: `"${excerpt$2(match[0], 70)}" is a banned wording: ${ban.why}`
823
+ message: `"${excerpt$3(match[0], 70)}" is a banned wording: ${ban.why}`
636
824
  });
637
825
  },
638
826
  finish: () => findings
@@ -641,8 +829,9 @@ const bannedCopy = {
641
829
  };
642
830
  /** The same sentence rendered twice on one page: a copy accident a reader sees at once. Within one
643
831
  * page only; across pages a shared section and an accident look the same. Waits while every page
644
- * is noindex (a site before launch repeats placeholder copy by design). A warning: the feed's
645
- * descriptions are on the page too. */
832
+ * is noindex (a site before launch repeats placeholder copy by design); the 404 page, which often
833
+ * carries no robots meta on a preview, does not wake it. A warning: the feed's descriptions are on
834
+ * the page too. */
646
835
  const duplicateSentences = {
647
836
  id: "duplicate-sentences",
648
837
  title: "A sentence printed twice on one page",
@@ -650,22 +839,22 @@ const duplicateSentences = {
650
839
  stage: "dist",
651
840
  begin: (ctx) => {
652
841
  if (!ctx.hasDist) return null;
653
- const allowed = new Set(ctx.options.allowDuplicateSentences.map(normalize$3));
842
+ const allowed = new Set(ctx.options.allowDuplicateSentences.map(normalize$2));
654
843
  const findings = [];
655
844
  let indexable = 0;
656
845
  return {
657
846
  visit: (page) => {
658
- if (!page.redirect && !page.noindex) indexable += 1;
847
+ if (isIndexable(page)) indexable += 1;
659
848
  if (excluded(page, ctx.options.copyExcludePaths)) return;
660
849
  const seen = /* @__PURE__ */ new Map();
661
850
  for (const sentence of sentencesOf(proseBlocks(page))) {
662
851
  if (sentence.length < MIN_SENTENCE) continue;
663
- const key = normalize$3(sentence);
852
+ const key = normalize$2(sentence);
664
853
  const count = (seen.get(key) ?? 0) + 1;
665
854
  seen.set(key, count);
666
855
  if (count === 2 && !allowed.has(key)) findings.push({
667
856
  path: page.path,
668
- message: `The same sentence is rendered twice on the page: "${excerpt$2(sentence)}"`
857
+ message: `The same sentence is rendered twice on the page: "${excerpt$3(sentence)}"`
669
858
  });
670
859
  }
671
860
  },
@@ -693,7 +882,8 @@ const readSources = (root, rel) => {
693
882
  /** Every `<blockquote>` quotes, word for word, a source the site recorded (`quoteSources`): a quote
694
883
  * matching none was paraphrased or made up. The attribution (`cite`, `footer`, `figcaption`) is
695
884
  * not part of the quote. A configured source that is missing is a finding, not a skip: the step
696
- * that writes it stopped and the check would verify nothing. */
885
+ * that writes it stopped and the check would verify nothing. With no source there at all, that is
886
+ * the finding: every quote reported besides would say the same thing once per quote. */
697
887
  const quoteSources = {
698
888
  id: "quote-sources",
699
889
  title: "Quotes match their sources",
@@ -703,26 +893,30 @@ const quoteSources = {
703
893
  if (!ctx.hasDist || ctx.options.quoteSources.length === 0) return null;
704
894
  const findings = [];
705
895
  const corpusParts = [];
896
+ let missing = 0;
706
897
  for (const rel of ctx.options.quoteSources) {
707
898
  const parts = readSources(ctx.root, rel);
708
- if (parts === null) findings.push({
709
- path: rel,
710
- message: `The quote source ${rel} is missing: the step that writes it did not run, so no quote was verified against it.`
711
- });
712
- else corpusParts.push(...parts);
899
+ if (parts === null) {
900
+ missing += 1;
901
+ findings.push({
902
+ path: rel,
903
+ message: `The quote source ${rel} is missing: the step that writes it did not run, so no quote was verified against it.`
904
+ });
905
+ } else corpusParts.push(...parts);
713
906
  }
714
- const corpus = normalize$3(corpusParts.join(" "));
907
+ const corpus = normalize$2(corpusParts.join(" "));
715
908
  const where = ctx.options.quoteSources.join(", ");
909
+ const allMissing = missing === ctx.options.quoteSources.length;
716
910
  return {
717
911
  visit: (page) => {
718
- if (excluded(page, ctx.options.copyExcludePaths)) return;
912
+ if (allMissing || excluded(page, ctx.options.copyExcludePaths)) return;
719
913
  for (const quote of page.document.querySelectorAll("blockquote")) {
720
914
  const copy = quote.cloneNode(true);
721
915
  for (const attribution of copy.querySelectorAll("cite, footer, figcaption")) attribution.remove();
722
916
  const text = blockText(copy);
723
- if (text.length >= MIN_QUOTE && !corpus.includes(normalize$3(text))) findings.push({
917
+ if (text.length >= MIN_QUOTE && !corpus.includes(normalize$2(text))) findings.push({
724
918
  path: page.path,
725
- message: `A <blockquote> is not word for word in ${where}: "${excerpt$2(text)}"`
919
+ message: `A <blockquote> is not word for word in ${where}: "${excerpt$3(text)}"`
726
920
  });
727
921
  }
728
922
  },
@@ -730,11 +924,11 @@ const quoteSources = {
730
924
  };
731
925
  }
732
926
  };
733
- //#endregion
734
- //#region src/checks/donorTerms.ts
927
+ // src/checks/donorTerms.ts
735
928
  /** More than this and the point is made; the runner keeps 25 anyway. */
736
929
  const MAX_RAW_FINDINGS = 100;
737
- const normalize$2 = (text) => text.normalize("NFC").toLowerCase().replace(/\s+/g, " ");
930
+ const collapse$2 = (text) => text.normalize("NFC").replace(/\s+/g, " ");
931
+ const normalize$1 = (text) => collapse$2(text).toLowerCase();
738
932
  const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
739
933
  const WORD = /[\p{L}\p{N}]/u;
740
934
  /** A term as a whole word: where it starts or ends with a letter or digit, the text next to it must
@@ -745,49 +939,72 @@ const wholeWord = (term) => {
745
939
  const chars = [...term];
746
940
  return new RegExp(`${WORD.test(chars[0]) ? "(?<![\\p{L}\\p{N}])" : ""}${escape(term)}${WORD.test(chars.at(-1)) ? "(?![\\p{L}\\p{N}])" : ""}`, "u");
747
941
  };
748
- const excerpt$1 = (haystack, at, length) => {
942
+ const excerpt$2 = (haystack, at, length) => {
749
943
  const start = Math.max(0, at - 30);
750
944
  const end = Math.min(haystack.length, at + length + 30);
751
945
  return `${start > 0 ? "…" : ""}${haystack.slice(start, end)}${end < haystack.length ? "…" : ""}`;
752
946
  };
947
+ const matchersOf = (options) => [...new Set(options.donorTerms.map(normalize$1).map((t) => t.trim()).filter(Boolean))].map((term) => ({
948
+ label: `donor term "${term}"`,
949
+ caseless: true,
950
+ re: wholeWord(term)
951
+ })).concat([...new Set(options.donorPatterns)].map((pattern) => ({
952
+ label: `donor pattern /${pattern}/`,
953
+ caseless: false,
954
+ re: new RegExp(pattern, "u")
955
+ })));
956
+ /** The findings of one check and the scan that fills them: one finding per matcher and place, from
957
+ * the first of the texts that contains it. Returns the labels it found, so a later scan of the
958
+ * same place can leave them out. */
959
+ const finder = (ctx, id, matchers) => {
960
+ const exclusions = ctx.options.exclude[id];
961
+ const excluded = Array.isArray(exclusions) ? exclusions : [];
962
+ const findings = [];
963
+ const scan = (texts, at, where, skip) => {
964
+ const found = /* @__PURE__ */ new Set();
965
+ let lower;
966
+ let cased;
967
+ for (const { label, caseless, re } of matchers) {
968
+ if (findings.length >= MAX_RAW_FINDINGS) break;
969
+ if (skip?.has(label)) continue;
970
+ const haystacks = caseless ? lower ??= texts.map(normalize$1) : cased ??= texts.map(collapse$2);
971
+ for (const haystack of haystacks) {
972
+ const match = re.exec(haystack);
973
+ if (!match) continue;
974
+ found.add(label);
975
+ const finding = {
976
+ path: at,
977
+ message: `${label} in ${where}: "${excerpt$2(haystack, match.index, match[0].length)}"`
978
+ };
979
+ if (!isExcluded(excluded, finding)) findings.push(finding);
980
+ break;
981
+ }
982
+ }
983
+ return found;
984
+ };
985
+ return {
986
+ findings,
987
+ scan
988
+ };
989
+ };
753
990
  /** Every site starts from a template ("donor") site, and nothing of it may ship: its brand, people,
754
- * places, phone, email, domain, asset names. The site lists the terms in `site-checks.config.json`
755
- * (`donorTerms`); without them the check skips, which the report shows. A term matches as a whole
756
- * word, case-insensitively with whitespace collapsed. Matched in the visible
757
- * text, the title, the inline scripts and styles (JSON-LD shows in search results) and the
758
- * attributes of every built page, in the built file names and in the shipped JS and CSS, where an
759
- * island's copy lives. */
991
+ * places, phone, email, domain, asset names. The site lists them in `site-checks.config.json`:
992
+ * `donorTerms` match as whole words, case-insensitively with whitespace collapsed;
993
+ * `donorPatterns` are regular expressions matched as written. Without either the check skips,
994
+ * which the report shows. Matched in the visible text, the title, the inline scripts and styles
995
+ * (JSON-LD shows in search results) and the attributes of every built page, in the built file
996
+ * names and in the shipped JS and CSS, where an island's copy lives. A warning: the built pages
997
+ * carry the PMS feed's text, which may name a place the template site named too. The site's own
998
+ * source is `donor-terms-source`, an error. */
760
999
  const donorTerms = {
761
1000
  id: "donor-terms",
762
1001
  title: "Terms of the template site in the built output",
763
- severity: "error",
1002
+ severity: "warning",
764
1003
  stage: "dist",
765
1004
  begin: (ctx) => {
766
- const terms = [...new Set(ctx.options.donorTerms.map(normalize$2).map((t) => t.trim()).filter(Boolean))].map((term) => ({
767
- term,
768
- re: wholeWord(term)
769
- }));
770
- if (terms.length === 0 || !ctx.hasDist) return null;
771
- const exclusions = ctx.options.exclude["donor-terms"];
772
- const excluded = Array.isArray(exclusions) ? exclusions : [];
773
- const findings = [];
774
- /** One finding per term and place: the first text of `texts` that contains it. */
775
- const scan = (texts, path, where) => {
776
- const haystacks = texts.map(normalize$2);
777
- for (const { term, re } of terms) {
778
- if (findings.length >= MAX_RAW_FINDINGS) return;
779
- for (const haystack of haystacks) {
780
- const match = re.exec(haystack);
781
- if (!match) continue;
782
- const finding = {
783
- path,
784
- message: `donor term "${term}" in ${where}: "${excerpt$1(haystack, match.index, term.length)}"`
785
- };
786
- if (!isExcluded(excluded, finding)) findings.push(finding);
787
- break;
788
- }
789
- }
790
- };
1005
+ const matchers = matchersOf(ctx.options);
1006
+ if (matchers.length === 0 || !ctx.hasDist) return null;
1007
+ const { findings, scan } = finder(ctx, "donor-terms", matchers);
791
1008
  return {
792
1009
  visit: (page) => {
793
1010
  scan([blockText(page.document.body ?? page.document.documentElement)], page.path, "the visible text");
@@ -804,19 +1021,82 @@ const donorTerms = {
804
1021
  };
805
1022
  }
806
1023
  };
807
- //#endregion
808
- //#region src/checks/htmlComments.ts
1024
+ /** The text files of `src/` read whole: code, styles, content, data. */
1025
+ const SOURCE_TEXT = new Set(".astro .ts .tsx .mts .cts .js .jsx .mjs .cjs .vue .svelte .css .scss .sass .less .md .mdx .markdoc .json .yaml .yml .toml .html .svg .txt .xml .webmanifest".split(" "));
1026
+ /** The files of `public/` the site writes as text (`llms.txt`, a manifest, data, an SVG): its code
1027
+ * and styles there are libraries it ships as they come, not the site's to word. */
1028
+ const PUBLIC_TEXT = new Set(".txt .json .webmanifest .xml .svg .html .md".split(" "));
1029
+ /** Where a line can open a comment that wraps onto the next. */
1030
+ const COMMENTED = new Set(".astro .ts .tsx .mts .cts .js .jsx .mjs .cjs .vue .svelte .css .scss .sass .less".split(" "));
1031
+ /** A line whose first characters open or continue a comment: `//`, `/*`, `{/*`, ` * `. */
1032
+ const COMMENT_LINE = /^\s*(?:\/\/|\/\*|\{\/\*|\*)/;
1033
+ /** A comment line's prose: the closer first, so a lone ` *\/` does not leave a `/` behind. */
1034
+ const commentText = (line) => line.trim().replace(/\*\/\}?\s*$/, "").replace(/^(?:\{\/\*+|\/\*+|\/\/+|\*+)/, "").trim();
1035
+ /** Each pair of adjacent comment lines joined both ways a wrap can cut a term: with a space (a
1036
+ * term wrapped at its space) and without (a domain wrapped mid-token). A line that holds no prose
1037
+ * (a JSDoc blank line) ends the pair. The tight join can invent a word nobody wrote; a finding
1038
+ * says where, so that stays inspectable. */
1039
+ const commentSeams = (text) => {
1040
+ const seams = [];
1041
+ let previous;
1042
+ for (const line of text.split(/\r?\n/)) {
1043
+ const prose = COMMENT_LINE.test(line) ? commentText(line) : "";
1044
+ if (prose && previous) seams.push(`${previous} ${prose}`, `${previous}${prose}`);
1045
+ previous = prose || void 0;
1046
+ }
1047
+ return seams;
1048
+ };
1049
+ /** Every file under `dir`, at any depth, `node_modules` left out. */
1050
+ const allFiles = (dir) => fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
1051
+ const full = path.join(dir, entry.name);
1052
+ if (entry.isDirectory()) return entry.name === "node_modules" ? [] : allFiles(full);
1053
+ return entry.isFile() ? [full] : [];
1054
+ }) : [];
1055
+ /** The donor's terms and patterns in what the site itself writes, before the build: every text file
1056
+ * under `src/` (code, comments, content, data) and the text and data files of `public/` (`llms.txt`,
1057
+ * a manifest, an SVG; not the scripts and styles it ships as they come), the Astro config and
1058
+ * `package.json`, with a term rejoined where a comment wraps it over two lines; and the
1059
+ * names of the files under `src/` and `public/` (a donor's logo left behind). An error: no PMS
1060
+ * data is in these files. The blueprint process docs (CUSTOMER.md, DESIGN.md, …) are not read. */
1061
+ const donorTermsSource = {
1062
+ id: "donor-terms-source",
1063
+ title: "Terms of the template site in the site's own source",
1064
+ severity: "error",
1065
+ stage: "src",
1066
+ begin: (ctx) => {
1067
+ const matchers = matchersOf(ctx.options);
1068
+ if (matchers.length === 0) return null;
1069
+ const { findings, scan } = finder(ctx, "donor-terms-source", matchers);
1070
+ return { finish: () => {
1071
+ const texts = [
1072
+ ...ctx.sourceFiles(SOURCE_TEXT),
1073
+ ...[...CONFIG_FILES, "package.json"].map((name) => path.join(ctx.root, name)),
1074
+ ...filesUnder(ctx.publicDir, PUBLIC_TEXT)
1075
+ ].filter((file) => fs.existsSync(file));
1076
+ for (const file of texts) {
1077
+ const text = ctx.readSource(file);
1078
+ const at = ctx.rel(file);
1079
+ const found = scan([text], at, "the source");
1080
+ if (COMMENTED.has(path.extname(file).toLowerCase())) scan(commentSeams(text), at, "a comment wrapped over two lines", found);
1081
+ }
1082
+ for (const file of [...allFiles(ctx.srcDir), ...allFiles(ctx.publicDir)].sort()) {
1083
+ const at = ctx.rel(file);
1084
+ scan([at], at, "a file name");
1085
+ }
1086
+ return findings;
1087
+ } };
1088
+ }
1089
+ };
1090
+ // src/checks/htmlComments.ts
1091
+ /** Files that hold no text: an image or font can carry the bytes `<!--` by chance, and reading
1092
+ * every photo under `src/assets/` costs time for nothing. */
1093
+ const BINARY_EXTENSIONS = new Set(".png .jpg .jpeg .gif .webp .avif .ico .bmp .tif .tiff .woff .woff2 .ttf .otf .eot .mp4 .webm .mov .mp3 .pdf .zip".split(" "));
1094
+ const MESSAGE = "An HTML comment ships to the built page, readable with View Source. Use {/* … */} in .astro and JSX markup, // in frontmatter and scripts, and remove it from Markdown; a note in a string the page renders (set:html) goes beside the code, outside the string.";
809
1095
  /** Astro passes an HTML comment in a template straight into the built page, where a visitor reads
810
- * it with View Source. Markdown pages too. */
811
- const SOURCE_EXTENSIONS$1 = /* @__PURE__ */ new Set([
812
- ".astro",
813
- ".tsx",
814
- ".jsx",
815
- ".md",
816
- ".mdx",
817
- ".html"
818
- ]);
819
- const MESSAGE = "An HTML comment ships to the built page, readable with View Source. Use {/* … */} in .astro and JSX markup, // in frontmatter, and remove it from Markdown.";
1096
+ * it with View Source; Markdown, an SVG and a string a page renders with `set:html` carry one
1097
+ * there too. Every text file under `src/` is read, as the commit hook's
1098
+ * `git grep -F '<!--' -- src/` did: a script comment that only talks about `<!--` is reported
1099
+ * too, and is reworded or excluded. */
820
1100
  const htmlComments = {
821
1101
  id: "html-comments",
822
1102
  title: "HTML comments in the source",
@@ -824,7 +1104,9 @@ const htmlComments = {
824
1104
  stage: "src",
825
1105
  begin: (ctx) => ({ finish: () => {
826
1106
  const findings = [];
827
- for (const file of ctx.sourceFiles(SOURCE_EXTENSIONS$1)) {
1107
+ const files = [...filesUnder(ctx.srcDir)].sort();
1108
+ for (const file of files) {
1109
+ if (BINARY_EXTENSIONS.has(path.extname(file).toLowerCase())) continue;
828
1110
  const text = ctx.readSource(file);
829
1111
  let index = text.indexOf("<!--");
830
1112
  while (index !== -1) {
@@ -839,8 +1121,7 @@ const htmlComments = {
839
1121
  return findings;
840
1122
  } })
841
1123
  };
842
- //#endregion
843
- //#region src/checks/imageFormats.ts
1124
+ // src/checks/imageFormats.ts
844
1125
  const RASTER = /* @__PURE__ */ new Set([
845
1126
  ".jpg",
846
1127
  ".jpeg",
@@ -853,6 +1134,45 @@ const RASTER = /* @__PURE__ */ new Set([
853
1134
  * An AVIF beside them serves nobody; a file named otherwise goes in `imageIgnore`. */
854
1135
  const ICON = /^(?:apple-touch-icon|favicon|icon-|android-chrome-|mstile-|web-app-manifest-)/;
855
1136
  const SHARE = /^(?:og[-_]|social-|twitter-|share-)|-(?:og|social)\./;
1137
+ const MANIFEST_IMAGE = /["'`]([^"'`?#]*\.(?:png|jpe?g|webp))(?:[?#][^"'`]*)?["'`]/gi;
1138
+ /** An Astro endpoint that writes the manifest (`src/pages/site.webmanifest.ts`). */
1139
+ const MANIFEST_ENDPOINT = /(?:\.webmanifest|manifest\.json)\.(?:[cm]?[jt]s)$/;
1140
+ /** The images the site's web manifests name (`*.webmanifest` anywhere under `public/`,
1141
+ * `public/manifest.json`, or the endpoint under `src/pages/` that writes one), as project-relative
1142
+ * paths: app icons and screenshots, which AVIF is no format for. Each name is resolved as the
1143
+ * browser does, from the site root or from the manifest's own folder, so an icon keeps its
1144
+ * exemption whatever its name, and an unrelated image of the same name has none. An absolute URL
1145
+ * names a file of this build only on the site's own origin: an icon on another host exempts
1146
+ * nothing here, and without a known site origin no absolute URL does. */
1147
+ const manifestImages = (publicDir, srcDir, rel, site) => {
1148
+ let origin;
1149
+ try {
1150
+ origin = site ? new URL(site).origin : void 0;
1151
+ } catch {
1152
+ origin = void 0;
1153
+ }
1154
+ const pagesDir = path.join(srcDir, "pages");
1155
+ const manifests = [...filesUnder(publicDir, /* @__PURE__ */ new Set([".webmanifest"])), ...[path.join(publicDir, "manifest.json")].filter((file) => fs.existsSync(file))].map((file) => ({
1156
+ file,
1157
+ folder: path.relative(publicDir, path.dirname(file))
1158
+ }));
1159
+ for (const file of filesUnder(pagesDir)) if (MANIFEST_ENDPOINT.test(file)) manifests.push({
1160
+ file,
1161
+ folder: path.relative(pagesDir, path.dirname(file))
1162
+ });
1163
+ const images = /* @__PURE__ */ new Set();
1164
+ for (const { file, folder } of manifests) for (const m of fs.readFileSync(file, "utf8").matchAll(MANIFEST_IMAGE)) {
1165
+ let url = m[1];
1166
+ if (/^(?:https?:)?\/\//i.test(url)) {
1167
+ const absolute = new URL(url, "https://unknown.invalid");
1168
+ if (!origin || absolute.origin !== origin) continue;
1169
+ url = absolute.pathname;
1170
+ }
1171
+ const inPublic = url.startsWith("/") ? url.slice(1) : path.posix.join(folder.split(path.sep).join("/"), url);
1172
+ images.add(rel(path.join(publicDir, path.posix.normalize(inPublic))));
1173
+ }
1174
+ return images;
1175
+ };
856
1176
  /** The URLs an element references for an image: `src`, `poster`, every `srcset` candidate. */
857
1177
  const imageUrls = (el) => {
858
1178
  const urls = [];
@@ -876,12 +1196,13 @@ const imageFormats = {
876
1196
  stage: "src",
877
1197
  begin: (ctx) => {
878
1198
  const ignored = new Set(ctx.options.imageIgnore);
1199
+ const manifest = manifestImages(ctx.publicDir, ctx.srcDir, ctx.rel, ctx.config.site);
879
1200
  return { finish: () => {
880
1201
  const findings = [];
881
1202
  for (const file of filesUnder(ctx.publicDir, RASTER)) {
882
1203
  const rel = ctx.rel(file);
883
1204
  const name = path.basename(file);
884
- if (ignored.has(rel) || ICON.test(name) || SHARE.test(name)) continue;
1205
+ if (ignored.has(rel) || manifest.has(rel) || ICON.test(name) || SHARE.test(name)) continue;
885
1206
  const stem = file.slice(0, -path.extname(file).length);
886
1207
  if (fs.existsSync(`${stem}.avif`)) continue;
887
1208
  findings.push({
@@ -893,9 +1214,15 @@ const imageFormats = {
893
1214
  } };
894
1215
  }
895
1216
  };
1217
+ /** An absolute URL inside text: an attribute value (island props, `style`, `data-*`), inline JSON
1218
+ * or CSS. It ends at a quote, a space, a comma (a `srcset`), a `)` (CSS `url()`), `&` (`&quot;`) or a backslash. */
1219
+ const TEXT_URL = /https?:\/\/[^\s"'`<>(),&\\]+/g;
896
1220
  /** A feed photo from the vOffice image hosts requested as JPEG or PNG where the host would serve
897
- * WebP. A warning: the photos come from the PMS feed, so a page shows them, and the finding, only
898
- * once the feed has them; that must not stop the nightly builds that update prices. */
1221
+ * WebP. Read wherever a page can carry a photo URL: `src`, `srcset` and `poster`, every other
1222
+ * attribute (an island's props: v9 search listings render their photos there, `style`), inline
1223
+ * scripts (JSON) and styles (`background-image`). A warning: the photos come from the PMS feed, so
1224
+ * a page shows them, and the finding, only once the feed has them; that must not stop the nightly
1225
+ * builds that update prices. */
899
1226
  const feedImageFormats = {
900
1227
  id: "feed-image-formats",
901
1228
  title: "Feed photo formats",
@@ -907,17 +1234,84 @@ const feedImageFormats = {
907
1234
  const findings = [];
908
1235
  return {
909
1236
  visit: (page) => {
910
- for (const el of page.document.querySelectorAll("img, source, video")) for (const url of imageUrls(el)) if (patterns.some((pattern) => pattern.test(url))) findings.push({
1237
+ const urls = /* @__PURE__ */ new Set();
1238
+ for (const el of page.document.querySelectorAll("img, source, video")) for (const url of imageUrls(el)) urls.add(url);
1239
+ const texts = [...page.attributeValues(), ...[...page.document.querySelectorAll("script, style")].map((el) => el.textContent ?? "")];
1240
+ for (const text of texts) for (const [url] of text.matchAll(TEXT_URL)) urls.add(url);
1241
+ for (const url of urls) if (patterns.some((pattern) => pattern.test(url))) findings.push({
911
1242
  path: page.path,
912
- message: `A feed photo is requested as JPEG or PNG: ${url}. Pass it through webpUrl() so the host serves WebP.`
1243
+ message: `A feed photo is requested as JPEG or PNG: ${url}. Pass it through webpUrl() so the host serves WebP, or end an imgproxy URL in .webp.`
913
1244
  });
914
1245
  },
915
1246
  finish: () => findings
916
1247
  };
917
1248
  }
918
1249
  };
919
- //#endregion
920
- //#region src/checks/launchHead.ts
1250
+ // src/sitemaps.ts
1251
+ /** A URL path as the sitemap checks compare it: query and fragment dropped, escapes decoded, no
1252
+ * trailing slash but the root's. The slash is a project-wide setting (`trailingSlash`), not a
1253
+ * statement about the page. */
1254
+ const normalize = (urlPath) => {
1255
+ let p = urlPath.split(/[?#]/, 1)[0] ?? "";
1256
+ try {
1257
+ p = decodeURIComponent(p);
1258
+ } catch {}
1259
+ return p.length > 1 ? p.replace(/\/+$/, "") : p;
1260
+ };
1261
+ /** `https://www.example.de/a/` and `/a/` → `/a`. */
1262
+ const toPath = (loc) => {
1263
+ const value = loc.trim();
1264
+ try {
1265
+ return normalize(new URL(value).pathname);
1266
+ } catch {
1267
+ return normalize(value);
1268
+ }
1269
+ };
1270
+ const locs = (xml) => [...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => xmlText(m[1]));
1271
+ /** One read per build: the checks of a stage share its file list, and three of them ask. */
1272
+ const read = /* @__PURE__ */ new WeakMap();
1273
+ /** Every page the build's sitemaps list: each `sitemap*.xml` at the root of the build (an index, a
1274
+ * stray hand-written one, the `/sitemap.xml` alias), and every sitemap an index names, once each,
1275
+ * so a cycle ends. `missing` holds the sitemaps an index names that the build lacks. */
1276
+ const readSitemaps = (ctx) => {
1277
+ let sitemaps = read.get(ctx.files);
1278
+ if (!sitemaps) read.set(ctx.files, sitemaps = walkSitemaps(ctx));
1279
+ return sitemaps;
1280
+ };
1281
+ const walkSitemaps = (ctx) => {
1282
+ const entries = [];
1283
+ const missing = [];
1284
+ const sitemaps = new Map(ctx.files.filter((f) => /^sitemap[^/]*\.xml$/.test(f)).map((file) => [file, ""]));
1285
+ for (const [sitemap, index] of sitemaps) {
1286
+ if (!ctx.has(sitemap)) {
1287
+ missing.push({
1288
+ path: index,
1289
+ message: `The sitemap index names ${sitemap}, which is not in the build.`
1290
+ });
1291
+ continue;
1292
+ }
1293
+ const xml = ctx.read(sitemap);
1294
+ if (/<sitemapindex\b/i.test(xml)) {
1295
+ for (const loc of locs(xml)) {
1296
+ const child = toPath(loc).replace(/^\//, "");
1297
+ if (!sitemaps.has(child)) sitemaps.set(child, sitemap);
1298
+ }
1299
+ continue;
1300
+ }
1301
+ for (const loc of locs(xml)) entries.push({
1302
+ sitemap,
1303
+ loc,
1304
+ path: toPath(loc)
1305
+ });
1306
+ }
1307
+ return {
1308
+ entries,
1309
+ missing
1310
+ };
1311
+ };
1312
+ /** The paths (`normalize`d) the build's sitemaps list; empty without a sitemap. */
1313
+ const sitemapPaths = (ctx) => new Set(readSitemaps(ctx).entries.map((entry) => entry.path));
1314
+ // src/checks/launchHead.ts
921
1315
  /** Hosts a site is previewed on before it has its own domain: a `site` there is not a launch. */
922
1316
  const PREVIEW_HOST = /(?:^|\.)(?:cloudfront\.net|vercel\.app|netlify\.app|pages\.dev|github\.io)$|^(?:localhost|127\.0\.0\.1)$|\.local$/i;
923
1317
  /** The site's production host, when the Astro config names one that is not a preview origin. */
@@ -929,58 +1323,104 @@ const productionSite = (ctx) => {
929
1323
  return;
930
1324
  }
931
1325
  };
1326
+ /** Runs `finish` once the site is launched: a production `site` in the Astro config and some
1327
+ * indexable page in the build. `null` (skipped) without a production `site` or a build; `[]`
1328
+ * while every page is noindex. */
1329
+ const whenLaunched = (ctx, finish) => {
1330
+ if (!ctx.hasDist || !productionSite(ctx)) return null;
1331
+ let launched = false;
1332
+ return {
1333
+ visit: (page) => {
1334
+ if (isIndexable(page)) launched = true;
1335
+ },
1336
+ finish: () => launched ? finish() : []
1337
+ };
1338
+ };
932
1339
  const isAbsolute = (url) => !!url && /^https?:\/\/[^/]/i.test(url.trim());
933
- /** A page the launch head applies to: indexable, read by someone, not the 404 page. */
934
- const indexable = (page) => !page.redirect && !page.noindex && page.path !== "404.html";
935
1340
  /** A check over the launched site's indexable pages: it waits while the site is a preview (no
936
1341
  * production `site` in the Astro config) or every page is noindex (the preview's blanket robots
937
- * meta), and starts with the build that lifts it. */
938
- const launchCheck = (base, inspect) => ({
1342
+ * meta), and starts with the build that lifts it. `start` sets the check up once and returns what
1343
+ * it reports of each indexable page. */
1344
+ const launchCheck = (base, start) => ({
939
1345
  ...base,
940
1346
  begin: (ctx) => {
941
1347
  const site = productionSite(ctx);
942
1348
  if (!ctx.hasDist || !site) return null;
1349
+ const inspect = start(ctx, site);
943
1350
  const findings = [];
944
1351
  let launched = false;
945
1352
  return {
946
1353
  visit: (page) => {
947
- if (!indexable(page)) return;
1354
+ if (!isIndexable(page)) return;
948
1355
  launched = true;
949
- findings.push(...inspect(page, site));
1356
+ findings.push(...inspect(page));
950
1357
  },
951
1358
  finish: () => launched ? findings : []
952
1359
  };
953
1360
  }
954
1361
  });
955
- /** Every indexable page of the launched site names its canonical URL, absolute (the `site` origin
956
- * and the path, no query): without one, a search engine picks among `/x`, `/x/` and `/x?ref=…`. */
1362
+ const canonicalOf = (page) => page.document.querySelector("link[rel=\"canonical\"]")?.getAttribute("href")?.trim();
1363
+ /** Every indexable page of the launched site names its canonical URL, absolute, on the site's own
1364
+ * origin, without a query, in the URL form `trailingSlash` serves: without one, a search engine
1365
+ * picks among `/x`, `/x/` and `/x?ref=…`, and one on a preview host hands the index to that host.
1366
+ * A page the sitemap lists names itself: the sitemap offers the URL, so a canonical naming another
1367
+ * page disowns it. A page the sitemap leaves out may point at the page it duplicates. */
957
1368
  const canonicalLink = launchCheck({
958
1369
  id: "canonical-link",
959
1370
  title: "Indexable pages name their canonical URL",
960
1371
  severity: "error",
961
1372
  stage: "dist"
962
- }, (page) => {
963
- const href = page.document.querySelector("link[rel=\"canonical\"]")?.getAttribute("href");
964
- if (isAbsolute(href)) return [];
965
- return [{
966
- path: page.path,
967
- message: href ? `The canonical URL "${href}" is not absolute: build it from the Astro \`site\` and the page path.` : "No <link rel=\"canonical\">: give every indexable page its absolute URL, from the Astro `site` and the path."
968
- }];
1373
+ }, (ctx, site) => {
1374
+ const origin = new URL(site).origin;
1375
+ const listed = sitemapPaths(ctx);
1376
+ const slash = ctx.config.trailingSlash;
1377
+ return (page) => {
1378
+ const href = canonicalOf(page);
1379
+ const finding = (message) => [{
1380
+ path: page.path,
1381
+ message
1382
+ }];
1383
+ if (!isAbsolute(href)) return finding(href ? `The canonical URL "${href}" is not absolute: build it from the Astro \`site\` and the page path.` : "No <link rel=\"canonical\">: give every indexable page its absolute URL, from the Astro `site` and the path.");
1384
+ let url;
1385
+ try {
1386
+ url = new URL(href);
1387
+ } catch {
1388
+ return finding(`The canonical URL "${href}" is not a URL a crawler can read.`);
1389
+ }
1390
+ if (url.origin !== origin) return finding(`The canonical URL "${href}" is on ${url.origin}, not on the site's ${origin}: build it from the Astro \`site\`.`);
1391
+ if (url.search || url.hash) return finding(`The canonical URL "${href}" carries a query or fragment: name the page's own URL without one.`);
1392
+ const own = normalize(page.url);
1393
+ if (listed.has(own) && normalize(url.pathname) !== own) return finding(`The canonical URL "${href}" names another page than ${own}, which the sitemap lists: the page disowns the URL the sitemap offers. Build the canonical from the page's own path.`);
1394
+ const root = url.pathname === "/";
1395
+ if (!root && slash === "never" && url.pathname.endsWith("/")) return finding(`The canonical URL "${href}" ends with a slash, and trailingSlash is "never": that URL redirects. Drop the slash.`);
1396
+ if (!root && slash === "always" && !url.pathname.endsWith("/")) return finding(`The canonical URL "${href}" has no trailing slash, and trailingSlash is "always": that URL redirects. Add the slash.`);
1397
+ return [];
1398
+ };
969
1399
  });
970
- /** Every indexable page of the launched site carries `og:url` and `og:image`, absolute: a shared
971
- * link renders bare without them. A warning: a rental page's image is the feed's first photo. */
1400
+ /** Every indexable page of the launched site carries `og:url` and `og:image`, absolute, and its
1401
+ * `og:url` is its canonical URL: a shared link renders bare without them, and an `og:url` that is
1402
+ * not the canonical one moves the share to another URL than search lists. A warning: a rental
1403
+ * page's image is the feed's first photo. */
972
1404
  const openGraph = launchCheck({
973
1405
  id: "open-graph",
974
1406
  title: "Indexable pages carry a share preview",
975
1407
  severity: "warning",
976
1408
  stage: "dist"
977
- }, (page) => {
978
- const meta = (name) => page.document.querySelector(`meta[property="${name}"], meta[name="${name}"]`)?.getAttribute("content");
1409
+ }, () => (page) => {
1410
+ const meta = (name) => page.document.querySelector(`meta[property="${name}"], meta[name="${name}"]`)?.getAttribute("content")?.trim();
1411
+ const findings = [];
979
1412
  const missing = ["og:url", "og:image"].filter((name) => !isAbsolute(meta(name)));
980
- return missing.length === 0 ? [] : [{
1413
+ if (missing.length > 0) findings.push({
981
1414
  path: page.path,
982
1415
  message: `No absolute ${missing.join(" and ")}: a shared link renders without its preview.`
983
- }];
1416
+ });
1417
+ const ogUrl = meta("og:url");
1418
+ const canonical = canonicalOf(page);
1419
+ if (ogUrl && canonical && ogUrl !== canonical) findings.push({
1420
+ path: page.path,
1421
+ message: `og:url "${ogUrl}" is not the canonical URL "${canonical}": a share points at another URL than search lists. Use one value for both.`
1422
+ });
1423
+ return findings;
984
1424
  });
985
1425
  /** The launched site declares `trailingSlash: "never"`: one URL form everywhere means one CDN rule
986
1426
  * set (`/x/` → 301 `/x`) and one redirect-map convention. Unset, the CDN decides per request and
@@ -991,58 +1431,151 @@ const trailingSlash = {
991
1431
  title: "The site declares trailingSlash \"never\"",
992
1432
  severity: "warning",
993
1433
  stage: "dist",
1434
+ begin: (ctx) => ctx.config.trailingSlash === void 0 ? null : whenLaunched(ctx, () => ctx.config.trailingSlash === "never" ? [] : [{ message: `trailingSlash is "${ctx.config.trailingSlash}" in the Astro config: set it to "never" and write internal links without a trailing slash.` }])
1435
+ };
1436
+ // src/checks/jsonLd.ts
1437
+ const blocksOf = (page) => [...page.document.querySelectorAll("script")].filter((s) => s.getAttribute("type")?.trim().toLowerCase() === "application/ld+json").map((s) => s.textContent ?? "");
1438
+ /** The blocks of a page that parse; the others are `json-ld`'s findings. */
1439
+ const parsedBlocks = (page) => blocksOf(page).flatMap((block) => {
1440
+ try {
1441
+ return [JSON.parse(block)];
1442
+ } catch {
1443
+ return [];
1444
+ }
1445
+ });
1446
+ /** Every node of a parsed JSON-LD value, `@graph` and nesting included. */
1447
+ const nodesOf = (value, into = []) => {
1448
+ if (Array.isArray(value)) for (const item of value) nodesOf(item, into);
1449
+ else if (typeof value === "object" && value !== null) {
1450
+ const node = value;
1451
+ into.push(node);
1452
+ for (const child of Object.values(node)) nodesOf(child, into);
1453
+ }
1454
+ return into;
1455
+ };
1456
+ /** A schema.org type as JSON-LD may write it: compact (`VacationRental`), prefixed
1457
+ * (`schema:VacationRental`) or as its IRI (`https://schema.org/VacationRental`). */
1458
+ const SCHEMA_PREFIX = /^(?:https?:\/\/schema\.org\/|schema:)/;
1459
+ const hasType = (node, type) => [node["@type"]].flat().some((t) => typeof t === "string" && t.replace(SCHEMA_PREFIX, "") === type);
1460
+ /** Every JSON-LD block of every page parses: a reader drops a block it cannot parse whole, and
1461
+ * says nothing. A JSON-LD block is the site's code (`JSON.stringify` of an object never fails to
1462
+ * parse), so it refuses the build. */
1463
+ const jsonLd = {
1464
+ id: "json-ld",
1465
+ title: "JSON-LD blocks parse",
1466
+ severity: "error",
1467
+ stage: "dist",
1468
+ begin: (ctx) => {
1469
+ if (!ctx.hasDist) return null;
1470
+ const findings = [];
1471
+ return {
1472
+ visit: (page) => {
1473
+ for (const block of blocksOf(page)) try {
1474
+ JSON.parse(block);
1475
+ } catch (err) {
1476
+ findings.push({
1477
+ path: page.path,
1478
+ message: `A JSON-LD block does not parse (${err.message}): every reader drops it. Build it from an object with JSON.stringify, never by joining strings.`
1479
+ });
1480
+ }
1481
+ },
1482
+ finish: () => findings
1483
+ };
1484
+ }
1485
+ };
1486
+ /** Every indexable rental page of the launched site carries `VacationRental` JSON-LD: search
1487
+ * engines and assistants read a rental's facts from it. The page is the site's (the rental blocks'
1488
+ * `data-rental-stats` marker); the markup is the site's code. A site launching without it on
1489
+ * purpose excludes `rental-markup`, with the reason. */
1490
+ const rentalMarkup = launchCheck({
1491
+ id: "rental-markup",
1492
+ title: "Rental pages carry VacationRental markup",
1493
+ severity: "error",
1494
+ stage: "dist"
1495
+ }, () => (page) => {
1496
+ if (!isRentalPage(page.document)) return [];
1497
+ return parsedBlocks(page).flatMap((block) => nodesOf(block)).some((node) => hasType(node, "VacationRental")) ? [] : [{
1498
+ path: page.path,
1499
+ message: "A rental page without VacationRental JSON-LD: search engines and assistants find none of its facts. Render the rental's VacationRental block from the feed's values."
1500
+ }];
1501
+ });
1502
+ /** Every item of a `BreadcrumbList` on the site's own origin points at a page of the build. A
1503
+ * warning: the trail of a rental page follows the feed. */
1504
+ const breadcrumbs = {
1505
+ id: "breadcrumbs",
1506
+ title: "Breadcrumb items point at built pages",
1507
+ severity: "warning",
1508
+ stage: "dist",
994
1509
  begin: (ctx) => {
995
- if (!ctx.hasDist || !productionSite(ctx) || ctx.config.trailingSlash === void 0) return null;
996
- let launched = false;
1510
+ if (!ctx.hasDist) return null;
1511
+ const origin = ctx.config.site ? new URL(ctx.config.site).origin : void 0;
1512
+ const findings = [];
997
1513
  return {
998
1514
  visit: (page) => {
999
- if (indexable(page)) launched = true;
1515
+ const lists = parsedBlocks(page).flatMap((block) => nodesOf(block)).filter((node) => hasType(node, "BreadcrumbList"));
1516
+ for (const list of lists) {
1517
+ const items = Array.isArray(list.itemListElement) ? list.itemListElement : [];
1518
+ for (const element of items) {
1519
+ const item = element?.item;
1520
+ const url = typeof item === "string" ? item : item?.["@id"];
1521
+ if (typeof url !== "string" || !isSameSiteReference(url, origin)) continue;
1522
+ if (!ctx.serves(resolveReference(page, url))) findings.push({
1523
+ path: page.path,
1524
+ message: `A breadcrumb item points at ${url}, which no page of the build serves.`
1525
+ });
1526
+ }
1527
+ }
1000
1528
  },
1001
- finish: () => !launched || ctx.config.trailingSlash === "never" ? [] : [{ message: `trailingSlash is "${ctx.config.trailingSlash}" in the Astro config: set it to "never" and write internal links without a trailing slash.` }]
1529
+ finish: () => findings
1002
1530
  };
1003
1531
  }
1004
1532
  };
1005
- //#endregion
1006
- //#region src/checks/listingLinks.ts
1533
+ // src/checks/listingLinks.ts
1007
1534
  /** A page that lists rentals renders the list into its HTML too, inside this container, so a
1008
1535
  * crawler running no JavaScript sees the rentals the live island will show. The search page of
1009
1536
  * the site starter marks its server-rendered results this way. */
1010
1537
  const LIST_CONTAINER = "[data-prerendered-results]";
1011
1538
  /** The live search island; a page that mounts it lists rentals, container or not. */
1012
1539
  const LIST_ISLAND = "SearchResults";
1013
- /** Below this many pages the build is a starter with an empty feed, where an empty list says
1014
- * nothing about the site's code. */
1015
- const SMALL_BUILD = 10;
1016
- const normalize$1 = (urlPath) => {
1017
- const p = urlPath.split(/[?#]/, 1)[0] ?? "";
1018
- return p.length > 1 ? p.replace(/\/+$/, "") : p;
1019
- };
1020
- /** The page as a listing, when it is one: its markup marks it, or `listingPages` names it. Links
1021
- * are those of the list's own markup: the container, else what the island rendered on the server
1022
- * (a client-only island renders nothing). A page known only from `listingPages` has neither, and
1023
- * its header, navigation and footer links are not a list either. */
1024
- const asListing = (ctx, configured, page) => {
1540
+ /** The favourites grid is the search island over the visitor's saved list, empty in the build and
1541
+ * rightly noindex: the kits' `window.__favoritesMode = true`, website-components' root
1542
+ * `data-search-scope="favorites"` when rendered on the server, its `scope={{ favorites: true }}`
1543
+ * prop (Astro serializes it `"favorites":[0,true]`) when client-only. */
1544
+ const FAVOURITES_FLAG = /__favoritesMode\s*=\s*true/;
1545
+ const FAVOURITES_SCOPE = "[data-search-scope=\"favorites\"]";
1546
+ const FAVOURITES_PROP = /"favorites":\[0,true\]/;
1547
+ const isFavourites = (page, islands) => !!page.document.querySelector(FAVOURITES_SCOPE) || islands.some((island) => FAVOURITES_PROP.test(island.getAttribute("props") ?? "")) || [...page.document.querySelectorAll("script:not([src])")].some((script) => FAVOURITES_FLAG.test(script.textContent ?? ""));
1548
+ /** The page as a listing, when it is one: its markup marks it, or `listingPages` names it; never a
1549
+ * rental page or the favourites grid. Links are those of the list's own markup: the container,
1550
+ * else what the island rendered on the server (a client-only island renders nothing). A page known
1551
+ * only from `listingPages` has neither, and its header, navigation and footer links are not a
1552
+ * list either. */
1553
+ const asListing = (configured, page) => {
1554
+ if (page.redirect || isRentalPage(page.document)) return null;
1025
1555
  const container = page.document.querySelector(LIST_CONTAINER);
1026
1556
  const islands = [...page.document.querySelectorAll("astro-island")].filter((el) => (el.getAttribute("component-url") ?? "").includes(LIST_ISLAND));
1027
- const url = normalize$1(page.url);
1557
+ const url = normalize(page.url);
1028
1558
  if (!container && islands.length === 0 && !configured.has(url)) return null;
1559
+ if (isFavourites(page, islands)) return null;
1029
1560
  const anchors = container ? [...container.querySelectorAll("a[href]")] : islands.length > 0 ? islands.flatMap((island) => [...island.querySelectorAll("a[href]")]) : [...page.document.querySelectorAll("a[href]")].filter((a) => !a.closest("header, nav, footer"));
1030
1561
  const links = /* @__PURE__ */ new Set();
1031
1562
  for (const a of anchors) {
1032
1563
  const href = a.getAttribute("href") ?? "";
1033
1564
  if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#")) continue;
1034
- const target = normalize$1(new URL(href, `http://site.invalid${page.base}`).pathname);
1035
- if (target !== url && ctx.serves(target)) links.add(target);
1565
+ links.add(normalize(new URL(href, `http://site.invalid${page.base}`).pathname));
1036
1566
  }
1037
1567
  return {
1038
1568
  path: page.path,
1039
1569
  url,
1040
- links: links.size
1570
+ links
1041
1571
  };
1042
1572
  };
1573
+ /** `listingClientOnly`'s paths: a listing whose list is the rentals free in a window is exempt
1574
+ * from both rules, as `scripts/listing-links.allow` exempted it. */
1575
+ const clientOnlyOf = (ctx) => new Set(ctx.options.listingClientOnly.map((c) => normalize(c.path)));
1043
1576
  /** Every page that lists rentals is indexable: a hidden listing hides its rentals with it. The
1044
- * site's own noindex routes decide this, not the feed, so it refuses the build. Skipped while
1045
- * every page is noindex (a site before launch). */
1577
+ * site's own noindex routes decide this, not the feed, so it refuses the build. Skipped while no
1578
+ * page is indexable (a site before launch; its 404 page and redirect stubs do not count). */
1046
1579
  const listingNoindex = {
1047
1580
  id: "listing-noindex",
1048
1581
  title: "Rental listings are indexable",
@@ -1050,26 +1583,28 @@ const listingNoindex = {
1050
1583
  stage: "dist",
1051
1584
  begin: (ctx) => {
1052
1585
  if (!ctx.hasDist) return null;
1053
- const configured = new Set(ctx.options.listingPages.map(normalize$1));
1586
+ const configured = new Set(ctx.options.listingPages.map(normalize));
1587
+ const clientOnly = clientOnlyOf(ctx);
1054
1588
  const hidden = [];
1055
- let indexable = 0;
1589
+ let launched = false;
1056
1590
  return {
1057
1591
  visit: (page) => {
1058
- if (page.redirect) return;
1059
- if (!page.noindex) indexable += 1;
1060
- else if (asListing(ctx, configured, page)) hidden.push(page.path);
1592
+ if (isIndexable(page)) launched = true;
1593
+ if (!page.noindex) return;
1594
+ const listing = asListing(configured, page);
1595
+ if (listing && !clientOnly.has(listing.url)) hidden.push(listing.path);
1061
1596
  },
1062
- finish: () => indexable === 0 ? [] : hidden.map((path) => ({
1597
+ finish: () => launched ? hidden.map((path) => ({
1063
1598
  path,
1064
1599
  message: "A page that lists rentals is noindex; the rentals it lists are hidden with it. Take it out of the noindex routes."
1065
- }))
1600
+ })) : []
1066
1601
  };
1067
1602
  }
1068
1603
  };
1069
- /** Every page that lists rentals carries links to them in its built HTML; a crawler without
1070
- * JavaScript otherwise sees an empty list. A warning: the links come from the PMS feed, and an
1071
- * empty or booked-out feed must not stop the nightly builds that update prices. Runs once some
1072
- * listing page has links, or the build is more than a starter's handful of pages. */
1604
+ /** Every page that lists rentals carries links to rental pages in its built HTML; a crawler
1605
+ * without JavaScript otherwise sees an empty list. A warning: the links come from the PMS feed,
1606
+ * and an empty or booked-out feed must not stop the nightly builds that update prices. Skipped
1607
+ * while the build has no rental page (a starter with an empty feed). */
1073
1608
  const listingLinks = {
1074
1609
  id: "listing-links",
1075
1610
  title: "Rental listings reach crawlers",
@@ -1077,21 +1612,21 @@ const listingLinks = {
1077
1612
  stage: "dist",
1078
1613
  begin: (ctx) => {
1079
1614
  if (!ctx.hasDist) return null;
1080
- const configured = new Set(ctx.options.listingPages.map(normalize$1));
1081
- const clientOnly = new Map(ctx.options.listingClientOnly.map((c) => [normalize$1(c.path), c]));
1615
+ const configured = new Set(ctx.options.listingPages.map(normalize));
1616
+ const clientOnly = clientOnlyOf(ctx);
1082
1617
  const listings = [];
1083
- let pages = 0;
1618
+ const rentals = /* @__PURE__ */ new Set();
1084
1619
  return {
1085
1620
  visit: (page) => {
1086
1621
  if (page.redirect) return;
1087
- pages += 1;
1088
- const listing = asListing(ctx, configured, page);
1089
- if (listing) listings.push(listing);
1622
+ if (isRentalPage(page.document)) rentals.add(normalize(page.url));
1623
+ const listing = asListing(configured, page);
1624
+ if (listing && !clientOnly.has(listing.url)) listings.push(listing);
1090
1625
  },
1091
1626
  finish: () => {
1092
1627
  const findings = [];
1093
- if (!listings.some((l) => l.links > 0) && pages <= SMALL_BUILD) return findings;
1094
- for (const listing of listings) if (listing.links === 0 && !clientOnly.has(listing.url)) findings.push({
1628
+ if (rentals.size === 0) return findings;
1629
+ for (const listing of listings) if (![...listing.links].some((link) => rentals.has(link))) findings.push({
1095
1630
  path: listing.path,
1096
1631
  message: "No links to rentals in the HTML: a crawler running no JavaScript sees an empty list. Render the list server-side (the search page's prerendered results), or list the page in listingClientOnly with the reason."
1097
1632
  });
@@ -1100,8 +1635,7 @@ const listingLinks = {
1100
1635
  };
1101
1636
  }
1102
1637
  };
1103
- //#endregion
1104
- //#region src/checks/loadOrder.ts
1638
+ // src/checks/loadOrder.ts
1105
1639
  /** Libraries that serve one feature a visitor reaches later (a map, a chart, a 3D view): `name` is
1106
1640
  * the package (a chunk named after it), `signature` a string only its code carries. */
1107
1641
  const ON_DEMAND = [
@@ -1142,12 +1676,36 @@ const STATIC_IMPORT = /(?:^|[;\n}])\s*(?:import|export)\s*(?:[\w$*{},\s]*?from\s
1142
1676
  const INLINE_IMPORT = /(?:import|from)\s*["'](\/[^"']+\.js)["']/g;
1143
1677
  /** Nothing under these is fetched at start: template content, a closed dialog, a hidden subtree. */
1144
1678
  const INERT = "template, dialog, [hidden]";
1145
- const STRIP_CLASS = /(?:^|\s)(?:snap-x|overflow-x-(?:auto|scroll))(?:\s|$)/;
1679
+ /** A swipe strip, under any variant (`md:overflow-x-auto`). */
1680
+ const STRIP_CLASS = /\b(?:snap-x|overflow-x-(?:auto|scroll))\b/;
1681
+ /** What hides a stacked slide while it still lies in the viewport, so `loading="lazy"` fetches it:
1682
+ * the class, or a breakpoint's (`md:opacity-0` hides it there, fetched all the same); never a state
1683
+ * variant, which is visible until hovered or focused (`group-hover:opacity-0`). */
1684
+ const SHUT_CLASS = /(?:^|\s)(?:(?:sm|md|lg|xl|2xl|max-[a-z0-9]+):)*(?:invisible|opacity-0)(?=\s|$)/;
1685
+ /** An icon is no slide: a decorative SVG under `aria-hidden` sits in a hero's badges and links. */
1686
+ const ICON_URL = /\.svg(?:[?#]|$)/i;
1146
1687
  const few = (pages) => {
1147
1688
  const list = [...pages];
1148
1689
  return list.slice(0, 3).join(", ") + (list.length > 3 ? ` (+${list.length - 3} more)` : "");
1149
1690
  };
1150
1691
  const add = (map, key, page) => map.set(key, (map.get(key) ?? /* @__PURE__ */ new Set()).add(page));
1692
+ /** A same-site URL as a file of the build; null for another host. */
1693
+ const toFile = (url) => url?.startsWith("/") ? (url.split(/[?#]/, 1)[0] ?? "").replace(/^\/+/, "") : null;
1694
+ /** A URL a browser fetches, not a `data:` stand-in. */
1695
+ const live = (url) => url && /^(?!data:)\S/.test(url) ? url : null;
1696
+ const firstCandidate = (srcset) => srcset?.trim().split(/[\s,]/, 1)[0];
1697
+ /** The file a current browser takes for an `<img>` in a `<picture>`: the first `<source>`'s. */
1698
+ const sourceUrl = (img) => firstCandidate(img.closest("picture")?.querySelector("source[srcset]")?.getAttribute("srcset"));
1699
+ /** An ancestor of `img`, up to and including `block`, hides it: out of the accessibility tree,
1700
+ * inert, shut by a class, or not rendered (`hidden`, a closed `<dialog>`; an eager image there is
1701
+ * fetched all the same). */
1702
+ const hiddenWithin = (img, block) => {
1703
+ for (let el = img.parentElement; el; el = el.parentElement) {
1704
+ if (el.getAttribute("aria-hidden") === "true" || el.hasAttribute("inert") || el.hasAttribute("hidden") || el.tagName === "DIALOG" && !el.hasAttribute("open") || SHUT_CLASS.test(el.getAttribute("class") ?? "")) return true;
1705
+ if (el === block) return false;
1706
+ }
1707
+ return false;
1708
+ };
1151
1709
  /** What a built page fetches at start on a slow phone, where each of these costs seconds before
1152
1710
  * the largest picture paints and no other check sees it:
1153
1711
  * - an on-demand library (a map engine, a chart library) in the start-up code: module scripts and
@@ -1155,9 +1713,9 @@ const add = (map, key, page) => map.set(key, (map.get(key) ?? /* @__PURE__ */ ne
1155
1713
  * statically;
1156
1714
  * - on a page with two or more card swipe strips, a photo after a strip's first carrying a URL
1157
1715
  * (native lazy loading reaches sideways on slow links);
1158
- * - a large first-paint photo (not lazy) in one size only, without a width `srcset`;
1159
- * - a `font-display: swap` face without a `size-adjust` stand-in behind it, which reflows the line.
1160
- * A warning: each is a cost, not a fault. */
1716
+ * - a `font-display: swap` face without a `size-adjust` stand-in behind it, which reflows the line
1717
+ * (a preloaded one at first paint; one not preloaded, likely below the fold, named apart).
1718
+ * A warning: each is a cost, not a fault. The first-paint photo rules are `first-paint-photos`. */
1161
1719
  const loadOrder = {
1162
1720
  id: "load-order",
1163
1721
  title: "What pages load at start",
@@ -1182,12 +1740,11 @@ const loadOrder = {
1182
1740
  }
1183
1741
  return known;
1184
1742
  };
1185
- const toFile = (url) => url?.startsWith("/") ? (url.split(/[?#]/, 1)[0] ?? "").replace(/^\/+/, "") : null;
1186
1743
  const libraries = /* @__PURE__ */ new Map();
1187
1744
  const large = /* @__PURE__ */ new Map();
1188
1745
  const strips = /* @__PURE__ */ new Map();
1189
- const oneSize = /* @__PURE__ */ new Map();
1190
1746
  const faces = /* @__PURE__ */ new Map();
1747
+ const lateFaces = /* @__PURE__ */ new Map();
1191
1748
  const startup = (page) => {
1192
1749
  const roots = /* @__PURE__ */ new Set();
1193
1750
  for (const script of page.document.querySelectorAll("script[type=\"module\"]")) {
@@ -1224,34 +1781,14 @@ const loadOrder = {
1224
1781
  let count = 0;
1225
1782
  for (const strip of page.document.querySelectorAll("[class]")) {
1226
1783
  if (!STRIP_CLASS.test(strip.getAttribute("class") ?? "") || strip.closest(INERT)) continue;
1227
- const live = [...strip.querySelectorAll("img")].slice(1).filter((img) => ["src", "srcset"].some((a) => /^(?!data:)\S/.test(img.getAttribute(a) ?? "")));
1228
- if (live.length > 0) {
1784
+ const fetched = [...strip.querySelectorAll("img")].filter((img) => !img.closest(INERT)).slice(1).filter((img) => live(img.getAttribute("src")) ?? live(img.getAttribute("srcset")));
1785
+ if (fetched.length > 0) {
1229
1786
  count += 1;
1230
- extra += live.length;
1787
+ extra += fetched.length;
1231
1788
  }
1232
1789
  }
1233
1790
  if (count >= 2) strips.set(page.path, extra);
1234
1791
  };
1235
- const sizeKb = (url) => {
1236
- const file = toFile(url);
1237
- if (!file || !ctx.has(file)) return null;
1238
- return fs.statSync(path.join(ctx.distDir, decodeURI(file))).size / 1024;
1239
- };
1240
- const widths = (el) => [el, ...el.querySelectorAll("[srcset]")].some((node) => ((node.getAttribute("srcset") ?? "").match(/\s\d+w\b/g) ?? []).length >= 2);
1241
- const oneSizePhotos = (page) => {
1242
- const note = (url) => {
1243
- const kb = sizeKb(url);
1244
- if (kb !== null && kb >= ONE_SIZE_KB) add(oneSize, `${url} (${Math.round(kb)} KB)`, page.path);
1245
- };
1246
- for (const link of page.document.querySelectorAll("link[rel=\"preload\"][as=\"image\"]")) if (!link.hasAttribute("imagesrcset")) note(link.getAttribute("href"));
1247
- for (const img of page.document.querySelectorAll("img")) {
1248
- if (img.closest(INERT) || img.getAttribute("loading") === "lazy") continue;
1249
- const picture = img.closest("picture");
1250
- if (widths(picture ?? img)) continue;
1251
- const first = picture?.querySelector("source[srcset]")?.getAttribute("srcset")?.trim().split(/[\s,]/, 1)[0];
1252
- note(first ?? img.getAttribute("src"));
1253
- }
1254
- };
1255
1792
  const sheets = /* @__PURE__ */ new Map();
1256
1793
  const sheet = (file) => {
1257
1794
  if (!sheets.has(file)) sheets.set(file, ctx.has(file) ? ctx.read(file) : "");
@@ -1283,8 +1820,8 @@ const loadOrder = {
1283
1820
  const adjusted = new Set(declared.filter((f) => f.adjusted).map((f) => f.family));
1284
1821
  const stacks = [...css.replace(/@font-face\s*\{[^}]*\}/g, "").matchAll(/font-family:\s*([^;}]+)/g)].map((m) => m[1].split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")));
1285
1822
  const preloaded = new Set([...page.document.querySelectorAll("link[rel=\"preload\"][href]")].map((l) => resolve(l.getAttribute("href"), page.base)));
1286
- for (const face of declared) if (face.swap && !face.adjusted && face.file && preloaded.has(face.file)) {
1287
- if (stacks.filter((stack) => stack[0] === face.family).some((stack) => !adjusted.has(stack[1] ?? ""))) add(faces, face.family, page.path);
1823
+ for (const face of declared) if (face.swap && !face.adjusted) {
1824
+ if (stacks.filter((stack) => stack[0] === face.family).some((stack) => !adjusted.has(stack[1] ?? ""))) add(face.file && preloaded.has(face.file) ? faces : lateFaces, face.family, page.path);
1288
1825
  }
1289
1826
  };
1290
1827
  return {
@@ -1292,7 +1829,6 @@ const loadOrder = {
1292
1829
  if (page.redirect) return;
1293
1830
  startup(page);
1294
1831
  swipeStrips(page);
1295
- oneSizePhotos(page);
1296
1832
  swappedFaces(page);
1297
1833
  },
1298
1834
  finish: () => {
@@ -1303,120 +1839,411 @@ const loadOrder = {
1303
1839
  path: page,
1304
1840
  message: `${extra} photo(s) after the first in the card swipe strips carry a URL. Render only the first slide's src/srcset and hand the rest theirs on first interaction.`
1305
1841
  });
1306
- for (const [photo, pages] of oneSize) findings.push({ message: `${photo} loads at start in one size only, on ${few(pages)}. Ship width variants in a srcset with a measured sizes; a preload names the same srcset/sizes pair.` });
1307
1842
  for (const [family, pages] of faces) findings.push({ message: `The preloaded face "${family}" swaps in without a width-matched stand-in (size-adjust) behind it, on ${few(pages)}. Add a local() stand-in with size-adjust right after it in the stack.` });
1843
+ for (const [family, pages] of lateFaces) if (!faces.has(family)) findings.push({ message: `The face "${family}" swaps in without a width-matched stand-in (size-adjust) behind it, on ${few(pages)}; not preloaded, so likely below the fold. A local() stand-in with size-adjust right after it in the stack keeps the line from moving.` });
1308
1844
  return findings;
1309
1845
  }
1310
1846
  };
1311
1847
  }
1312
1848
  };
1313
- //#endregion
1314
- //#region src/checks/sitemapNoindex.ts
1315
- const SITEMAP_INDEX = "sitemap-index.xml";
1316
- const LLMS = "llms.txt";
1317
- /** A URL path as the sitemap checks compare it: query and fragment dropped, escapes decoded, no
1318
- * trailing slash but the root's. */
1319
- const normalize = (urlPath) => {
1320
- let p = urlPath.split(/[?#]/, 1)[0] ?? "";
1321
- try {
1322
- p = decodeURIComponent(p);
1323
- } catch {}
1324
- return p.length > 1 ? p.replace(/\/+$/, "") : p;
1325
- };
1326
- /** `https://www.example.de/a/` and `/a/` → `/a`. */
1327
- const toPath = (loc) => {
1328
- const value = loc.trim();
1329
- try {
1330
- return normalize(new URL(value).pathname);
1331
- } catch {
1332
- return normalize(value);
1333
- }
1334
- };
1335
- const locs = (xml) => [...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => xmlText(m[1]));
1336
- /** The URL lists the build publishes agree with the pages it built: no sitemap entry whose own page
1337
- * says noindex or is not in the build, no `llms.txt` link to a page that is not there. Skipped when
1338
- * the build publishes neither. While every page is noindex (a site before launch, under its blanket
1339
- * robots meta), a sitemap listing them is not refused: that disagreement ends with the launch. */
1340
- const sitemapNoindex = {
1341
- id: "sitemap-noindex",
1342
- title: "Published URL lists match the built pages",
1849
+ /** The photos of the first paint, the site's own markup in both rules, so they refuse the build:
1850
+ * - a first-paint photo (not lazy) or an image preload from 100 KB up in one size only, without a
1851
+ * width `srcset` (`imagesrcset` on the preload). Only a file of the build is measured, a photo
1852
+ * the site serves itself; the feed's photos come from the PMS hosts and are never weighed;
1853
+ * - in the block (innermost `<header>`/`<section>`) holding the `fetchpriority="high"` photo, a
1854
+ * hidden slide carrying a URL: an image under `aria-hidden="true"`, `inert`, `invisible` or
1855
+ * `opacity-0`. Stacked slides lie in the viewport, so `loading="lazy"` fetches them at once,
1856
+ * beside the first one; the hidden marking is what tells a slideshow from a gallery.
1857
+ * Nothing under `<template>`, `<dialog>` or `hidden` counts: it is not fetched. */
1858
+ const firstPaintPhotos = {
1859
+ id: "first-paint-photos",
1860
+ title: "First-paint photos",
1343
1861
  severity: "error",
1344
1862
  stage: "dist",
1345
1863
  begin: (ctx) => {
1346
1864
  if (!ctx.hasDist) return null;
1347
- const start = ctx.has(SITEMAP_INDEX) ? [SITEMAP_INDEX] : ctx.files.filter((f) => /^sitemap[^/]*\.xml$/.test(f));
1348
- if (start.length === 0 && !ctx.has(LLMS)) return null;
1349
- const noindex = /* @__PURE__ */ new Map();
1350
- let indexable = 0;
1351
- return {
1352
- visit: (page) => {
1353
- if (page.redirect) return;
1354
- if (page.noindex) noindex.set(normalize(page.url), page.path);
1355
- else indexable += 1;
1356
- },
1357
- finish: () => {
1358
- const findings = [];
1359
- const sitemaps = new Map(start.map((file) => [file, ""]));
1360
- for (const [sitemap, index] of sitemaps) {
1361
- if (!ctx.has(sitemap)) {
1362
- findings.push({
1363
- path: index,
1364
- message: `The sitemap index names ${sitemap}, which is not in the build.`
1365
- });
1366
- continue;
1367
- }
1368
- const xml = ctx.read(sitemap);
1369
- if (/<sitemapindex\b/i.test(xml)) {
1370
- for (const loc of locs(xml)) {
1371
- const child = toPath(loc).replace(/^\//, "");
1372
- if (!sitemaps.has(child)) sitemaps.set(child, sitemap);
1373
- }
1374
- continue;
1375
- }
1376
- for (const loc of locs(xml)) {
1377
- const urlPath = toPath(loc);
1378
- if (!ctx.serves(urlPath)) findings.push({
1379
- path: sitemap,
1380
- message: `The sitemap lists ${loc}, which is not in the build.`
1381
- });
1382
- else if (indexable > 0 && noindex.has(urlPath)) findings.push({
1383
- path: sitemap,
1384
- message: `The sitemap lists ${loc}, whose page says noindex: the sitemap filter and the noindex routes disagree.`
1385
- });
1386
- }
1865
+ const oneSize = /* @__PURE__ */ new Map();
1866
+ const slides = /* @__PURE__ */ new Map();
1867
+ const sizeKb = (url) => {
1868
+ const file = toFile(url);
1869
+ if (!file || !ctx.has(file)) return null;
1870
+ return fs.statSync(path.join(ctx.distDir, decodeURI(file))).size / 1024;
1871
+ };
1872
+ const widths = (el) => [el, ...el.querySelectorAll("[srcset]")].some((node) => ((node.getAttribute("srcset") ?? "").match(/\s\d+w\b/g) ?? []).length >= 2);
1873
+ const oneSizePhotos = (page) => {
1874
+ const note = (url) => {
1875
+ const kb = sizeKb(url);
1876
+ if (kb !== null && kb >= ONE_SIZE_KB) add(oneSize, `${url} (${Math.round(kb)} KB)`, page.path);
1877
+ };
1878
+ for (const link of page.document.querySelectorAll("link[rel=\"preload\"][as=\"image\"]")) if (!link.hasAttribute("imagesrcset")) note(link.getAttribute("href"));
1879
+ for (const img of page.document.querySelectorAll("img")) {
1880
+ if (img.closest(INERT) || img.getAttribute("loading") === "lazy") continue;
1881
+ const picture = img.closest("picture");
1882
+ if (widths(picture ?? img)) continue;
1883
+ note(sourceUrl(img) ?? img.getAttribute("src"));
1884
+ }
1885
+ };
1886
+ const hiddenSlides = (page) => {
1887
+ const lcp = [...page.document.querySelectorAll("img[fetchpriority=\"high\"]")].find((img) => !img.closest(INERT));
1888
+ const block = lcp?.closest("header, section");
1889
+ if (!lcp || !block) return;
1890
+ for (const img of block.querySelectorAll("img")) {
1891
+ if (img === lcp || img.closest("template")) continue;
1892
+ if (img.closest(INERT) && img.getAttribute("loading") === "lazy") continue;
1893
+ if (!hiddenWithin(img, block)) continue;
1894
+ const url = live(sourceUrl(img)) ?? live(img.getAttribute("src")) ?? live(firstCandidate(img.getAttribute("srcset")));
1895
+ if (url && !ICON_URL.test(url)) add(slides, url, page.path);
1896
+ }
1897
+ };
1898
+ return {
1899
+ visit: (page) => {
1900
+ if (page.redirect) return;
1901
+ oneSizePhotos(page);
1902
+ hiddenSlides(page);
1903
+ },
1904
+ finish: () => {
1905
+ const findings = [];
1906
+ for (const [photo, pages] of oneSize) findings.push({ message: `${photo} loads at start in one size only, on ${few(pages)}. Ship width variants in a srcset with a measured sizes; a preload names the same srcset/sizes pair.` });
1907
+ for (const [url, pages] of slides) findings.push({ message: `${url} sits in a hidden slide beside the first-paint photo and loads at start, on ${few(pages)}. Ship hidden slides without src/srcset (data-src, data-srcset) and hand each its URL after the page has loaded; loading="lazy" fetches stacked slides at once.` });
1908
+ return findings;
1909
+ }
1910
+ };
1911
+ }
1912
+ };
1913
+ // src/checks/orphanPages.ts
1914
+ /** Every indexable page but the home page is linked from another page of the build, in its HTML: a
1915
+ * page only the sitemap reaches reads as unimportant to a crawler. Links an island renders in the
1916
+ * browser do not count, which is the point: a crawler that runs no JavaScript sees none of them. A
1917
+ * warning: rental pages are linked from listings the feed fills. */
1918
+ const orphanPages = {
1919
+ id: "orphan-pages",
1920
+ title: "Indexable pages are linked from another page",
1921
+ severity: "warning",
1922
+ stage: "dist",
1923
+ begin: (ctx) => {
1924
+ if (!ctx.hasDist) return null;
1925
+ const origin = ctx.config.site ? new URL(ctx.config.site).origin : void 0;
1926
+ const linked = /* @__PURE__ */ new Set();
1927
+ const pages = [];
1928
+ return {
1929
+ visit: (page) => {
1930
+ const own = normalize(page.url);
1931
+ for (const a of page.document.querySelectorAll("a[href]")) {
1932
+ const href = a.getAttribute("href") ?? "";
1933
+ if (!isSameSiteReference(href, origin)) continue;
1934
+ const target = normalize(resolveReference(page, href));
1935
+ if (target !== own) linked.add(target);
1387
1936
  }
1388
- if (ctx.has(LLMS)) for (const match of ctx.read(LLMS).matchAll(/\]\(([^)\s]+)\)/g)) {
1389
- const link = match[1];
1390
- if (/^[a-z][a-z0-9+.-]*:/i.test(link) && !ctx.config.site) continue;
1391
- if (/^[a-z][a-z0-9+.-]*:/i.test(link)) {
1392
- let host;
1393
- try {
1394
- host = new URL(link).host;
1395
- } catch {
1396
- continue;
1397
- }
1398
- if (host !== new URL(ctx.config.site).host) continue;
1399
- }
1400
- if (!ctx.serves(toPath(link))) findings.push({
1401
- path: LLMS,
1402
- message: `llms.txt links ${link}, which is not in the build.`
1937
+ if (isIndexable(page) && own !== "/") pages.push({
1938
+ path: page.path,
1939
+ url: own
1940
+ });
1941
+ },
1942
+ finish: () => pages.filter((p) => !linked.has(p.url)).map((p) => ({
1943
+ path: p.path,
1944
+ message: `No other page links to ${p.url} in its HTML: link it from a page a crawler reaches (navigation, a listing, the footer).`
1945
+ }))
1946
+ };
1947
+ }
1948
+ };
1949
+ // src/siteTexts.ts
1950
+ const CODE_EXTENSIONS = /* @__PURE__ */ new Set([
1951
+ ".ts",
1952
+ ".tsx",
1953
+ ".jsx",
1954
+ ".astro",
1955
+ ".mjs",
1956
+ ".js"
1957
+ ]);
1958
+ const OWN_EXTENSIONS = /* @__PURE__ */ new Set([
1959
+ ".astro",
1960
+ ".ts",
1961
+ ".tsx",
1962
+ ".jsx",
1963
+ ".js",
1964
+ ".mjs",
1965
+ ".md",
1966
+ ".mdx",
1967
+ ".html",
1968
+ ".json",
1969
+ ".yml",
1970
+ ".yaml"
1971
+ ]);
1972
+ const filesOf = (ctx, extensions) => ctx.sourceFiles(extensions).filter((file) => !file.endsWith(".d.ts"));
1973
+ const lineAt = (text, index) => text.slice(0, index).split("\n").length;
1974
+ /** The code of the value that starts at `start`: up to the comma or closing bracket at its own
1975
+ * depth, quotes respected. */
1976
+ const valueAt = (src, start) => {
1977
+ let depth = 0;
1978
+ let quote = null;
1979
+ for (let j = start; j < src.length; j += 1) {
1980
+ const c = src[j];
1981
+ if (quote) {
1982
+ if (c === "\\") j += 1;
1983
+ else if (c === quote) quote = null;
1984
+ continue;
1985
+ }
1986
+ if (c === "\"" || c === "'" || c === "`") quote = c;
1987
+ else if ("([{".includes(c)) depth += 1;
1988
+ else if (")]}".includes(c)) {
1989
+ if (depth === 0) return src.slice(start, j);
1990
+ depth -= 1;
1991
+ } else if (c === "," && depth === 0) return src.slice(start, j);
1992
+ }
1993
+ return src.slice(start);
1994
+ };
1995
+ const LITERAL = /"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|`((?:[^`\\]|\\.)*)`/g;
1996
+ const ESCAPES = {
1997
+ n: "\n",
1998
+ r: "\r",
1999
+ t: " ",
2000
+ b: "\b",
2001
+ f: "\f",
2002
+ v: "\v",
2003
+ 0: "\0"
2004
+ };
2005
+ const ESCAPE = /\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|\r?\n|[\s\S])/g;
2006
+ /** One escape's text (after its backslash): `n` a line break, `u00e4` „ä", a line continuation
2007
+ * nothing. Decoded, never run. */
2008
+ const unescapeOne = (e) => {
2009
+ if (e.startsWith("u") && e.length > 1) return String.fromCodePoint(parseInt(e.startsWith("u{") ? e.slice(2, -1) : e.slice(1), 16));
2010
+ if (/^x[0-9a-fA-F]{2}$/.test(e)) return String.fromCharCode(parseInt(e.slice(1), 16));
2011
+ if (e === "\n" || e === "\r\n") return "";
2012
+ return ESCAPES[e] ?? e;
2013
+ };
2014
+ /** A literal's text as it renders: its escapes decoded (`"Hallo\nSie"` is two lines, and „Sie"
2015
+ * starts the second). */
2016
+ const decode = (raw) => raw.replace(ESCAPE, (_, e) => unescapeOne(e));
2017
+ /** The same, keeping every character's place: each escape becomes its text, padded with the
2018
+ * dropped `\u0000` and keeping its own line break, so a source line still maps to its text. */
2019
+ const decodeInPlace = (raw) => raw.replace(ESCAPE, (seq, e) => {
2020
+ const text = unescapeOne(e).replace(/\s/g, " ");
2021
+ return text + seq.slice(text.length).replace(/[^\n]/g, "\0");
2022
+ });
2023
+ /** Every string literal in the value of a `"<lang>-XX":` key in the site's code: language-kit's
2024
+ * `defineTexts`, `Localized<…>` data. The value is a string, an arrow returning a template, or an
2025
+ * object or array of them. Comments are blanked first (newlines kept, so lines still count): a
2026
+ * wording left in one renders nowhere. */
2027
+ const localizedTexts = (ctx, lang) => {
2028
+ const key = new RegExp(`["']${lang}-[A-Z]{2}["']\\s*:\\s*`, "g");
2029
+ const out = [];
2030
+ for (const file of filesOf(ctx, CODE_EXTENSIONS)) {
2031
+ const src = blankSourceComments(ctx.readSource(file), path.extname(file).toLowerCase());
2032
+ for (const m of src.matchAll(key)) {
2033
+ const start = m.index + m[0].length;
2034
+ const value = valueAt(src, start);
2035
+ for (const lit of value.matchAll(LITERAL)) {
2036
+ const before = value.slice(0, lit.index).trimEnd();
2037
+ const after = value.slice(lit.index + lit[0].length);
2038
+ if (/[{,]$/.test(before) && /^\s*:/.test(after)) continue;
2039
+ out.push({
2040
+ path: `${ctx.rel(file)}:${lineAt(src, start + lit.index)}`,
2041
+ text: decode((lit[1] ?? lit[2] ?? lit[3] ?? "").replace(/\$\{[^}]*\}/g, " "))
2042
+ });
2043
+ }
2044
+ }
2045
+ }
2046
+ return out;
2047
+ };
2048
+ /** Files whose strings escape: code, and JSON and YAML data (`"pure\nErholung"`). */
2049
+ const ESCAPING = /* @__PURE__ */ new Set([
2050
+ ".ts",
2051
+ ".tsx",
2052
+ ".jsx",
2053
+ ".js",
2054
+ ".mjs",
2055
+ ".json",
2056
+ ".yml",
2057
+ ".yaml"
2058
+ ]);
2059
+ /** Tags inside a line of text: their words run on (`Ferien<em>wohnung</em>` reads „Ferienwohnung").
2060
+ * Any other tag separates words. */
2061
+ const INLINE_TAGS = new Set("a abbr b bdi bdo cite code data dfn em i kbd mark q s samp small span strong sub sup time u var wbr".split(" "));
2062
+ /** Attributes and props that carry no words a visitor reads. Every other one's value is text: a
2063
+ * `title`, `alt`, `placeholder`, `aria-label`, a component's `heading="…"`. */
2064
+ const TECHNICAL_ATTRIBUTE = /^(?:class|className|style|id|key|ref|href|src|srcset|sizes|type|rel|for|htmlFor|name|role|lang|dir|width|height|loading|decoding|fetchpriority|target|method|action|slot|tabindex|xmlns|viewBox|d|fill|stroke|data-.*|aria-(?!label$).*|on[a-z].*|client:.*|is:.*|set:.*|transition:.*)$/i;
2065
+ /** `name="…"`, `name='…'`, `name={"…"}`: the value's place in the tag (group 2, 3 or 5). */
2066
+ const ATTRIBUTE = /([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(["'`])((?:(?!\4)[^\\]|\\.)*)\4\s*\})/dg;
2067
+ /** A tag as prose: the values of its text-bearing attributes, where they stand, and nothing else.
2068
+ * An inline tag that holds none runs its words on (`Ferien<em>wohnung</em>`); any other tag, or one
2069
+ * that does, separates them. Line breaks are kept. */
2070
+ const flattenTag = (tag, name) => {
2071
+ const keep = Array.from({ length: tag.length }, () => false);
2072
+ for (const m of tag.matchAll(ATTRIBUTE)) {
2073
+ if (TECHNICAL_ATTRIBUTE.test(m[1])) continue;
2074
+ const span = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[5];
2075
+ if (span) keep.fill(true, span[0], span[1]);
2076
+ }
2077
+ const filler = INLINE_TAGS.has(name.toLowerCase()) && !keep.includes(true) ? "\0" : " ";
2078
+ return tag.split("").map((c, i) => c === "\n" || keep[i] ? c : filler).join("");
2079
+ };
2080
+ const flatten = (raw, extension) => {
2081
+ const blank = (m) => m.replace(/[^\n]/g, " ");
2082
+ const blanked = blankSourceComments(raw, extension);
2083
+ const s = (ESCAPING.has(extension) ? decodeInPlace(blanked) : blanked).replace(/<!--[\s\S]*?-->/g, blank).replace(/<\/?>/g, blank).replace(/<\/?([A-Za-z][\w.:-]*)[^>]*>/g, (tag, name) => flattenTag(tag, name)).replace(/&shy;|­/g, (m) => "\0".repeat(m.length)).replace(/&nbsp;/g, " ");
2084
+ let text = "";
2085
+ let line = 1;
2086
+ const lines = [];
2087
+ for (let i = 0; i < s.length; i += 1) {
2088
+ const c = s[i];
2089
+ if (c === "\n") line += 1;
2090
+ if (c === "\0") continue;
2091
+ if (/\s/.test(c)) {
2092
+ if (text.endsWith(" ")) continue;
2093
+ text += " ";
2094
+ } else text += c;
2095
+ lines.push(line);
2096
+ }
2097
+ return {
2098
+ text,
2099
+ lines
2100
+ };
2101
+ };
2102
+ /** Every text file under `src/` (components, pages, data, Markdown, JSON, YAML), flattened. */
2103
+ const flatSources = (ctx) => filesOf(ctx, OWN_EXTENSIONS).map((file) => ({
2104
+ rel: ctx.rel(file),
2105
+ ...flatten(ctx.readSource(file), path.extname(file).toLowerCase())
2106
+ }));
2107
+ // src/checks/ownCopy.ts
2108
+ /** The copy checks over the site's own words in `src/` (`siteTexts.ts`), never the built pages,
2109
+ * which also print the PMS feed's text: what they find is the site's to fix, so they are errors. */
2110
+ const excerpt$1 = (text, max) => {
2111
+ const flat = text.replace(/\s+/g, " ").trim();
2112
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
2113
+ };
2114
+ /** The German words a translation carries over, with the English for them. */
2115
+ const GERMANISMS = [
2116
+ [/—/, "an em dash"],
2117
+ [/\bImprint\b/, "Imprint (write Legal notice)"],
2118
+ [/\bGTC\b/, "GTC (write Terms and conditions)"],
2119
+ [/\bfinal cleaning\b/i, "final cleaning (write Cleaning fee)"],
2120
+ [/\bvacation (?:apartment|house|flat)s?\b/i, "vacation apartment/house (write Apartment, House, vacation rental)"],
2121
+ [/\bpictures?\b/i, "pictures (write Photos)"],
2122
+ [/\baccommodations\b/i, "accommodations (write stays or properties)"]
2123
+ ];
2124
+ /** Every `"en-XX"` text the site writes: no em dash, none of the Germanisms above. */
2125
+ const copyEnglish = {
2126
+ id: "copy-english",
2127
+ title: "The site's English texts read as English",
2128
+ severity: "error",
2129
+ stage: "src",
2130
+ begin: (ctx) => ({ finish: () => {
2131
+ const findings = [];
2132
+ for (const { path, text } of localizedTexts(ctx, "en")) {
2133
+ if (!/[A-Za-z]/.test(text)) continue;
2134
+ for (const [re, what] of GERMANISMS) if (re.test(text)) findings.push({
2135
+ path,
2136
+ message: `An English text uses ${what}: "${excerpt$1(text, 90)}"`
2137
+ });
2138
+ }
2139
+ return findings;
2140
+ } })
2141
+ };
2142
+ const DU_PRONOUN = "[Dd]u|[Dd]ich|[Dd]ir|[Dd]ein|[Dd]eine[mnrs]?|[Dd]eins|[Ee]uch|[Ee]uer|[Ee]uere[mnrs]?|[Ee]ure[mnrs]?";
2143
+ const SIE_PRONOUN = "Sie|Ihnen|Ihr|Ihre[mnrs]?";
2144
+ /** du commands, lower case and capitalised: a verb's -e form or bare stem is only ever a du
2145
+ * command or the first person, which „ich" marks, so they are safe on Sie text. One that clashes
2146
+ * with a noun or adjective is in `DU_COMMANDS_LOWER`; one that clashes everywhere is left out:
2147
+ * achte (ordinal), sichere (adjective), teil (the particle of „nehmen … teil"). A command this
2148
+ * misses goes into the list. */
2149
+ const DU_COMMANDS = [
2150
+ "schreib schreibe wähl wähle gib prüf prüfe versuch versuche lass lasse ändere änder setz setze zoom zoome verschieb verschiebe probier probiere sieh schau schaue meld melde rufe frag nimm hinterlass hinterlasse erzähl erzähle vergleiche entdeck entdecke stöber stöbere nutz nutze klicke tippe komm geh lies bleib gönn gönne spar spare mach mache leg lege füll lad lade hol hole merk merke find finde such reservier reserviere pack packe bring bringe genieß genieße starte schick schicke sende öffne zeig zeige wechsle trag trage kontaktier kontaktiere schließ schließe scroll scrolle",
2151
+ "bestätige bestätig akzeptiere akzeptier aktiviere aktivier deaktiviere registriere registrier logg logge abonniere abonnier informiere informier fordere fordre beschreib beschreibe nenn nenne ergänze ergänz korrigiere korrigier füg füge entferne entfern lösche lösch kopiere kopier speichere filtere sortiere sortier storniere stornier bezahl bezahle zahle beachte stell denk denke warte halte zieh ziehe drück drücke wisch wische schalt schalte hör höre sag antworte vergiss hilf wirf triff sprich iss bewirb empfiehl",
2152
+ "erleb erlebe erkunde erfahr erfahre verbring verbringe tauch tauche atme spür spüre lausch lausche wander wandere radel radle schwimm schwimme spazier spaziere fahr fahre folg lern lerne guck gucke gestalte bewerte vertrau vertraue trau traue überzeug überzeuge miet vermiete feiere koche lehn profitier profitiere"
2153
+ ].flatMap((group) => group.split(" "));
2154
+ /** du commands that are also a noun or adjective (Teile, Plane, Besuch, Fülle): lower case
2155
+ * anywhere, capitalised only at the start of a clause before „jetzt", „uns" and the like. */
2156
+ const DU_COMMANDS_LOWER = ["ruf klick tipp teile buch buche plan plane stelle fülle speicher zahl miete besuch besuche frage antwort sage lauf spiel spiele koch grill feier folge lehne wart"].flatMap((group) => group.split(" "));
2157
+ const cap = (w) => w[0].toUpperCase() + w.slice(1);
2158
+ /** Whole words only: a letter, digit or code punctuation beside the word (`/de/dir/`, `dir=ltr`)
2159
+ * makes it part of something else. */
2160
+ const word = (alt) => new RegExp(`(?<![\\p{L}\\p{N}_/.$@#=:\\[-])(?:${alt})(?![\\p{L}\\p{N}_/=@(\\[-])`, "gu");
2161
+ /** A polite command carries „Sie"; „ich" marks the first person („Gerne erzähle ich"). */
2162
+ const NOT_POLITE = "(?!\\s+(?:Sie|ich)(?![\\p{L}]))";
2163
+ /** A clause starts the text, follows . ! ? : ; or an opening quote, or follows „Bitte". */
2164
+ const CLAUSE = "(?<=(?:^|[.!?:;]\\s+|[„\"(]\\s*|[Bb]itte\\s+))";
2165
+ const CLASH_FOLLOW = "(?=\\s+(?:jetzt|gleich|direkt|sofort|online|einfach|hier|uns|mir|mal)(?![\\p{L}]))";
2166
+ const COMMANDS = [word(`(?:${[...DU_COMMANDS.flatMap((w) => [w, cap(w)]), ...DU_COMMANDS_LOWER].join("|")})${NOT_POLITE}`), word(`${CLAUSE}(?:${DU_COMMANDS_LOWER.map(cap).join("|")})${CLASH_FOLLOW}`)];
2167
+ /** The distinct words the patterns find, less the guest's own question („Wie ändere ich …"). */
2168
+ const hits = (patterns, text) => [...new Set(patterns.flatMap((re) => [...text.matchAll(re)].map((m) => m[0])))].filter((hit) => !new RegExp(`(?:^|\\s)ich\\s+${hit}(?![\\p{L}])`, "u").test(text));
2169
+ const collapse$1 = (text) => text.replace(/\s+/g, " ").trim();
2170
+ /** Every `"de-XX"` text the site writes uses the site's one form of address (`address`): no
2171
+ * pronoun of the other form, and on a Sie site no du command without a pronoun („Schreib uns.",
2172
+ * „Bitte wähle ein Land."). A polite command always carries „Sie", so a du site needs no verb
2173
+ * list. The feed's and the kit's texts are not the site's words and are not read. Waits for
2174
+ * `address`. */
2175
+ const copyAddress = {
2176
+ id: "copy-address",
2177
+ title: "The site's German texts use its one form of address",
2178
+ severity: "error",
2179
+ stage: "src",
2180
+ begin: (ctx) => {
2181
+ const { address } = ctx.options;
2182
+ if (!address) return null;
2183
+ const allowed = new Set(ctx.options.addressAllow.map(collapse$1));
2184
+ const pronoun = [word(address === "du" ? SIE_PRONOUN : DU_PRONOUN)];
2185
+ const commands = address === "du" ? [] : COMMANDS;
2186
+ return { finish: () => {
2187
+ const findings = [];
2188
+ for (const { path, text } of localizedTexts(ctx, "de")) {
2189
+ if (!/\p{L}{2}/u.test(text) || allowed.has(collapse$1(text))) continue;
2190
+ const pronouns = hits(pronoun, text);
2191
+ const verbs = hits(commands, text);
2192
+ if (pronouns.length === 0 && verbs.length === 0) continue;
2193
+ const what = [pronouns.length > 0 ? `pronoun ${pronouns.join(", ")}` : "", verbs.length > 0 ? `du command ${verbs.join(", ")}` : ""].filter(Boolean).join(" and ");
2194
+ findings.push({
2195
+ path,
2196
+ message: `A German text uses ${what}, but this site says ${address}: "${excerpt$1(text, 110)}"`
2197
+ });
2198
+ }
2199
+ return findings;
2200
+ } };
2201
+ }
2202
+ };
2203
+ /** The `bannedCopy` wordings scoped `"in": "src"`, found in the site's own text: every file under
2204
+ * `src/` with comments and tags blanked. What the feed renders never reaches it, so no page has to
2205
+ * be unchecked for the feed's sake. A file or folder named after a `copyExcludePaths` or
2206
+ * `bannedCopyExcludePaths` entry is skipped like its page (`src/pages/agb.astro` for `/agb`,
2207
+ * `src/data/faq.ts` for `/faq`), and so is every prefix in the ban's own `srcExclude`. */
2208
+ const bannedCopySrc = {
2209
+ id: "banned-copy-src",
2210
+ title: "Wordings banned by a recorded correction, in the site's own text",
2211
+ severity: "error",
2212
+ stage: "src",
2213
+ begin: (ctx) => {
2214
+ const bans = ctx.options.bannedCopy.filter((ban) => ban.in === "src");
2215
+ if (bans.length === 0) return null;
2216
+ const routeNames = [...ctx.options.copyExcludePaths, ...ctx.options.bannedCopyExcludePaths].map((entry) => entry.replace(/\/+$/, "").split("/").pop() ?? "").filter(Boolean);
2217
+ return { finish: () => {
2218
+ const findings = [];
2219
+ const sources = flatSources(ctx).filter(({ rel }) => {
2220
+ const parts = rel.replace(/\.[^/.]+$/, "").split("/");
2221
+ return !routeNames.some((name) => parts.includes(name));
2222
+ });
2223
+ for (const { pattern, why, srcExclude = [] } of bans) {
2224
+ const re = new RegExp(pattern, "g");
2225
+ for (const { rel, text, lines } of sources) {
2226
+ if (srcExclude.some((prefix) => rel.startsWith(prefix))) continue;
2227
+ for (const match of text.matchAll(re)) if (match[0]) findings.push({
2228
+ path: `${rel}:${lines[match.index] ?? 1}`,
2229
+ message: `"${excerpt$1(match[0], 70)}" is a banned wording in the site's own text: ${why}`
1403
2230
  });
1404
2231
  }
1405
- return findings;
1406
2232
  }
1407
- };
2233
+ return findings;
2234
+ } };
1408
2235
  }
1409
2236
  };
1410
- //#endregion
1411
- //#region src/checks/pageHeads.ts
2237
+ // src/checks/pageHeads.ts
1412
2238
  const MAX_TITLE = 60;
1413
2239
  const MAX_DESCRIPTION = 160;
1414
2240
  /** The head of every indexable page as a search result shows it: a title over 60 or a description
1415
2241
  * over 160 characters is cut, an empty description is replaced by whatever the crawler picks, and a
1416
- * title or description another page repeats makes the two compete. Language versions of one page
1417
- * that name each other as `<link rel="alternate" hreflang>` do not compete: a search engine shows
1418
- * the one in the searcher's language. A missing title or description is the build worker's
1419
- * `page-metadata` finding, not repeated here. A warning: the page works. */
2242
+ * title or description another page repeats makes the two compete, and a title naming the site
2243
+ * (`og:site_name`) twice spends its width on the brand. Language versions of one page that name
2244
+ * each other as `<link rel="alternate" hreflang>` do not compete: a search engine shows the one in
2245
+ * the searcher's language. A missing title or description is the build worker's `page-metadata`
2246
+ * finding, not repeated here. A warning: the page works. */
1420
2247
  const pageHeads = {
1421
2248
  id: "page-heads",
1422
2249
  title: "Titles and descriptions of indexable pages",
@@ -1435,7 +2262,7 @@ const pageHeads = {
1435
2262
  const remember = (map, value, path) => map.set(value, [...map.get(value) ?? [], path]);
1436
2263
  return {
1437
2264
  visit: (page) => {
1438
- if (page.redirect || page.noindex || page.path === "404.html") return;
2265
+ if (!isIndexable(page)) return;
1439
2266
  const own = normalize(page.url);
1440
2267
  urls.set(page.path, own);
1441
2268
  const named = /* @__PURE__ */ new Set();
@@ -1451,6 +2278,11 @@ const pageHeads = {
1451
2278
  message: `The title has ${title.length} characters; search results cut it after ${MAX_TITLE}.`
1452
2279
  });
1453
2280
  remember(titles, title, page.path);
2281
+ const siteName = page.document.querySelector("meta[property=\"og:site_name\"], meta[name=\"og:site_name\"]")?.getAttribute("content")?.trim().toLowerCase();
2282
+ if (siteName && title.toLowerCase().split(siteName).length > 2) findings.push({
2283
+ path: page.path,
2284
+ message: `The title "${title}" names the site twice; name it once, at the end.`
2285
+ });
1454
2286
  }
1455
2287
  if (description !== void 0) {
1456
2288
  if (description === "") findings.push({
@@ -1499,8 +2331,7 @@ const pageHeads = {
1499
2331
  };
1500
2332
  }
1501
2333
  };
1502
- //#endregion
1503
- //#region src/checks/pageStructure.ts
2334
+ // src/checks/pageStructure.ts
1504
2335
  /** Not in the document's structure: icon internals answer no alt or label question, template markup
1505
2336
  * is not in the page until a script clones it. */
1506
2337
  const OUTSIDE = "svg, script, style, noscript, template";
@@ -1516,19 +2347,32 @@ const SELF_NAMING = /* @__PURE__ */ new Set([
1516
2347
  const RATIO_FLOOR = 10;
1517
2348
  const RATIO_TIMES = 3;
1518
2349
  const inDocument = (page, selector) => [...page.document.querySelectorAll(selector)].filter((el) => !el.closest(OUTSIDE));
2350
+ /** A PMS document rendered by RichText (descriptions, property texts, legal documents): its
2351
+ * headings keep the document's own relative depth, so a skip between two of them is the owner's
2352
+ * text, which a nightly build can bring; the step into the block is still the site's. */
2353
+ const PMS_TEXT = "[data-part=\"rich-text\"]";
2354
+ const headings = (page) => inDocument(page, "h1, h2, h3, h4, h5, h6").map((h) => ({
2355
+ level: Number(h.tagName[1]),
2356
+ block: h.closest(PMS_TEXT)
2357
+ }));
2358
+ /** Out of the accessibility tree and out of the tab order: a widget's hidden form mirror (Base
2359
+ * UI's select and checkbox render `aria-hidden` and `tabindex="-1"` on it), which nobody reaches.
2360
+ * `aria-hidden` alone hides a control from a screen reader that the keyboard still lands on. */
2361
+ const unreachable = (control) => control.getAttribute("tabindex")?.trim() === "-1" && !!control.closest("[aria-hidden=\"true\"]");
1519
2362
  /** Each rule's fault on one page, keyed by rule id, as a printable detail. */
1520
2363
  const structureFaults = (page) => {
1521
2364
  const faults = /* @__PURE__ */ new Map();
1522
- const levels = inDocument(page, "h1, h2, h3, h4, h5, h6").map((h) => Number(h.tagName[1]));
1523
- const h1 = levels.filter((level) => level === 1).length;
2365
+ const levels = headings(page);
2366
+ const h1 = levels.filter(({ level }) => level === 1).length;
1524
2367
  if (h1 !== 1) faults.set("one-h1", h1 === 0 ? "no <h1>: a page names itself once" : `${h1} <h1>: a page names itself once`);
1525
- for (let i = 1; i < levels.length; i += 1) if (levels[i] > levels[i - 1] + 1) {
1526
- faults.set("heading-skip", `<h${levels[i - 1]}> is followed by <h${levels[i]}>`);
1527
- break;
2368
+ for (let i = 1; i < levels.length; i += 1) {
2369
+ const [before, heading] = [levels[i - 1], levels[i]];
2370
+ if (heading.block && heading.block === before.block) continue;
2371
+ if (heading.level > before.level + 1) {
2372
+ faults.set("heading-skip", `<h${before.level}> is followed by <h${heading.level}>`);
2373
+ break;
2374
+ }
1528
2375
  }
1529
- const h2 = levels.filter((level) => level === 2).length;
1530
- const h3 = levels.filter((level) => level === 3).length;
1531
- if (h3 >= RATIO_FLOOR && h3 > RATIO_TIMES * Math.max(h2, 1)) faults.set("heading-ratio", `${h3} <h3> under ${h2} <h2>: usually a card title marked up as a heading. A name on a card is a label; style a <p> to look the same`);
1532
2376
  if (inDocument(page, "main").length === 0) faults.set("landmark-main", "no <main> landmark");
1533
2377
  const noAlt = inDocument(page, "img").filter((img) => !img.hasAttribute("alt"));
1534
2378
  if (noAlt.length > 0) faults.set("img-alt", `${noAlt.length} <img> without alt, e.g. ${noAlt[0].getAttribute("src") ?? "(no src)"}`);
@@ -1536,7 +2380,7 @@ const structureFaults = (page) => {
1536
2380
  const unlabelled = inDocument(page, "input, select, textarea").filter((control) => {
1537
2381
  const type = (control.getAttribute("type") ?? "text").toLowerCase();
1538
2382
  if (control.tagName === "INPUT" && SELF_NAMING.has(type)) return false;
1539
- if (control.closest("[aria-hidden=\"true\"]")) return false;
2383
+ if (unreachable(control)) return false;
1540
2384
  if ([
1541
2385
  "aria-label",
1542
2386
  "aria-labelledby",
@@ -1560,10 +2404,11 @@ const structureFaults = (page) => {
1560
2404
  };
1561
2405
  /** The built pages' own structure, which a screen reader navigates by and nothing else reads: one
1562
2406
  * `<h1>`, no skipped heading level, a `<main>` landmark, `alt` on every image, a label on every
1563
- * control, a caption (or `aria-label`/`aria-labelledby`) and scoped headers on every table, and
1564
- * no flood of small headings under few sections. Contrast, focus order and keyboard traps are not
1565
- * decidable from static markup. A warning: the alt text of feed photos and the headings of feed
1566
- * text come from the PMS. A site declines a rule in `structureIgnore`. */
2407
+ * control, a caption (or `aria-label`/`aria-labelledby`) and scoped headers on every table.
2408
+ * Contrast, focus order and keyboard traps are not decidable from static markup. A warning on
2409
+ * every build, previews included: a site under construction sees its faults from the first build,
2410
+ * and no push waits on them; the fix is in the site's components. A site declines a rule in
2411
+ * `structureIgnore`. */
1567
2412
  const pageStructure = {
1568
2413
  id: "page-structure",
1569
2414
  title: "Page outline, landmarks, alt text, labels and tables",
@@ -1585,13 +2430,325 @@ const pageStructure = {
1585
2430
  };
1586
2431
  }
1587
2432
  };
1588
- //#endregion
1589
- //#region src/checks/rentalFacts.ts
2433
+ /** Many `<h3>` under few `<h2>`: usually card titles marked up as headings, which bury the
2434
+ * outline. A warning, apart from `page-structure`: a long index can look the same and be right.
2435
+ * `structureIgnore: ["heading-ratio"]` declines it, as it did when the rule was part of
2436
+ * `page-structure`. */
2437
+ const headingRatio = {
2438
+ id: "heading-ratio",
2439
+ title: "Small headings do not swamp the outline",
2440
+ severity: "warning",
2441
+ stage: "dist",
2442
+ begin: (ctx) => {
2443
+ if (!ctx.hasDist || ctx.options.structureIgnore.includes("heading-ratio")) return null;
2444
+ const findings = [];
2445
+ return {
2446
+ visit: (page) => {
2447
+ if (page.redirect) return;
2448
+ const levels = headings(page);
2449
+ const h2 = levels.filter(({ level }) => level === 2).length;
2450
+ const h3 = levels.filter(({ level }) => level === 3).length;
2451
+ if (h3 >= RATIO_FLOOR && h3 > RATIO_TIMES * Math.max(h2, 1)) findings.push({
2452
+ path: page.path,
2453
+ message: `${h3} <h3> under ${h2} <h2>: usually a card title marked up as a heading. A name on a card is a label; style a <p> to look the same.`
2454
+ });
2455
+ },
2456
+ finish: () => findings
2457
+ };
2458
+ }
2459
+ };
2460
+ // src/env.ts
2461
+ /** The env files a production build reads, in the order Vite applies them (a later file wins per
2462
+ * key). The `.local` pair is left out on purpose: it is the developer's machine, never what the
2463
+ * deployed site builds against, and a site must not commit it. */
2464
+ const BUILD_ENV_FILES = [".env", ".env.production"];
2465
+ /** Files Vite loads after the committed ones in every mode; committed, they win in CI too. */
2466
+ const LOCAL_ENV_FILES = [".env.local", ".env.production.local"];
2467
+ const ASSIGNMENT = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
2468
+ /** `KEY=value` lines of one env file: `export` allowed, a value in matching quotes unquoted, a
2469
+ * ` # comment` after the value (quoted or not) dropped. The last assignment of a key wins. */
2470
+ const parseEnv = (text) => {
2471
+ const env = {};
2472
+ for (const line of text.split(/\r?\n/)) {
2473
+ const match = ASSIGNMENT.exec(line);
2474
+ if (!match) continue;
2475
+ let value = match[2].trim();
2476
+ const quoted = /^(["'])(.*?)\1(?:\s+#.*)?$/.exec(value);
2477
+ value = quoted ? quoted[2] : value.replace(/\s+#.*$/, "").trim();
2478
+ env[match[1]] = value;
2479
+ }
2480
+ return env;
2481
+ };
2482
+ const readEnvFile = (root, file) => {
2483
+ const full = path.join(root, file);
2484
+ return fs.existsSync(full) ? parseEnv(fs.readFileSync(full, "utf8")) : {};
2485
+ };
2486
+ /** What a production build of the site reads from its committed env files. */
2487
+ const buildEnv = (root) => Object.assign({}, ...BUILD_ENV_FILES.map((file) => readEnvFile(root, file)));
2488
+ /** The SDK's env names (`SDK_ENV` in `@v-office/website-headless`) a build reads, and the two v9
2489
+ * config switches of the Website SDK CLI. */
2490
+ const SDK_NAMES = [
2491
+ "CMS_BACKEND",
2492
+ "CMS_STAGE",
2493
+ "HUB_API_KEY",
2494
+ "HUB_GRAPHQL_URL",
2495
+ "HUB_V0_API_BASE_URL",
2496
+ "HUB_V1_API_BASE_URL",
2497
+ "IMAGE_PROXY_BASE_URL",
2498
+ "VOFFICE_LOCAL_DEV_ACCESS_TOKEN",
2499
+ "VOFFICE_API_ENDPOINT",
2500
+ "VOFFICE_SEARCH_ENDPOINT",
2501
+ "VOFFICE_IMAGE_BASE_URL",
2502
+ "HUB_RENTAL_SCOPE_PROPERTY_KIND",
2503
+ "HUB_RENTAL_IDS_SEARCH"
2504
+ ];
2505
+ /** The env name the SDK reads a backend's token under (`SDK_ENV` in `@v-office/website-headless`). */
2506
+ const TOKEN_NAMES = {
2507
+ v9: "HUB_API_KEY",
2508
+ v10: "VOFFICE_LOCAL_DEV_ACCESS_TOKEN"
2509
+ };
2510
+ /** The SDK env the build runs with, resolved the way the site starter does: a value in the
2511
+ * process env wins over the committed files (Vite's order), and what neither sets comes from what
2512
+ * AI Studio's builder passes: the website's PMS generation as `PMS_BACKEND`, its key as
2513
+ * `PMS_TOKEN` (`HUB_API_KEY` on v9, `VOFFICE_LOCAL_DEV_ACCESS_TOKEN` on v10). A template site
2514
+ * commits no backend, so without the fallback a v9 site there would read as no site at all. */
2515
+ const sdkEnv = (root, processEnv = process.env) => {
2516
+ const env = {};
2517
+ for (const [name, value] of Object.entries(buildEnv(root))) if (value.trim()) env[name] = value.trim();
2518
+ for (const name of SDK_NAMES) {
2519
+ const value = processEnv[name]?.trim();
2520
+ if (value) env[name] = value;
2521
+ }
2522
+ if (!env.CMS_BACKEND && processEnv.PMS_BACKEND?.trim()) env.CMS_BACKEND = processEnv.PMS_BACKEND.trim();
2523
+ const token = TOKEN_NAMES[env.CMS_BACKEND ?? ""];
2524
+ if (token && !env[token] && processEnv.PMS_TOKEN?.trim()) env[token] = processEnv.PMS_TOKEN.trim();
2525
+ return env;
2526
+ };
2527
+ /** What the developer's `.local` files set. */
2528
+ const localEnv = (root) => Object.assign({}, ...LOCAL_ENV_FILES.map((file) => readEnvFile(root, file)));
2529
+ // src/checks/v9.ts
2530
+ /** The be-on! Hub endpoints per stage, as `@v-office/website-headless` resolves `CMS_STAGE` for v9
2531
+ * (`sdk/endpoints.ts`). Production is what a live v9 site calls. */
2532
+ const HUB = {
2533
+ production: {
2534
+ api: "https://api.voffice.be-on.io",
2535
+ imageProxy: "https://imgproxy.voffice.be-on.io"
2536
+ },
2537
+ development: {
2538
+ api: "https://api.voffice.demo-on.de",
2539
+ imageProxy: "https://imgproxy.voffice.demo-on.de"
2540
+ }
2541
+ };
2542
+ const hubUrls = (stage) => ({
2543
+ HUB_V1_API_BASE_URL: `${HUB[stage].api}/api/v1`,
2544
+ HUB_V0_API_BASE_URL: `${HUB[stage].api}/api/v0`,
2545
+ HUB_GRAPHQL_URL: `${HUB[stage].api}/graphql`,
2546
+ IMAGE_PROXY_BASE_URL: HUB[stage].imageProxy
2547
+ });
2548
+ /** The build's SDK env, when it builds a v9 site: `CMS_BACKEND=v9` from the process env, the
2549
+ * committed `.env` / `.env.production`, or AI Studio's `PMS_BACKEND` (`sdkEnv`). Every v9 check
2550
+ * starts here, so a v10 site, or one with no backend at all, never runs one. */
2551
+ const v9Env = (ctx) => {
2552
+ const env = sdkEnv(ctx.root);
2553
+ return env.CMS_BACKEND === "v9" ? env : null;
2554
+ };
2555
+ /** How long the Hub may take to answer before the check gives up. */
2556
+ const HUB_TIMEOUT_MS = 6e4;
2557
+ /** The Website SDK CLI's v9 config, from the build's SDK env (`sdkEnv`): the stage's endpoints with
2558
+ * `CMS_STAGE`, else the URL variables, and the key. */
2559
+ const cliConfig = (env) => {
2560
+ const stage = env.CMS_STAGE === "production" || env.CMS_STAGE === "development" ? env.CMS_STAGE : void 0;
2561
+ const urls = stage ? hubUrls(stage) : env;
2562
+ return {
2563
+ backend: "v9",
2564
+ apiKey: env.HUB_API_KEY ?? "",
2565
+ graphqlUrl: urls.HUB_GRAPHQL_URL ?? "",
2566
+ imageProxyBaseUrl: urls.IMAGE_PROXY_BASE_URL ?? "",
2567
+ ...urls.HUB_V0_API_BASE_URL ? { v0ApiBaseUrl: urls.HUB_V0_API_BASE_URL } : {},
2568
+ ...urls.HUB_V1_API_BASE_URL ? { v1ApiBaseUrl: urls.HUB_V1_API_BASE_URL } : {},
2569
+ ...env.HUB_RENTAL_SCOPE_PROPERTY_KIND === "facility" || env.HUB_RENTAL_SCOPE_PROPERTY_KIND === "objectGroup" ? { rentalScopePropertyKind: env.HUB_RENTAL_SCOPE_PROPERTY_KIND } : {},
2570
+ ...env.HUB_RENTAL_IDS_SEARCH === "true" || env.HUB_RENTAL_IDS_SEARCH === "false" ? { rentalIdsSearch: env.HUB_RENTAL_IDS_SEARCH === "true" } : {}
2571
+ };
2572
+ };
2573
+ const sdkVersion = (root) => {
2574
+ try {
2575
+ const file = path.join(root, "node_modules", "@v-office", "website-sdk", "package.json");
2576
+ return JSON.parse(fs.readFileSync(file, "utf8")).version ?? "unknown version";
2577
+ } catch {
2578
+ return "unknown version";
2579
+ }
2580
+ };
2581
+ const run = async (cli, args, cwd) => {
2582
+ const { execFile } = await import("node:child_process");
2583
+ return new Promise((resolve) => {
2584
+ execFile(cli, args, {
2585
+ cwd,
2586
+ timeout: HUB_TIMEOUT_MS,
2587
+ maxBuffer: 1048576
2588
+ }, (err, stdout, stderr) => resolve({
2589
+ code: err ? typeof err.code === "number" ? err.code : 1 : 0,
2590
+ output: `${stdout}${stderr}`.trim()
2591
+ }));
2592
+ });
2593
+ };
2594
+ /** The backend-filter definitions a v9 site passes to the SDK, as its own data file. */
2595
+ const HUB_FILTERS_FILE = path.join("data", "hub-filters.json");
2596
+ /** Every be-on! Hub filter the site's search needs (the scope filter, the Merkliste's rental-id
2597
+ * filter, each searchable backend-filter definition) exists in the Hub the site builds against.
2598
+ * A filter the Hub does not serve matches nothing, or everything once a date is set. Asks the Hub
2599
+ * through the site's own `website-sdk hub-filters check`, with the build's env and the SDK
2600
+ * options in `hubFilterOptions`; the site's own list in `src/data/hub-filters.json`, when it has
2601
+ * one, is the `customAttributeFilterDefinitions`, so no copy of it can drift. A warning: the
2602
+ * outcome is the Hub's data, and a Hub that cannot be asked must not stop the nightly builds; it
2603
+ * is reported, never passed. v9 only. */
2604
+ const v9HubFilters = {
2605
+ id: "v9-hub-filters",
2606
+ title: "The be-on! Hub serves the filters the v9 site needs",
2607
+ severity: "warning",
2608
+ stage: "src",
2609
+ begin: (ctx) => {
2610
+ const env = v9Env(ctx);
2611
+ if (!env) return null;
2612
+ return { finish: async () => {
2613
+ let hubFilterOptions = ctx.options.hubFilterOptions;
2614
+ const listFile = path.join(ctx.srcDir, HUB_FILTERS_FILE);
2615
+ if (fs.existsSync(listFile)) {
2616
+ let list;
2617
+ try {
2618
+ list = JSON.parse(fs.readFileSync(listFile, "utf8"));
2619
+ } catch {}
2620
+ if (!Array.isArray(list)) return [{
2621
+ path: ctx.rel(listFile),
2622
+ message: `${ctx.rel(listFile)} is not a JSON array of filter definitions, so the Hub could not be asked.`
2623
+ }];
2624
+ hubFilterOptions = {
2625
+ ...hubFilterOptions,
2626
+ customAttributeFilterDefinitions: list
2627
+ };
2628
+ }
2629
+ const cli = path.join(ctx.root, "node_modules", ".bin", process.platform === "win32" ? "website-sdk.cmd" : "website-sdk");
2630
+ if (!fs.existsSync(cli)) return [{ message: "node_modules/.bin/website-sdk is missing, so the Hub could not be asked. Install @v-office/website-sdk." }];
2631
+ const config = cliConfig(env);
2632
+ if (!config.apiKey || !config.graphqlUrl) return [{ message: "No HUB_API_KEY or Hub URLs in the build's env, so the Hub could not be asked." }];
2633
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "site-checks-hub-"));
2634
+ try {
2635
+ const configFile = path.join(dir, "config.json");
2636
+ const optionsFile = path.join(dir, "options.json");
2637
+ fs.writeFileSync(configFile, JSON.stringify(config));
2638
+ fs.writeFileSync(optionsFile, JSON.stringify(hubFilterOptions));
2639
+ const { code, output } = await run(cli, [
2640
+ "--backend",
2641
+ "v9",
2642
+ "--config",
2643
+ configFile,
2644
+ "--options",
2645
+ optionsFile,
2646
+ "hub-filters",
2647
+ "check"
2648
+ ], ctx.root);
2649
+ if (code === 0) return [];
2650
+ if (/Unknown subcommand "hub-filters"/.test(output)) return [{ message: `The installed @v-office/website-sdk (${sdkVersion(ctx.root)}) has no \`hub-filters check\`, so the Hub could not be asked. Update @v-office/website-sdk.` }];
2651
+ return [{ message: `The be-on! Hub (${new URL(config.graphqlUrl).host}) does not serve every filter the site needs: ${output || `website-sdk exited ${code}`} Add the missing entries in the Hub (website-sdk hub-filters request) or drop them from the site's SDK options.` }];
2652
+ } finally {
2653
+ fs.rmSync(dir, {
2654
+ recursive: true,
2655
+ force: true
2656
+ });
2657
+ }
2658
+ } };
2659
+ }
2660
+ };
2661
+ // src/checks/productionEnv.ts
2662
+ /** The v10 endpoints of production, as `@v-office/website-headless` resolves `CMS_STAGE`
2663
+ * (`sdk/endpoints.ts`, `VOFFICE_ENDPOINTS`). */
2664
+ const V10_PRODUCTION = {
2665
+ VOFFICE_API_ENDPOINT: "https://api.production.v-office.io",
2666
+ VOFFICE_SEARCH_ENDPOINT: "https://search.production.v-office.io/search",
2667
+ VOFFICE_IMAGE_BASE_URL: "https://images.production.v-office.io"
2668
+ };
2669
+ const sameUrl = (a, b) => (a ?? "").replace(/\/+$/, "") === b.replace(/\/+$/, "");
2670
+ /** The `.local` env files git tracks; empty outside a git checkout (nothing to tell then). */
2671
+ const committedLocalFiles = async (root) => {
2672
+ const { execFileSync } = await import("node:child_process");
2673
+ return LOCAL_ENV_FILES.filter((file) => {
2674
+ try {
2675
+ execFileSync("git", [
2676
+ "ls-files",
2677
+ "--error-unmatch",
2678
+ "--",
2679
+ file
2680
+ ], {
2681
+ cwd: root,
2682
+ stdio: "ignore"
2683
+ });
2684
+ return true;
2685
+ } catch {
2686
+ return false;
2687
+ }
2688
+ });
2689
+ };
2690
+ const WHERE = `the build's env (${BUILD_ENV_FILES.join(" / ")} or the process env)`;
2691
+ /** A launched site of one PMS generation builds against that PMS's production: the build's env says
2692
+ * `CMS_STAGE=production`, or names the production endpoints. The endpoints are baked in at build
2693
+ * time, so a site built against the development PMS renders fine, only with the test catalogue.
2694
+ * Also reported: a committed `.env.local` (Vite loads it after `.env` in every mode, so CI builds
2695
+ * from it) and a committed token that is the developer's own, from `.env.local`. Waits while every
2696
+ * page is noindex, and while the Astro `site` is a preview host or unset: before launch a site
2697
+ * builds against the test PMS on purpose. An error: every finding is the site's own env. A token
2698
+ * the build's env lacks is no finding: AI Studio's builder passes it (`PMS_TOKEN`), and a build
2699
+ * without one fails in the SDK before any check runs. */
2700
+ const productionEnv = (base, backend, pms, expected) => ({
2701
+ ...base,
2702
+ severity: "error",
2703
+ stage: "dist",
2704
+ begin: (ctx) => {
2705
+ const env = sdkEnv(ctx.root);
2706
+ if (env.CMS_BACKEND !== backend) return null;
2707
+ return whenLaunched(ctx, async () => {
2708
+ const findings = [];
2709
+ for (const file of await committedLocalFiles(ctx.root)) findings.push({
2710
+ path: file,
2711
+ message: `${file} is committed: Vite loads it after .env in every mode, so the live site builds from it. Untrack it (git rm --cached) and keep it ignored.`
2712
+ });
2713
+ if (env.CMS_STAGE) {
2714
+ if (env.CMS_STAGE !== "production") findings.push({
2715
+ path: ".env",
2716
+ message: `CMS_STAGE is "${env.CMS_STAGE}" in ${WHERE}: the live site calls the ${env.CMS_STAGE} ${pms}. Set CMS_STAGE=production.`
2717
+ });
2718
+ } else {
2719
+ const wrong = Object.keys(expected).filter((name) => !sameUrl(env[name], expected[name]));
2720
+ if (wrong.length > 0) findings.push({
2721
+ path: ".env",
2722
+ message: `${WHERE[0].toUpperCase()}${WHERE.slice(1)} does not call the production ${pms}: ${wrong.map((name) => `${name}=${env[name] || "(unset)"}`).join(", ")}. Set ${wrong.map((name) => `${name}=${expected[name]}`).join(", ")}, or CMS_STAGE=production without the URLs.`
2723
+ });
2724
+ }
2725
+ const name = TOKEN_NAMES[backend];
2726
+ const token = env[name];
2727
+ if (token && token === localEnv(ctx.root)[name]) findings.push({
2728
+ path: ".env",
2729
+ message: backend === "v9" ? "HUB_API_KEY in the build's env is the key of .env.local, the developer's key: production needs this customer's production key, which be-on! issues." : "VOFFICE_LOCAL_DEV_ACCESS_TOKEN in the build's env is the token of .env.local, the developer's token: production needs the customer's token from the production environment."
2730
+ });
2731
+ return findings;
2732
+ });
2733
+ }
2734
+ });
2735
+ /** v9: the production be-on! Hub. */
2736
+ const v9ProductionHub = productionEnv({
2737
+ id: "v9-production-hub",
2738
+ title: "A launched v9 site calls the production Hub"
2739
+ }, "v9", "Hub", hubUrls("production"));
2740
+ /** v10: the production vOffice API. */
2741
+ const v10ProductionApi = productionEnv({
2742
+ id: "v10-production-api",
2743
+ title: "A launched v10 site calls the production vOffice API"
2744
+ }, "v10", "vOffice API", V10_PRODUCTION);
2745
+ // src/checks/rentalFacts.ts
1590
2746
  /** The markers the platform's rental blocks carry for this check (`GATE_MARKERS` in
1591
2747
  * `@v-office/website-headless`): the fact row, the owner's description, the amenity section and
1592
- * its all-amenities dialog. */
2748
+ * its all-amenities dialog. A site's own layout may put facts in a chip row marked
2749
+ * `data-rental-facts` as well: both are read, or the facts in the other one go unchecked. */
1593
2750
  const MARKERS = {
1594
- stats: "[data-rental-stats]",
2751
+ stats: "[data-rental-stats], [data-rental-facts]",
1595
2752
  description: "[data-rental-description]",
1596
2753
  amenities: "[data-rental-amenities]",
1597
2754
  amenitiesModal: "[data-amenities-modal]"
@@ -1616,17 +2773,20 @@ const WORDS = {
1616
2773
  elf: 11,
1617
2774
  zwölf: 12
1618
2775
  };
1619
- /** Grouped thousands first, or `\d+` matches only the tail: "2.000 m²" would read as 0. Never the
1620
- * tail of a decimal ("2,5 Badezimmer" is no count of 5) or of a longer word ("dreizehn" is not
1621
- * "zehn": a compound number is not read at all). */
1622
- const NUM = `(?<![\\d.,\\p{L}])(\\d{1,3}(?:\\.\\d{3})+|\\d+|${Object.keys(WORDS).join("|")})`;
2776
+ /** Grouped thousands first, or `\d+` matches only the tail: "2.000 m²" would read as 0. A decimal
2777
+ * comma is part of the number ("4,5 Badezimmer" is 4.5). Never the tail of a decimal ("2.5" is no
2778
+ * count of 5) or of a longer word ("dreizehn" is not "zehn": a compound number is not read at
2779
+ * all); a dot after a word is no decimal ("ca.130 qm" is 130). */
2780
+ const NUM = `(?<![\\d\\p{L}])(?<!\\d[.,])(\\d{1,3}(?:\\.\\d{3})+|\\d+(?:,\\d+)?|${Object.keys(WORDS).join("|")})`;
1623
2781
  /** "ca." / "etwa" / "rund": the author's own approximation, a rounded statement. The group is
1624
2782
  * load-bearing: without it `?` binds to the trailing `\s*` and only hedged figures match. */
1625
2783
  const HEDGE = "(?:(?:ca\\.|etwa|rund)\\s*)";
1626
2784
  const toNumber = (token) => {
1627
2785
  const plain = token.replace(/\./g, "");
1628
- return /^\d+$/.test(plain) ? Number(plain) : WORDS[plain.toLowerCase()] ?? NaN;
2786
+ return /^\d+(?:,\d+)?$/.test(plain) ? Number(plain.replace(",", ".")) : WORDS[plain.toLowerCase()] ?? NaN;
1629
2787
  };
2788
+ /** A count as the finding and its `factCheckAccepted` key write it: 2, or 2,5. */
2789
+ const german = (value) => String(value).replace(".", ",");
1630
2790
  /** Prose pattern (group 1 the number) and fact pattern (group 1 the number, or `km` a kilometre
1631
2791
  * figure), in every form a site renders and the older ones. Prose is matched case-insensitively:
1632
2792
  * a sentence may open with the number word ("Drei Schlafzimmer …"). */
@@ -1665,15 +2825,23 @@ const PART_KINDS = /* @__PURE__ */ new Set([
1665
2825
  "bathrooms"
1666
2826
  ]);
1667
2827
  /** Occupancy only: a capacity that belongs to a room or a furnishing ("eine Sauna für bis zu zwei
1668
- * Personen"). Never applied to other kinds: "Zimmer" is inside "Badezimmer" and "Schlafzimmer". */
1669
- const NOT_CAPACITY = /Schlafzimmer|Zimmer|Bett|Sofa|Couch|Küche|Tisch|Essplatz|Essbereich|Sauna|Whirlpool|Gartenmöbel|Terrasse|Sitzgruppe|Balkon/i;
2828
+ * Personen", "Geschirr für 8 Personen"). Never applied to other kinds: "Zimmer" is inside
2829
+ * "Badezimmer" and "Schlafzimmer". */
2830
+ const NOT_CAPACITY = /Schlafzimmer|Zimmer|Bett|Sofa|Couch|Küche|Tisch|Essplatz|Essbereich|Sauna|Whirlpool|Gartenmöbel|Terrasse|Sitzgruppe|Balkon|Geschirr|Besteck|Gläser|Tassen|Kochutensilien/i;
2831
+ /** Occupancy only: the capacity of this unit combined with another ("kann mit der Nachbarwohnung
2832
+ * kombiniert werden und bietet so Platz für 8 Personen"). "kombiniert" alone is not enough: "Die
2833
+ * Wohnung kombiniert Komfort mit Tradition" still states the unit's own. */
2834
+ const COMBINED = /kombinierbar|kombinieren|kombiniert\s+(?:werden|und)|in Kombination mit|(?:zusammen|gemeinsam|dazu|hinzu|zusätzlich)\s*(?:ge)?buch|Nachbar(?:wohnung|haus|apartment|appartement)|benachbarte[nrsm]?\s+(?:Ferien)?(?:wohnung|haus|apartment|appartement)/i;
1670
2835
  /** The unit as the clause's subject: whichever subject comes first governs the claim. */
1671
2836
  const UNIT_SUBJECT = /Ferienwohnung|Ferienhaus|Wohnung|Apartment|Appartement|Unterkunft|Ferienunterkunft|Objekt|Haus\b|Hauses\b/i;
1672
2837
  /** ':' ends a clause too: in "… Bereich des Hauses: Eine Sauna für …" the sauna governs. */
1673
2838
  const CLAUSE_END = /[.!?•:]/g;
1674
2839
  /** A part stated alone, with no total on the page ("im Erdgeschoss zwei Schlafzimmer"). Loose
1675
2840
  * stems: feeds carry typos ("Erdgschoss") and both the -ss and -ß spellings. */
1676
- const PART_SCOPE = /(?:Erd|Ober|Dach|Unter|Zwischen)g\p{L}*scho|Souterrain|Etage|Stockwerk|die anderen|die beiden anderen|weitere[nrs]?(?![\p{L}])/iu;
2841
+ const PART_SCOPE = /(?:Erd|Ober|Dach|Unter|Zwischen)g\p{L}*scho|Souterrain|Etage|Stockwerk|Gescho[sß]|Ebene(?![\p{L}])|die anderen|die beiden anderen|weitere[nrs]?(?![\p{L}])/iu;
2842
+ /** The floor abbreviations ("im EG 1 Schlafzimmer, im OG 2", "im 1. OG"), case-sensitive: "eg" and
2843
+ * "og" are no floors. */
2844
+ const FLOOR_ABBREVIATION = /(?<![\p{L}])(?:EG|OG|UG|DG|KG)(?![\p{L}])/u;
1677
2845
  const OUTDOOR_SCOPE = /Grundst\p{L}*ck|Garten|Gartens|Terrasse|Wiese|Parzelle|Areal|Rasen|Außenbereich|Hofst\p{L}*|Innenhof/iu;
1678
2846
  const clauseBefore = (prose, start) => {
1679
2847
  let from = 0;
@@ -1690,7 +2858,12 @@ const roomScoped = (prose, start) => {
1690
2858
  /** German puts the noun after the measurement ("auf einem 3000 m² großen Grundstück"), so this
1691
2859
  * looks both ways. */
1692
2860
  const outdoorScoped = (prose, start, end) => OUTDOOR_SCOPE.test(`${clauseBefore(prose, start)} ${prose.slice(end, end + 60).split(".")[0]}`);
1693
- const partScoped = (prose, start) => PART_SCOPE.test(clauseBefore(prose, start));
2861
+ /** Both ways, to the sentence's end: "Platz für 7 Personen, wenn Sie die Nachbarwohnung dazubuchen". */
2862
+ const combinedScoped = (prose, start, end) => COMBINED.test(`${clauseBefore(prose, start)} ${prose.slice(end, end + 200).split(/[.!?]/)[0]}`);
2863
+ const partScoped = (prose, start) => {
2864
+ const clause = clauseBefore(prose, start);
2865
+ return PART_SCOPE.test(clause) || FLOOR_ABBREVIATION.test(clause);
2866
+ };
1694
2867
  /** The first fact a kind reads, with its tolerance: a km fact is metres rounded to its last digit
1695
2868
  * ("4,2 km" is 4150–4250 m), every other fact is exact. */
1696
2869
  const factValue = (pattern, facts) => {
@@ -1733,13 +2906,15 @@ const scanRental = (slug, input) => {
1733
2906
  let agrees = false;
1734
2907
  for (const match of prose.matchAll(proseRe)) {
1735
2908
  const start = match.index;
1736
- if (kind === "occupancy" && roomScoped(prose, start)) continue;
1737
- if (kind === "area" && outdoorScoped(prose, start, start + match[0].length)) continue;
2909
+ const end = start + match[0].length;
2910
+ if (kind === "occupancy" && (roomScoped(prose, start) || combinedScoped(prose, start, end))) continue;
2911
+ if (kind === "area" && outdoorScoped(prose, start, end)) continue;
1738
2912
  const got = toNumber(match[1]);
1739
2913
  if (Number.isNaN(got)) continue;
1740
2914
  if (PART_KINDS.has(kind) && got < value && partScoped(prose, start)) continue;
1741
2915
  compared += 1;
1742
- if (Math.abs(got - value) <= tolerance) {
2916
+ const diff = Math.abs(got - value);
2917
+ if (diff <= tolerance || !Number.isInteger(got) && diff < 1) {
1743
2918
  agrees = true;
1744
2919
  continue;
1745
2920
  }
@@ -1750,8 +2925,8 @@ const scanRental = (slug, input) => {
1750
2925
  if (agrees && PART_KINDS.has(kind) && got <= value) continue;
1751
2926
  found.push({
1752
2927
  kind,
1753
- key: `${slug} ${kind} prose=${got} feed=${value}`,
1754
- message: `The description says ${got}${hedged ? " (approximately)" : ""}, the ${kind} fact says ${value}. Both come from the PMS: the customer corrects one of them there.`
2928
+ key: `${slug} ${kind} prose=${german(got)} feed=${value}`,
2929
+ message: `The description says ${german(got)}${hedged ? " (approximately)" : ""}, the ${kind} fact says ${value}. Both come from the PMS: the customer corrects one of them there.`
1755
2930
  });
1756
2931
  }
1757
2932
  }
@@ -1780,34 +2955,42 @@ const rentalFacts = {
1780
2955
  stage: "dist",
1781
2956
  begin: (ctx) => {
1782
2957
  if (!ctx.hasDist) return null;
1783
- const accepted = new Set(ctx.options.factCheckAccepted.map((line) => line.trim().split(/\s+/).join(" ")));
2958
+ const accepted = new Set(ctx.options.factCheckAccepted.map((line) => line.trim().split(/\s+/).join(" ")).filter((line) => line !== ""));
1784
2959
  const perksFile = path.join(ctx.root, PERKS_FILE);
1785
2960
  const perks = fs.existsSync(perksFile) ? [...fs.readFileSync(perksFile, "utf8").matchAll(/^\s*"([^"]+)",\s*$/gm)].map((m) => m[1]) : [];
1786
2961
  const findings = [];
1787
2962
  const seen = /* @__PURE__ */ new Set();
1788
2963
  let marked = 0;
2964
+ let compared = 0;
2965
+ let undescribed = 0;
2966
+ let firstMarked;
1789
2967
  let unmarked;
1790
2968
  return {
1791
2969
  visit: (page) => {
1792
2970
  if (page.redirect) return;
1793
2971
  const { document } = page;
1794
2972
  const stats = [...document.querySelectorAll(MARKERS.stats)];
1795
- if (stats.length === 0) {
2973
+ if (stats.length === 0 || !isRentalPage(document)) {
1796
2974
  if (document.querySelector(FACTS_PART)) unmarked ??= page.path;
1797
2975
  return;
1798
2976
  }
1799
2977
  marked += 1;
2978
+ firstMarked ??= page.path;
1800
2979
  const description = document.querySelector(MARKERS.description);
1801
- if (!description) return;
2980
+ if (!description) {
2981
+ undescribed += 1;
2982
+ return;
2983
+ }
1802
2984
  const facts = stats.flatMap((row) => [...row.querySelectorAll("span")].map((span) => (span.textContent ?? "").replace(/\s+/g, " ").trim()));
1803
2985
  const slug = slugOf(page);
1804
- const { found } = scanRental(slug, {
2986
+ const scanned = scanRental(slug, {
1805
2987
  facts,
1806
2988
  prose: textOf(description),
1807
2989
  amenities: textOf(document.querySelector(MARKERS.amenitiesModal) ?? document.querySelector(MARKERS.amenities)),
1808
2990
  perks
1809
2991
  });
1810
- for (const f of found) {
2992
+ compared += scanned.compared;
2993
+ for (const f of scanned.found) {
1811
2994
  seen.add(f.key);
1812
2995
  if (!accepted.has(f.key)) findings.push({
1813
2996
  path: page.path,
@@ -1820,7 +3003,11 @@ const rentalFacts = {
1820
3003
  path: unmarked,
1821
3004
  message: "The rental fact row carries no data-rental-stats marker, so no rental page was compared. The marker comes from @v-office/website-components; a site's own fact row adds it."
1822
3005
  });
1823
- if (marked > 0) {
3006
+ if (firstMarked && compared === 0) findings.push({
3007
+ path: firstMarked,
3008
+ message: `${marked === 1 ? "A rental page carries" : `${marked} rental pages carry`} the fact row, but no fact was compared on any of them: ` + (undescribed > 0 ? `${undescribed} of them have no data-rental-description marker on the owner's description, or ` : "") + "no description states a figure the fact row shows (guests, bedrooms, bathrooms, m², beach). Mark the description, or exclude this finding where the descriptions state no figures."
3009
+ });
3010
+ if (compared > 0) {
1824
3011
  for (const key of accepted) if (!seen.has(key)) findings.push({ message: `factCheckAccepted lists "${key}", which no longer disagrees: remove the entry.` });
1825
3012
  }
1826
3013
  return findings;
@@ -1828,358 +3015,287 @@ const rentalFacts = {
1828
3015
  };
1829
3016
  }
1830
3017
  };
1831
- //#endregion
1832
- //#region src/checks/syncOnce.ts
1833
- const LOADER_FILES = ["src/content.config.ts", "src/content/config.ts"];
1834
- /** A loader written inline, as opposed to `glob()` or `file()`. */
1835
- const INLINE_LOADER = /\bloader\s*:\s*\{/;
1836
- /** It talks to the PMS. */
1837
- const LIVE_FETCH = /\bfetch\s*\(|createWebsiteSDK|createVofficeSdk|\.static\./;
1838
- /** The reuse idiom: the loader keeps the sync token in the store's meta and, when the token the
1839
- * build was started with is still the same, serves the entries it already has. */
1840
- const REUSE_IDIOM = [
1841
- /CONTENT_SYNC_TOKEN/,
1842
- /\bmeta\.get\(/,
1843
- /\bstore\.keys\(\)/
1844
- ];
1845
- /** `astro check` and `astro build` each run the content loader, so an unguarded loader pays every
1846
- * remote fetch twice on every build, against a rate-limited PMS. The build worker starts both with
1847
- * one `CONTENT_SYNC_TOKEN`; a loader that keys its store on it syncs once. A text heuristic, hence
1848
- * a warning. */
1849
- const syncOnce = {
1850
- id: "sync-once",
1851
- title: "Content loaders sync the PMS once per build",
1852
- severity: "warning",
1853
- stage: "src",
1854
- begin: (ctx) => {
1855
- const loader = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts"])).find((file) => LOADER_FILES.includes(ctx.rel(file)));
1856
- if (!loader) return null;
1857
- return { finish: () => {
1858
- const text = ctx.readSource(loader);
1859
- if (!INLINE_LOADER.test(text) || !LIVE_FETCH.test(text)) return [];
1860
- if (REUSE_IDIOM.every((idiom) => idiom.test(text))) return [];
1861
- return [{
1862
- path: ctx.rel(loader),
1863
- message: "A content loader fetches the PMS without the CONTENT_SYNC_TOKEN idiom; astro check and astro build each sync it, twice per build. Keep the token in the store's meta (meta.get) and reuse the entries (store.keys()) when it matches."
1864
- }];
1865
- } };
1866
- }
1867
- };
1868
- //#endregion
1869
- //#region src/env.ts
1870
- /** The env files a production build reads, in the order Vite applies them (a later file wins per
1871
- * key). The `.local` pair is left out on purpose: it is the developer's machine, never what the
1872
- * deployed site builds against, and a site must not commit it. */
1873
- const BUILD_ENV_FILES = [".env", ".env.production"];
1874
- /** Files Vite loads after the committed ones in every mode; committed, they win in CI too. */
1875
- const LOCAL_ENV_FILES = [".env.local", ".env.production.local"];
1876
- const ASSIGNMENT = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
1877
- /** `KEY=value` lines of one env file: `export` allowed, a value in matching quotes unquoted, a
1878
- * ` # comment` after the value (quoted or not) dropped. The last assignment of a key wins. */
1879
- const parseEnv = (text) => {
1880
- const env = {};
1881
- for (const line of text.split(/\r?\n/)) {
1882
- const match = ASSIGNMENT.exec(line);
1883
- if (!match) continue;
1884
- let value = match[2].trim();
1885
- const quoted = /^(["'])(.*?)\1(?:\s+#.*)?$/.exec(value);
1886
- value = quoted ? quoted[2] : value.replace(/\s+#.*$/, "").trim();
1887
- env[match[1]] = value;
1888
- }
1889
- return env;
1890
- };
1891
- const readEnvFile = (root, file) => {
1892
- const full = path.join(root, file);
1893
- return fs.existsSync(full) ? parseEnv(fs.readFileSync(full, "utf8")) : {};
1894
- };
1895
- /** What a production build of the site reads from its committed env files. */
1896
- const buildEnv = (root) => Object.assign({}, ...BUILD_ENV_FILES.map((file) => readEnvFile(root, file)));
1897
- /** The SDK's env names (`SDK_ENV` in `@v-office/website-headless`) a build reads, and the two v9
1898
- * config switches of the Website SDK CLI. */
1899
- const SDK_NAMES = [
1900
- "CMS_BACKEND",
1901
- "CMS_STAGE",
1902
- "HUB_API_KEY",
1903
- "HUB_GRAPHQL_URL",
1904
- "HUB_V0_API_BASE_URL",
1905
- "HUB_V1_API_BASE_URL",
1906
- "IMAGE_PROXY_BASE_URL",
1907
- "HUB_RENTAL_SCOPE_PROPERTY_KIND",
1908
- "HUB_RENTAL_IDS_SEARCH"
3018
+ // src/checks/robotsTxt.ts
3019
+ /** The extensions an Astro endpoint is written in. */
3020
+ const ENDPOINT_EXTENSIONS = [
3021
+ ".ts",
3022
+ ".js",
3023
+ ".mjs",
3024
+ ".mts"
1909
3025
  ];
1910
- /** The SDK env the build runs with, resolved the way the site starter does: a value in the
1911
- * process env wins over the committed files (Vite's order), and what neither sets comes from what
1912
- * AI Studio's builder passes: the website's PMS generation as `PMS_BACKEND`, its key as
1913
- * `PMS_TOKEN`. A template site commits no backend, so without the fallback a v9 site there would
1914
- * read as no site at all. */
1915
- const sdkEnv = (root, processEnv = process.env) => {
1916
- const env = {};
1917
- for (const [name, value] of Object.entries(buildEnv(root))) if (value.trim()) env[name] = value.trim();
1918
- for (const name of SDK_NAMES) {
1919
- const value = processEnv[name]?.trim();
1920
- if (value) env[name] = value;
1921
- }
1922
- if (!env.CMS_BACKEND && processEnv.PMS_BACKEND?.trim()) env.CMS_BACKEND = processEnv.PMS_BACKEND.trim();
1923
- if (env.CMS_BACKEND === "v9" && !env.HUB_API_KEY && processEnv.PMS_TOKEN?.trim()) env.HUB_API_KEY = processEnv.PMS_TOKEN.trim();
1924
- return env;
1925
- };
1926
- /** What the developer's `.local` files set. */
1927
- const localEnv = (root) => Object.assign({}, ...LOCAL_ENV_FILES.map((file) => readEnvFile(root, file)));
1928
- //#endregion
1929
- //#region src/checks/v9.ts
1930
- /** The be-on! Hub endpoints per stage, as `@v-office/website-headless` resolves `CMS_STAGE` for v9
1931
- * (`sdk/endpoints.ts`). Production is what a live v9 site calls. */
1932
- const HUB = {
1933
- production: {
1934
- api: "https://api.voffice.be-on.io",
1935
- imageProxy: "https://imgproxy.voffice.be-on.io"
1936
- },
1937
- development: {
1938
- api: "https://api.voffice.demo-on.de",
1939
- imageProxy: "https://imgproxy.voffice.demo-on.de"
3026
+ /** A site that generates robots.txt (`src/pages/robots.txt.ts`) ships no `public/robots.txt`
3027
+ * beside it: both answer `/robots.txt`, and which one the build keeps is not the site's choice. */
3028
+ const robotsTxt = {
3029
+ id: "robots-txt",
3030
+ title: "One file answers /robots.txt",
3031
+ severity: "error",
3032
+ stage: "src",
3033
+ begin: (ctx) => {
3034
+ const generator = ENDPOINT_EXTENSIONS.map((ext) => path.join(ctx.srcDir, "pages", `robots.txt${ext}`)).find((file) => fs.existsSync(file));
3035
+ const file = path.join(ctx.publicDir, "robots.txt");
3036
+ if (!generator) return null;
3037
+ return { finish: () => fs.existsSync(file) ? [{
3038
+ path: ctx.rel(file),
3039
+ message: `${ctx.rel(file)} and the generator ${ctx.rel(generator)} both answer /robots.txt. Delete ${ctx.rel(file)} and keep any rule it adds in the generator.`
3040
+ }] : [] };
1940
3041
  }
1941
3042
  };
1942
- const hubUrls = (stage) => ({
1943
- HUB_V1_API_BASE_URL: `${HUB[stage].api}/api/v1`,
1944
- HUB_V0_API_BASE_URL: `${HUB[stage].api}/api/v0`,
1945
- HUB_GRAPHQL_URL: `${HUB[stage].api}/graphql`,
1946
- IMAGE_PROXY_BASE_URL: HUB[stage].imageProxy
1947
- });
1948
- /** The build's SDK env, when it builds a v9 site: `CMS_BACKEND=v9` from the process env, the
1949
- * committed `.env` / `.env.production`, or AI Studio's `PMS_BACKEND` (`sdkEnv`). Every v9 check
1950
- * starts here, so a v10 site, or one with no backend at all, never runs one. */
1951
- const v9Env = (ctx) => {
1952
- const env = sdkEnv(ctx.root);
1953
- return env.CMS_BACKEND === "v9" ? env : null;
1954
- };
1955
- const sameUrl = (a, b) => (a ?? "").replace(/\/+$/, "") === b.replace(/\/+$/, "");
1956
- /** The `.local` env files git tracks; empty outside a git checkout (nothing to tell then). */
1957
- const committedLocalFiles = async (root) => {
1958
- const { execFileSync } = await import("node:child_process");
1959
- return LOCAL_ENV_FILES.filter((file) => {
1960
- try {
1961
- execFileSync("git", [
1962
- "ls-files",
1963
- "--error-unmatch",
1964
- "--",
1965
- file
1966
- ], {
1967
- cwd: root,
1968
- stdio: "ignore"
1969
- });
1970
- return true;
1971
- } catch {
1972
- return false;
1973
- }
1974
- });
3043
+ // src/checks/sitemapNoindex.ts
3044
+ const SITEMAP = /^sitemap[^/]*\.xml$/;
3045
+ const SITEMAP_INDEX = "sitemap-index.xml";
3046
+ const LLMS = "llms.txt";
3047
+ /** What keeps an `llms.txt` from the llms.txt spec's shape: a `# ` heading naming the site on the
3048
+ * first line, a `> ` summary above the first section, `## ` sections of links. The content is the
3049
+ * site's; only the shape is checked. A blockquote below the first section is no summary. */
3050
+ const llmsShape = (text) => {
3051
+ const body = text.split(/\r?\n/).filter((line) => line.trim() !== "");
3052
+ const problems = [];
3053
+ if (!body[0]?.startsWith("# ")) problems.push("no `# ` heading naming the site on the first line");
3054
+ const firstSection = body.findIndex((line) => line.startsWith("## "));
3055
+ if (!(firstSection === -1 ? body : body.slice(0, firstSection)).some((line) => line.startsWith("> "))) problems.push("no `> ` summary above the first section");
3056
+ if (firstSection === -1) problems.push("no `## ` section");
3057
+ return problems;
1975
3058
  };
1976
- /** A launched v9 site builds against the production be-on! Hub: the build's env says
1977
- * `CMS_STAGE=production`, or names the production Hub URLs. The Hub URLs are baked in at build
1978
- * time, so a site built against the demo Hub renders fine, only with the demo catalogue. Also
1979
- * reported: a committed `.env.local` (Vite loads it after `.env` in every mode, so CI builds from
1980
- * it) and a committed `HUB_API_KEY` that is the developer's local key. Waits while every page is
1981
- * noindex, and while the Astro `site` is a preview host or unset: before launch a site builds
1982
- * against the test Hub on purpose. v9 only. */
1983
- const v9ProductionHub = {
1984
- id: "v9-production-hub",
1985
- title: "A launched v9 site calls the production Hub",
1986
- severity: "warning",
3059
+ /** The URL lists the build publishes agree with the pages it built: no sitemap entry whose own page
3060
+ * says noindex or is not in the build, an `llms.txt` in the spec's shape and without a link to a
3061
+ * page that is not there. Every `sitemap*.xml` of the build is read, and every sitemap an index
3062
+ * names. Skipped when the build publishes neither. While every page is noindex (a site before
3063
+ * launch, under its blanket robots meta; the 404 page and redirect stubs do not count), a sitemap
3064
+ * listing them is not refused: that disagreement ends with the launch. */
3065
+ const sitemapNoindex = {
3066
+ id: "sitemap-noindex",
3067
+ title: "Published URL lists match the built pages",
3068
+ severity: "error",
1987
3069
  stage: "dist",
1988
3070
  begin: (ctx) => {
1989
- const env = v9Env(ctx);
1990
- if (!env || !ctx.hasDist || !productionSite(ctx)) return null;
3071
+ if (!ctx.hasDist) return null;
3072
+ if (!ctx.files.some((f) => SITEMAP.test(f)) && !ctx.has(LLMS)) return null;
3073
+ const noindex = /* @__PURE__ */ new Set();
1991
3074
  let launched = false;
1992
3075
  return {
1993
3076
  visit: (page) => {
1994
- if (!page.redirect && !page.noindex && page.path !== "404.html") launched = true;
3077
+ if (page.redirect) return;
3078
+ if (page.noindex) noindex.add(normalize(page.url));
3079
+ else if (isIndexable(page)) launched = true;
1995
3080
  },
1996
- finish: async () => {
1997
- if (!launched) return [];
1998
- const findings = [];
1999
- const where = `the build's env (${BUILD_ENV_FILES.join(" / ")} or the process env)`;
2000
- for (const file of await committedLocalFiles(ctx.root)) findings.push({
2001
- path: file,
2002
- message: `${file} is committed: Vite loads it after .env in every mode, so the live site builds from it. Untrack it (git rm --cached) and keep it ignored.`
3081
+ finish: () => {
3082
+ const { entries, missing } = readSitemaps(ctx);
3083
+ const findings = [...missing];
3084
+ for (const { sitemap, loc, path } of entries) if (!ctx.serves(path)) findings.push({
3085
+ path: sitemap,
3086
+ message: `The sitemap lists ${loc}, which is not in the build.`
2003
3087
  });
2004
- if (env.CMS_STAGE) {
2005
- if (env.CMS_STAGE !== "production") findings.push({
2006
- path: ".env",
2007
- message: `CMS_STAGE is "${env.CMS_STAGE}" in ${where}: the live site calls the ${env.CMS_STAGE} Hub. Set CMS_STAGE=production.`
2008
- });
2009
- } else {
2010
- const expected = hubUrls("production");
2011
- const wrong = Object.keys(expected).filter((name) => !sameUrl(env[name], expected[name]));
2012
- if (wrong.length > 0) findings.push({
2013
- path: ".env",
2014
- message: `${where[0].toUpperCase()}${where.slice(1)} does not call the production Hub: ${wrong.map((name) => `${name}=${env[name] || "(unset)"}`).join(", ")}. Set ${wrong.map((name) => `${name}=${expected[name]}`).join(", ")}, or CMS_STAGE=production without the URLs.`
3088
+ else if (launched && noindex.has(path)) findings.push({
3089
+ path: sitemap,
3090
+ message: `The sitemap lists ${loc}, whose page says noindex: the sitemap filter and the noindex routes disagree.`
3091
+ });
3092
+ if (ctx.has(LLMS)) {
3093
+ const text = ctx.read(LLMS);
3094
+ const shape = llmsShape(text);
3095
+ if (shape.length > 0) findings.push({
3096
+ path: LLMS,
3097
+ message: `llms.txt does not follow the spec's shape: ${shape.join("; ")}. Start with \`# \` and the site's name, a \`> \` summary, then \`## \` sections of links.`
2015
3098
  });
3099
+ for (const match of text.matchAll(/\]\(([^)\s]+)\)/g)) {
3100
+ const link = match[1];
3101
+ if (/^(?:mailto|tel):|^#/i.test(link)) continue;
3102
+ if (/^[a-z][a-z0-9+.-]*:/i.test(link)) {
3103
+ if (!ctx.config.site) continue;
3104
+ let host;
3105
+ try {
3106
+ host = new URL(link).host;
3107
+ } catch {
3108
+ continue;
3109
+ }
3110
+ if (host !== new URL(ctx.config.site).host) continue;
3111
+ }
3112
+ if (!ctx.serves(toPath(link))) findings.push({
3113
+ path: LLMS,
3114
+ message: `llms.txt links ${link}, which is not in the build.`
3115
+ });
3116
+ }
2016
3117
  }
2017
- const key = env.HUB_API_KEY;
2018
- if (key && key === localEnv(ctx.root).HUB_API_KEY) findings.push({
2019
- path: ".env",
2020
- message: "HUB_API_KEY in the build's env is the key of .env.local, the developer's key: production needs this customer's production key, which be-on! issues."
2021
- });
2022
3118
  return findings;
2023
3119
  }
2024
3120
  };
2025
3121
  }
2026
3122
  };
2027
- /** How long the Hub may take to answer before the check gives up. */
2028
- const HUB_TIMEOUT_MS = 6e4;
2029
- /** The Website SDK CLI's v9 config, from the build's SDK env (`sdkEnv`): the stage's endpoints with
2030
- * `CMS_STAGE`, else the URL variables, and the key. */
2031
- const cliConfig = (env) => {
2032
- const stage = env.CMS_STAGE === "production" || env.CMS_STAGE === "development" ? env.CMS_STAGE : void 0;
2033
- const urls = stage ? hubUrls(stage) : env;
2034
- return {
2035
- backend: "v9",
2036
- apiKey: env.HUB_API_KEY ?? "",
2037
- graphqlUrl: urls.HUB_GRAPHQL_URL ?? "",
2038
- imageProxyBaseUrl: urls.IMAGE_PROXY_BASE_URL ?? "",
2039
- ...urls.HUB_V0_API_BASE_URL ? { v0ApiBaseUrl: urls.HUB_V0_API_BASE_URL } : {},
2040
- ...urls.HUB_V1_API_BASE_URL ? { v1ApiBaseUrl: urls.HUB_V1_API_BASE_URL } : {},
2041
- ...env.HUB_RENTAL_SCOPE_PROPERTY_KIND === "facility" || env.HUB_RENTAL_SCOPE_PROPERTY_KIND === "objectGroup" ? { rentalScopePropertyKind: env.HUB_RENTAL_SCOPE_PROPERTY_KIND } : {},
2042
- ...env.HUB_RENTAL_IDS_SEARCH === "true" || env.HUB_RENTAL_IDS_SEARCH === "false" ? { rentalIdsSearch: env.HUB_RENTAL_IDS_SEARCH === "true" } : {}
2043
- };
3123
+ /** Every indexable page is in the sitemap, and a build with `sitemap-index.xml` also serves
3124
+ * `/sitemap.xml`, the URL tools and search consoles try first (static hosting redirects nothing).
3125
+ * A warning: a page can be left out for a reason this cannot see. Skipped without a sitemap. */
3126
+ const sitemapCoverage = {
3127
+ id: "sitemap-coverage",
3128
+ title: "The sitemap covers the indexable pages",
3129
+ severity: "warning",
3130
+ stage: "dist",
3131
+ begin: (ctx) => {
3132
+ if (!ctx.hasDist || !ctx.files.some((f) => SITEMAP.test(f))) return null;
3133
+ const listed = new Set(readSitemaps(ctx).entries.map((entry) => entry.path));
3134
+ const findings = [];
3135
+ if (ctx.has(SITEMAP_INDEX) && !ctx.has("sitemap.xml")) findings.push({
3136
+ path: SITEMAP_INDEX,
3137
+ message: "sitemap-index.xml has no /sitemap.xml beside it, the URL tools and search consoles try first: write a copy of the index as sitemap.xml at build time."
3138
+ });
3139
+ return {
3140
+ visit: (page) => {
3141
+ if (isIndexable(page) && !listed.has(normalize(page.url))) findings.push({
3142
+ path: page.path,
3143
+ message: `${page.url} is indexable but not in the sitemap: list it, or give it noindex if it must stay out.`
3144
+ });
3145
+ },
3146
+ finish: () => findings
3147
+ };
3148
+ }
2044
3149
  };
2045
- const sdkVersion = (root) => {
3150
+ // src/checks/syncOnce.ts
3151
+ const LOADER_FILES = ["src/content.config.ts", "src/content/config.ts"];
3152
+ /** A loader written inline, as opposed to `glob()` or `file()`. */
3153
+ const INLINE_LOADER = /\bloader\s*:\s*\{/;
3154
+ /** It talks to the PMS: a fetch, the SDK by its factory or its package (imported under any name),
3155
+ * or a store it clears to fill again. */
3156
+ const LIVE_FETCH = /\bfetch\s*\(|createWebsiteSDK|createVofficeSdk|\.static\.|["']@v-office\/website-(?:sdk|headless)\b|\bstore\.clear\(\)/;
3157
+ /** The reuse idiom: the loader keeps the sync token in the store's meta and, when the token the
3158
+ * build was started with is still the same, serves the entries it already has. */
3159
+ const REUSE_IDIOM = [
3160
+ /CONTENT_SYNC_TOKEN/,
3161
+ /\bmeta\.get\(/,
3162
+ /\bstore\.keys\(\)/
3163
+ ];
3164
+ /** A script that runs the type check and then the build in one shell. */
3165
+ const CHECK_THEN_BUILD = /\bastro\s+check\b[\s\S]*\bastro\s+build\b/;
3166
+ /** The `package.json` scripts that chain `astro check` and `astro build` without minting a
3167
+ * `CONTENT_SYNC_TOKEN`: run from a shell that sets none, the loader syncs the PMS in both. */
3168
+ const tokenlessScripts = (root) => {
2046
3169
  try {
2047
- const file = path.join(root, "node_modules", "@v-office", "website-sdk", "package.json");
2048
- return JSON.parse(fs.readFileSync(file, "utf8")).version ?? "unknown version";
3170
+ const { scripts } = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
3171
+ return Object.entries(scripts ?? {}).filter(([, script]) => typeof script === "string" && CHECK_THEN_BUILD.test(script) && !script.includes("CONTENT_SYNC_TOKEN")).map(([name]) => name);
2049
3172
  } catch {
2050
- return "unknown version";
3173
+ return [];
2051
3174
  }
2052
3175
  };
2053
- const run = async (cli, args, cwd) => {
2054
- const { execFile } = await import("node:child_process");
2055
- return new Promise((resolve) => {
2056
- execFile(cli, args, {
2057
- cwd,
2058
- timeout: HUB_TIMEOUT_MS,
2059
- maxBuffer: 1048576
2060
- }, (err, stdout, stderr) => resolve({
2061
- code: err ? typeof err.code === "number" ? err.code : 1 : 0,
2062
- output: `${stdout}${stderr}`.trim()
2063
- }));
2064
- });
2065
- };
2066
- /** Every be-on! Hub filter the site's search needs (the scope filter, the Merkliste's rental-id
2067
- * filter, each searchable backend-filter definition) exists in the Hub the site builds against.
2068
- * A filter the Hub does not serve matches nothing, or everything once a date is set. Asks the Hub
2069
- * through the site's own `website-sdk hub-filters check`, with the build's env and the SDK
2070
- * options in `hubFilterOptions`. A warning: the outcome is the Hub's data, and a Hub that cannot be
2071
- * asked must not stop the nightly builds; it is reported, never passed. v9 only. */
2072
- const v9HubFilters = {
2073
- id: "v9-hub-filters",
2074
- title: "The be-on! Hub serves the filters the v9 site needs",
3176
+ /** `astro check` and `astro build` each run the content loader, so an unguarded loader pays every
3177
+ * remote fetch twice on every build, against a rate-limited PMS. The build worker starts both with
3178
+ * one `CONTENT_SYNC_TOKEN`; a loader that keys its store on it syncs once. A loader that does is
3179
+ * then let down by a `package.json` script that chains the two without a token, also reported.
3180
+ * A text heuristic, hence a warning. */
3181
+ const syncOnce = {
3182
+ id: "sync-once",
3183
+ title: "Content loaders sync the PMS once per build",
2075
3184
  severity: "warning",
2076
3185
  stage: "src",
2077
3186
  begin: (ctx) => {
2078
- const env = v9Env(ctx);
2079
- if (!env) return null;
2080
- return { finish: async () => {
2081
- const cli = path.join(ctx.root, "node_modules", ".bin", process.platform === "win32" ? "website-sdk.cmd" : "website-sdk");
2082
- if (!fs.existsSync(cli)) return [{ message: "node_modules/.bin/website-sdk is missing, so the Hub could not be asked. Install @v-office/website-sdk." }];
2083
- const config = cliConfig(env);
2084
- if (!config.apiKey || !config.graphqlUrl) return [{ message: "No HUB_API_KEY or Hub URLs in the build's env, so the Hub could not be asked." }];
2085
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "site-checks-hub-"));
2086
- try {
2087
- const configFile = path.join(dir, "config.json");
2088
- const optionsFile = path.join(dir, "options.json");
2089
- fs.writeFileSync(configFile, JSON.stringify(config));
2090
- fs.writeFileSync(optionsFile, JSON.stringify(ctx.options.hubFilterOptions));
2091
- const { code, output } = await run(cli, [
2092
- "--backend",
2093
- "v9",
2094
- "--config",
2095
- configFile,
2096
- "--options",
2097
- optionsFile,
2098
- "hub-filters",
2099
- "check"
2100
- ], ctx.root);
2101
- if (code === 0) return [];
2102
- if (/Unknown subcommand "hub-filters"/.test(output)) return [{ message: `The installed @v-office/website-sdk (${sdkVersion(ctx.root)}) has no \`hub-filters check\`, so the Hub could not be asked. Update @v-office/website-sdk.` }];
2103
- return [{ message: `The be-on! Hub (${new URL(config.graphqlUrl).host}) does not serve every filter the site needs: ${output || `website-sdk exited ${code}`} Add the missing entries in the Hub (website-sdk hub-filters request) or drop them from the site's SDK options.` }];
2104
- } finally {
2105
- fs.rmSync(dir, {
2106
- recursive: true,
2107
- force: true
2108
- });
2109
- }
3187
+ const loader = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts"])).find((file) => LOADER_FILES.includes(ctx.rel(file)));
3188
+ if (!loader) return null;
3189
+ return { finish: () => {
3190
+ const text = ctx.readSource(loader);
3191
+ const code = text.replace(/^\s*import\s+type\b[\s\S]*?\bfrom\s*["'][^"'\n]*["'];?/gm, "").replace(/^\s*import\s*\{([^}]*)\}\s*from\s*["'][^"'\n]*["'];?/gm, (line, names) => names.split(",").map((n) => n.trim()).filter(Boolean).every((n) => /^type\s/.test(n)) ? "" : line);
3192
+ if (!INLINE_LOADER.test(text) || !LIVE_FETCH.test(code)) return [];
3193
+ if (REUSE_IDIOM.every((idiom) => idiom.test(text))) return tokenlessScripts(ctx.root).map((name) => ({
3194
+ path: "package.json",
3195
+ message: `The "${name}" script runs astro check and astro build without a CONTENT_SYNC_TOKEN, so the content loader syncs the PMS in both. Set one token for the pair (export CONTENT_SYNC_TOKEN="\$(date +%s)" && astro check && astro build) or run site-checks verify.`
3196
+ }));
3197
+ return [{
3198
+ path: ctx.rel(loader),
3199
+ message: "A content loader fetches the PMS without the CONTENT_SYNC_TOKEN idiom; astro check and astro build each sync it, twice per build. Keep the token in the store's meta (meta.get) and reuse the entries (store.keys()) when it matches."
3200
+ }];
2110
3201
  } };
2111
3202
  }
2112
3203
  };
2113
- //#endregion
2114
- //#region src/checks/viewSource.ts
2115
- /** Comments the frameworks themselves write into static HTML, and no developer did: Astro's
2116
- * island and server-island markers, React 19's SSR markers (`<!--$-->`, `<!--/$-->`, …, and the
2117
- * `<!-- -->` text separator), Vue's SSR fragment and teleport markers. Matched on the trimmed
2118
- * comment text. A framework upgrade that adds a marker shows up as a refused build; extend the
2119
- * list here, in one place. */
3204
+ // src/checks/viewSource.ts
3205
+ /** Comments the frameworks themselves write into static HTML, and no developer did, matched
3206
+ * exactly on the trimmed comment text: Astro's island end and server-island start, React 19's
3207
+ * form-state and document markers, Vue's teleport markers and its placeholder for a false `v-if`
3208
+ * (`createCommentVNode("v-if")`, e.g. a closed reka-ui dialog portal). A comment without a letter
3209
+ * or digit is a marker too and needs no entry (React's `<!--$-->`, `<!--/$-->`, `<!-- -->`, Vue's
3210
+ * `<!--[-->`, `<!--]-->`): it has nothing to say. Named exactly, so `<!--astro: TODO-->` is a
3211
+ * note. A framework upgrade that adds a marker shows up as a refused build; extend the list here,
3212
+ * in one place. */
2120
3213
  const FRAMEWORK_COMMENTS = /* @__PURE__ */ new Set([
2121
- "",
2122
- "$",
2123
- "/$",
2124
- "$!",
2125
- "$?",
2126
- "&",
2127
- "/&",
3214
+ "astro:end",
3215
+ "[if astro]>server-island-start<![endif]",
2128
3216
  "F",
2129
3217
  "F!",
2130
3218
  "html",
2131
3219
  "head",
2132
3220
  "body",
2133
- "[",
2134
- "]",
2135
3221
  "teleport start",
2136
3222
  "teleport end",
2137
3223
  "v-if"
2138
3224
  ]);
3225
+ const WORDLESS = /^[^\p{L}\p{N}]*$/u;
2139
3226
  const isFrameworkComment = (data) => {
2140
3227
  const text = data.trim();
2141
- return FRAMEWORK_COMMENTS.has(text) || text.startsWith("astro:") || text.startsWith("server-island");
2142
- };
2143
- /** Licence banners and bundler annotations survive minification on purpose and say nothing. */
2144
- const LEGAL_BLOCK_COMMENT = /^\/\*\s*[!@#]|@license|@preserve/;
2145
- const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
2146
- const SOURCE_MAP_URL = /(?:\/\/|\/\*)# sourceMappingURL=/;
2147
- /** Line-comment directives: a source-map pointer (reported on its own) and a legal comment. */
2148
- const DIRECTIVE = /^\/\/[#!]/;
2149
- const LINE_BREAK = /* @__PURE__ */ new Set("\n\r\u2028\u2029");
3228
+ return WORDLESS.test(text) || FRAMEWORK_COMMENTS.has(text);
3229
+ };
3230
+ /** Licence banners (`/*!`, `//!`, `@license`, `@preserve`) survive minification on purpose. */
3231
+ const LEGAL_COMMENT = /^\/[*/]!|@license|@preserve/;
3232
+ /** Markers a build tool writes into its own output, named exactly: a note that merely mentions
3233
+ * one (`/* @todo … *\/`) is still a note. */
3234
+ const TOOL_MARKER = /^\/\*\s*(?:empty css|@vite-ignore|[#@]__PURE__|[#@]__NO_SIDE_EFFECTS__)\s*\*\/$/;
3235
+ /** A library the site ships as it comes, from `public/`: minified (`*.min.js`), in a `vendor/`
3236
+ * folder, or opening with a licence banner. Its notes are its authors', not the site's to remove. */
3237
+ const VENDORED_NAME = /(?:^|\/)vendor\/|\.min\.(?:m?js|css)$/;
3238
+ const VENDORED_BANNER = /^\s*\/\*!|^\s*\/\*[\s\S]{0,400}?@license/;
3239
+ const vendored = (ctx, file, text) => fs.existsSync(path.join(ctx.publicDir, file)) && (VENDORED_NAME.test(file) || VENDORED_BANNER.test(text.slice(0, 600)));
3240
+ /** A source-map pointer, reported on its own. */
3241
+ const SOURCE_MAP_URL = /(?:\/\/|\/\*)[#@] sourceMappingURL=/;
3242
+ /** A comment that tells a visitor nothing of the developer's. */
3243
+ const saysNothing = (comment) => LEGAL_COMMENT.test(comment) || TOOL_MARKER.test(comment) || SOURCE_MAP_URL.test(comment) || WORDLESS.test(comment);
3244
+ /** CSS has one comment form; a string may hold `/*` (`content: "/*"`). */
3245
+ const cssComments = (text) => {
3246
+ const comments = [];
3247
+ let i = 0;
3248
+ while (i < text.length) {
3249
+ const c = text[i];
3250
+ if (c === "'" || c === "\"") {
3251
+ i += 1;
3252
+ while (i < text.length && text[i] !== c && text[i] !== "\n") i += text[i] === "\\" ? 2 : 1;
3253
+ i += 1;
3254
+ } else if (c === "/" && text[i + 1] === "*") {
3255
+ const close = text.indexOf("*/", i + 2);
3256
+ const end = close === -1 ? text.length : close + 2;
3257
+ comments.push(text.slice(i, end));
3258
+ i = end;
3259
+ } else i += 1;
3260
+ }
3261
+ return comments;
3262
+ };
2150
3263
  const excerpt = (text) => {
2151
3264
  const flat = text.replace(/\s+/g, " ").trim();
2152
3265
  return flat.length > 80 ? `${flat.slice(0, 79)}…` : flat;
2153
3266
  };
2154
- const blockComments = (text) => (text.match(BLOCK_COMMENT) ?? []).filter((comment) => !LEGAL_BLOCK_COMMENT.test(comment));
2155
- /** Line comments at the start of a line, read as JavaScript: a `//` line inside a string or
2156
- * template literal (a bundled library's shader source or CSS-in-JS) is text. `//` after code on
2157
- * the same line is not read, and `//#` and `//!` are directives (source maps, legal comments),
2158
- * reported or allowed on their own. */
2159
- const lineComments = (text) => findComments(text).filter(({ start, text: comment }) => {
2160
- if (!comment.startsWith("//") || DIRECTIVE.test(comment)) return false;
2161
- let k = start;
2162
- while (k > 0 && (text[k - 1] === " " || text[k - 1] === " ")) k -= 1;
2163
- return k === 0 || LINE_BREAK.has(text[k - 1]);
2164
- }).map((comment) => comment.text);
2165
- /** The site's own text files, where a comment it wrote into an inline script, style or handler
2166
- * lives. */
2167
- const SOURCE_EXTENSIONS = new Set(".astro .tsx .jsx .ts .js .mjs .cjs .css .scss .vue .md .mdx .html .json .svg".split(" "));
3267
+ /** The project's own text files, where a comment it wrote lives: `src/`, `public/`, the Astro
3268
+ * config and the integrations it injects from. */
3269
+ const SOURCE_EXTENSIONS = new Set(".astro .tsx .jsx .ts .mts .cts .js .mjs .cjs .css .scss .sass .less .vue .svelte .md .mdx .mdoc .html .json .svg".split(" "));
2168
3270
  /** Below this length a comment's inner text appears in almost any source by accident; such a
2169
3271
  * comment is matched whole, with its markers. */
2170
3272
  const MIN_INNER_TEXT = 8;
2171
3273
  const collapse = (text) => text.replace(/\s+/g, " ").trim();
2172
- /** Whether the site wrote a comment found in an inline script, style or handler: its text,
2173
- * whitespace collapsed, appears in a file under `src/` or `public/`. A comment in none of them
2174
- * was rendered by a dependency during the build (c15t's theme `<style>` in the consent kit) and
2175
- * is not the site's to remove. The files are read once, on the first inline comment. */
3274
+ /** Every text file of the project, as the old guard's `git grep -- . ':!dist'` read it: the
3275
+ * build's output, `node_modules` and dot folders (`.git`, `.astro`) are no source. No git call, so
3276
+ * a checkout without `.git` reads the same. */
3277
+ const projectFiles = (ctx) => {
3278
+ const root = path.resolve(ctx.root);
3279
+ const dist = path.resolve(ctx.distDir) + path.sep;
3280
+ return fs.readdirSync(root, { withFileTypes: true }).flatMap((entry) => {
3281
+ const full = path.join(root, entry.name);
3282
+ if (entry.name.startsWith(".") || entry.name === "node_modules") return [];
3283
+ if (entry.isDirectory()) return [...filesUnder(full, SOURCE_EXTENSIONS)];
3284
+ return SOURCE_EXTENSIONS.has(path.extname(entry.name).toLowerCase()) ? [full] : [];
3285
+ }).filter((file) => !file.startsWith(dist));
3286
+ };
3287
+ /** Whether the site wrote a comment found in an inline script, style or attribute, or in a shipped
3288
+ * JS or CSS file: its text, whitespace collapsed, appears in a file of the project. A comment in
3289
+ * none of them was rendered or bundled from a dependency (c15t's theme `<style>` in the consent
3290
+ * kit, a library's banner in `_astro/`) and is not the site's to remove. The files are read once,
3291
+ * on the first such comment. */
2176
3292
  const siteWrote = (ctx) => {
2177
3293
  let corpus;
2178
3294
  const seen = /* @__PURE__ */ new Map();
2179
3295
  return (comment) => {
2180
3296
  let wrote = seen.get(comment);
2181
3297
  if (wrote === void 0) {
2182
- corpus ??= [...filesUnder(ctx.srcDir, SOURCE_EXTENSIONS), ...filesUnder(ctx.publicDir, SOURCE_EXTENSIONS)].map((file) => collapse(ctx.readSource(file))).join("\n");
3298
+ corpus ??= projectFiles(ctx).map((file) => collapse(ctx.readSource(file))).join("\n");
2183
3299
  const inner = collapse(comment.startsWith("//") ? comment.slice(2) : comment.slice(2, -2));
2184
3300
  wrote = corpus.includes(inner.length < MIN_INNER_TEXT ? collapse(comment) : inner);
2185
3301
  seen.set(comment, wrote);
@@ -2187,8 +3303,93 @@ const siteWrote = (ctx) => {
2187
3303
  return wrote;
2188
3304
  };
2189
3305
  };
2190
- //#endregion
2191
- //#region src/checks/index.ts
3306
+ /** What a visitor can read with View Source, and no developer meant for them: every HTML comment
3307
+ * in the built pages, before and after `<html>` included; comments in their inline scripts,
3308
+ * styles, `style` attributes and event handlers, and in every shipped JS and CSS file (`_astro/`
3309
+ * and `public/` alike), that the project's own files contain; source maps and references to them
3310
+ * in every shipped file. Scripts and handlers are read as JavaScript and styles as CSS, so `//` in
3311
+ * `"https://…"`, a regular expression or a shader in a template literal is text. Vite minifies
3312
+ * what it bundles, so a comment left in `_astro/` is a licence banner (allowed) or a dependency's
3313
+ * (not in the project's files). */
3314
+ const viewSource = {
3315
+ id: "view-source",
3316
+ title: "Developer notes visible in View Source",
3317
+ severity: "error",
3318
+ stage: "dist",
3319
+ begin: (ctx) => {
3320
+ if (!ctx.hasDist) return null;
3321
+ const findings = [];
3322
+ const report = (path, what, text) => findings.push({
3323
+ path,
3324
+ message: `${what}: "${excerpt(text)}"`
3325
+ });
3326
+ const wrote = siteWrote(ctx);
3327
+ const reportWritten = (path, what, comments) => {
3328
+ for (const comment of comments) if (!saysNothing(comment) && wrote(comment)) report(path, what, comment);
3329
+ };
3330
+ const visit = (page) => {
3331
+ for (const comment of page.comments()) if (!isFrameworkComment(comment)) report(page.path, "HTML comment in the page", comment);
3332
+ for (const el of page.document.querySelectorAll("*")) for (const name of el.getAttributeNames()) {
3333
+ const isStyle = name === "style";
3334
+ if (!isStyle && !name.startsWith("on")) continue;
3335
+ const code = el.getAttribute(name) ?? "";
3336
+ if (isStyle) reportWritten(page.path, "comment in an inline style", cssComments(code));
3337
+ else reportWritten(page.path, `comment in an inline ${name} handler`, jsComments(code));
3338
+ }
3339
+ for (const el of page.document.querySelectorAll("script, style")) {
3340
+ const text = el.textContent ?? "";
3341
+ const tag = el.tagName.toLowerCase();
3342
+ if (SOURCE_MAP_URL.test(text)) report(page.path, `source map reference in an inline <${tag}>`, text);
3343
+ const comments = tag === "script" ? jsComments(text) : cssComments(text);
3344
+ reportWritten(page.path, `comment in an inline <${tag}>`, comments);
3345
+ }
3346
+ };
3347
+ const finish = () => {
3348
+ for (const file of ctx.files) {
3349
+ if (file.endsWith(".map")) {
3350
+ findings.push({
3351
+ path: file,
3352
+ message: "A source map ships the original source to anyone who asks for it."
3353
+ });
3354
+ continue;
3355
+ }
3356
+ const isJs = /\.m?js$/.test(file);
3357
+ const isCss = file.endsWith(".css");
3358
+ if (!isJs && !isCss) continue;
3359
+ const text = ctx.read(file);
3360
+ if (vendored(ctx, file, text)) continue;
3361
+ if (SOURCE_MAP_URL.test(text)) report(file, "source map reference", "sourceMappingURL");
3362
+ if (isCss) reportWritten(file, "comment in shipped CSS", cssComments(text));
3363
+ else reportWritten(file, "comment in shipped JS", jsComments(text));
3364
+ }
3365
+ return findings;
3366
+ };
3367
+ return {
3368
+ visit,
3369
+ finish
3370
+ };
3371
+ }
3372
+ };
3373
+ // src/checks/vofficeCredit.ts
3374
+ /** The host itself, not a substring: `v-office.com.example` is someone else's, `dyn.v-office.com`
3375
+ * the photo host. */
3376
+ const CREDIT = /^https?:\/\/(?:www\.)?v-office\.com(?:[/?#]|$)/i;
3377
+ /** A `<footer>` inside one of these belongs to that block (a card, a quote), not to the site. */
3378
+ const SECTIONING = "article, aside, main, nav, section, blockquote, figure, dialog";
3379
+ /** The home page, and a locale's (`de/index.html`, `en-gb/index.html`): where a root redirects to
3380
+ * its language, the locale home is the one a visitor lands on. */
3381
+ const HOME = /^(?:[a-z]{2}(?:-[a-z]{2})?\/)?index\.html$/i;
3382
+ /** The page's site footers (a `<footer>` in no sectioning block and no other footer), and whether
3383
+ * one of them links v-office.com. */
3384
+ const footerCredit = (document) => {
3385
+ const footers = [...document.querySelectorAll("footer")].filter((footer) => !footer.parentElement?.closest(`footer, ${SECTIONING}`));
3386
+ const credit = footers.some((footer) => [...footer.querySelectorAll("a[href]")].some((a) => CREDIT.test((a.getAttribute("href") ?? "").trim())));
3387
+ return {
3388
+ footers: footers.length,
3389
+ credit
3390
+ };
3391
+ };
3392
+ // src/checks/index.ts
2192
3393
  /** The site checks, in the order the report shows them: the `src` stage first, then the `dist`
2193
3394
  * stage. Each check names its stage; `site-checks src` runs the first group before the build and
2194
3395
  * `site-checks dist` the second after it, together with the platform's dist checks
@@ -2199,87 +3400,66 @@ const checks = [
2199
3400
  imageFormats,
2200
3401
  syncOnce,
2201
3402
  v9HubFilters,
2202
- {
2203
- id: "view-source",
2204
- title: "Developer notes visible in View Source",
2205
- severity: "error",
2206
- stage: "dist",
2207
- begin: (ctx) => {
2208
- if (!ctx.hasDist) return null;
2209
- const findings = [];
2210
- const report = (path, what, text) => findings.push({
2211
- path,
2212
- message: `${what}: "${excerpt(text)}"`
2213
- });
2214
- const wrote = siteWrote(ctx);
2215
- const reportInline = (path, what, comment) => {
2216
- if (wrote(comment)) report(path, what, comment);
2217
- };
2218
- const visit = (page) => {
2219
- for (const comment of page.comments()) if (!isFrameworkComment(comment)) report(page.path, "HTML comment in the page", comment);
2220
- for (const el of page.document.querySelectorAll("*")) for (const name of el.getAttributeNames()) {
2221
- if (!name.startsWith("on")) continue;
2222
- const code = el.getAttribute(name) ?? "";
2223
- const what = `comment in an inline ${name} handler`;
2224
- for (const comment of jsComments(code)) if (!DIRECTIVE.test(comment) && !LEGAL_BLOCK_COMMENT.test(comment)) reportInline(page.path, what, comment);
2225
- }
2226
- for (const el of page.document.querySelectorAll("script, style")) {
2227
- const text = el.textContent ?? "";
2228
- const what = `comment in an inline <${el.tagName.toLowerCase()}>`;
2229
- for (const comment of blockComments(text)) reportInline(page.path, what, comment);
2230
- if (el.tagName === "SCRIPT") {
2231
- if (SOURCE_MAP_URL.test(text)) report(page.path, "source map reference in an inline <script>", text);
2232
- for (const comment of lineComments(text)) reportInline(page.path, what, comment);
2233
- }
2234
- }
2235
- };
2236
- const finish = () => {
2237
- for (const file of ctx.files) {
2238
- if (file.endsWith(".map")) {
2239
- findings.push({
2240
- path: file,
2241
- message: "A source map ships the original source to anyone who asks for it."
2242
- });
2243
- continue;
2244
- }
2245
- const isJs = /\.m?js$/.test(file);
2246
- const isCss = file.endsWith(".css");
2247
- if (!isJs && !isCss) continue;
2248
- const text = ctx.read(file);
2249
- if (SOURCE_MAP_URL.test(text)) report(file, "source map reference", "sourceMappingURL");
2250
- if (!fs.existsSync(path.join(ctx.publicDir, file))) continue;
2251
- if (isCss) for (const comment of blockComments(text)) report(file, "comment in shipped CSS", comment);
2252
- if (isJs) for (const comment of lineComments(text)) report(file, "comment in shipped JS", comment);
2253
- }
2254
- return findings;
2255
- };
2256
- return {
2257
- visit,
2258
- finish
2259
- };
2260
- }
2261
- },
3403
+ bannedCopySrc,
3404
+ copyEnglish,
3405
+ copyAddress,
3406
+ donorTermsSource,
3407
+ consentGateSource,
3408
+ robotsTxt,
3409
+ viewSource,
2262
3410
  donorTerms,
2263
3411
  consentGate,
2264
3412
  feedImageFormats,
2265
3413
  listingNoindex,
2266
3414
  listingLinks,
2267
3415
  sitemapNoindex,
3416
+ sitemapCoverage,
3417
+ orphanPages,
2268
3418
  pageHeads,
2269
3419
  canonicalLink,
2270
3420
  openGraph,
2271
3421
  trailingSlash,
3422
+ jsonLd,
3423
+ rentalMarkup,
3424
+ breadcrumbs,
2272
3425
  v9ProductionHub,
3426
+ v10ProductionApi,
2273
3427
  pageStructure,
3428
+ headingRatio,
3429
+ {
3430
+ id: "voffice-credit",
3431
+ title: "The site footer credits vOffice",
3432
+ severity: "error",
3433
+ stage: "dist",
3434
+ begin: (ctx) => {
3435
+ if (!ctx.hasDist) return null;
3436
+ const findings = [];
3437
+ return {
3438
+ visit: (page) => {
3439
+ if (page.redirect) return;
3440
+ const { footers, credit } = footerCredit(page.document);
3441
+ if (footers === 0 && HOME.test(page.path)) findings.push({
3442
+ path: page.path,
3443
+ message: "The home page has no site footer, so it carries no vOffice credit. Render the site footer (a <footer> outside main, article, section, …) with: Realisiert mit <a href=\"https://www.v-office.com\">vOffice</a>."
3444
+ });
3445
+ else if (footers > 0 && !credit) findings.push({
3446
+ path: page.path,
3447
+ message: "The site footer does not link https://www.v-office.com. Add the credit line: Realisiert mit <a href=\"https://www.v-office.com\">vOffice</a> (the starter's footer has it, worded per language)."
3448
+ });
3449
+ },
3450
+ finish: () => findings
3451
+ };
3452
+ }
3453
+ },
2274
3454
  loadOrder,
3455
+ firstPaintPhotos,
2275
3456
  bannedCopy,
2276
3457
  duplicateSentences,
2277
3458
  quoteSources,
2278
3459
  rentalFacts
2279
3460
  ];
2280
3461
  const checksOf = (stage) => checks.filter((check) => check.stage === stage);
2281
- //#endregion
2282
- //#region src/options.ts
3462
+ // src/options.ts
2283
3463
  const CONFIG_FILE = "site-checks.config.json";
2284
3464
  /** Keys of checks earlier versions had. A file that still carries one is noted, never refused: a
2285
3465
  * site mid-rollout must not be stopped by a key it was told to add a release ago. */
@@ -2287,9 +3467,16 @@ const RETIRED_KEYS = {
2287
3467
  wiring: "the wiring check was removed in 0.3.0",
2288
3468
  optimizeDepsIgnore: "the optimize-deps check was removed in 0.3.0"
2289
3469
  };
2290
- /** The vOffice image hosts that answer JPEG unless asked for WebP: imgproxy's `plain` path (v9,
2291
- * `…jpg@webp`) and `dyn.v-office.com` (`….webp`). The v10 host answers WebP by itself. */
2292
- const DEFAULT_FEED_IMAGE_PATTERNS = ["\\/_\\/[^\\s]*\\/plain\\/[^\\s@]+\\.(?:jpe?g|png)$", "^https:\\/\\/dyn\\.v-office\\.com\\/image\\/[^\\s]+\\.(?:jpe?g|png)$"];
3470
+ /** The vOffice image hosts that answer JPEG unless asked for WebP: imgproxy's `plain` path on any
3471
+ * host (v9, `…jpg@webp`), any path on an `imgproxy.*` host and imgproxy's base64 form on any host
3472
+ * (`/_/rs:fit:…/aHR0….jpg`, `….webp`), and `dyn.v-office.com` (`….webp`). The v10 host
3473
+ * (`images.*.v-office.io`) answers WebP by itself and `webpUrl()` leaves it as it is. */
3474
+ const DEFAULT_FEED_IMAGE_PATTERNS = [
3475
+ "\\/_\\/[^\\s]*\\/plain\\/[^\\s@]+\\.(?:jpe?g|png)$",
3476
+ "^https:\\/\\/imgproxy\\.[a-z0-9.-]+\\/_\\/[^\\s]+\\.(?:jpe?g|png)$",
3477
+ "\\/_\\/[^\\s]*\\/aHR0[A-Za-z0-9_=\\/-]*\\.(?:jpe?g|png)$",
3478
+ "^https:\\/\\/dyn\\.v-office\\.com\\/image\\/[^\\s]+\\.(?:jpe?g|png)$"
3479
+ ];
2293
3480
  const STRUCTURE_RULES = [
2294
3481
  "one-h1",
2295
3482
  "heading-skip",
@@ -2321,6 +3508,13 @@ const stringList = (source, key, value) => {
2321
3508
  };
2322
3509
  const VALIDATORS = {
2323
3510
  donorTerms: stringList,
3511
+ donorPatterns: (source, key, value) => {
3512
+ if (!isStringList(value) || !value.every(nonEmpty)) throw new Error(`[site-checks] ${source}: "${key}" must be an array of non-empty strings`);
3513
+ for (const pattern of value) {
3514
+ if (pattern.includes("[[:")) throw new Error(`[site-checks] ${source}: "${key}" has a POSIX class in ${JSON.stringify(pattern)}: write [[:space:]] as \\s, [[:alpha:]] as \\p{L}`);
3515
+ compiles(source, key, pattern, "u");
3516
+ }
3517
+ },
2324
3518
  imageIgnore: stringList,
2325
3519
  feedImagePatterns: (source, key, value) => {
2326
3520
  stringList(source, key, value);
@@ -2332,11 +3526,15 @@ const VALIDATORS = {
2332
3526
  },
2333
3527
  consentAllowedHosts: stringList,
2334
3528
  bannedCopy: (source, key, value) => {
2335
- if (!isListOf(value, (e) => nonEmpty(e.pattern) && nonEmpty(e.why))) throw new Error(`[site-checks] ${source}: "${key}" must be an array of { pattern, why }`);
3529
+ if (!isListOf(value, (e) => nonEmpty(e.pattern) && nonEmpty(e.why) && (e.in === void 0 || e.in === "src") && (e.srcExclude === void 0 || isStringList(e.srcExclude)))) throw new Error(`[site-checks] ${source}: "${key}" must be an array of { pattern, why } ("in" is "src" when given, "srcExclude" a list of paths)`);
2336
3530
  for (const { pattern } of value) compiles(source, key, pattern, "g");
2337
3531
  },
2338
3532
  copyExcludePaths: stringList,
2339
3533
  bannedCopyExcludePaths: stringList,
3534
+ address: (source, key, value) => {
3535
+ if (value !== null && value !== "du" && value !== "Sie") throw new Error(`[site-checks] ${source}: "${key}" must be "du", "Sie" or null`);
3536
+ },
3537
+ addressAllow: stringList,
2340
3538
  allowDuplicateSentences: stringList,
2341
3539
  quoteSources: stringList,
2342
3540
  factCheckAccepted: stringList,
@@ -2390,6 +3588,7 @@ function loadOptions(root, overrides = {}, note = () => {}) {
2390
3588
  const pick = (key, fallback) => given[key] ?? fromFile[key] ?? fallback;
2391
3589
  return {
2392
3590
  donorTerms: pick("donorTerms", []),
3591
+ donorPatterns: pick("donorPatterns", []),
2393
3592
  imageIgnore: pick("imageIgnore", []),
2394
3593
  feedImagePatterns: pick("feedImagePatterns", DEFAULT_FEED_IMAGE_PATTERNS),
2395
3594
  listingPages: pick("listingPages", []),
@@ -2398,6 +3597,8 @@ function loadOptions(root, overrides = {}, note = () => {}) {
2398
3597
  bannedCopy: pick("bannedCopy", []),
2399
3598
  copyExcludePaths: pick("copyExcludePaths", []),
2400
3599
  bannedCopyExcludePaths: pick("bannedCopyExcludePaths", []),
3600
+ address: given.address !== void 0 ? given.address : fromFile.address ?? null,
3601
+ addressAllow: pick("addressAllow", []),
2401
3602
  allowDuplicateSentences: pick("allowDuplicateSentences", []),
2402
3603
  quoteSources: pick("quoteSources", []),
2403
3604
  factCheckAccepted: pick("factCheckAccepted", []),
@@ -2406,8 +3607,7 @@ function loadOptions(root, overrides = {}, note = () => {}) {
2406
3607
  exclude: pick("exclude", {})
2407
3608
  };
2408
3609
  }
2409
- //#endregion
2410
- //#region src/runner.ts
3610
+ // src/runner.ts
2411
3611
  /** Findings kept per check in the report; the rest is counted in `omitted`. */
2412
3612
  const MAX_FINDINGS_PER_CHECK = 25;
2413
3613
  /** The controller's `siteCheckReportSchema` accepts a finding message of at most 2000 characters
@@ -2538,8 +3738,7 @@ const contextInput = (input) => ({
2538
3738
  const runSiteChecks = (input, list = checks) => runChecks(() => loadContext(contextInput(input)), list, (ctx) => ctx.options.exclude);
2539
3739
  /** Results with status `error`: the ones `site-checks` exits non-zero for. */
2540
3740
  const blockingResults = (report) => report.results.filter((r) => r.status === "error");
2541
- //#endregion
2542
- //#region src/report.ts
3741
+ // src/report.ts
2543
3742
  /** The `dist` stage's report file under `dist/`. The build worker reads it after the build and
2544
3743
  * never uploads it (it names source paths and configured terms). */
2545
3744
  const SITE_CHECKS_FILE = "site-checks.json";
@@ -2567,8 +3766,7 @@ const refusalMessage = (report, stage, reportFile) => {
2567
3766
  };
2568
3767
  /** One line naming what refused the build, for the studio: the failing checks and their counts. */
2569
3768
  const summarizeBlocking = (report) => "Checks refused the build: " + blockingResults(report).map((r) => `${r.id} (${plural(count(r), "finding")})`).join(", ");
2570
- //#endregion
2571
- //#region src/distChecks/insecureResources.ts
3769
+ // src/distChecks/insecureResources.ts
2572
3770
  /** `<link>` relations the browser fetches as a subresource; canonical,
2573
3771
  * alternate, preconnect and friends are hints or metadata, not loads. */
2574
3772
  const RESOURCE_RELS = /* @__PURE__ */ new Set([
@@ -2615,8 +3813,7 @@ const insecureResources = {
2615
3813
  };
2616
3814
  }
2617
3815
  };
2618
- //#endregion
2619
- //#region src/distChecks/internalLinks.ts
3816
+ // src/distChecks/internalLinks.ts
2620
3817
  /** A same-site reference (`href`, `src`, `srcset`, `poster`) that no file of
2621
3818
  * the build serves — the 404 class, caught before a guest hits it. One finding
2622
3819
  * per missing target, on the first page that references it and with the count
@@ -2661,8 +3858,7 @@ const internalLinks = {
2661
3858
  };
2662
3859
  }
2663
3860
  };
2664
- //#endregion
2665
- //#region src/distChecks/keyPages.ts
3861
+ // src/distChecks/keyPages.ts
2666
3862
  /** The pages every build must emit: the home page, and on an Astro site the
2667
3863
  * 404 page the hosting serves for unknown paths. */
2668
3864
  const keyPages = {
@@ -2682,8 +3878,7 @@ const keyPages = {
2682
3878
  return { finish: () => findings };
2683
3879
  }
2684
3880
  };
2685
- //#endregion
2686
- //#region src/distChecks/legalPages.ts
3881
+ // src/distChecks/legalPages.ts
2687
3882
  /** German sites owe an Impressum (§ 5 DDG) and a privacy notice (Art. 13
2688
3883
  * DSGVO) reachable from every page; English wordings count too. Matched on
2689
3884
  * the link's target and its text, so a footer link named either way passes.
@@ -2719,30 +3914,62 @@ const legalPages = {
2719
3914
  };
2720
3915
  }
2721
3916
  };
2722
- //#endregion
2723
- //#region src/distChecks/notFoundBeacon.ts
2724
- const BEACON = /\/api\/404-log\b/;
2725
- /** The hosting serves 404.html for every unknown path, and AI Studio learns of
2726
- * the miss only when that page posts the URL to /api/404-log
2727
- * (docs/internal/operations/404-logging.md). Without the beacon the site's 404 list stays
2728
- * empty and no redirect is ever suggested. Astro bundles page scripts into
2729
- * files under _astro/, so the page's same-site scripts count as well. */
3917
+ // src/distChecks/notFoundBeacon.ts
3918
+ /** A call that posts to the endpoint, not the bare path: a comment or a string naming
3919
+ * `/api/404-log` logs nothing. `fetch("/api/404-log", …)`, `fetch(new URL("/api/404-log", …))`,
3920
+ * `navigator.sendBeacon("…/api/404-log", …)`. */
3921
+ /** The start of a call that posts what follows: `fetch(…)`, `fetch(new URL(…))`,
3922
+ * `fetch(new Request(…))`, `navigator.sendBeacon(…)`, optional calls (`sendBeacon?.(…)`) too. A
3923
+ * Request is no URL for `sendBeacon`. */
3924
+ const POSTS_TO = "\\b(?:fetch\\s*(?:\\?\\.)?\\s*\\(\\s*(?:new\\s+(?:URL|Request)\\s*\\(\\s*)?|sendBeacon\\s*(?:\\?\\.)?\\s*\\(\\s*(?:new\\s+URL\\s*\\(\\s*)?)";
3925
+ const BEACON = new RegExp(`${POSTS_TO}["'\`][^"'\`]*\\/api\\/404-log\\b`);
3926
+ /** A binding that holds the endpoint, as written or minified: `const endpoint = "/api/404-log"`,
3927
+ * `let a=1,e="/api/404-log"`. It counts only where a call posts to it. */
3928
+ const ENDPOINT_BINDING = /(?:\b(?:const|let|var)\s+|,\s*)([A-Za-z_$][\w$]*)\s*=\s*(?:new\s+(?:URL|Request)\s*\(\s*)?["'`][^"'`]*\/api\/404-log\b/g;
3929
+ const callsBinding = (code) => [...code.matchAll(ENDPOINT_BINDING)].some((m) => new RegExp(`${POSTS_TO}${m[1].replace(/\$/g, "\\$")}(?![\\w$])`).test(code));
3930
+ /** The modules a script imports, statically or on demand: Astro splits a page's script into chunks
3931
+ * under _astro/ that import each other. */
3932
+ const IMPORT = /(?:\bfrom\s*|\bimport\s*\(?\s*)["']([^"']+\.m?js)(?:\?[^"']*)?["']/g;
3933
+ /** The hosting serves 404.html for every unknown path, and AI Studio learns of the miss only when
3934
+ * that page posts the URL to /api/404-log (docs/internal/operations/404-logging.md). Without the
3935
+ * beacon the site's 404 list stays empty and no redirect is ever suggested. Astro bundles page
3936
+ * scripts into files under _astro/, so the page's same-site scripts count, with the chunks they
3937
+ * import. An error: the 404 page is the site's own code. Astro builds only: the guest and owner
3938
+ * apps route every path themselves and have no 404 page. */
2730
3939
  const notFoundBeacon = {
2731
3940
  id: "not-found-beacon",
2732
3941
  title: "The 404 page reports missing URLs to AI Studio",
2733
- severity: "warning",
3942
+ severity: "error",
2734
3943
  begin(ctx) {
2735
3944
  if (!ctx.isAstro || !ctx.has("404.html")) return null;
2736
3945
  let beacon = false;
3946
+ /** Whether the code, or a build file it imports (`dir` is where it resolves from), calls the
3947
+ * beacon. Each file is read once. */
3948
+ const seen = /* @__PURE__ */ new Set();
3949
+ const calls = (code, dir) => {
3950
+ const stripped = stripComments(code);
3951
+ if (BEACON.test(stripped) || callsBinding(stripped)) return true;
3952
+ for (const match of stripped.matchAll(IMPORT)) {
3953
+ const spec = match[1];
3954
+ if (!spec.startsWith("/") && !spec.startsWith(".")) continue;
3955
+ const rel = path.posix.normalize(spec.startsWith("/") ? spec : path.posix.join(dir, spec)).replace(/^\/+/, "");
3956
+ if (seen.has(rel) || !ctx.has(rel)) continue;
3957
+ seen.add(rel);
3958
+ if (calls(ctx.read(rel), path.posix.dirname(`/${rel}`))) return true;
3959
+ }
3960
+ return false;
3961
+ };
2737
3962
  const visit = (page) => {
2738
3963
  if (page.path !== "404.html") return;
2739
- beacon = [...page.document.querySelectorAll("script")].map((script) => {
3964
+ beacon = [...page.document.querySelectorAll("script")].some((script) => {
2740
3965
  const src = script.getAttribute("src");
2741
- if (!src) return script.textContent ?? "";
2742
- if (!isSameSiteReference(src, ctx.origin)) return "";
3966
+ if (!src) return calls(script.textContent ?? "", page.base.replace(/[^/]*$/, ""));
3967
+ if (!isSameSiteReference(src, ctx.origin)) return false;
2743
3968
  const file = resolveReference(page, src).replace(/^\//, "");
2744
- return ctx.has(file) ? ctx.read(file) : "";
2745
- }).some((code) => BEACON.test(code));
3969
+ if (seen.has(file) || !ctx.has(file)) return false;
3970
+ seen.add(file);
3971
+ return calls(ctx.read(file), path.posix.dirname(`/${file}`));
3972
+ });
2746
3973
  };
2747
3974
  const finish = () => beacon ? [] : [{
2748
3975
  message: "404.html does not call /api/404-log: missing URLs are never logged",
@@ -2754,8 +3981,7 @@ const notFoundBeacon = {
2754
3981
  };
2755
3982
  }
2756
3983
  };
2757
- //#endregion
2758
- //#region src/distChecks/pageMetadata.ts
3984
+ // src/distChecks/pageMetadata.ts
2759
3985
  /** What every page needs in its head: a title, a description, the document
2760
3986
  * language. Missing ones are the classic leftovers of a generated layout. A
2761
3987
  * redirect stub is no page anyone reads and is skipped. */
@@ -2787,8 +4013,7 @@ const pageMetadata = {
2787
4013
  };
2788
4014
  }
2789
4015
  };
2790
- //#endregion
2791
- //#region src/distChecks/placeholderContent.ts
4016
+ // src/distChecks/placeholderContent.ts
2792
4017
  /** Text that should never reach a visitor: template filler, a value that was
2793
4018
  * rendered instead of formatted, a template expression the build did not
2794
4019
  * evaluate. And references to development hosts or example domains. */
@@ -2854,8 +4079,7 @@ const placeholderContent = {
2854
4079
  };
2855
4080
  }
2856
4081
  };
2857
- //#endregion
2858
- //#region src/distChecks/siteManifest.ts
4082
+ // src/distChecks/siteManifest.ts
2859
4083
  const FILE = "site-manifest.json";
2860
4084
  const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
2861
4085
  const manifestFindings = (ctx) => {
@@ -2894,8 +4118,7 @@ const siteManifest = {
2894
4118
  severity: "warning",
2895
4119
  begin: (ctx) => ({ finish: () => manifestFindings(ctx) })
2896
4120
  };
2897
- //#endregion
2898
- //#region src/distChecks/sitemap.ts
4121
+ // src/distChecks/sitemap.ts
2899
4122
  const pathOf = (url) => {
2900
4123
  try {
2901
4124
  return new URL(url.trim(), "http://site.invalid").pathname;
@@ -2903,8 +4126,7 @@ const pathOf = (url) => {
2903
4126
  return null;
2904
4127
  }
2905
4128
  };
2906
- //#endregion
2907
- //#region src/distChecks/index.ts
4129
+ // src/distChecks/index.ts
2908
4130
  /**
2909
4131
  * The dist checks: the platform's checks over a build's `dist/`. They are part of the `dist`
2910
4132
  * stage (`site-checks dist` runs them after the site's own), and the build worker also runs them
@@ -2979,8 +4201,7 @@ const runDistChecks = (distDir, opts, list = distChecks) => {
2979
4201
  assertKnownChecks(exclude, [...checks, ...distChecks].map((check) => check.id));
2980
4202
  return runChecks(() => loadDistContext(distDir, opts), list, () => exclude);
2981
4203
  };
2982
- //#endregion
2983
- //#region src/stages.ts
4204
+ // src/stages.ts
2984
4205
  /**
2985
4206
  * Runs one stage over a project. `src` runs the source checks and leaves any `dist/` unread;
2986
4207
  * `dist` runs the site's dist-stage checks and the platform's dist checks over the build output,
@@ -3017,8 +4238,7 @@ const runStage = async (stage, input) => {
3017
4238
  isAstro
3018
4239
  }), list, () => exclude);
3019
4240
  };
3020
- //#endregion
3021
- //#region src/cli.ts
4241
+ // src/cli.ts
3022
4242
  const USAGE = `Usage: site-checks <src | dist | verify> [options]
3023
4243
 
3024
4244
  src the source checks, before the build (reads the project, never dist/)
@@ -3205,5 +4425,4 @@ async function verify(root, site, io, cwd) {
3205
4425
  io.out(`[site-checks] verify passed: ${passed.join(", ")}`);
3206
4426
  return 0;
3207
4427
  }
3208
- //#endregion
3209
4428
  export { loadOptions as _, runDistChecks as a, readAstroConfig as b, refusalMessage as c, MAX_FINDINGS_PER_CHECK as d, MAX_MESSAGE_CHARS as f, CONFIG_FILE as g, runSiteChecks as h, distChecks as i, summarizeBlocking as l, blockingResults as m, cli as n, SITE_CHECKS_FILE as o, MAX_PATH_CHARS as p, runStage as r, findingLine as s, USAGE as t, summaryLines as u, checks as v, checksOf as y };