@v-office/site-checks 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,8 +2,209 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parseHTML } from "linkedom";
4
4
  import { brotliCompressSync, constants } from "node:zlib";
5
- import { execFile, execFileSync } from "node:child_process";
6
5
  import os from "node:os";
6
+ import { parseArgs } from "node:util";
7
+ //#region src/jsComments.ts
8
+ /** One pass over JavaScript (or the script parts of a component): its comments, and the code with
9
+ * them blanked. String and template literals are kept whole, so `//` in `"https://…"` or `/*` in
10
+ * `'a /* b'` is no comment; `${…}` inside a template is code again, to its matching `}`. `'…'` and
11
+ * `"…"` end at their quote or at a newline (an apostrophe in markup text shields only the rest of
12
+ * its line). A block comment keeps its newlines, so line starts stay line starts. A regular
13
+ * expression literal (`/[/*]/g`) is kept whole too, where a `/` can only start one: after an
14
+ * operator or opening bracket, or a keyword such as `return`. */
15
+ /** Where a `/` begins a regular expression rather than a division: after one of these, an arrow,
16
+ * or a keyword that takes an expression. Never after a lone `<` or `>`, so markup paths stay text,
17
+ * and never after `)`, where a division is the common case. */
18
+ const BEFORE_REGEX = /* @__PURE__ */ new Set("(,=:[!&|?{};");
19
+ const KEYWORD_BEFORE = /\b(?:return|typeof|case|do|else|in|of|void|yield|await|delete|new)$/;
20
+ /** Longer than the longest keyword, so the tail holds the character before it. */
21
+ const KEYWORD_TAIL = 8;
22
+ const SPACE = /\s/;
23
+ /** A line comment ends at any line terminator, not only LF. */
24
+ const LINE_END = /[\n\r\u2028\u2029]/g;
25
+ /** Whether a `/` at `at` starts a regular expression, judged by the last code before it: the text
26
+ * read backwards past whitespace and the comments found so far. Only that short tail is read, so a
27
+ * multi-megabyte bundle scans in linear time. */
28
+ const startsRegex = (text, at, comments) => {
29
+ let end = at;
30
+ let c = comments.length - 1;
31
+ while (end > 0) if (c >= 0 && comments[c].end === end) end = comments[c--].start;
32
+ else if (SPACE.test(text[end - 1])) end -= 1;
33
+ else break;
34
+ if (end === 0) return true;
35
+ const last = text[end - 1];
36
+ return BEFORE_REGEX.has(last) || last === ">" && text[end - 2] === "=" || KEYWORD_BEFORE.test(text.slice(Math.max(0, end - KEYWORD_TAIL), end));
37
+ };
38
+ /** The index past a regular expression literal starting at `start`, its flags included: `/` inside
39
+ * a character class or after `\` does not end it. A newline first means it was no literal: the
40
+ * `/` alone is consumed. */
41
+ const regexEnd = (text, start) => {
42
+ let inClass = false;
43
+ for (let j = start + 1; j < text.length; j += 1) {
44
+ const ch = text[j];
45
+ if (ch === "\\") j += 1;
46
+ else if (ch === "\n") break;
47
+ else if (ch === "[") inClass = true;
48
+ else if (ch === "]") inClass = false;
49
+ else if (ch === "/" && !inClass) {
50
+ let end = j + 1;
51
+ while (end < text.length && /[a-z]/i.test(text[end])) end += 1;
52
+ return end;
53
+ }
54
+ }
55
+ return start + 1;
56
+ };
57
+ /** Every comment in the text, in order, with its position. Everything else is code, as written. */
58
+ const findComments = (text) => {
59
+ const comments = [];
60
+ let i = 0;
61
+ const n = text.length;
62
+ const templates = [];
63
+ let depth = 0;
64
+ while (i < n) {
65
+ const c = text[i];
66
+ if (templates.length > 0 && templates.at(-1) === -1) {
67
+ if (c === "\\") i += 2;
68
+ else if (c === "`") {
69
+ templates.pop();
70
+ i += 1;
71
+ } else if (c === "$" && text[i + 1] === "{") {
72
+ templates[templates.length - 1] = depth;
73
+ depth += 1;
74
+ i += 2;
75
+ } else i += 1;
76
+ continue;
77
+ }
78
+ if (c === "\\") i += 2;
79
+ else if (c === "/" && text[i + 1] === "/") {
80
+ LINE_END.lastIndex = i;
81
+ const end = LINE_END.exec(text)?.index ?? n;
82
+ comments.push({
83
+ start: i,
84
+ end,
85
+ text: text.slice(i, end)
86
+ });
87
+ i = end;
88
+ } else if (c === "/" && text[i + 1] === "*") {
89
+ const close = text.indexOf("*/", i + 2);
90
+ const end = close === -1 ? n : close + 2;
91
+ comments.push({
92
+ start: i,
93
+ end,
94
+ text: text.slice(i, end)
95
+ });
96
+ i = end;
97
+ } else if (c === "/" && startsRegex(text, i, comments)) i = regexEnd(text, i);
98
+ else if (c === "'" || c === "\"") {
99
+ let j = i + 1;
100
+ while (j < n && text[j] !== c && text[j] !== "\n") j += text[j] === "\\" ? 2 : 1;
101
+ if (j < n && text[j] === c) j += 1;
102
+ i = j;
103
+ } else if (c === "`") {
104
+ templates.push(-1);
105
+ i += 1;
106
+ } else {
107
+ if (c === "{") depth += 1;
108
+ else if (c === "}") {
109
+ depth -= 1;
110
+ if (templates.length > 0 && templates.at(-1) === depth) templates[templates.length - 1] = -1;
111
+ }
112
+ i += 1;
113
+ }
114
+ }
115
+ return comments;
116
+ };
117
+ /** The text with its comments blanked: a line comment becomes a space, a block comment a space
118
+ * and its newlines. */
119
+ const stripComments = (text) => {
120
+ let out = "";
121
+ let from = 0;
122
+ for (const { start, end, text: comment } of findComments(text)) {
123
+ out += `${text.slice(from, start)} ${"\n".repeat((comment.match(/\n/g) ?? []).length)}`;
124
+ from = end;
125
+ }
126
+ return out + text.slice(from);
127
+ };
128
+ /** Every comment in the text, as written. */
129
+ const jsComments = (text) => findComments(text).map((c) => c.text);
130
+ //#endregion
131
+ //#region src/astroConfig.ts
132
+ /** The Astro config files, in the order Astro itself looks for them. */
133
+ const CONFIG_FILES = [
134
+ "astro.config.mjs",
135
+ "astro.config.js",
136
+ "astro.config.ts",
137
+ "astro.config.mts",
138
+ "astro.config.cjs",
139
+ "astro.config.cts"
140
+ ];
141
+ /** Astro's `trailingSlash` when the config does not set it. */
142
+ const ASTRO_DEFAULT_TRAILING_SLASH = "ignore";
143
+ /** The settings that move the source or public folder away from `src/` and `public/`. */
144
+ const LAYOUT_KEYS = [
145
+ "root",
146
+ "srcDir",
147
+ "publicDir"
148
+ ];
149
+ /** A property whose whole value is one quoted string, its key bare or quoted: the value must end
150
+ * the property (a comma, the object's end or the file's, line breaks allowed before them), so a
151
+ * computed value (`"https://www." + DOMAIN`, on one line or two) is not taken for its first part.
152
+ * No multiline flag: `$` is the file's end, never a line's. The value patterns exclude `$`, so a
153
+ * template with `${…}` never matches. */
154
+ const literal = (text, key, value) => new RegExp(`(?:^|[\\s,{])(["']?)${key}\\1\\s*:\\s*(["'\`])(${value})\\2\\s*(?:,|\\}|$)`).exec(text)?.[3];
155
+ /** A string or template literal (the comments are already gone). */
156
+ const STRING = /`(?:\\[\s\S]|[^\\`])*`|(["'])(?:\\.|(?!\1)[^\\\n])*\1/g;
157
+ /** The text with every string blanked but the object keys (`"site": …`): a module specifier
158
+ * (`"@v-office/site-manifest/astro"`) or a value (`"https://my-site.de"`) names no setting. */
159
+ const code = (text) => text.replace(STRING, (string, _quote, at) => /^\s*:/.test(text.slice(at + string.length)) ? string : "\"\"");
160
+ /** How often the code names the setting at all: a property, a quoted key, a shorthand
161
+ * (`{ trailingSlash }`), a variable. */
162
+ const mentions = (text, key) => code(text).match(new RegExp(`\\b${key}\\b`, "g"))?.length ?? 0;
163
+ /** A named object spread into another (`...defaults`, `...base`): it may carry any setting, and
164
+ * override one written beside it. */
165
+ const NAMED_SPREAD = /\.\.\.\s*[A-Za-z_$]/;
166
+ /** Any spread. An inline one (`...(isProd ? { site: "https://…" } : {})`) shows its keys in the
167
+ * text, but a value inside it may be on a branch the config does not take. */
168
+ const SPREAD = /\.\.\./;
169
+ /**
170
+ * One setting of the config, read as text, or `undefined` when it cannot be told safely. The file
171
+ * is not parsed, so only the unambiguous case counts: the file names the setting exactly once, as
172
+ * a property whose whole value is a plain string, and spreads nothing. Anything else (a computed
173
+ * value, a variable or shorthand, the name twice, any spread) is unknown, and the checks that need
174
+ * it wait. A file that never names it and spreads no named object surely leaves it `unset`.
175
+ *
176
+ * This is the whole rule, on purpose: the builder passes `--site`, so the reader serves local runs
177
+ * only. A config shape it does not follow (a ternary around the whole export, say) is not chased
178
+ * with another rule; `--site` settles the site.
179
+ */
180
+ const setting = (text, key, value, unset) => {
181
+ if (NAMED_SPREAD.test(text)) return void 0;
182
+ const count = mentions(text, key);
183
+ if (count === 0) return unset;
184
+ return count === 1 && !SPREAD.test(text) ? literal(text, key, value) : void 0;
185
+ };
186
+ /** The facts the checks need from the Astro config, read from the file as text: importing the
187
+ * config would run every integration in it. Comments are stripped first, so a commented-out
188
+ * value never stands in for the active one. A value that is computed (`site:
189
+ * process.env.SITE_URL`) or ambiguous is not taken; the builder passes the site URL, and without
190
+ * one the checks that need it wait. */
191
+ const readAstroConfig = (root) => {
192
+ const file = CONFIG_FILES.map((name) => path.join(root, name)).find((f) => fs.existsSync(f));
193
+ if (!file) return {
194
+ found: false,
195
+ site: void 0,
196
+ trailingSlash: void 0,
197
+ layoutKey: void 0
198
+ };
199
+ const text = stripComments(fs.readFileSync(file, "utf8"));
200
+ return {
201
+ found: true,
202
+ site: setting(text, "site", "https?:\\/\\/[^\"'`\\s$]+", void 0),
203
+ trailingSlash: setting(text, "trailingSlash", "always|never|ignore", ASTRO_DEFAULT_TRAILING_SLASH),
204
+ layoutKey: LAYOUT_KEYS.find((key) => mentions(text, key) > 0)
205
+ };
206
+ };
207
+ //#endregion
7
208
  //#region src/checks/consentGate.ts
8
209
  /** The consent kit's files in a site: its presence under `src/lib/consent/` is what makes the
9
210
  * check apply; the vendors the site enables and the fleet registry's review of them. */
@@ -22,11 +223,14 @@ const hostOf = (url) => {
22
223
  };
23
224
  /** No third-party script or iframe loads outside the consent layer (the kit injects a vendor's
24
225
  * script after consent, so one in the HTML loads before it), and no vendor the site enables is
25
- * still unapproved in the fleet's consent registry. Skipped in a project without the kit. */
226
+ * still unapproved in the fleet's consent registry. Skipped in a project without the kit. The
227
+ * page scan waits while the site's own host is unknown (no `--site`, a computed `site`): without
228
+ * it a same-site absolute URL would read as third-party. The registry check runs regardless. */
26
229
  const consentGate = {
27
230
  id: "consent-gate",
28
231
  title: "Third-party resources wait for consent",
29
232
  severity: "error",
233
+ stage: "dist",
30
234
  begin: (ctx) => {
31
235
  const sources = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts", ".json"]));
32
236
  const byRel = new Map(sources.map((file) => [ctx.rel(file), file]));
@@ -36,6 +240,7 @@ const consentGate = {
36
240
  const findings = [];
37
241
  return {
38
242
  visit: (page) => {
243
+ if (!siteHost) return;
39
244
  for (const el of page.document.querySelectorAll("script[src], iframe[src]")) {
40
245
  const raw = (el.getAttribute("src") ?? "").trim();
41
246
  const src = raw.startsWith("//") ? `https:${raw}` : raw;
@@ -162,8 +367,8 @@ const loadDistContext = (distDir, opts) => ({
162
367
  origin: opts.siteUrl ? new URL(opts.siteUrl).origin : void 0
163
368
  });
164
369
  const loadContext = (input) => {
165
- const { root, srcDir, publicDir, distDir, config, options } = input;
166
- const hasDist = fs.existsSync(distDir);
370
+ const { root, srcDir, publicDir, distDir, stage, config, options } = input;
371
+ const hasDist = stage === "src" ? false : stage === "dist" || fs.existsSync(distDir);
167
372
  return {
168
373
  ...hasDist ? loadBuildOutput(distDir) : noBuildOutput(distDir),
169
374
  root,
@@ -178,6 +383,16 @@ const loadContext = (input) => {
178
383
  packageJson: readPackageJson(root)
179
384
  };
180
385
  };
386
+ /** The `dist` stage's context: the site's, with the build, plus what a dist check reads of it.
387
+ * Throws when `dist/` cannot be read, so the runner fails every check of the stage. */
388
+ const loadDistStageContext = (input) => ({
389
+ ...loadContext({
390
+ ...input,
391
+ stage: "dist"
392
+ }),
393
+ isAstro: input.isAstro,
394
+ origin: input.config.site ? new URL(input.config.site).origin : void 0
395
+ });
181
396
  const readPage = (ctx, file) => {
182
397
  const url = fileToUrl(file);
183
398
  const { document } = parseHTML(ctx.read(file));
@@ -370,6 +585,7 @@ const bannedCopy = {
370
585
  id: "banned-copy",
371
586
  title: "Wordings banned by a recorded correction",
372
587
  severity: "warning",
588
+ stage: "dist",
373
589
  begin: (ctx) => {
374
590
  if (!ctx.hasDist || ctx.options.bannedCopy.length === 0) return null;
375
591
  const skip = [...ctx.options.copyExcludePaths, ...ctx.options.bannedCopyExcludePaths];
@@ -399,6 +615,7 @@ const duplicateSentences = {
399
615
  id: "duplicate-sentences",
400
616
  title: "A sentence printed twice on one page",
401
617
  severity: "warning",
618
+ stage: "dist",
402
619
  begin: (ctx) => {
403
620
  if (!ctx.hasDist) return null;
404
621
  const allowed = new Set(ctx.options.allowDuplicateSentences.map(normalize$3));
@@ -449,6 +666,7 @@ const quoteSources = {
449
666
  id: "quote-sources",
450
667
  title: "Quotes match their sources",
451
668
  severity: "warning",
669
+ stage: "dist",
452
670
  begin: (ctx) => {
453
671
  if (!ctx.hasDist || ctx.options.quoteSources.length === 0) return null;
454
672
  const findings = [];
@@ -485,7 +703,7 @@ const quoteSources = {
485
703
  /** More than this and the point is made; the runner keeps 25 anyway. */
486
704
  const MAX_RAW_FINDINGS = 100;
487
705
  const normalize$2 = (text) => text.normalize("NFC").toLowerCase().replace(/\s+/g, " ");
488
- const escape$1 = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
706
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
489
707
  const WORD = /[\p{L}\p{N}]/u;
490
708
  /** A term as a whole word: where it starts or ends with a letter or digit, the text next to it must
491
709
  * not continue the word, so "schlei" does not match "wendeschleife" and "emden" not "fremden". A
@@ -493,7 +711,7 @@ const WORD = /[\p{L}\p{N}]/u;
493
711
  * there as written. */
494
712
  const wholeWord = (term) => {
495
713
  const chars = [...term];
496
- return new RegExp(`${WORD.test(chars[0]) ? "(?<![\\p{L}\\p{N}])" : ""}${escape$1(term)}${WORD.test(chars.at(-1)) ? "(?![\\p{L}\\p{N}])" : ""}`, "u");
714
+ return new RegExp(`${WORD.test(chars[0]) ? "(?<![\\p{L}\\p{N}])" : ""}${escape(term)}${WORD.test(chars.at(-1)) ? "(?![\\p{L}\\p{N}])" : ""}`, "u");
497
715
  };
498
716
  const excerpt$1 = (haystack, at, length) => {
499
717
  const start = Math.max(0, at - 30);
@@ -511,6 +729,7 @@ const donorTerms = {
511
729
  id: "donor-terms",
512
730
  title: "Terms of the template site in the built output",
513
731
  severity: "error",
732
+ stage: "dist",
514
733
  begin: (ctx) => {
515
734
  const terms = [...new Set(ctx.options.donorTerms.map(normalize$2).map((t) => t.trim()).filter(Boolean))].map((term) => ({
516
735
  term,
@@ -554,7 +773,7 @@ const donorTerms = {
554
773
  //#region src/checks/htmlComments.ts
555
774
  /** Astro passes an HTML comment in a template straight into the built page, where a visitor reads
556
775
  * it with View Source. Markdown pages too. */
557
- const SOURCE_EXTENSIONS$2 = /* @__PURE__ */ new Set([
776
+ const SOURCE_EXTENSIONS$1 = /* @__PURE__ */ new Set([
558
777
  ".astro",
559
778
  ".tsx",
560
779
  ".jsx",
@@ -567,9 +786,10 @@ const htmlComments = {
567
786
  id: "html-comments",
568
787
  title: "HTML comments in the source",
569
788
  severity: "error",
789
+ stage: "src",
570
790
  begin: (ctx) => ({ finish: () => {
571
791
  const findings = [];
572
- for (const file of ctx.sourceFiles(SOURCE_EXTENSIONS$2)) {
792
+ for (const file of ctx.sourceFiles(SOURCE_EXTENSIONS$1)) {
573
793
  const text = ctx.readSource(file);
574
794
  let index = text.indexOf("<!--");
575
795
  while (index !== -1) {
@@ -592,8 +812,9 @@ const RASTER = /* @__PURE__ */ new Set([
592
812
  ".png",
593
813
  ".webp"
594
814
  ]);
595
- /** Icons browsers and web manifests load as PNG by name: an AVIF beside them serves nobody. */
596
- const ICON = /^public\/(?:apple-touch-icon|favicon|icon-\d+)[^/]*\.png$/;
815
+ /** Icons browsers and web manifests load as PNG by name, at the root of `public/` or in its
816
+ * `favicon/` folder (the site starter's layout): an AVIF beside them serves nobody. */
817
+ const ICON = /^public\/(?:favicon\/)?(?:apple-touch-icon|favicon|icon-\d+|web-app-manifest-\d+x\d+)[^/]*\.png$/;
597
818
  /** The URLs an element references for an image: `src`, `poster`, every `srcset` candidate. */
598
819
  const imageUrls = (el) => {
599
820
  const urls = [];
@@ -614,6 +835,7 @@ const imageFormats = {
614
835
  id: "image-formats",
615
836
  title: "Image formats",
616
837
  severity: "error",
838
+ stage: "src",
617
839
  begin: (ctx) => {
618
840
  const ignored = new Set(ctx.options.imageIgnore);
619
841
  return { finish: () => {
@@ -639,6 +861,7 @@ const feedImageFormats = {
639
861
  id: "feed-image-formats",
640
862
  title: "Feed photo formats",
641
863
  severity: "warning",
864
+ stage: "dist",
642
865
  begin: (ctx) => {
643
866
  if (!ctx.hasDist) return null;
644
867
  const patterns = ctx.options.feedImagePatterns.map((source) => new RegExp(source, "i"));
@@ -695,7 +918,8 @@ const launchCheck = (base, inspect) => ({
695
918
  const canonicalLink = launchCheck({
696
919
  id: "canonical-link",
697
920
  title: "Indexable pages name their canonical URL",
698
- severity: "error"
921
+ severity: "error",
922
+ stage: "dist"
699
923
  }, (page) => {
700
924
  const href = page.document.querySelector("link[rel=\"canonical\"]")?.getAttribute("href");
701
925
  if (isAbsolute(href)) return [];
@@ -709,7 +933,8 @@ const canonicalLink = launchCheck({
709
933
  const openGraph = launchCheck({
710
934
  id: "open-graph",
711
935
  title: "Indexable pages carry a share preview",
712
- severity: "warning"
936
+ severity: "warning",
937
+ stage: "dist"
713
938
  }, (page) => {
714
939
  const meta = (name) => page.document.querySelector(`meta[property="${name}"], meta[name="${name}"]`)?.getAttribute("content");
715
940
  const missing = ["og:url", "og:image"].filter((name) => !isAbsolute(meta(name)));
@@ -720,19 +945,21 @@ const openGraph = launchCheck({
720
945
  });
721
946
  /** The launched site declares `trailingSlash: "never"`: one URL form everywhere means one CDN rule
722
947
  * set (`/x/` → 301 `/x`) and one redirect-map convention. Unset, the CDN decides per request and
723
- * `/x` and `/x/` are two URLs for one page. */
948
+ * `/x` and `/x/` are two URLs for one page. Waits while the setting cannot be read (computed, or
949
+ * set twice in the config file). */
724
950
  const trailingSlash = {
725
951
  id: "trailing-slash",
726
952
  title: "The site declares trailingSlash \"never\"",
727
953
  severity: "warning",
954
+ stage: "dist",
728
955
  begin: (ctx) => {
729
- if (!ctx.hasDist || !productionSite(ctx)) return null;
956
+ if (!ctx.hasDist || !productionSite(ctx) || ctx.config.trailingSlash === void 0) return null;
730
957
  let launched = false;
731
958
  return {
732
959
  visit: (page) => {
733
960
  if (indexable(page)) launched = true;
734
961
  },
735
- finish: () => !launched || ctx.config.trailingSlash === "never" ? [] : [{ message: `trailingSlash is "${ctx.config.trailingSlash ?? "ignore"}" in the Astro config: set it to "never" and write internal links without a trailing slash.` }]
962
+ 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.` }]
736
963
  };
737
964
  }
738
965
  };
@@ -781,6 +1008,7 @@ const listingNoindex = {
781
1008
  id: "listing-noindex",
782
1009
  title: "Rental listings are indexable",
783
1010
  severity: "error",
1011
+ stage: "dist",
784
1012
  begin: (ctx) => {
785
1013
  if (!ctx.hasDist) return null;
786
1014
  const configured = new Set(ctx.options.listingPages.map(normalize$1));
@@ -807,6 +1035,7 @@ const listingLinks = {
807
1035
  id: "listing-links",
808
1036
  title: "Rental listings reach crawlers",
809
1037
  severity: "warning",
1038
+ stage: "dist",
810
1039
  begin: (ctx) => {
811
1040
  if (!ctx.hasDist) return null;
812
1041
  const configured = new Set(ctx.options.listingPages.map(normalize$1));
@@ -894,6 +1123,7 @@ const loadOrder = {
894
1123
  id: "load-order",
895
1124
  title: "What pages load at start",
896
1125
  severity: "warning",
1126
+ stage: "dist",
897
1127
  begin: (ctx) => {
898
1128
  if (!ctx.hasDist) return null;
899
1129
  const chunks = /* @__PURE__ */ new Map();
@@ -1042,69 +1272,6 @@ const loadOrder = {
1042
1272
  }
1043
1273
  };
1044
1274
  //#endregion
1045
- //#region src/checks/optimizeDeps.ts
1046
- const SOURCE_EXTENSIONS$1 = /* @__PURE__ */ new Set([
1047
- ".ts",
1048
- ".tsx",
1049
- ".js",
1050
- ".jsx",
1051
- ".mjs",
1052
- ".astro"
1053
- ]);
1054
- /** `import … from "x"`, `import "x"`, `export … from "x"` and `import("x")`. Type-only forms load
1055
- * nothing and are skipped. */
1056
- const IMPORT_RE = /\b(?:import|export)\s+(type\s+)?(?:[^'"`;]*?\s+from\s+)?['"]([^'"]+)['"]|\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
1057
- /** The package a specifier belongs to: `@scope/name` or `name`. */
1058
- const packageOf = (specifier) => {
1059
- const parts = specifier.split("/");
1060
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? specifier;
1061
- };
1062
- /** Styles and assets are served, not pre-bundled: `maplibre-gl/dist/maplibre-gl.css` is no entry. */
1063
- const ASSET = /\.(?:css|scss|sass|less|json|svg|png|jpe?g|webp|avif|gif|woff2?)$/i;
1064
- const isBare = (specifier) => !/^[./#]/.test(specifier) && !/^(?:node|astro|virtual|data):/.test(specifier) && !ASSET.test(specifier);
1065
- /** Every runtime package `src/` imports is either reached by the dev server's startup crawl or
1066
- * named in `vite.optimizeDeps.include`; one that is neither gets discovered mid-session, which
1067
- * re-stamps every pre-bundled dependency and leaves an open tab asking for files that no longer
1068
- * exist. The sites' convention is to list every runtime package, which is what is checked: a bare
1069
- * specifier of a `dependencies` package, not exactly in `include` and not ignored. A warning: it
1070
- * slows the dev server, it changes nothing a visitor sees. */
1071
- const optimizeDeps = {
1072
- id: "optimize-deps",
1073
- title: "Runtime packages missing from vite.optimizeDeps.include",
1074
- severity: "warning",
1075
- begin: (ctx) => ({ finish: () => {
1076
- const included = new Set(ctx.config.optimizeDepsInclude);
1077
- const ignored = new Set(ctx.options.optimizeDepsIgnore);
1078
- const runtime = ctx.packageJson.dependencies;
1079
- const importers = /* @__PURE__ */ new Map();
1080
- for (const file of ctx.sourceFiles(SOURCE_EXTENSIONS$1)) {
1081
- const text = ctx.readSource(file);
1082
- for (const match of text.matchAll(IMPORT_RE)) {
1083
- const [, typeOnly, fromSpecifier, dynamicSpecifier] = match;
1084
- const specifier = fromSpecifier ?? dynamicSpecifier;
1085
- if (typeOnly || !specifier || !isBare(specifier)) continue;
1086
- const pkg = packageOf(specifier);
1087
- if (pkg === "astro" || pkg.startsWith("@types/") || !(pkg in runtime)) continue;
1088
- if (included.has(specifier) || ignored.has(specifier) || ignored.has(pkg)) continue;
1089
- const files = importers.get(specifier) ?? [];
1090
- const rel = ctx.rel(file);
1091
- if (!files.includes(rel)) files.push(rel);
1092
- importers.set(specifier, files);
1093
- }
1094
- }
1095
- const findings = [];
1096
- for (const [specifier, files] of [...importers].sort(([a], [b]) => a.localeCompare(b))) {
1097
- const shown = files.slice(0, 3).join(", ");
1098
- const more = files.length > 3 ? ` (+${files.length - 3} more)` : "";
1099
- findings.push({
1100
- path: files[0],
1101
- message: `"${specifier}" is imported by ${shown}${more} but not in vite.optimizeDeps.include. Add it there, or to optimizeDepsIgnore in site-checks.config.json if only server-side code uses it.`
1102
- });
1103
- }
1104
- return findings;
1105
- } })
1106
- };
1107
- //#endregion
1108
1275
  //#region src/checks/pageHeads.ts
1109
1276
  const MAX_TITLE = 60;
1110
1277
  const MAX_DESCRIPTION = 160;
@@ -1116,6 +1283,7 @@ const pageHeads = {
1116
1283
  id: "page-heads",
1117
1284
  title: "Titles and descriptions of indexable pages",
1118
1285
  severity: "warning",
1286
+ stage: "dist",
1119
1287
  begin: (ctx) => {
1120
1288
  if (!ctx.hasDist) return null;
1121
1289
  const findings = [];
@@ -1234,6 +1402,7 @@ const pageStructure = {
1234
1402
  id: "page-structure",
1235
1403
  title: "Page outline, landmarks, alt text, labels and tables",
1236
1404
  severity: "warning",
1405
+ stage: "dist",
1237
1406
  begin: (ctx) => {
1238
1407
  if (!ctx.hasDist) return null;
1239
1408
  const ignored = new Set(ctx.options.structureIgnore);
@@ -1442,6 +1611,7 @@ const rentalFacts = {
1442
1611
  id: "rental-facts",
1443
1612
  title: "Rental facts agree with the description",
1444
1613
  severity: "warning",
1614
+ stage: "dist",
1445
1615
  begin: (ctx) => {
1446
1616
  if (!ctx.hasDist) return null;
1447
1617
  const accepted = new Set(ctx.options.factCheckAccepted.map((line) => line.trim().split(/\s+/).join(" ")));
@@ -1521,6 +1691,7 @@ const sitemapNoindex = {
1521
1691
  id: "sitemap-noindex",
1522
1692
  title: "Published URL lists match the built pages",
1523
1693
  severity: "error",
1694
+ stage: "dist",
1524
1695
  begin: (ctx) => {
1525
1696
  if (!ctx.hasDist) return null;
1526
1697
  const start = ctx.has(SITEMAP_INDEX) ? [SITEMAP_INDEX] : ctx.files.filter((f) => /^sitemap[^/]*\.xml$/.test(f));
@@ -1608,6 +1779,7 @@ const syncOnce = {
1608
1779
  id: "sync-once",
1609
1780
  title: "Content loaders sync the PMS once per build",
1610
1781
  severity: "warning",
1782
+ stage: "src",
1611
1783
  begin: (ctx) => {
1612
1784
  const loader = ctx.sourceFiles(/* @__PURE__ */ new Set([".ts"])).find((file) => LOADER_FILES.includes(ctx.rel(file)));
1613
1785
  if (!loader) return null;
@@ -1711,22 +1883,25 @@ const v9Env = (ctx) => {
1711
1883
  };
1712
1884
  const sameUrl = (a, b) => (a ?? "").replace(/\/+$/, "") === b.replace(/\/+$/, "");
1713
1885
  /** The `.local` env files git tracks; empty outside a git checkout (nothing to tell then). */
1714
- const committedLocalFiles = (root) => LOCAL_ENV_FILES.filter((file) => {
1715
- try {
1716
- execFileSync("git", [
1717
- "ls-files",
1718
- "--error-unmatch",
1719
- "--",
1720
- file
1721
- ], {
1722
- cwd: root,
1723
- stdio: "ignore"
1724
- });
1725
- return true;
1726
- } catch {
1727
- return false;
1728
- }
1729
- });
1886
+ const committedLocalFiles = async (root) => {
1887
+ const { execFileSync } = await import("node:child_process");
1888
+ return LOCAL_ENV_FILES.filter((file) => {
1889
+ try {
1890
+ execFileSync("git", [
1891
+ "ls-files",
1892
+ "--error-unmatch",
1893
+ "--",
1894
+ file
1895
+ ], {
1896
+ cwd: root,
1897
+ stdio: "ignore"
1898
+ });
1899
+ return true;
1900
+ } catch {
1901
+ return false;
1902
+ }
1903
+ });
1904
+ };
1730
1905
  /** A launched v9 site builds against the production be-on! Hub: the build's env says
1731
1906
  * `CMS_STAGE=production`, or names the production Hub URLs. The Hub URLs are baked in at build
1732
1907
  * time, so a site built against the demo Hub renders fine, only with the demo catalogue. Also
@@ -1738,6 +1913,7 @@ const v9ProductionHub = {
1738
1913
  id: "v9-production-hub",
1739
1914
  title: "A launched v9 site calls the production Hub",
1740
1915
  severity: "warning",
1916
+ stage: "dist",
1741
1917
  begin: (ctx) => {
1742
1918
  const env = v9Env(ctx);
1743
1919
  if (!env || !ctx.hasDist || !productionSite(ctx)) return null;
@@ -1746,11 +1922,11 @@ const v9ProductionHub = {
1746
1922
  visit: (page) => {
1747
1923
  if (!page.redirect && !page.noindex && page.path !== "404.html") launched = true;
1748
1924
  },
1749
- finish: () => {
1925
+ finish: async () => {
1750
1926
  if (!launched) return [];
1751
1927
  const findings = [];
1752
1928
  const where = `the build's env (${BUILD_ENV_FILES.join(" / ")} or the process env)`;
1753
- for (const file of committedLocalFiles(ctx.root)) findings.push({
1929
+ for (const file of await committedLocalFiles(ctx.root)) findings.push({
1754
1930
  path: file,
1755
1931
  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.`
1756
1932
  });
@@ -1803,16 +1979,19 @@ const sdkVersion = (root) => {
1803
1979
  return "unknown version";
1804
1980
  }
1805
1981
  };
1806
- const run = (cli, args, cwd) => new Promise((resolve) => {
1807
- execFile(cli, args, {
1808
- cwd,
1809
- timeout: HUB_TIMEOUT_MS,
1810
- maxBuffer: 1048576
1811
- }, (err, stdout, stderr) => resolve({
1812
- code: err ? typeof err.code === "number" ? err.code : 1 : 0,
1813
- output: `${stdout}${stderr}`.trim()
1814
- }));
1815
- });
1982
+ const run = async (cli, args, cwd) => {
1983
+ const { execFile } = await import("node:child_process");
1984
+ return new Promise((resolve) => {
1985
+ execFile(cli, args, {
1986
+ cwd,
1987
+ timeout: HUB_TIMEOUT_MS,
1988
+ maxBuffer: 1048576
1989
+ }, (err, stdout, stderr) => resolve({
1990
+ code: err ? typeof err.code === "number" ? err.code : 1 : 0,
1991
+ output: `${stdout}${stderr}`.trim()
1992
+ }));
1993
+ });
1994
+ };
1816
1995
  /** Every be-on! Hub filter the site's search needs (the scope filter, the Merkliste's rental-id
1817
1996
  * filter, each searchable backend-filter definition) exists in the Hub the site builds against.
1818
1997
  * A filter the Hub does not serve matches nothing, or everything once a date is set. Asks the Hub
@@ -1823,6 +2002,7 @@ const v9HubFilters = {
1823
2002
  id: "v9-hub-filters",
1824
2003
  title: "The be-on! Hub serves the filters the v9 site needs",
1825
2004
  severity: "warning",
2005
+ stage: "src",
1826
2006
  begin: (ctx) => {
1827
2007
  const env = v9Env(ctx);
1828
2008
  if (!env) return null;
@@ -1860,158 +2040,34 @@ const v9HubFilters = {
1860
2040
  }
1861
2041
  };
1862
2042
  //#endregion
1863
- //#region src/jsComments.ts
1864
- /** One pass over JavaScript (or the script parts of a component): its comments, and the code with
1865
- * them blanked. String and template literals are kept whole, so `//` in `"https://…"` or `/*` in
1866
- * `'a /* b'` is no comment; `${…}` inside a template is code again, to its matching `}`. `'…'` and
1867
- * `"…"` end at their quote or at a newline (an apostrophe in markup text shields only the rest of
1868
- * its line). A block comment keeps its newlines, so line starts stay line starts. A regular
1869
- * expression literal (`/[/*]/g`) is kept whole too, where a `/` can only start one: after an
1870
- * operator or opening bracket, or a keyword such as `return`. */
1871
- /** Where a `/` begins a regular expression rather than a division: after one of these, an arrow,
1872
- * or a keyword that takes an expression. Never after a lone `<` or `>`, so markup paths stay text,
1873
- * and never after `)`, where a division is the common case. */
1874
- const BEFORE_REGEX = /* @__PURE__ */ new Set("(,=:[!&|?{};");
1875
- const KEYWORD_BEFORE = /\b(?:return|typeof|case|do|else|in|of|void|yield|await|delete|new)$/;
1876
- /** Longer than the longest keyword, so the tail holds the character before it. */
1877
- const KEYWORD_TAIL = 8;
1878
- const SPACE = /\s/;
1879
- /** A line comment ends at any line terminator, not only LF. */
1880
- const LINE_END = /[\n\r\u2028\u2029]/g;
1881
- /** Whether a `/` at `at` starts a regular expression, judged by the last code before it: the text
1882
- * read backwards past whitespace and the comments found so far. Only that short tail is read, so a
1883
- * multi-megabyte bundle scans in linear time. */
1884
- const startsRegex = (text, at, comments) => {
1885
- let end = at;
1886
- let c = comments.length - 1;
1887
- while (end > 0) if (c >= 0 && comments[c].end === end) end = comments[c--].start;
1888
- else if (SPACE.test(text[end - 1])) end -= 1;
1889
- else break;
1890
- if (end === 0) return true;
1891
- const last = text[end - 1];
1892
- return BEFORE_REGEX.has(last) || last === ">" && text[end - 2] === "=" || KEYWORD_BEFORE.test(text.slice(Math.max(0, end - KEYWORD_TAIL), end));
1893
- };
1894
- /** The index past a regular expression literal starting at `start`, its flags included: `/` inside
1895
- * a character class or after `\` does not end it. A newline first means it was no literal: the
1896
- * `/` alone is consumed. */
1897
- const regexEnd = (text, start) => {
1898
- let inClass = false;
1899
- for (let j = start + 1; j < text.length; j += 1) {
1900
- const ch = text[j];
1901
- if (ch === "\\") j += 1;
1902
- else if (ch === "\n") break;
1903
- else if (ch === "[") inClass = true;
1904
- else if (ch === "]") inClass = false;
1905
- else if (ch === "/" && !inClass) {
1906
- let end = j + 1;
1907
- while (end < text.length && /[a-z]/i.test(text[end])) end += 1;
1908
- return end;
1909
- }
1910
- }
1911
- return start + 1;
1912
- };
1913
- /** Every comment in the text, in order, with its position. Everything else is code, as written. */
1914
- const findComments = (text) => {
1915
- const comments = [];
1916
- let i = 0;
1917
- const n = text.length;
1918
- const templates = [];
1919
- let depth = 0;
1920
- while (i < n) {
1921
- const c = text[i];
1922
- if (templates.length > 0 && templates.at(-1) === -1) {
1923
- if (c === "\\") i += 2;
1924
- else if (c === "`") {
1925
- templates.pop();
1926
- i += 1;
1927
- } else if (c === "$" && text[i + 1] === "{") {
1928
- templates[templates.length - 1] = depth;
1929
- depth += 1;
1930
- i += 2;
1931
- } else i += 1;
1932
- continue;
1933
- }
1934
- if (c === "\\") i += 2;
1935
- else if (c === "/" && text[i + 1] === "/") {
1936
- LINE_END.lastIndex = i;
1937
- const end = LINE_END.exec(text)?.index ?? n;
1938
- comments.push({
1939
- start: i,
1940
- end,
1941
- text: text.slice(i, end)
1942
- });
1943
- i = end;
1944
- } else if (c === "/" && text[i + 1] === "*") {
1945
- const close = text.indexOf("*/", i + 2);
1946
- const end = close === -1 ? n : close + 2;
1947
- comments.push({
1948
- start: i,
1949
- end,
1950
- text: text.slice(i, end)
1951
- });
1952
- i = end;
1953
- } else if (c === "/" && startsRegex(text, i, comments)) i = regexEnd(text, i);
1954
- else if (c === "'" || c === "\"") {
1955
- let j = i + 1;
1956
- while (j < n && text[j] !== c && text[j] !== "\n") j += text[j] === "\\" ? 2 : 1;
1957
- if (j < n && text[j] === c) j += 1;
1958
- i = j;
1959
- } else if (c === "`") {
1960
- templates.push(-1);
1961
- i += 1;
1962
- } else {
1963
- if (c === "{") depth += 1;
1964
- else if (c === "}") {
1965
- depth -= 1;
1966
- if (templates.length > 0 && templates.at(-1) === depth) templates[templates.length - 1] = -1;
1967
- }
1968
- i += 1;
1969
- }
1970
- }
1971
- return comments;
1972
- };
1973
- /** The text with its comments blanked: a line comment becomes a space, a block comment a space
1974
- * and its newlines. */
1975
- const stripComments = (text) => {
1976
- let out = "";
1977
- let from = 0;
1978
- for (const { start, end, text: comment } of findComments(text)) {
1979
- out += `${text.slice(from, start)} ${"\n".repeat((comment.match(/\n/g) ?? []).length)}`;
1980
- from = end;
1981
- }
1982
- return out + text.slice(from);
1983
- };
1984
- /** Every comment in the text, as written. */
1985
- const jsComments = (text) => findComments(text).map((c) => c.text);
1986
- //#endregion
1987
- //#region src/checks/viewSource.ts
1988
- /** Comments the frameworks themselves write into static HTML, and no developer did: Astro's
1989
- * island and server-island markers, React 19's SSR markers (`<!--$-->`, `<!--/$-->`, …, and the
1990
- * `<!-- -->` text separator), Vue's SSR fragment and teleport markers. Matched on the trimmed
1991
- * comment text. A framework upgrade that adds a marker shows up as a refused build; extend the
1992
- * list here, in one place. */
1993
- const FRAMEWORK_COMMENTS = /* @__PURE__ */ new Set([
1994
- "",
1995
- "$",
1996
- "/$",
1997
- "$!",
1998
- "$?",
1999
- "&",
2000
- "/&",
2001
- "F",
2002
- "F!",
2003
- "html",
2004
- "head",
2005
- "body",
2006
- "[",
2007
- "]",
2008
- "teleport start",
2009
- "teleport end",
2010
- "v-if"
2011
- ]);
2012
- const isFrameworkComment = (data) => {
2013
- const text = data.trim();
2014
- return FRAMEWORK_COMMENTS.has(text) || text.startsWith("astro:") || text.startsWith("server-island");
2043
+ //#region src/checks/viewSource.ts
2044
+ /** Comments the frameworks themselves write into static HTML, and no developer did: Astro's
2045
+ * island and server-island markers, React 19's SSR markers (`<!--$-->`, `<!--/$-->`, …, and the
2046
+ * `<!-- -->` text separator), Vue's SSR fragment and teleport markers. Matched on the trimmed
2047
+ * comment text. A framework upgrade that adds a marker shows up as a refused build; extend the
2048
+ * list here, in one place. */
2049
+ const FRAMEWORK_COMMENTS = /* @__PURE__ */ new Set([
2050
+ "",
2051
+ "$",
2052
+ "/$",
2053
+ "$!",
2054
+ "$?",
2055
+ "&",
2056
+ "/&",
2057
+ "F",
2058
+ "F!",
2059
+ "html",
2060
+ "head",
2061
+ "body",
2062
+ "[",
2063
+ "]",
2064
+ "teleport start",
2065
+ "teleport end",
2066
+ "v-if"
2067
+ ]);
2068
+ const isFrameworkComment = (data) => {
2069
+ const text = data.trim();
2070
+ return FRAMEWORK_COMMENTS.has(text) || text.startsWith("astro:") || text.startsWith("server-island");
2015
2071
  };
2016
2072
  /** Licence banners and bundler annotations survive minification on purpose and say nothing. */
2017
2073
  const LEGAL_BLOCK_COMMENT = /^\/\*\s*[!@#]|@license|@preserve/;
@@ -2060,279 +2116,80 @@ const siteWrote = (ctx) => {
2060
2116
  return wrote;
2061
2117
  };
2062
2118
  };
2063
- /** What a visitor can read with View Source, and no developer meant for them: comments in the
2064
- * built pages; comments in their inline scripts, styles and event handlers that the site's own
2065
- * source contains (one a dependency rendered during the build is not the site's); comments in
2066
- * the JS and CSS copied verbatim from `public/` (line comments at a line start in JS, block
2067
- * comments in CSS); source maps and references to them in every shipped file. JS and CSS the
2068
- * bundler produced (`_astro/…`) are not scanned for comments: Vite minifies them and keeps only
2069
- * licence banners, so what still looks like one is text inside a string (a bundled library's
2070
- * shader or styles). */
2071
- const viewSource = {
2072
- id: "view-source",
2073
- title: "Developer notes visible in View Source",
2074
- severity: "error",
2075
- begin: (ctx) => {
2076
- if (!ctx.hasDist) return null;
2077
- const findings = [];
2078
- const report = (path, what, text) => findings.push({
2079
- path,
2080
- message: `${what}: "${excerpt(text)}"`
2081
- });
2082
- const wrote = siteWrote(ctx);
2083
- const reportInline = (path, what, comment) => {
2084
- if (wrote(comment)) report(path, what, comment);
2085
- };
2086
- const visit = (page) => {
2087
- for (const comment of page.comments()) if (!isFrameworkComment(comment)) report(page.path, "HTML comment in the page", comment);
2088
- for (const el of page.document.querySelectorAll("*")) for (const name of el.getAttributeNames()) {
2089
- if (!name.startsWith("on")) continue;
2090
- const code = el.getAttribute(name) ?? "";
2091
- const what = `comment in an inline ${name} handler`;
2092
- for (const comment of jsComments(code)) if (!DIRECTIVE.test(comment) && !LEGAL_BLOCK_COMMENT.test(comment)) reportInline(page.path, what, comment);
2093
- }
2094
- for (const el of page.document.querySelectorAll("script, style")) {
2095
- const text = el.textContent ?? "";
2096
- const what = `comment in an inline <${el.tagName.toLowerCase()}>`;
2097
- for (const comment of blockComments(text)) reportInline(page.path, what, comment);
2098
- if (el.tagName === "SCRIPT") {
2099
- if (SOURCE_MAP_URL.test(text)) report(page.path, "source map reference in an inline <script>", text);
2100
- for (const comment of lineComments(text)) reportInline(page.path, what, comment);
2101
- }
2102
- }
2103
- };
2104
- const finish = () => {
2105
- for (const file of ctx.files) {
2106
- if (file.endsWith(".map")) {
2107
- findings.push({
2108
- path: file,
2109
- message: "A source map ships the original source to anyone who asks for it."
2110
- });
2111
- continue;
2112
- }
2113
- const isJs = /\.m?js$/.test(file);
2114
- const isCss = file.endsWith(".css");
2115
- if (!isJs && !isCss) continue;
2116
- const text = ctx.read(file);
2117
- if (SOURCE_MAP_URL.test(text)) report(file, "source map reference", "sourceMappingURL");
2118
- if (!fs.existsSync(path.join(ctx.publicDir, file))) continue;
2119
- if (isCss) for (const comment of blockComments(text)) report(file, "comment in shipped CSS", comment);
2120
- if (isJs) for (const comment of lineComments(text)) report(file, "comment in shipped JS", comment);
2121
- }
2122
- return findings;
2123
- };
2124
- return {
2125
- visit,
2126
- finish
2127
- };
2128
- }
2129
- };
2130
- //#endregion
2131
- //#region src/checks/wiring.ts
2132
- const FN_KEYWORD = /\bfunction\s*\*?\s*$/;
2133
- const MEMBER_START = /(?:^|[{};,]|\b(?:async|static|get|set|public|private|protected|readonly|abstract|override|declare))\s*$/;
2134
- const LINE_START = /\n[ \t]*$/;
2135
- /** After one of these the expression goes on, so a line start does not begin a member. */
2136
- const CONTINUES = /* @__PURE__ */ new Set("?:=(.,&|+-*/%<>!~^[");
2137
- const closeParen = (text, open) => {
2138
- let depth = 0;
2139
- for (let i = open; i < text.length; i += 1) {
2140
- const c = text[i];
2141
- if (c === "'" || c === "\"" || c === "`") {
2142
- i += 1;
2143
- while (i < text.length && text[i] !== c) i += text[i] === "\\" ? 2 : 1;
2144
- } else if (c === "(") depth += 1;
2145
- else if (c === ")") {
2146
- depth -= 1;
2147
- if (depth === 0) return i + 1;
2148
- }
2149
- }
2150
- return null;
2151
- };
2152
- /** `NAME(` that opens a definition — `function NAME(`, a method `NAME(…) {`, a signature
2153
- * `NAME(…): T` where a member starts — rather than a call. A file that defines the function it
2154
- * must call would otherwise pass with the real call deleted. */
2155
- const isDefinition = (text, start, paren) => {
2156
- const before = text.slice(0, start);
2157
- if (FN_KEYWORD.test(before)) return true;
2158
- const end = closeParen(text, paren);
2159
- if (end === null) return false;
2160
- const after = text.slice(end).trimStart();
2161
- if (after.startsWith("{")) return true;
2162
- if (after.startsWith(":")) {
2163
- if (MEMBER_START.test(before)) return true;
2164
- const prev = before.trimEnd();
2165
- if (LINE_START.test(before) && prev !== "" && !CONTINUES.has(prev.at(-1))) return true;
2166
- }
2167
- return false;
2168
- };
2169
- const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2170
- /** A real call of `fn` in comment-stripped code: not an import, not prose, not its definition. */
2171
- const calls = (code, fn) => [...code.matchAll(new RegExp(`\\b${escape(fn)}\\s*\\(`, "g"))].some((m) => !isDefinition(code, m.index, m.index + m[0].length - 1));
2172
- /** `@bound-by-parent <init> [<init>…]`: the initializers a leaf hands to whoever renders it. The
2173
- * list may wrap onto a comment's next line; names run until the first token that is not one. */
2174
- const OPT_OUT = /@bound-by-parent((?:[ \t]*,?[ \t]*(?:\r?\n[ \t]*(?:\*|\/\/))?[ \t]+init[A-Za-z0-9_]*)+)/g;
2175
- const handedUp = (text) => new Set([...text.matchAll(OPT_OUT)].flatMap((m) => m[1].split(/[^A-Za-z0-9_]+/).filter((token) => token.startsWith("init"))));
2176
- const COMPONENT_EXTENSIONS = /* @__PURE__ */ new Set([".astro", ".tsx"]);
2177
- const SCRIPT_EXTENSIONS = /* @__PURE__ */ new Set([
2178
- ".ts",
2179
- ".js",
2180
- ".mjs",
2181
- ".jsx"
2182
- ]);
2183
- /** Files whose text is partly markup, which the comment scanner cannot tell from script. */
2184
- const MARKUP_EXTENSIONS = /* @__PURE__ */ new Set([
2185
- ".astro",
2186
- ".tsx",
2187
- ".jsx",
2188
- ".html",
2189
- ".md",
2190
- ".mdx"
2191
- ]);
2192
- const readComponents = (ctx) => ctx.sourceFiles(COMPONENT_EXTENSIONS).map((file) => {
2193
- const raw = ctx.readSource(file);
2194
- return {
2195
- file,
2196
- rel: ctx.rel(file),
2197
- stem: path.basename(file, path.extname(file)),
2198
- raw,
2199
- code: stripComments(raw),
2200
- up: handedUp(raw)
2201
- };
2202
- });
2203
- /** A project-relative path inside the project, or null. */
2204
- const inside = (ctx, rel) => {
2205
- if (path.isAbsolute(rel)) return null;
2206
- const full = path.resolve(ctx.root, rel);
2207
- return full.startsWith(`${path.resolve(ctx.root)}${path.sep}`) ? full : null;
2208
- };
2209
- const checkKept = (ctx, entry) => {
2210
- const full = inside(ctx, entry.file);
2211
- if (!full) return `wiring: "file" must be a path inside the project, got "${entry.file}"`;
2212
- if (!fs.existsSync(full)) return `${entry.file} is missing; it must contain \`${entry.contains}\`. Guard: ${entry.guard}`;
2213
- const raw = fs.readFileSync(full, "utf8");
2214
- const literal = MARKUP_EXTENSIONS.has(path.extname(full)) && (entry.contains.includes("//") || entry.contains.includes("/*"));
2215
- if (stripComments(raw).includes(entry.contains) || literal && raw.includes(entry.contains)) return null;
2216
- const where = raw.includes(entry.contains) ? " (only in a comment)" : "";
2217
- return `${entry.file} no longer contains \`${entry.contains}\`${where}. Guard: ${entry.guard}`;
2218
- };
2219
- /** The findings of one binding hook. */
2220
- const checkHook = (ctx, hook, components, scripts) => {
2221
- const { init, marker } = hook;
2222
- if (hook.file !== void 0) {
2223
- const full = inside(ctx, hook.file);
2224
- if (!full) return [{ message: `wiring: "file" must be a path inside the project, got "${hook.file}"` }];
2225
- if (!fs.existsSync(full)) return [{
2226
- path: hook.file,
2227
- message: `${hook.file} is missing; the entry binds \`${marker}\` there. Update the entry.`
2228
- }];
2229
- const raw = fs.readFileSync(full, "utf8");
2230
- if (!stripComments(raw).includes(marker)) {
2231
- const where = raw.includes(marker) ? " (only in a comment)" : "";
2232
- return [{
2233
- path: hook.file,
2234
- message: `The marker \`${marker}\` is not in ${hook.file}${where}: the entry no longer binds. Update it.`
2235
- }];
2236
- }
2237
- if (hook.scope === "section" && !COMPONENT_EXTENSIONS.has(path.extname(full)) && !calls(stripComments(raw), init) && !handedUp(raw).has(init)) return [{
2238
- path: hook.file,
2239
- message: `${hook.file} carries \`${marker}\` but never calls ${init}().`
2240
- }];
2241
- }
2242
- const carriers = new Set(components.filter((c) => c.code.includes(marker)));
2243
- const namedCarrier = hook.file !== void 0 && !COMPONENT_EXTENSIONS.has(path.extname(hook.file));
2244
- if (carriers.size === 0 && !namedCarrier) return [];
2245
- const binders = new Set(components.filter((c) => calls(c.code, init)));
2246
- if (hook.scope === "global") return binders.size > 0 || scripts.some((code) => calls(code, init)) ? [] : [{ message: `${carriers.size || 1} file(s) carry \`${marker}\` (e.g. ${[...carriers][0]?.rel ?? hook.file}) but nothing in src/ calls ${init}(): the markup renders and does nothing.` }];
2247
- const delegators = new Set([...carriers].filter((c) => c.up.has(init)));
2248
- for (let grew = true; grew;) {
2249
- grew = false;
2250
- const names = [...delegators].map((d) => d.stem);
2251
- for (const c of components) {
2252
- if (delegators.has(c) || binders.has(c)) continue;
2253
- if (!names.some((name) => new RegExp(`<${escape(name)}\\b`).test(c.code))) continue;
2254
- carriers.add(c);
2255
- if (c.up.has(init)) {
2256
- delegators.add(c);
2257
- grew = true;
2258
- }
2259
- }
2260
- }
2261
- return [...carriers].filter((c) => !c.up.has(init) && !binders.has(c)).sort((a, b) => a.rel.localeCompare(b.rel)).map((c) => ({
2262
- path: c.rel,
2263
- message: `${c.rel} carries \`${marker}\` but never calls ${init}(): the markup renders and does nothing. Call it, or mark the leaf \`@bound-by-parent ${init}\` when its parent owns the call.`
2264
- }));
2265
- };
2266
- /** Markup is inert until a script binds it: every component carrying a configured hook's marker is
2267
- * bound, and every kept text is still in its file. A type check, the build and a screenshot all
2268
- * pass over a control whose initializer call was deleted; only this sees it. Comments are
2269
- * stripped before any match. Configured by `wiring` (the former `scripts/wiring.json`). */
2270
- const wiring = {
2271
- id: "wiring",
2272
- title: "Markup hooks are bound",
2273
- severity: "error",
2274
- begin: (ctx) => {
2275
- if (ctx.options.wiring.length === 0) return null;
2276
- return { finish: () => {
2277
- const components = readComponents(ctx);
2278
- const scripts = ctx.sourceFiles(SCRIPT_EXTENSIONS).map((file) => stripComments(ctx.readSource(file)));
2279
- const findings = [];
2280
- for (const entry of ctx.options.wiring) if ("contains" in entry) {
2281
- const problem = checkKept(ctx, entry);
2282
- if (problem) findings.push({
2283
- path: entry.file,
2284
- message: problem
2285
- });
2286
- } else findings.push(...checkHook(ctx, entry, components, scripts));
2287
- return findings;
2288
- } };
2289
- }
2290
- };
2291
- const SCRIPTS_DIR = "src/scripts";
2292
- const EXPORTED_INIT = /export\s+(?:async\s+)?function\s*\*?\s*(init[A-Za-z0-9_]+)/g;
2293
2119
  //#endregion
2294
2120
  //#region src/checks/index.ts
2295
- /** The site checks, in the order the report shows them: the source first, then the built pages.
2296
- * The integration runs these inside the site's own `astro build`; the build worker's checks are
2297
- * the other family (`distChecks/`), and an id here must not reuse one of theirs (a test holds the
2298
- * rule). Adding a check is one file here, one entry, one test, a README row and a CHANGELOG
2299
- * entry. */
2121
+ /** The site checks, in the order the report shows them: the `src` stage first, then the `dist`
2122
+ * stage. Each check names its stage; `site-checks src` runs the first group before the build and
2123
+ * `site-checks dist` the second after it, together with the platform's dist checks
2124
+ * (`distChecks/`), whose ids a check here must not reuse (a test holds the rule). Adding a check
2125
+ * is one file here, one entry, one test, a README row and a CHANGELOG entry. */
2300
2126
  const checks = [
2301
2127
  htmlComments,
2128
+ imageFormats,
2302
2129
  syncOnce,
2303
- optimizeDeps,
2304
- wiring,
2130
+ v9HubFilters,
2305
2131
  {
2306
- id: "unused-initializers",
2307
- title: "Exported initializers are called",
2308
- severity: "warning",
2132
+ id: "view-source",
2133
+ title: "Developer notes visible in View Source",
2134
+ severity: "error",
2135
+ stage: "dist",
2309
2136
  begin: (ctx) => {
2310
- const dir = path.join(ctx.root, SCRIPTS_DIR);
2311
- if (!fs.existsSync(dir)) return null;
2312
- return { finish: () => {
2313
- const scripts = fs.readdirSync(dir).filter((name) => name.endsWith(".ts")).sort().map((name) => {
2314
- const raw = fs.readFileSync(path.join(dir, name), "utf8");
2315
- return {
2316
- rel: `${SCRIPTS_DIR}/${name}`,
2317
- code: stripComments(raw)
2318
- };
2319
- });
2320
- const components = readComponents(ctx);
2321
- const modules = ctx.sourceFiles(SCRIPT_EXTENSIONS).map((file) => stripComments(ctx.readSource(file)));
2322
- const findings = [];
2323
- for (const script of scripts) for (const [, fn] of script.code.matchAll(EXPORTED_INIT)) if (!(components.some((c) => calls(c.code, fn)) || modules.some((code) => calls(code, fn)))) findings.push({
2324
- path: script.rel,
2325
- message: `${fn}() is exported and never called: wire the feature, or delete the leftover.`
2326
- });
2137
+ if (!ctx.hasDist) return null;
2138
+ const findings = [];
2139
+ const report = (path, what, text) => findings.push({
2140
+ path,
2141
+ message: `${what}: "${excerpt(text)}"`
2142
+ });
2143
+ const wrote = siteWrote(ctx);
2144
+ const reportInline = (path, what, comment) => {
2145
+ if (wrote(comment)) report(path, what, comment);
2146
+ };
2147
+ const visit = (page) => {
2148
+ for (const comment of page.comments()) if (!isFrameworkComment(comment)) report(page.path, "HTML comment in the page", comment);
2149
+ for (const el of page.document.querySelectorAll("*")) for (const name of el.getAttributeNames()) {
2150
+ if (!name.startsWith("on")) continue;
2151
+ const code = el.getAttribute(name) ?? "";
2152
+ const what = `comment in an inline ${name} handler`;
2153
+ for (const comment of jsComments(code)) if (!DIRECTIVE.test(comment) && !LEGAL_BLOCK_COMMENT.test(comment)) reportInline(page.path, what, comment);
2154
+ }
2155
+ for (const el of page.document.querySelectorAll("script, style")) {
2156
+ const text = el.textContent ?? "";
2157
+ const what = `comment in an inline <${el.tagName.toLowerCase()}>`;
2158
+ for (const comment of blockComments(text)) reportInline(page.path, what, comment);
2159
+ if (el.tagName === "SCRIPT") {
2160
+ if (SOURCE_MAP_URL.test(text)) report(page.path, "source map reference in an inline <script>", text);
2161
+ for (const comment of lineComments(text)) reportInline(page.path, what, comment);
2162
+ }
2163
+ }
2164
+ };
2165
+ const finish = () => {
2166
+ for (const file of ctx.files) {
2167
+ if (file.endsWith(".map")) {
2168
+ findings.push({
2169
+ path: file,
2170
+ message: "A source map ships the original source to anyone who asks for it."
2171
+ });
2172
+ continue;
2173
+ }
2174
+ const isJs = /\.m?js$/.test(file);
2175
+ const isCss = file.endsWith(".css");
2176
+ if (!isJs && !isCss) continue;
2177
+ const text = ctx.read(file);
2178
+ if (SOURCE_MAP_URL.test(text)) report(file, "source map reference", "sourceMappingURL");
2179
+ if (!fs.existsSync(path.join(ctx.publicDir, file))) continue;
2180
+ if (isCss) for (const comment of blockComments(text)) report(file, "comment in shipped CSS", comment);
2181
+ if (isJs) for (const comment of lineComments(text)) report(file, "comment in shipped JS", comment);
2182
+ }
2327
2183
  return findings;
2328
- } };
2184
+ };
2185
+ return {
2186
+ visit,
2187
+ finish
2188
+ };
2329
2189
  }
2330
2190
  },
2331
- v9HubFilters,
2332
- viewSource,
2333
2191
  donorTerms,
2334
2192
  consentGate,
2335
- imageFormats,
2336
2193
  feedImageFormats,
2337
2194
  listingNoindex,
2338
2195
  listingLinks,
@@ -2349,9 +2206,16 @@ const checks = [
2349
2206
  quoteSources,
2350
2207
  rentalFacts
2351
2208
  ];
2209
+ const checksOf = (stage) => checks.filter((check) => check.stage === stage);
2352
2210
  //#endregion
2353
2211
  //#region src/options.ts
2354
2212
  const CONFIG_FILE = "site-checks.config.json";
2213
+ /** Keys of checks earlier versions had. A file that still carries one is noted, never refused: a
2214
+ * site mid-rollout must not be stopped by a key it was told to add a release ago. */
2215
+ const RETIRED_KEYS = {
2216
+ wiring: "the wiring check was removed in 0.3.0",
2217
+ optimizeDepsIgnore: "the optimize-deps check was removed in 0.3.0"
2218
+ };
2355
2219
  /** The vOffice image hosts that answer JPEG unless asked for WebP: imgproxy's `plain` path (v9,
2356
2220
  * `…jpg@webp`) and `dyn.v-office.com` (`….webp`). The v10 host answers WebP by itself. */
2357
2221
  const DEFAULT_FEED_IMAGE_PATTERNS = ["\\/_\\/[^\\s]*\\/plain\\/[^\\s@]+\\.(?:jpe?g|png)$", "^https:\\/\\/dyn\\.v-office\\.com\\/image\\/[^\\s]+\\.(?:jpe?g|png)$"];
@@ -2377,17 +2241,11 @@ const compiles = (source, key, pattern, flags) => {
2377
2241
  throw new Error(`[site-checks] ${source}: "${key}" has an invalid regular expression ${JSON.stringify(pattern)}: ${err.message}`);
2378
2242
  }
2379
2243
  };
2380
- /** A `wiring` entry is one of two kinds; one carrying both is an authoring mistake, never a merge. */
2381
- const isWiringEntry = (entry) => {
2382
- if ("contains" in entry) return nonEmpty(entry.file) && nonEmpty(entry.contains) && nonEmpty(entry.guard) && !("init" in entry) && !("marker" in entry) && !("scope" in entry);
2383
- return nonEmpty(entry.init) && nonEmpty(entry.marker) && (entry.scope === "section" || entry.scope === "global") && (entry.file === void 0 || nonEmpty(entry.file));
2384
- };
2385
2244
  const stringList = (source, key, value) => {
2386
2245
  if (!isStringList(value)) throw new Error(`[site-checks] ${source}: "${key}" must be an array of strings`);
2387
2246
  };
2388
2247
  const VALIDATORS = {
2389
2248
  donorTerms: stringList,
2390
- optimizeDepsIgnore: stringList,
2391
2249
  imageIgnore: stringList,
2392
2250
  feedImagePatterns: (source, key, value) => {
2393
2251
  stringList(source, key, value);
@@ -2407,9 +2265,6 @@ const VALIDATORS = {
2407
2265
  allowDuplicateSentences: stringList,
2408
2266
  quoteSources: stringList,
2409
2267
  factCheckAccepted: stringList,
2410
- wiring: (source, key, value) => {
2411
- if (!isListOf(value, isWiringEntry)) throw new Error(`[site-checks] ${source}: "${key}" must be an array of { init, marker, scope: "section" | "global", file? } or { file, contains, guard } entries, each of one kind`);
2412
- },
2413
2268
  structureIgnore: (source, key, value) => {
2414
2269
  stringList(source, key, value);
2415
2270
  const known = new Set(STRUCTURE_RULES);
@@ -2419,21 +2274,28 @@ const VALIDATORS = {
2419
2274
  if (!isObject(value)) throw new Error(`[site-checks] ${source}: "${key}" must be an object`);
2420
2275
  }
2421
2276
  };
2422
- const validate = (source, raw) => {
2277
+ const validate = (source, raw, note) => {
2423
2278
  if (!isObject(raw)) throw new Error(`[site-checks] ${source} must be a JSON object`);
2424
2279
  const known = Object.keys(VALIDATORS);
2425
2280
  const options = {};
2426
2281
  for (const [key, value] of Object.entries(raw)) {
2427
2282
  const check = VALIDATORS[key];
2428
- if (!check) throw new Error(`[site-checks] ${source}: unknown key "${key}" (known: ${known.join(", ")})`);
2283
+ if (!check) {
2284
+ const retired = RETIRED_KEYS[key];
2285
+ if (retired) {
2286
+ note(`[site-checks] ${source}: "${key}" is no longer read (${retired}); delete the key.`);
2287
+ continue;
2288
+ }
2289
+ throw new Error(`[site-checks] ${source}: unknown key "${key}" (known: ${known.join(", ")})`);
2290
+ }
2429
2291
  check(source, key, value);
2430
2292
  options[key] = value;
2431
2293
  }
2432
2294
  return options;
2433
2295
  };
2434
- /** The file's keys with the integration's options on top. A file that cannot be parsed throws:
2435
- * a broken config must not silently disable a check. */
2436
- function loadOptions(root, overrides = {}) {
2296
+ /** The file's keys with the given options on top. A file that cannot be parsed throws: a broken
2297
+ * config must not silently disable a check. `note` hears about a retired key. */
2298
+ function loadOptions(root, overrides = {}, note = () => {}) {
2437
2299
  const file = path.join(root, CONFIG_FILE);
2438
2300
  let fromFile = {};
2439
2301
  if (fs.existsSync(file)) {
@@ -2443,13 +2305,12 @@ function loadOptions(root, overrides = {}) {
2443
2305
  } catch (err) {
2444
2306
  throw new Error(`[site-checks] ${CONFIG_FILE} is not valid JSON: ${err.message}`);
2445
2307
  }
2446
- fromFile = validate(CONFIG_FILE, raw);
2308
+ fromFile = validate(CONFIG_FILE, raw, note);
2447
2309
  }
2448
- const given = validate("siteChecks() options", overrides);
2310
+ const given = validate("options", overrides, note);
2449
2311
  const pick = (key, fallback) => given[key] ?? fromFile[key] ?? fallback;
2450
2312
  return {
2451
2313
  donorTerms: pick("donorTerms", []),
2452
- optimizeDepsIgnore: pick("optimizeDepsIgnore", []),
2453
2314
  imageIgnore: pick("imageIgnore", []),
2454
2315
  feedImagePatterns: pick("feedImagePatterns", DEFAULT_FEED_IMAGE_PATTERNS),
2455
2316
  listingPages: pick("listingPages", []),
@@ -2461,7 +2322,6 @@ function loadOptions(root, overrides = {}) {
2461
2322
  allowDuplicateSentences: pick("allowDuplicateSentences", []),
2462
2323
  quoteSources: pick("quoteSources", []),
2463
2324
  factCheckAccepted: pick("factCheckAccepted", []),
2464
- wiring: pick("wiring", []),
2465
2325
  structureIgnore: pick("structureIgnore", []),
2466
2326
  hubFilterOptions: pick("hubFilterOptions", {})
2467
2327
  };
@@ -2564,40 +2424,41 @@ const runChecks = async (load, list) => {
2564
2424
  results: list.map((check) => results.get(check))
2565
2425
  };
2566
2426
  };
2567
- /** Runs every site check over the project and its build. */
2568
- const runSiteChecks = (input, list = checks) => runChecks(() => loadContext({
2427
+ /** The context input of a run: the defaults filled in. */
2428
+ const contextInput = (input) => ({
2569
2429
  root: input.root,
2570
2430
  srcDir: input.srcDir ?? `${input.root}/src`,
2571
2431
  publicDir: input.publicDir ?? `${input.root}/public`,
2572
2432
  distDir: input.distDir,
2433
+ stage: input.stage,
2573
2434
  config: {
2574
2435
  site: input.config?.site,
2575
- optimizeDepsInclude: input.config?.optimizeDepsInclude ?? [],
2576
2436
  trailingSlash: input.config?.trailingSlash
2577
2437
  },
2578
- options: loadOptions(input.root, input.options)
2579
- }), list);
2438
+ options: loadOptions(input.root, input.options, input.note)
2439
+ });
2440
+ /** Runs the given site checks over the project, with its build when there is one and the stage
2441
+ * does not exclude it. The stages (`stages.ts`) are built on this; tests run one check through it. */
2442
+ const runSiteChecks = (input, list = checks) => runChecks(() => loadContext(contextInput(input)), list);
2580
2443
  /** Results with status `error`: the only ones that refuse a build. */
2581
2444
  const blockingResults = (report) => report.results.filter((r) => r.status === "error");
2582
2445
  //#endregion
2583
2446
  //#region src/report.ts
2584
- /** The report's file name under `dist/`. The build worker reads it after `astro build`, merges it
2585
- * with its own checks and never uploads it (it names source paths and configured terms). */
2447
+ /** The `dist` stage's report file under `dist/`. The build worker reads it after the build and
2448
+ * never uploads it (it names source paths and configured terms). */
2586
2449
  const SITE_CHECKS_FILE = "site-checks.json";
2587
- const writeSiteChecksReport = (distDir, report) => {
2588
- fs.mkdirSync(distDir, { recursive: true });
2589
- fs.writeFileSync(path.join(distDir, SITE_CHECKS_FILE), JSON.stringify(report, null, 2) + "\n");
2590
- };
2591
2450
  const count = (result) => result.findings.length + result.omitted;
2592
2451
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
2593
- const line = (finding) => finding.path ? `${finding.path}: ${finding.message}` : finding.message;
2452
+ /** `<path>: <message>`, or the message alone. */
2453
+ const findingLine = (finding) => finding.path ? `${finding.path}: ${finding.message}` : finding.message;
2454
+ const line = findingLine;
2594
2455
  /** One line per check that found something or could not run, for the build log. */
2595
2456
  const summaryLines = (report) => report.results.filter((r) => r.status !== "ok" && r.status !== "skipped").map((r) => `[site-checks] ${r.id}: ${r.status}, ${plural(count(r), "finding")}`);
2596
- /** The error `astro build` ends with when a check refuses: every failing check, its first findings,
2597
- * and where the whole report is. */
2598
- const refusalMessage = (report) => {
2457
+ /** What a refused stage ends with: every failing check, its first findings, and where the whole
2458
+ * report is when one was written. */
2459
+ const refusalMessage = (report, stage, reportFile) => {
2599
2460
  const blocking = blockingResults(report);
2600
- const lines = [`[site-checks] build refused: ${plural(blocking.length, "check")} with errors`];
2461
+ const lines = [`[site-checks] ${stage} refused: ${plural(blocking.length, "check")} with errors`];
2601
2462
  for (const result of blocking) {
2602
2463
  const shown = result.findings.slice(0, 3);
2603
2464
  const more = count(result) - shown.length;
@@ -2605,10 +2466,566 @@ const refusalMessage = (report) => {
2605
2466
  for (const finding of shown) lines.push(` ${line(finding)}`);
2606
2467
  if (more > 0) lines.push(` (+${more} more)`);
2607
2468
  }
2608
- lines.push(` Report: dist/${SITE_CHECKS_FILE}`);
2469
+ if (reportFile) lines.push(` Report: ${reportFile}`);
2609
2470
  return lines.join("\n");
2610
2471
  };
2611
2472
  /** One line naming what refused the build, for the studio: the failing checks and their counts. */
2612
2473
  const summarizeBlocking = (report) => "Checks refused the build: " + blockingResults(report).map((r) => `${r.id} (${plural(count(r), "finding")})`).join(", ");
2613
2474
  //#endregion
2614
- export { referencedUrls as _, writeSiteChecksReport as a, MAX_PATH_CHARS as c, runSiteChecks as d, CONFIG_FILE as f, loadDistContext as g, isSameSiteReference as h, summaryLines as i, blockingResults as l, checks as m, refusalMessage as n, MAX_FINDINGS_PER_CHECK as o, loadOptions as p, summarizeBlocking as r, MAX_MESSAGE_CHARS as s, SITE_CHECKS_FILE as t, runChecks as u, resolveReference as v, xmlText as y };
2475
+ //#region src/distChecks/insecureResources.ts
2476
+ /** `<link>` relations the browser fetches as a subresource; canonical,
2477
+ * alternate, preconnect and friends are hints or metadata, not loads. */
2478
+ const RESOURCE_RELS = /* @__PURE__ */ new Set([
2479
+ "stylesheet",
2480
+ "preload",
2481
+ "modulepreload",
2482
+ "prefetch",
2483
+ "icon",
2484
+ "apple-touch-icon",
2485
+ "manifest"
2486
+ ]);
2487
+ const isResource = (el) => {
2488
+ if (el.tagName === "A" || el.tagName === "AREA" || el.tagName === "BASE") return false;
2489
+ if (el.tagName !== "LINK") return true;
2490
+ return (el.getAttribute("rel") ?? "").toLowerCase().split(/\s+/).some((rel) => RESOURCE_RELS.has(rel));
2491
+ };
2492
+ /** A resource loaded over plain http on an https site is blocked or downgraded
2493
+ * by the browser (mixed content); the page renders without it. Links a
2494
+ * visitor clicks (`<a href>`) are not resources and are left alone. */
2495
+ const insecureResources = {
2496
+ id: "insecure-resources",
2497
+ title: "No script, style, image or media is loaded over http://",
2498
+ severity: "warning",
2499
+ begin() {
2500
+ const findings = [];
2501
+ const visit = (page) => {
2502
+ const seen = /* @__PURE__ */ new Set();
2503
+ for (const el of page.document.querySelectorAll("[href], [src], [srcset], [poster]")) {
2504
+ if (!isResource(el)) continue;
2505
+ for (const value of referencedUrls(el)) {
2506
+ const v = value.trim();
2507
+ if (!/^http:\/\//i.test(v) || seen.has(v)) continue;
2508
+ seen.add(v);
2509
+ findings.push({
2510
+ message: `${el.tagName.toLowerCase()} loads ${v} over http://`,
2511
+ path: page.path
2512
+ });
2513
+ }
2514
+ }
2515
+ };
2516
+ return {
2517
+ visit,
2518
+ finish: () => findings
2519
+ };
2520
+ }
2521
+ };
2522
+ //#endregion
2523
+ //#region src/distChecks/internalLinks.ts
2524
+ /** A same-site reference (`href`, `src`, `srcset`, `poster`) that no file of
2525
+ * the build serves — the 404 class, caught before a guest hits it. One finding
2526
+ * per missing target, on the first page that references it and with the count
2527
+ * of pages that do: a layout link to one missing file must not bury every other
2528
+ * finding under a copy per page. On a single-page app only file-like paths
2529
+ * (with an extension) are checked: its routes are handled by the app, not by
2530
+ * files. */
2531
+ const internalLinks = {
2532
+ id: "internal-links",
2533
+ title: "Every internal link and asset reference is served by the build",
2534
+ severity: "warning",
2535
+ begin(ctx) {
2536
+ const missing = /* @__PURE__ */ new Map();
2537
+ const visit = (page) => {
2538
+ const seen = /* @__PURE__ */ new Set();
2539
+ for (const el of page.document.querySelectorAll("[href], [src], [srcset], [poster]")) {
2540
+ if (el.tagName === "BASE") continue;
2541
+ for (const value of referencedUrls(el)) {
2542
+ if (!isSameSiteReference(value, ctx.origin)) continue;
2543
+ const target = resolveReference(page, value);
2544
+ if (seen.has(target)) continue;
2545
+ seen.add(target);
2546
+ if (!ctx.isAstro && !/\.[a-z0-9]+$/i.test(target)) continue;
2547
+ if (ctx.serves(target)) continue;
2548
+ const known = missing.get(target);
2549
+ if (known) known.pages++;
2550
+ else missing.set(target, {
2551
+ tag: el.tagName.toLowerCase(),
2552
+ path: page.path,
2553
+ pages: 1
2554
+ });
2555
+ }
2556
+ }
2557
+ };
2558
+ const finish = () => [...missing].map(([target, { tag, path, pages }]) => ({
2559
+ message: `${tag} references ${target}, which no file in the build serves${pages > 1 ? ` (from ${pages} pages)` : ""}`,
2560
+ path
2561
+ }));
2562
+ return {
2563
+ visit,
2564
+ finish
2565
+ };
2566
+ }
2567
+ };
2568
+ //#endregion
2569
+ //#region src/distChecks/keyPages.ts
2570
+ /** The pages every build must emit: the home page, and on an Astro site the
2571
+ * 404 page the hosting serves for unknown paths. */
2572
+ const keyPages = {
2573
+ id: "key-pages",
2574
+ title: "The home page and the 404 page are in the build",
2575
+ severity: "warning",
2576
+ begin(ctx) {
2577
+ const findings = [];
2578
+ if (!ctx.has("index.html")) findings.push({
2579
+ message: "No index.html: the site has no home page",
2580
+ path: "index.html"
2581
+ });
2582
+ if (ctx.isAstro && !ctx.has("404.html")) findings.push({
2583
+ message: "No 404.html: unknown paths get the hosting's default error page",
2584
+ path: "404.html"
2585
+ });
2586
+ return { finish: () => findings };
2587
+ }
2588
+ };
2589
+ //#endregion
2590
+ //#region src/distChecks/legalPages.ts
2591
+ /** German sites owe an Impressum (§ 5 DDG) and a privacy notice (Art. 13
2592
+ * DSGVO) reachable from every page; English wordings count too. Matched on
2593
+ * the link's target and its text, so a footer link named either way passes.
2594
+ * The 404 page and redirect stubs are skipped. */
2595
+ const LEGAL = [{
2596
+ name: "Impressum / legal notice",
2597
+ pattern: /impressum|imprint|legal[-_ ]?notice|colophon/i
2598
+ }, {
2599
+ name: "Datenschutz / privacy notice",
2600
+ pattern: /datenschutz|privacy/i
2601
+ }];
2602
+ const legalPages = {
2603
+ id: "legal-pages",
2604
+ title: "Every page links to an Impressum and a privacy notice",
2605
+ severity: "warning",
2606
+ begin(ctx) {
2607
+ if (!ctx.isAstro) return null;
2608
+ const findings = [];
2609
+ const visit = (page) => {
2610
+ if (page.path === "404.html" || page.redirect) return;
2611
+ const links = [...page.document.querySelectorAll("a[href]")].map((a) => `${a.getAttribute("href") ?? ""} ${a.textContent ?? ""}`);
2612
+ for (const { name, pattern } of LEGAL) {
2613
+ if (pattern.test(page.path)) continue;
2614
+ if (!links.some((link) => pattern.test(link))) findings.push({
2615
+ message: `No link to a ${name} on this page`,
2616
+ path: page.path
2617
+ });
2618
+ }
2619
+ };
2620
+ return {
2621
+ visit,
2622
+ finish: () => findings
2623
+ };
2624
+ }
2625
+ };
2626
+ //#endregion
2627
+ //#region src/distChecks/notFoundBeacon.ts
2628
+ const BEACON = /\/api\/404-log\b/;
2629
+ /** The hosting serves 404.html for every unknown path, and AI Studio learns of
2630
+ * the miss only when that page posts the URL to /api/404-log
2631
+ * (docs/internal/operations/404-logging.md). Without the beacon the site's 404 list stays
2632
+ * empty and no redirect is ever suggested. Astro bundles page scripts into
2633
+ * files under _astro/, so the page's same-site scripts count as well. */
2634
+ const notFoundBeacon = {
2635
+ id: "not-found-beacon",
2636
+ title: "The 404 page reports missing URLs to AI Studio",
2637
+ severity: "warning",
2638
+ begin(ctx) {
2639
+ if (!ctx.isAstro || !ctx.has("404.html")) return null;
2640
+ let beacon = false;
2641
+ const visit = (page) => {
2642
+ if (page.path !== "404.html") return;
2643
+ beacon = [...page.document.querySelectorAll("script")].map((script) => {
2644
+ const src = script.getAttribute("src");
2645
+ if (!src) return script.textContent ?? "";
2646
+ if (!isSameSiteReference(src, ctx.origin)) return "";
2647
+ const file = resolveReference(page, src).replace(/^\//, "");
2648
+ return ctx.has(file) ? ctx.read(file) : "";
2649
+ }).some((code) => BEACON.test(code));
2650
+ };
2651
+ const finish = () => beacon ? [] : [{
2652
+ message: "404.html does not call /api/404-log: missing URLs are never logged",
2653
+ path: "404.html"
2654
+ }];
2655
+ return {
2656
+ visit,
2657
+ finish
2658
+ };
2659
+ }
2660
+ };
2661
+ //#endregion
2662
+ //#region src/distChecks/pageMetadata.ts
2663
+ /** What every page needs in its head: a title, a description, the document
2664
+ * language. Missing ones are the classic leftovers of a generated layout. A
2665
+ * redirect stub is no page anyone reads and is skipped. */
2666
+ const pageMetadata = {
2667
+ id: "page-metadata",
2668
+ title: "Every page has a title, a description and a language",
2669
+ severity: "warning",
2670
+ begin() {
2671
+ const findings = [];
2672
+ const visit = (page) => {
2673
+ if (page.redirect) return;
2674
+ const { document } = page;
2675
+ if (!document.querySelector("title")?.textContent?.trim()) findings.push({
2676
+ message: "No <title>",
2677
+ path: page.path
2678
+ });
2679
+ if (!document.querySelector("meta[name=\"description\"]")?.getAttribute("content")?.trim()) findings.push({
2680
+ message: "No <meta name=\"description\">",
2681
+ path: page.path
2682
+ });
2683
+ if (!document.documentElement?.getAttribute("lang")?.trim()) findings.push({
2684
+ message: "No lang attribute on <html>",
2685
+ path: page.path
2686
+ });
2687
+ };
2688
+ return {
2689
+ visit,
2690
+ finish: () => findings
2691
+ };
2692
+ }
2693
+ };
2694
+ //#endregion
2695
+ //#region src/distChecks/placeholderContent.ts
2696
+ /** Text that should never reach a visitor: template filler, a value that was
2697
+ * rendered instead of formatted, a template expression the build did not
2698
+ * evaluate. And references to development hosts or example domains. */
2699
+ const TEXT_PATTERNS = [
2700
+ {
2701
+ name: "lorem ipsum",
2702
+ pattern: /lorem ipsum/i
2703
+ },
2704
+ {
2705
+ name: "[object Object]",
2706
+ pattern: /\[object Object\]/
2707
+ },
2708
+ {
2709
+ name: "a bare 'undefined'",
2710
+ pattern: /(?<![\w-])undefined(?![\w-])/
2711
+ },
2712
+ {
2713
+ name: "a bare 'NaN'",
2714
+ pattern: /(?<![\w-])NaN(?![\w-])/
2715
+ },
2716
+ {
2717
+ name: "an unrendered template expression",
2718
+ pattern: /\{\{[^}]*\}\}/
2719
+ }
2720
+ ];
2721
+ /** Development hosts and the RFC 2606 example domains, including their
2722
+ * subdomains — but not a real host that merely ends in "example.com", such as
2723
+ * counterexample.com (fixed 2026-09-24). */
2724
+ const DEV_HOSTS = /^(https?:)?\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|(?:[^/:?#]+\.)?example\.(com|org|net))(?=[/:?#]|$)/i;
2725
+ const CONTEXT = 40;
2726
+ const placeholderContent = {
2727
+ id: "placeholder-content",
2728
+ title: "No placeholder text or development hosts reach the visitor",
2729
+ severity: "warning",
2730
+ begin() {
2731
+ const findings = [];
2732
+ const visit = (page) => {
2733
+ const text = page.visibleText();
2734
+ for (const { name, pattern } of TEXT_PATTERNS) {
2735
+ const match = pattern.exec(text);
2736
+ if (!match) continue;
2737
+ const start = Math.max(0, match.index - CONTEXT);
2738
+ const snippet = text.slice(start, match.index + match[0].length + CONTEXT).trim();
2739
+ findings.push({
2740
+ message: `Visible text contains ${name}: "…${snippet}…"`,
2741
+ path: page.path
2742
+ });
2743
+ }
2744
+ const seen = /* @__PURE__ */ new Set();
2745
+ for (const el of page.document.querySelectorAll("[href], [src], [srcset], [poster]")) for (const value of referencedUrls(el)) {
2746
+ const v = value.trim();
2747
+ if (!DEV_HOSTS.test(v) || seen.has(v)) continue;
2748
+ seen.add(v);
2749
+ findings.push({
2750
+ message: `References a development or example host: ${v}`,
2751
+ path: page.path
2752
+ });
2753
+ }
2754
+ };
2755
+ return {
2756
+ visit,
2757
+ finish: () => findings
2758
+ };
2759
+ }
2760
+ };
2761
+ //#endregion
2762
+ //#region src/distChecks/siteManifest.ts
2763
+ const FILE = "site-manifest.json";
2764
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
2765
+ const manifestFindings = (ctx) => {
2766
+ if (!ctx.has(FILE)) return [{
2767
+ message: "No site-manifest.json in the build: the site has not adopted @v-office/site-manifest and no rollout can reach it",
2768
+ path: FILE
2769
+ }];
2770
+ let doc;
2771
+ try {
2772
+ doc = JSON.parse(ctx.read(FILE));
2773
+ } catch {
2774
+ return [{
2775
+ message: "site-manifest.json is not valid JSON",
2776
+ path: FILE
2777
+ }];
2778
+ }
2779
+ if (!isRecord(doc)) return [{
2780
+ message: "site-manifest.json is not a JSON object",
2781
+ path: FILE
2782
+ }];
2783
+ if (doc.manifestVersion !== 1) return [{
2784
+ message: `manifestVersion ${JSON.stringify(doc.manifestVersion)} is not one of the versions the controller reads (1); the build is reported without a manifest`,
2785
+ path: FILE
2786
+ }];
2787
+ if (!isRecord(doc.packages) || Object.keys(doc.packages).length === 0) return [{
2788
+ message: "packages is empty: no installed version was recorded",
2789
+ path: FILE
2790
+ }];
2791
+ return [];
2792
+ };
2793
+ /** A site without a readable manifest is outside every rollout: the controller
2794
+ * reads manifestVersion 1 and skips everything else. */
2795
+ const siteManifest = {
2796
+ id: "site-manifest",
2797
+ title: "The build wrote a readable site-manifest.json",
2798
+ severity: "warning",
2799
+ begin: (ctx) => ({ finish: () => manifestFindings(ctx) })
2800
+ };
2801
+ //#endregion
2802
+ //#region src/distChecks/sitemap.ts
2803
+ const pathOf = (url) => {
2804
+ try {
2805
+ return new URL(url.trim(), "http://site.invalid").pathname;
2806
+ } catch {
2807
+ return null;
2808
+ }
2809
+ };
2810
+ //#endregion
2811
+ //#region src/distChecks/index.ts
2812
+ /**
2813
+ * The dist checks: the platform's checks over a build's `dist/`. They are part of the `dist`
2814
+ * stage (`site-checks dist` runs them after the site's own), and the build worker also runs them
2815
+ * on its own, at its pinned version, over every build of every website: public sites, the guest
2816
+ * and owner apps, and sites without this package. A site configures nothing for them. A check
2817
+ * every website must pass, whether or not it has this package, belongs here.
2818
+ * See docs/website-platform/process/10-dist-checks.md.
2819
+ */
2820
+ const distChecks = [
2821
+ siteManifest,
2822
+ keyPages,
2823
+ notFoundBeacon,
2824
+ internalLinks,
2825
+ legalPages,
2826
+ pageMetadata,
2827
+ placeholderContent,
2828
+ insecureResources,
2829
+ {
2830
+ id: "sitemap",
2831
+ title: "robots.txt and the sitemap point at files of the build",
2832
+ severity: "warning",
2833
+ begin(ctx) {
2834
+ if (!ctx.isAstro) return null;
2835
+ const findings = [];
2836
+ const sitemaps = new Set(ctx.files.filter((f) => /^sitemap[^/]*\.xml$/i.test(f)));
2837
+ if (!ctx.has("robots.txt")) findings.push({
2838
+ message: "No robots.txt",
2839
+ path: "robots.txt"
2840
+ });
2841
+ else for (const line of ctx.read("robots.txt").split(/\r?\n/)) {
2842
+ const match = /^\s*sitemap\s*:\s*(\S+)/i.exec(line);
2843
+ if (!match) continue;
2844
+ const file = pathOf(match[1])?.replace(/^\/+/, "");
2845
+ if (file && !ctx.has(file)) findings.push({
2846
+ message: `robots.txt names sitemap ${match[1]}, which is not in the build`,
2847
+ path: "robots.txt"
2848
+ });
2849
+ else if (file) sitemaps.add(file);
2850
+ }
2851
+ if (sitemaps.size === 0) findings.push({
2852
+ message: "No sitemap in the build",
2853
+ path: "sitemap-index.xml"
2854
+ });
2855
+ for (const file of sitemaps) {
2856
+ if (!ctx.has(file)) continue;
2857
+ for (const match of ctx.read(file).matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)) {
2858
+ const target = pathOf(xmlText(match[1]));
2859
+ if (target === null) continue;
2860
+ const asFile = target.replace(/^\/+/, "");
2861
+ if (/\.xml$/i.test(asFile)) {
2862
+ if (ctx.has(asFile)) sitemaps.add(asFile);
2863
+ else findings.push({
2864
+ message: `Sitemap index lists ${target}, which is not in the build`,
2865
+ path: file
2866
+ });
2867
+ } else if (!ctx.serves(target)) findings.push({
2868
+ message: `Sitemap lists ${target}, which no file in the build serves`,
2869
+ path: file
2870
+ });
2871
+ }
2872
+ }
2873
+ return { finish: () => findings };
2874
+ }
2875
+ }
2876
+ ];
2877
+ /** Runs every dist check over `distDir`. Never throws: a check that throws is a `failed` result,
2878
+ * an unreadable `distDir` fails every check the same way. */
2879
+ const runDistChecks = (distDir, opts, list = distChecks) => runChecks(() => loadDistContext(distDir, opts), list);
2880
+ //#endregion
2881
+ //#region src/stages.ts
2882
+ /**
2883
+ * Runs one stage over a project. `src` runs the source checks and leaves any `dist/` unread;
2884
+ * `dist` runs the site's dist-stage checks and the platform's dist checks over the build output,
2885
+ * each page parsed once for all of them. Never throws for a check's sake: a check that throws is
2886
+ * a `failed` result. A config file that cannot be read throws before anything runs, and so does
2887
+ * an Astro config that names `root`, `srcDir` or `publicDir`: the checks read `src/` and `public/`
2888
+ * under the root, and must not pass over folders the build does not use. A site URL that is no
2889
+ * URL throws too: the dist stage would fail every check on it, and failed checks do not refuse.
2890
+ */
2891
+ const runStage = async (stage, input) => {
2892
+ const astro = readAstroConfig(input.root);
2893
+ if (astro.layoutKey) throw new Error(`site-checks: the Astro config names \`${astro.layoutKey}\`; the checks read src/ and public/ under the project root only (Astro's default layout). Remove the setting.`);
2894
+ const site = input.site ?? astro.site;
2895
+ if (site !== void 0 && !URL.canParse(site)) throw new Error(`site-checks: the site URL ${JSON.stringify(site)} is not a valid URL.`);
2896
+ const base = contextInput({
2897
+ root: input.root,
2898
+ distDir: input.distDir ?? path.join(input.root, "dist"),
2899
+ stage,
2900
+ config: {
2901
+ site,
2902
+ trailingSlash: astro.trailingSlash
2903
+ },
2904
+ options: input.options,
2905
+ note: input.note
2906
+ });
2907
+ if (stage === "src") return runChecks(() => loadContext(base), checksOf("src"));
2908
+ const isAstro = astro.found || fs.existsSync(path.join(input.root, "node_modules", "astro"));
2909
+ const list = [...distChecks, ...checksOf("dist")];
2910
+ return runChecks(() => loadDistStageContext({
2911
+ ...base,
2912
+ isAstro
2913
+ }), list);
2914
+ };
2915
+ //#endregion
2916
+ //#region src/cli.ts
2917
+ const USAGE = `Usage: site-checks <src | dist> [options]
2918
+
2919
+ src the source checks, before the build (reads the project, never dist/)
2920
+ dist the checks over the built output, after the build
2921
+
2922
+ Options:
2923
+ --root <dir> the project (default: the current directory)
2924
+ --dist <dir> the build output, relative to the root (default: dist; dist stage only)
2925
+ --site <url> the site's public URL (default: \`site\` in the Astro config file)
2926
+ --report <file> write the report as JSON here (default for dist: <dist>/${SITE_CHECKS_FILE})
2927
+ -h, --help this text
2928
+
2929
+ Exits 0 when nothing refused, 1 when a check with severity error found something, 2 on a usage
2930
+ or configuration error. Data for the checks: ${CONFIG_FILE} at the project root.`;
2931
+ const STAGES = ["src", "dist"];
2932
+ const isStage = (value) => value !== void 0 && STAGES.includes(value);
2933
+ const isUrl = (value) => {
2934
+ try {
2935
+ return /^https?:$/.test(new URL(value).protocol);
2936
+ } catch {
2937
+ return false;
2938
+ }
2939
+ };
2940
+ /** Every finding of every check that found something or could not run, for the terminal. */
2941
+ const findingLines = (report) => {
2942
+ const lines = [];
2943
+ for (const result of report.results) {
2944
+ if (result.status === "ok" || result.status === "skipped") continue;
2945
+ lines.push(...summaryLines({
2946
+ ...report,
2947
+ results: [result]
2948
+ }));
2949
+ for (const finding of result.findings) lines.push(` ${findingLine(finding)}`);
2950
+ if (result.omitted > 0) lines.push(` (+${result.omitted} more)`);
2951
+ }
2952
+ return lines;
2953
+ };
2954
+ const OPTIONS = {
2955
+ root: { type: "string" },
2956
+ dist: { type: "string" },
2957
+ site: { type: "string" },
2958
+ report: { type: "string" },
2959
+ help: {
2960
+ type: "boolean",
2961
+ short: "h"
2962
+ }
2963
+ };
2964
+ /** The command line. Returns the exit code; prints to `io`. */
2965
+ async function cli(argv, io, cwd = process.cwd()) {
2966
+ let parsed;
2967
+ try {
2968
+ parsed = parseArgs({
2969
+ args: [...argv],
2970
+ allowPositionals: true,
2971
+ options: OPTIONS
2972
+ });
2973
+ } catch (err) {
2974
+ io.err(`site-checks: ${err.message}\n\n${USAGE}`);
2975
+ return 2;
2976
+ }
2977
+ const { values, positionals } = parsed;
2978
+ if (values.help) {
2979
+ io.out(USAGE);
2980
+ return 0;
2981
+ }
2982
+ const [stage, ...rest] = positionals;
2983
+ if (!isStage(stage) || rest.length > 0) {
2984
+ io.err(USAGE);
2985
+ return 2;
2986
+ }
2987
+ if (values.site !== void 0 && !isUrl(values.site)) {
2988
+ io.err(`site-checks: --site must be an http(s) URL, got ${JSON.stringify(values.site)}`);
2989
+ return 2;
2990
+ }
2991
+ const root = path.resolve(cwd, values.root ?? ".");
2992
+ const distDir = path.resolve(root, values.dist ?? "dist");
2993
+ if (!fs.statSync(root, { throwIfNoEntry: false })?.isDirectory()) {
2994
+ io.err(`site-checks: no project at ${root}; pass --root with the site's directory.`);
2995
+ return 2;
2996
+ }
2997
+ if (stage === "dist" && !fs.statSync(distDir, { throwIfNoEntry: false })?.isDirectory()) {
2998
+ io.err(`site-checks: no build output at ${distDir}; run the build first, or pass --dist.`);
2999
+ return 2;
3000
+ }
3001
+ let report;
3002
+ try {
3003
+ report = await runStage(stage, {
3004
+ root,
3005
+ distDir,
3006
+ site: values.site,
3007
+ note: io.err
3008
+ });
3009
+ } catch (err) {
3010
+ io.err(err.message);
3011
+ return 2;
3012
+ }
3013
+ const reportFile = values.report !== void 0 ? path.resolve(cwd, values.report) : stage === "dist" ? path.join(distDir, SITE_CHECKS_FILE) : void 0;
3014
+ if (reportFile) try {
3015
+ fs.mkdirSync(path.dirname(reportFile), { recursive: true });
3016
+ fs.writeFileSync(reportFile, JSON.stringify(report, null, 2) + "\n");
3017
+ } catch (err) {
3018
+ io.err(`site-checks: cannot write the report to ${reportFile}: ${err.message}`);
3019
+ return 2;
3020
+ }
3021
+ for (const line of findingLines(report)) io.err(line);
3022
+ const shown = reportFile ? path.relative(cwd, reportFile) : void 0;
3023
+ if (blockingResults(report).length > 0) {
3024
+ io.err(refusalMessage(report, stage, shown));
3025
+ return 1;
3026
+ }
3027
+ io.out(`[site-checks] ${stage}: ${report.results.length} checks, nothing refused` + (shown ? ` (report: ${shown})` : ""));
3028
+ return 0;
3029
+ }
3030
+ //#endregion
3031
+ 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 };