@lariocpt/crust-site 0.0.0-stage → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +99 -2
- package/docs/USAGE.md +1128 -0
- package/package.json +33 -4
- package/src/assets.ts +875 -0
- package/src/build-lock.ts +214 -0
- package/src/build.ts +755 -0
- package/src/cli.ts +269 -0
- package/src/config.ts +538 -0
- package/src/content.ts +267 -0
- package/src/dev.ts +821 -0
- package/src/diagnostics.ts +382 -0
- package/src/emit.ts +260 -0
- package/src/fence.ts +593 -0
- package/src/frontmatter.ts +240 -0
- package/src/fs-path.ts +54 -0
- package/src/html.ts +400 -0
- package/src/index.ts +128 -0
- package/src/markdown.ts +444 -0
- package/src/pages.ts +169 -0
- package/src/publication.ts +245 -0
- package/src/render.ts +940 -0
- package/src/routes.ts +363 -0
- package/src/types.ts +250 -0
- package/src/url.ts +273 -0
- package/src/validate.ts +367 -0
package/src/url.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// The URL policy (plan §1): the ONE function that decides whether a URL string
|
|
2
|
+
// may reach a URL-bearing attribute. `ctx.url()` (the render chunk) wraps it,
|
|
3
|
+
// and the fence re-runs it over every URL-bearing attribute whose value
|
|
4
|
+
// contains a tracked template value — so an author who forgets `url()` is
|
|
5
|
+
// caught at build time, not at click time.
|
|
6
|
+
//
|
|
7
|
+
// The policy is TOTAL and reject-first: anything that is not unambiguously
|
|
8
|
+
// one of the allowed forms is an error. The pre-parse rejects run BEFORE
|
|
9
|
+
// `new URL()` because the WHATWG parser normalizes aggressively (it strips
|
|
10
|
+
// `\t\r\n` from any position and percent-decodes nothing in schemes we care
|
|
11
|
+
// about) — a parser that "fixes" input is a fence that misses attacks.
|
|
12
|
+
|
|
13
|
+
import type { Diagnostic, DiagnosticCode } from "./diagnostics";
|
|
14
|
+
|
|
15
|
+
/** Schemes allowed in a URL. Everything else is rejected (plan §1). */
|
|
16
|
+
const ALLOWED_SCHEMES = new Set(["http:", "https:", "mailto:", "tel:", "sms:"]);
|
|
17
|
+
|
|
18
|
+
/** Attributes whose value is a URL and is re-checked by the fence. */
|
|
19
|
+
export const URL_ATTRIBUTES = [
|
|
20
|
+
"href",
|
|
21
|
+
"src",
|
|
22
|
+
"action",
|
|
23
|
+
"formaction",
|
|
24
|
+
"poster",
|
|
25
|
+
"cite",
|
|
26
|
+
"background",
|
|
27
|
+
"data",
|
|
28
|
+
] as const;
|
|
29
|
+
|
|
30
|
+
export type UrlAttribute = (typeof URL_ATTRIBUTES)[number];
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Options for URL resolution.
|
|
34
|
+
*
|
|
35
|
+
* `siteUrl` is the site's configured base URL — the FULL value from the
|
|
36
|
+
* config, **path prefix included** (`https://x.dev/docs`), no trailing slash
|
|
37
|
+
* (defineSite enforces). It is NOT `new URL(site).origin`: for a path-prefixed
|
|
38
|
+
* site (GH Pages under `/docs/`) an origin base silently drops the prefix from
|
|
39
|
+
* every relative-ref resolution.
|
|
40
|
+
*
|
|
41
|
+
* `pageRoute` is the current page's normalized route (prefix NOT included —
|
|
42
|
+
* routes are prefix-less, see routes.canonicalUrl). When given, relative refs
|
|
43
|
+
* resolve against `siteUrl + pageRoute`; when omitted, against the site root.
|
|
44
|
+
*
|
|
45
|
+
* The invariant every caller relies on (and that tests/render.test.ts pins):
|
|
46
|
+
*
|
|
47
|
+
* urlBase({ siteUrl: site, pageRoute: route }) === canonicalUrl(site, route)
|
|
48
|
+
*
|
|
49
|
+
* i.e. the base a relative ref resolves against is exactly the page's
|
|
50
|
+
* canonical URL. markdown link validation (pages.ts → markdown.ts), `ctx.url()`
|
|
51
|
+
* and the fence all derive their options the same way, so a relative link and
|
|
52
|
+
* a canonical URL can never disagree.
|
|
53
|
+
*/
|
|
54
|
+
export interface UrlPolicyOptions {
|
|
55
|
+
siteUrl: string;
|
|
56
|
+
pageRoute?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The ONE base a relative reference resolves against (see UrlPolicyOptions).
|
|
61
|
+
* Derived here and nowhere else so the markdown checker, `ctx.url()`, the
|
|
62
|
+
* fence and the emitter cannot drift apart. Internal helper: exported from
|
|
63
|
+
* this module for the render chunk and the tests, not from index.ts.
|
|
64
|
+
*/
|
|
65
|
+
export function urlBase(opts: UrlPolicyOptions): string {
|
|
66
|
+
return opts.pageRoute ? `${opts.siteUrl}${opts.pageRoute}` : `${opts.siteUrl}/`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function urlDiagnostic(code: DiagnosticCode, value: string, message: string): Diagnostic {
|
|
70
|
+
return {
|
|
71
|
+
code,
|
|
72
|
+
severity: "error",
|
|
73
|
+
sourcePath: "",
|
|
74
|
+
message: `url ${JSON.stringify(value)}: ${message}`,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Validate a URL value. Returns the value UNCHANGED when valid (so callers
|
|
80
|
+
* can pipe it straight into the markup); throws a Diagnostic when invalid.
|
|
81
|
+
*
|
|
82
|
+
* Pre-parse rejects (checked on the RAW text, before any parsing):
|
|
83
|
+
* - url.control-char — any char below U+0020, U+007F, or U+0020 (space)
|
|
84
|
+
* - url.bad-char — `"` `'` `` ` `` `\`
|
|
85
|
+
* - url.entity-escape — the substring `&#` (the raw form of an HTML
|
|
86
|
+
* entity reference; `java script:` becomes
|
|
87
|
+
* `javascript:` in a browser that decodes first)
|
|
88
|
+
* - url.protocol-relative — a leading `//` (no scheme; the browser resolves
|
|
89
|
+
* it against the CURRENT page's origin — v1
|
|
90
|
+
* rejects it outright instead of guessing)
|
|
91
|
+
*
|
|
92
|
+
* Then the shape policy:
|
|
93
|
+
* - a pure fragment `#...` is valid (same page, by construction)
|
|
94
|
+
* - a relative or root-relative ref is valid by construction: it resolves
|
|
95
|
+
* against the site (same origin); we still resolve it and re-check the
|
|
96
|
+
* origin so a future base change cannot smuggle a cross-origin ref in
|
|
97
|
+
* - an absolute URL: `new URL` parse (a parse failure is url.scheme — the
|
|
98
|
+
* input claimed to be absolute but is not a URL); the lowercased scheme
|
|
99
|
+
* must be in {http:, https:, mailto:, tel:, sms:} (url.scheme otherwise);
|
|
100
|
+
* http/https require a non-empty host (url.no-host) and reject userinfo
|
|
101
|
+
* outright in v1 (url.userinfo)
|
|
102
|
+
*
|
|
103
|
+
* NOTE: absolute http(s) URLs to OTHER origins are ACCEPTED — external links
|
|
104
|
+
* are legitimate. The same-origin rule applies to RELATIVE refs only (and it
|
|
105
|
+
* holds by construction: a relative ref resolves against the site origin).
|
|
106
|
+
*/
|
|
107
|
+
export function validateUrl(value: string, opts: UrlPolicyOptions): string {
|
|
108
|
+
if (typeof value !== "string") {
|
|
109
|
+
throw urlDiagnostic("url.scheme", String(value), "must be a string");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// --- pre-parse rejects -------------------------------------------------
|
|
113
|
+
let i = 0;
|
|
114
|
+
for (; i < value.length; i++) {
|
|
115
|
+
const code = value.charCodeAt(i);
|
|
116
|
+
// code <= 0x20 covers the C0 controls AND U+0020 (space) itself;
|
|
117
|
+
// 0x7F is DEL. All are invisible-ish in a printed URL and are exactly
|
|
118
|
+
// what the WHATWG parser strips (`java\tscript:` → `javascript:`).
|
|
119
|
+
if (code <= 0x20 || code === 0x7f) {
|
|
120
|
+
throw urlDiagnostic(
|
|
121
|
+
"url.control-char",
|
|
122
|
+
value,
|
|
123
|
+
`contains a control character or space (U+${code.toString(16).toUpperCase()})`,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
for (const ch of ['"', "'", "`", "\\"]) {
|
|
128
|
+
if (value.includes(ch)) {
|
|
129
|
+
throw urlDiagnostic("url.bad-char", value, `contains ${JSON.stringify(ch)}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (value.includes("&#")) {
|
|
133
|
+
throw urlDiagnostic(
|
|
134
|
+
"url.entity-escape",
|
|
135
|
+
value,
|
|
136
|
+
"contains an HTML entity reference (`&#`); decode it away or use a plain URL",
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
// Named entity references (`	`, `
`, `:`, …): a browser
|
|
140
|
+
// decodes the FULL HTML5 named set in an attribute value BEFORE the URL
|
|
141
|
+
// parser runs, and 	/
 decode to characters the URL parser
|
|
142
|
+
// strips — `java	script:x` IS `javascript:x` in a browser. The fence's
|
|
143
|
+
// decodeEntities covers only the five entities html.ts emits plus numeric
|
|
144
|
+
// references; shipping the ~2200-entry table to decode the rest is not an
|
|
145
|
+
// honest option, so the conservative rule wins: any surviving `&name;`
|
|
146
|
+
// pattern is rejected outright. Linear scan (no backtracking regex): each
|
|
147
|
+
// '&' starts one name probe; name chars are visited O(1) times overall.
|
|
148
|
+
for (let k = value.indexOf("&"); k !== -1; k = value.indexOf("&", k + 1)) {
|
|
149
|
+
let m = k + 1;
|
|
150
|
+
while (m < value.length) {
|
|
151
|
+
const c = value.charCodeAt(m);
|
|
152
|
+
const isAlnum =
|
|
153
|
+
(c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a);
|
|
154
|
+
if (!isAlnum) break;
|
|
155
|
+
m++;
|
|
156
|
+
}
|
|
157
|
+
if (m > k + 1 && m < value.length && value[m] === ";") {
|
|
158
|
+
throw urlDiagnostic(
|
|
159
|
+
"url.entity-escape",
|
|
160
|
+
value,
|
|
161
|
+
"contains a named HTML entity reference (`&name;`); browsers decode it before the URL parser runs (	/
 smuggle stripped chars, : smuggles a scheme) — use a plain URL",
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (value.startsWith("//")) {
|
|
166
|
+
throw urlDiagnostic(
|
|
167
|
+
"url.protocol-relative",
|
|
168
|
+
value,
|
|
169
|
+
"protocol-relative URLs (`//host/...`) are rejected in v1; use an absolute http(s) URL",
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let siteOrigin: URL;
|
|
174
|
+
try {
|
|
175
|
+
siteOrigin = new URL(opts.siteUrl);
|
|
176
|
+
} catch {
|
|
177
|
+
// A caller that hands over an unparseable base is a caller bug, not a
|
|
178
|
+
// value problem — but the function must stay total (never a raw throw).
|
|
179
|
+
throw urlDiagnostic(
|
|
180
|
+
"url.scheme",
|
|
181
|
+
value,
|
|
182
|
+
`the base ${JSON.stringify(opts.siteUrl)} is not a parseable URL`,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// --- pure fragment: same page, always safe -----------------------------
|
|
187
|
+
if (value.startsWith("#")) return value;
|
|
188
|
+
|
|
189
|
+
// Absolute input = starts with a URL scheme (WHATWG:
|
|
190
|
+
// [a-zA-Z][a-zA-Z0-9+.-]*:). `mailto:x@y.com`, `tel:+1` and `sms:1` have
|
|
191
|
+
// NO "://" — testing for "://" would misroute them as relative refs.
|
|
192
|
+
// (`//` is already rejected as protocol-relative above.) Everything else
|
|
193
|
+
// is a relative or root-relative ref.
|
|
194
|
+
const SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:/;
|
|
195
|
+
if (!SCHEME.test(value)) {
|
|
196
|
+
const base = urlBase(opts);
|
|
197
|
+
let resolved: URL;
|
|
198
|
+
try {
|
|
199
|
+
resolved = new URL(value, base);
|
|
200
|
+
} catch {
|
|
201
|
+
throw urlDiagnostic("url.scheme", value, "is not a parseable URL or relative reference");
|
|
202
|
+
}
|
|
203
|
+
// A relative ref can only leave the site if the base is not the site —
|
|
204
|
+
// re-check the origin anyway (defense in depth against base misuse).
|
|
205
|
+
// NOTE this compares the ORIGIN of the (possibly prefixed) site base, so
|
|
206
|
+
// a path prefix in `siteUrl` neither weakens nor strengthens the check.
|
|
207
|
+
if (
|
|
208
|
+
(resolved.protocol === "http:" || resolved.protocol === "https:") &&
|
|
209
|
+
resolved.origin !== siteOrigin.origin
|
|
210
|
+
) {
|
|
211
|
+
throw urlDiagnostic(
|
|
212
|
+
"url.scheme",
|
|
213
|
+
value,
|
|
214
|
+
`resolves cross-origin to ${resolved.origin}; relative refs must stay on the site`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// --- absolute URLs -------------------------------------------------------
|
|
221
|
+
const schemeMatch = SCHEME.exec(value);
|
|
222
|
+
// Special-scheme values must use the `//` authority form. WHATWG normalizes
|
|
223
|
+
// `https:evil.com` (and `https:/evil.com`) to `https://evil.com/` — the
|
|
224
|
+
// parser REWRITES the input, and a parser that rewrites is a fence that
|
|
225
|
+
// misses (this file's header rule). A value that only becomes an external
|
|
226
|
+
// URL after normalization is rejected, not silently accepted.
|
|
227
|
+
if (schemeMatch) {
|
|
228
|
+
const claimed = schemeMatch[0].toLowerCase();
|
|
229
|
+
if (
|
|
230
|
+
(claimed === "http:" || claimed === "https:") &&
|
|
231
|
+
!value.toLowerCase().startsWith(`${claimed}//`)
|
|
232
|
+
) {
|
|
233
|
+
throw urlDiagnostic(
|
|
234
|
+
"url.scheme",
|
|
235
|
+
value,
|
|
236
|
+
"http(s) URLs must use the `//` authority form (`https://…`): WHATWG normalizes `https:x` to `https://x/`, so this value is not what it appears to be",
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
let parsed: URL;
|
|
241
|
+
try {
|
|
242
|
+
parsed = new URL(value);
|
|
243
|
+
} catch {
|
|
244
|
+
// A special-scheme URL with an EMPTY host (http://, https://?x) is a
|
|
245
|
+
// parse failure per WHATWG ("missing host") — report it as such, not as
|
|
246
|
+
// an unknown scheme. Other parse failures are a scheme-shape problem.
|
|
247
|
+
const inScheme = schemeMatch ? schemeMatch[0] : "";
|
|
248
|
+
const rest = value.slice(inScheme.length);
|
|
249
|
+
const hostPart =
|
|
250
|
+
(rest.startsWith("//") ? rest.slice(2) : rest.replace(/^\//, "")).split(/[/?#]/)[0] ?? "";
|
|
251
|
+
if ((inScheme === "http:" || inScheme === "https:") && hostPart === "") {
|
|
252
|
+
throw urlDiagnostic("url.no-host", value, "http(s) URLs require a non-empty host");
|
|
253
|
+
}
|
|
254
|
+
throw urlDiagnostic("url.scheme", value, "is not a parseable absolute URL");
|
|
255
|
+
}
|
|
256
|
+
const scheme = parsed.protocol.toLowerCase();
|
|
257
|
+
if (!ALLOWED_SCHEMES.has(scheme)) {
|
|
258
|
+
throw urlDiagnostic(
|
|
259
|
+
"url.scheme",
|
|
260
|
+
value,
|
|
261
|
+
`scheme "${scheme}" is not allowed (allowed: ${[...ALLOWED_SCHEMES].sort().join(", ")})`,
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
if (scheme === "http:" || scheme === "https:") {
|
|
265
|
+
if (parsed.host === "") {
|
|
266
|
+
throw urlDiagnostic("url.no-host", value, "http(s) URLs require a non-empty host");
|
|
267
|
+
}
|
|
268
|
+
if (parsed.username !== "" || parsed.password !== "") {
|
|
269
|
+
throw urlDiagnostic("url.userinfo", value, "userinfo (user:pass@) is rejected in v1");
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return value;
|
|
273
|
+
}
|
package/src/validate.ts
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
// Post-render validation — pipeline step 7 (plan §4.7): runs AFTER render and
|
|
2
|
+
// BEFORE emit/publish, over the FINAL emitted documents. Three checks, all
|
|
3
|
+
// collected (never first-error-fatal) and handed to the build's diagnostic
|
|
4
|
+
// pool, where errors block the publish and warnings join BuildResult.warnings:
|
|
5
|
+
//
|
|
6
|
+
// 1. Internal links — every internal link extracted during render (the
|
|
7
|
+
// page's `links`, which contains ONLY internal destinations: .md links
|
|
8
|
+
// resolved against the route table and same-page fragments — external
|
|
9
|
+
// URLs are never recorded, so they are never fragment-checked):
|
|
10
|
+
// - destination is the generated 404 route → link.broken (the 404
|
|
11
|
+
// page is generated, excluded from the sitemap, and is not a link
|
|
12
|
+
// target — plan, "Locked decisions" 2);
|
|
13
|
+
// - destination is in neither the route table (production) nor the
|
|
14
|
+
// drafts → link.broken, naming the source page, the line and the
|
|
15
|
+
// destination;
|
|
16
|
+
// - destination is a draft → link.draft.
|
|
17
|
+
// Severity (plan §5 — crust rule 1, no false pass): in a production
|
|
18
|
+
// build (mode "build") both are ERRORS; in dev (mode "dev", chunk 9
|
|
19
|
+
// passes it) both are WARNINGS, because the dev server renders and
|
|
20
|
+
// serves drafts, so the link really resolves there.
|
|
21
|
+
//
|
|
22
|
+
// 2. Fragments — a link carrying #fragment requires the destination page's
|
|
23
|
+
// FINAL EMITTED html to contain id="fragment". The ids are collected
|
|
24
|
+
// ONCE per emitted page (route → Set<ids>, scanning the emitted bytes)
|
|
25
|
+
// and shared across every link in the run. Same-page fragments are
|
|
26
|
+
// included (a fragment link's route is its own page). The check applies
|
|
27
|
+
// only to destinations that were actually emitted: a draft destination
|
|
28
|
+
// in a production build has no emitted bytes (its link.draft above is
|
|
29
|
+
// the report), so its fragment is not checked twice.
|
|
30
|
+
//
|
|
31
|
+
// 3. Metadata — per emitted page (INCLUDING the generated 404): exactly
|
|
32
|
+
// one <meta charset> (head() never emits one — the layout hand-writes
|
|
33
|
+
// it), exactly one <title>, exactly one rel="canonical". head() is the
|
|
34
|
+
// only producer of title and canonical in v1, so a document with no
|
|
35
|
+
// canonical is reported as metadata.head-missing ("the layout never
|
|
36
|
+
// called head()"); a document with none is never a silent pass.
|
|
37
|
+
//
|
|
38
|
+
// WHY A REGEX OVER THE EMITTED BYTES IS ACCEPTABLE HERE (and nowhere else in
|
|
39
|
+
// the package): every byte of these documents is OUR OWN output. The fence
|
|
40
|
+
// (finalizeDocument) already guaranteed the well-formedness of everything
|
|
41
|
+
// the author interpolated — value ranges cannot cross comment/script/
|
|
42
|
+
// attribute boundaries, every attribute is double-quoted, every URL-bearing
|
|
43
|
+
// attribute re-passed the URL policy (so no `"` or `>` inside a value) —
|
|
44
|
+
// and the only other content is static markup the engine and the layout
|
|
45
|
+
// template wrote literally (markdown bodies are fully escaped: html:false,
|
|
46
|
+
// so an `id="..."` sequence inside text or code is entity-escaped and can
|
|
47
|
+
// only ever be matched as a real attribute). Scanning own, fenced bytes is
|
|
48
|
+
// a linear-time state machine (the plan's DoS rule), never a parse of
|
|
49
|
+
// untrusted input. Three scanning rules follow from that, each pinned by a
|
|
50
|
+
// test that fails without it:
|
|
51
|
+
//
|
|
52
|
+
// - COMMENTS ARE STRIPPED before any scan. A commented-out
|
|
53
|
+
// `<meta charset>`/`<title>`/`id="…"` is not a head fact or an anchor,
|
|
54
|
+
// and counting it would be a false pass (a dead fragment link passing,
|
|
55
|
+
// a head-less page satisfying the charset check). `<!--` can only
|
|
56
|
+
// appear as literal layout markup (the fence escapes `<` in every
|
|
57
|
+
// interpolated value, markdown escapes raw HTML), so a linear
|
|
58
|
+
// `<!--…-->` strip is safe over our bytes.
|
|
59
|
+
// - IDS ARE QUOTED-ONLY (double or single). Broadening to unquoted values
|
|
60
|
+
// is UNSOUND: an unquoted `id=x` inside a code fence contains no
|
|
61
|
+
// escapable characters, survives escaping verbatim, and would be
|
|
62
|
+
// byte-identical to layout markup — fragments would false-pass from
|
|
63
|
+
// code samples. A quoted id can never survive escaping ("), so a
|
|
64
|
+
// quoted-only match is always a real attribute. Layouts must quote
|
|
65
|
+
// their ids; an unquoted hand-written id is not recognized (documented).
|
|
66
|
+
// - `<title>` INSIDE `<svg>` IS NOT THE DOCUMENT TITLE. An accessible
|
|
67
|
+
// svg icon carries its own <title>; counting it would false-fail every
|
|
68
|
+
// page that uses one (title-duplicate) and false-satisfy the title check
|
|
69
|
+
// for a head-less page. Titles are counted with linear svg-depth
|
|
70
|
+
// tracking (svg is never nested in svg in practice; the depth clamps).
|
|
71
|
+
//
|
|
72
|
+
// Drafts' OWN links: a production build renders (and emits) no drafts, so
|
|
73
|
+
// the validator is only ever FEED production pages plus the 404 in
|
|
74
|
+
// "build" mode — a draft's links are not validated in a build (there are no
|
|
75
|
+
// bytes to check fragments against, and its links would 404 by
|
|
76
|
+
// construction anyway). In "dev" mode chunk 9 feeds the full page set, and
|
|
77
|
+
// a draft's own broken links are then flagged (as warnings). Defense in
|
|
78
|
+
// depth: if a draft page is nevertheless handed to a "build" validator, it
|
|
79
|
+
// is skipped WHOLE (links and metadata) — validating bytes that will never
|
|
80
|
+
// be published would only produce false errors.
|
|
81
|
+
|
|
82
|
+
import { type Diagnostic, type Severity, sortDiagnostics } from "./diagnostics";
|
|
83
|
+
import type { InternalLink } from "./types";
|
|
84
|
+
|
|
85
|
+
/** One document that will (or did) land in the output. */
|
|
86
|
+
export interface EmittedPage {
|
|
87
|
+
/** The page's normalized route. */
|
|
88
|
+
readonly route: string;
|
|
89
|
+
/** posix, relative to the config directory ("<generated>" for the 404). */
|
|
90
|
+
readonly sourcePath: string;
|
|
91
|
+
/** The final emitted html (what the file on disk will contain). */
|
|
92
|
+
readonly html: string;
|
|
93
|
+
/** The internal links extracted during this page's render. */
|
|
94
|
+
readonly links: readonly InternalLink[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** One known route: a production page, or a draft (dev table / link target). */
|
|
98
|
+
export interface KnownRoute {
|
|
99
|
+
/** true when the route belongs to a draft page. */
|
|
100
|
+
readonly draft: boolean;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface ValidationOptions {
|
|
104
|
+
/**
|
|
105
|
+
* "build" = a production build: the validator sees the production pages
|
|
106
|
+
* plus the generated 404, and draft links are ERRORS. "dev" = the dev
|
|
107
|
+
* server's validation (chunk 9): the validator sees the FULL page set
|
|
108
|
+
* (drafts included, their links validated), and draft links are WARNINGS
|
|
109
|
+
* (plan §5).
|
|
110
|
+
*/
|
|
111
|
+
readonly mode: "build" | "dev";
|
|
112
|
+
/** The emitted documents, in any order (diagnostics are sorted). */
|
|
113
|
+
readonly pages: readonly EmittedPage[];
|
|
114
|
+
/**
|
|
115
|
+
* Every KNOWN route the site can have: production pages AND drafts —
|
|
116
|
+
* EXCLUDING "/404" (the generated 404 is not a link target and is
|
|
117
|
+
* special-cased as link.broken).
|
|
118
|
+
*/
|
|
119
|
+
readonly routes: ReadonlyMap<string, KnownRoute>;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The scanners (see the header for why regex over our own bytes is sound).
|
|
123
|
+
// All are linear-time; attribute NAMES match case-insensitively (HTML is
|
|
124
|
+
// case-insensitive for them), values case-sensitively (ids are).
|
|
125
|
+
const ID_ATTR = /\sid\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
126
|
+
const CHARSET_META = /<meta\s+charset\s*=/gi;
|
|
127
|
+
const CANONICAL_LINK = /<link\b[^>]*\brel\s*=\s*["']canonical["'][^>]*>/gi;
|
|
128
|
+
const HTML_COMMENT = /<!--[\s\S]*?-->/g;
|
|
129
|
+
// svg-depth tracking for the title count: <svg …> opens, </svg …> closes,
|
|
130
|
+
// <title> at depth 0 is the document title (an svg <title> is an icon's
|
|
131
|
+
// accessible name, not the page's).
|
|
132
|
+
const SVG_OR_TITLE = /<svg\b|<\/svg\s*>|<title[\s>]/gi;
|
|
133
|
+
|
|
134
|
+
/** Literal HTML comments removed (see the header: safe over own bytes). */
|
|
135
|
+
function stripComments(html: string): string {
|
|
136
|
+
return html.replace(HTML_COMMENT, "");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Every id attribute value in one emitted document (markdown heading ids
|
|
141
|
+
* and any hand-written layout ids alike). Collected once per page and
|
|
142
|
+
* shared across all fragment checks of the run. Comments are stripped
|
|
143
|
+
* first (a commented-out id is not an anchor); values are quoted-only
|
|
144
|
+
* (see the header for why unquoted matching would false-pass).
|
|
145
|
+
*/
|
|
146
|
+
export function collectIds(html: string): ReadonlySet<string> {
|
|
147
|
+
const ids = new Set<string>();
|
|
148
|
+
for (const m of stripComments(html).matchAll(ID_ATTR)) ids.add(m[1] ?? m[2] ?? "");
|
|
149
|
+
return ids;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** <title> count OUTSIDE <svg> (svg <title> is an icon label, not the page title). */
|
|
153
|
+
function countTitles(html: string): number {
|
|
154
|
+
let count = 0;
|
|
155
|
+
let svgDepth = 0;
|
|
156
|
+
for (const m of html.matchAll(SVG_OR_TITLE)) {
|
|
157
|
+
const tok = m[0].toLowerCase();
|
|
158
|
+
if (tok.startsWith("<svg")) svgDepth++;
|
|
159
|
+
else if (tok.startsWith("</svg")) svgDepth = Math.max(0, svgDepth - 1);
|
|
160
|
+
else if (svgDepth === 0) count++;
|
|
161
|
+
}
|
|
162
|
+
return count;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function countMatches(text: string, re: RegExp): number {
|
|
166
|
+
const m = text.match(re);
|
|
167
|
+
return m === null ? 0 : m.length;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** "on line 6 of \"content/index.md\"" / "in \"content/index.md\"". */
|
|
171
|
+
function at(page: EmittedPage, line: number | null): string {
|
|
172
|
+
return line === null
|
|
173
|
+
? `in ${JSON.stringify(page.sourcePath)}`
|
|
174
|
+
: `on line ${line} of ${JSON.stringify(page.sourcePath)}`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The link-severity for the mode (plan §5): error in prod, warning in dev. */
|
|
178
|
+
function linkSeverity(mode: "build" | "dev"): Severity {
|
|
179
|
+
return mode === "build" ? "error" : "warning";
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Check ONE emitted page's metadata contract (plan §3): exactly one
|
|
184
|
+
* `<meta charset>`, exactly one `<title>`, exactly one `rel="canonical"`.
|
|
185
|
+
* `head()` is the only title/canonical producer in v1, so:
|
|
186
|
+
* - zero canonical → metadata.head-missing ("head() never called");
|
|
187
|
+
* - two+ canonical → metadata.canonical-duplicate;
|
|
188
|
+
* - zero/two+ title → metadata.title-missing / metadata.title-duplicate
|
|
189
|
+
* (svg <title> elements do not count — see countTitles);
|
|
190
|
+
* - zero/two+ charset → metadata.charset-missing / metadata.charset-duplicate.
|
|
191
|
+
* Comments are stripped before counting (a commented-out tag satisfies
|
|
192
|
+
* nothing). All errors, in every mode — a page missing its head is broken
|
|
193
|
+
* output whether it ships or merely serves.
|
|
194
|
+
*/
|
|
195
|
+
function validateMetadata(page: EmittedPage, out: Diagnostic[]): void {
|
|
196
|
+
const html = stripComments(page.html);
|
|
197
|
+
const charset = countMatches(html, CHARSET_META);
|
|
198
|
+
if (charset === 0) {
|
|
199
|
+
out.push({
|
|
200
|
+
code: "metadata.charset-missing",
|
|
201
|
+
severity: "error",
|
|
202
|
+
sourcePath: page.sourcePath,
|
|
203
|
+
message:
|
|
204
|
+
`the emitted document for ${JSON.stringify(page.sourcePath)} has no <meta charset>: ` +
|
|
205
|
+
"the layout must hand-write one (head() never emits charset)",
|
|
206
|
+
});
|
|
207
|
+
} else if (charset > 1) {
|
|
208
|
+
out.push({
|
|
209
|
+
code: "metadata.charset-duplicate",
|
|
210
|
+
severity: "error",
|
|
211
|
+
sourcePath: page.sourcePath,
|
|
212
|
+
message:
|
|
213
|
+
`the emitted document for ${JSON.stringify(page.sourcePath)} carries ${charset} <meta charset> tags: ` +
|
|
214
|
+
"exactly one is required",
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const title = countTitles(html);
|
|
219
|
+
if (title === 0) {
|
|
220
|
+
out.push({
|
|
221
|
+
code: "metadata.title-missing",
|
|
222
|
+
severity: "error",
|
|
223
|
+
sourcePath: page.sourcePath,
|
|
224
|
+
message:
|
|
225
|
+
`the emitted document for ${JSON.stringify(page.sourcePath)} has no <title>: ` +
|
|
226
|
+
"the layout must include ctx.head() (head() is the only <title> producer)",
|
|
227
|
+
});
|
|
228
|
+
} else if (title > 1) {
|
|
229
|
+
out.push({
|
|
230
|
+
code: "metadata.title-duplicate",
|
|
231
|
+
severity: "error",
|
|
232
|
+
sourcePath: page.sourcePath,
|
|
233
|
+
message:
|
|
234
|
+
`the emitted document for ${JSON.stringify(page.sourcePath)} carries ${title} <title> tags: ` +
|
|
235
|
+
"exactly one is required",
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const canonical = countMatches(html, CANONICAL_LINK);
|
|
240
|
+
if (canonical === 0) {
|
|
241
|
+
out.push({
|
|
242
|
+
code: "metadata.head-missing",
|
|
243
|
+
severity: "error",
|
|
244
|
+
sourcePath: page.sourcePath,
|
|
245
|
+
message:
|
|
246
|
+
`the emitted document for ${JSON.stringify(page.sourcePath)} has no rel="canonical" link: ` +
|
|
247
|
+
"the layout never called head() (head() is the only canonical producer)",
|
|
248
|
+
});
|
|
249
|
+
} else if (canonical > 1) {
|
|
250
|
+
out.push({
|
|
251
|
+
code: "metadata.canonical-duplicate",
|
|
252
|
+
severity: "error",
|
|
253
|
+
sourcePath: page.sourcePath,
|
|
254
|
+
message:
|
|
255
|
+
`the emitted document for ${JSON.stringify(page.sourcePath)} carries ${canonical} rel="canonical" links: ` +
|
|
256
|
+
"exactly one is required",
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Check one internal link of one emitted page against the known routes and
|
|
263
|
+
* the emitted id sets (see the module header for the pinned rules).
|
|
264
|
+
*/
|
|
265
|
+
function validateLink(
|
|
266
|
+
page: EmittedPage,
|
|
267
|
+
link: InternalLink,
|
|
268
|
+
routes: ReadonlyMap<string, KnownRoute>,
|
|
269
|
+
ids: ReadonlyMap<string, ReadonlySet<string>>,
|
|
270
|
+
severity: Severity,
|
|
271
|
+
out: Diagnostic[],
|
|
272
|
+
): void {
|
|
273
|
+
const dest = link.route;
|
|
274
|
+
const line = link.line === null ? undefined : link.line;
|
|
275
|
+
|
|
276
|
+
// The generated 404 page is not a link target (plan, "Locked decisions" 2)
|
|
277
|
+
// — in every mode.
|
|
278
|
+
if (dest === "/404") {
|
|
279
|
+
out.push({
|
|
280
|
+
code: "link.broken",
|
|
281
|
+
severity,
|
|
282
|
+
sourcePath: page.sourcePath,
|
|
283
|
+
line,
|
|
284
|
+
message:
|
|
285
|
+
`internal link ${at(page, link.line)} points at ${JSON.stringify(dest)}: ` +
|
|
286
|
+
"the 404 page is generated, not authored content, and is not a link target",
|
|
287
|
+
});
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const known = routes.get(dest);
|
|
292
|
+
if (known === undefined) {
|
|
293
|
+
out.push({
|
|
294
|
+
code: "link.broken",
|
|
295
|
+
severity,
|
|
296
|
+
sourcePath: page.sourcePath,
|
|
297
|
+
line,
|
|
298
|
+
message:
|
|
299
|
+
`internal link ${at(page, link.line)} points at ${JSON.stringify(dest)}: ` +
|
|
300
|
+
"that route is not a page of this site (not in the route table, not a draft)",
|
|
301
|
+
});
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (known.draft) {
|
|
306
|
+
out.push({
|
|
307
|
+
code: "link.draft",
|
|
308
|
+
severity,
|
|
309
|
+
sourcePath: page.sourcePath,
|
|
310
|
+
line,
|
|
311
|
+
message:
|
|
312
|
+
`internal link ${at(page, link.line)} points at the draft page ${JSON.stringify(dest)}: ` +
|
|
313
|
+
(severity === "error"
|
|
314
|
+
? "drafts are not published — the link would 404 on the production site"
|
|
315
|
+
: "the link resolves here (dev renders drafts) but would 404 on the production build"),
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// Fragment: the destination's FINAL EMITTED html must carry the id. Only
|
|
320
|
+
// checked when the destination was actually emitted — a draft destination
|
|
321
|
+
// in a production build has no emitted bytes (its link.draft above is the
|
|
322
|
+
// report), and external URLs never reach this function (they are not
|
|
323
|
+
// internal links: the renderer records them as none).
|
|
324
|
+
if (link.fragment !== null) {
|
|
325
|
+
const target = ids.get(dest);
|
|
326
|
+
if (target !== undefined && !target.has(link.fragment)) {
|
|
327
|
+
out.push({
|
|
328
|
+
code: "link.missing-fragment",
|
|
329
|
+
severity: "error",
|
|
330
|
+
sourcePath: page.sourcePath,
|
|
331
|
+
line,
|
|
332
|
+
message:
|
|
333
|
+
`internal link ${at(page, link.line)} carries fragment ${JSON.stringify(link.fragment)} ` +
|
|
334
|
+
`but the emitted document for ${JSON.stringify(dest)} contains no id=${JSON.stringify(link.fragment)}`,
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Run the full step-7 validation over the emitted documents and return the
|
|
342
|
+
* collected diagnostics, sorted (the caller folds them into its pool; a
|
|
343
|
+
* BuildError re-sorts, so determinism holds either way). Never throws.
|
|
344
|
+
*/
|
|
345
|
+
export function validatePages(options: ValidationOptions): Diagnostic[] {
|
|
346
|
+
const out: Diagnostic[] = [];
|
|
347
|
+
const severity = linkSeverity(options.mode);
|
|
348
|
+
|
|
349
|
+
// Every emitted page's ids, once per page (plan §4.7: fragments are
|
|
350
|
+
// checked against the ids collected from the final emitted HTML).
|
|
351
|
+
const ids = new Map<string, ReadonlySet<string>>();
|
|
352
|
+
for (const page of options.pages) ids.set(page.route, collectIds(page.html));
|
|
353
|
+
|
|
354
|
+
for (const page of options.pages) {
|
|
355
|
+
// A draft page is emitted in DEV only. A production build feeds this
|
|
356
|
+
// function no drafts (they are not rendered); if one slips through
|
|
357
|
+
// anyway, skip it WHOLE — its links are not validated in a build, and
|
|
358
|
+
// its metadata would fail a page that is never published (a false
|
|
359
|
+
// error). In dev the draft is genuinely served, so it is checked like
|
|
360
|
+
// any page.
|
|
361
|
+
if (options.mode === "build" && options.routes.get(page.route)?.draft === true) continue;
|
|
362
|
+
|
|
363
|
+
validateMetadata(page, out);
|
|
364
|
+
for (const link of page.links) validateLink(page, link, options.routes, ids, severity, out);
|
|
365
|
+
}
|
|
366
|
+
return sortDiagnostics(out);
|
|
367
|
+
}
|