@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.
@@ -0,0 +1,382 @@
1
+ // Diagnostics: the closed code vocabulary (plan §5) and the error that carries
2
+ // them.
3
+ //
4
+ // Codes are `namespace.name` strings in ONE frozen registry. The registry is
5
+ // the single source of truth: adding a code is exactly one line, and codes are
6
+ // never repurposed or removed (contractVersion rules — a rename is a major).
7
+ // Later chunks append their namespaces here (asset.*, link.*, render.*,
8
+ // output.*, dev.*) without touching anything else.
9
+ //
10
+ // Every diagnostic produced by the package must use a code from this registry;
11
+ // `isDiagnostic` checks membership, so a typo'd code fails loudly instead of
12
+ // reaching users as an unknown string.
13
+
14
+ export type Severity = "error" | "warning";
15
+
16
+ /**
17
+ * The closed v1 code vocabulary. One line per code; the key and the value are
18
+ * the same string so the registry doubles as the runtime validator.
19
+ */
20
+ export const DiagnosticCodes = Object.freeze({
21
+ "config.unknown-key": "config.unknown-key",
22
+ "config.site": "config.site",
23
+ "config.layout-type": "config.layout-type",
24
+ "config.asset-name-clash": "config.asset-name-clash",
25
+ "config.asset-name": "config.asset-name",
26
+ "config.output-overlap": "config.output-overlap",
27
+ "config.port": "config.port",
28
+ // The config FILE itself could not be loaded: the dynamic import threw, or
29
+ // the default export is not a defineSite() result. Distinct from every
30
+ // config.* validation code — those mean "the config loaded and is wrong";
31
+ // this means "there is no config to validate".
32
+ "config.load": "config.load",
33
+ // A known key whose value has the wrong type/shape. Distinct from
34
+ // config.unknown-key (the key itself is not in the schema) and from the
35
+ // specific codes above; crust rule 1 — a wrong-typed value must be an error
36
+ // at validation time, never a crash (or a silent pass) three steps later.
37
+ "config.type": "config.type",
38
+ "route.invalid": "route.invalid",
39
+ "route.query-fragment": "route.query-fragment",
40
+ "route.traversal": "route.traversal",
41
+ "route.shape": "route.shape",
42
+ "route.case-collision": "route.case-collision",
43
+ "route.duplicate": "route.duplicate",
44
+ "frontmatter.missing": "frontmatter.missing",
45
+ "frontmatter.not-mapping": "frontmatter.not-mapping",
46
+ "frontmatter.duplicate-key": "frontmatter.duplicate-key",
47
+ "frontmatter.unknown-key": "frontmatter.unknown-key",
48
+ "frontmatter.missing-title": "frontmatter.missing-title",
49
+ "frontmatter.bad-value": "frontmatter.bad-value",
50
+ // The block is delimited but is not parseable YAML at all (not even a
51
+ // partial mapping). Distinct from frontmatter.not-mapping, which means
52
+ // "parsed fine, but it is not a mapping" — conflating them would tell the
53
+ // user their document has the wrong shape when it has a syntax error.
54
+ "frontmatter.parse-error": "frontmatter.parse-error",
55
+ // description was absent and derived from the first paragraph; the message
56
+ // carries the derived value (plan §2 — a warning, not an error).
57
+ "frontmatter.derived-description": "frontmatter.derived-description",
58
+ // description was absent AND there was no text to derive from (empty body,
59
+ // or a first paragraph without text). The description stays "" and the
60
+ // page is otherwise legal — a warning, never an error. Distinct from
61
+ // derived-description: claiming a derivation that did not happen would be
62
+ // a false report (crust rule 1).
63
+ "frontmatter.missing-description": "frontmatter.missing-description",
64
+ // The content directory produced no NON-DRAFT pages: a production build
65
+ // would emit no content pages (only the generated 404 page). Suspicious
66
+ // but legal (a drafts-only site is a legitimate dev state) — a warning,
67
+ // never an error. The message distinguishes "zero pages at all" from
68
+ // "N drafts, zero production".
69
+ "content.no-pages": "content.no-pages",
70
+ // content.parseData threw, or returned something that is not a plain
71
+ // object. The thrown Error's message is folded into this diagnostic.
72
+ "frontmatter.data-invalid": "frontmatter.data-invalid",
73
+ // Neither frontmatter `route` nor content.route produced a route for the
74
+ // page. Distinct from route.invalid (a route EXISTS but is malformed).
75
+ "route.missing": "route.missing",
76
+ // frontmatter.layout (or defaultLayout) names a key that is not in the
77
+ // layouts registry; the message names the page and the available keys.
78
+ "layout.unknown": "layout.unknown",
79
+ // A markdown link/image destination failed the URL policy (url.ts), or an
80
+ // internal .md target is not a valid route shape. The offending
81
+ // destination is stripped from the emitted markup, so the output is inert
82
+ // even if the build is continued past the error.
83
+ "link.invalid": "link.invalid",
84
+ // markdown-it itself threw while rendering (it is otherwise error-tolerant
85
+ // and treats almost everything as text). Line is in FULL-FILE coordinates.
86
+ "markdown.parse-error": "markdown.parse-error",
87
+ // An internal link whose destination is not a page of the site (not in the
88
+ // route table, and not the /404 special case which has its own wording).
89
+ // ERROR in a production build, WARNING in dev (plan §5: broken internal
90
+ // links are demoted in dev so the dev server can still show the rest of
91
+ // the site — never silently dropped). The diagnostic names the source
92
+ // page, the (best-effort) line, and the destination route.
93
+ "link.broken": "link.broken",
94
+ // An internal link whose destination is a DRAFT page. Drafts are excluded
95
+ // from a production build, so the link would 404 on the published site:
96
+ // ERROR in build mode, WARNING in dev (where drafts are rendered and the
97
+ // link actually resolves — plan §5).
98
+ "link.draft": "link.draft",
99
+ // A link carrying a #fragment whose destination page's FINAL EMITTED html
100
+ // contains no id="fragment" (checked against the ids collected from the
101
+ // emitted bytes, same-page fragments included). Always an error: a dead
102
+ // anchor publishes a link that scrolls nowhere.
103
+ "link.missing-fragment": "link.missing-fragment",
104
+ // metadata.* — the per-emitted-page metadata validation (plan §3: head()
105
+ // emits title/description/canonical/og:* but NEVER charset; the layout
106
+ // hand-writes <meta charset>, and this step errors when the contract is
107
+ // broken). All are errors in every mode: a page missing its charset or
108
+ // its head block is broken output, in dev as much as in prod.
109
+ // The emitted document carries no <meta charset> at all.
110
+ "metadata.charset-missing": "metadata.charset-missing",
111
+ // More than one <meta charset> (a layout that both hand-writes one and
112
+ // calls head() is the only way head() could contribute a second — it never
113
+ // emits charset, so in practice this is a layout duplicating its own tag).
114
+ "metadata.charset-duplicate": "metadata.charset-duplicate",
115
+ // No <title> in the emitted document: the layout never included head()
116
+ // (head() is the only <title> producer in v1).
117
+ "metadata.title-missing": "metadata.title-missing",
118
+ // More than one <title>: head() emitted one and the layout hand-wrote
119
+ // another.
120
+ "metadata.title-duplicate": "metadata.title-duplicate",
121
+ // More than one rel="canonical": head() emitted one and the layout added
122
+ // another. (Zero is reported as metadata.head-missing, not a separate
123
+ // canonical-missing code: in v1 head() is the ONLY canonical producer, so
124
+ // an absent canonical IS "head() never called".)
125
+ "metadata.canonical-duplicate": "metadata.canonical-duplicate",
126
+ // No rel="canonical" in the emitted document — the detection for "the
127
+ // layout never called head()" (head() is the only canonical producer).
128
+ "metadata.head-missing": "metadata.head-missing",
129
+ // render.* — the template value contract (plan §1: "never a false pass,
130
+ // never a silent coercion"). All render.bad-value; the message says what
131
+ // the value was. A value we cannot name a safe rendering for is a build
132
+ // error, full stop — true/NaN/Infinity/thenables/Symbol/bigint/functions/
133
+ // objects throw BEFORE any toString/valueOf is invoked.
134
+ "render.bad-value": "render.bad-value",
135
+ // The layout function returned (or a Promise resolved to) something that
136
+ // is not an Html, without throwing. Page-attributed; the page's render is
137
+ // aborted (no output) while the rest of the build pass continues.
138
+ "render.bad-result": "render.bad-result",
139
+ // The layout — or the engine's own render/fence stage — threw something
140
+ // that is not a diagnostic. The message carries the error's message AND
141
+ // its stack; the page's render is aborted, the pass never crashes.
142
+ "render.threw": "render.threw",
143
+ // head() called a SECOND time within one render. The second call emits
144
+ // nothing (the document already has its title/canonical) and this
145
+ // diagnostic is what fails the build (plan §3: "a build error diagnostic,
146
+ // not a throw") — the page still renders.
147
+ "head.duplicate": "head.duplicate",
148
+ // public-asset.* — the public-directory URL helper (render chunk). The
149
+ // argument is a FILE PATH, not a URL: it is never percent-decoded (%2e%2e
150
+ // is a literal filename), so the only traversal vectors are literal ones.
151
+ // Any of `..` segments, a leading "/", a backslash, a drive letter, NUL
152
+ // or an empty path is rejected BEFORE any filesystem access; the
153
+ // normalized path is recorded for the emitter's existence check.
154
+ "public-asset.traversal": "public-asset.traversal",
155
+ // The emitter's existence check (chunk 7, promised by public-asset.traversal
156
+ // and the render.ts publicDir contract): a path a layout recorded via
157
+ // publicAsset() is not a readable file under assets.publicDirectory — the
158
+ // page would publish a dead reference (crust rule 1), so this is an error.
159
+ // No publicDirectory configured makes EVERY recorded path missing.
160
+ "public-asset.missing": "public-asset.missing",
161
+ // readText.* — the config-directory text reader (render chunk). The
162
+ // confinement contract: root = REALPATH of the config directory; the
163
+ // FINAL realpath must stay inside it (a symlink never extends a
164
+ // boundary); 10 MiB size cap; strict UTF-8.
165
+ // A path that escapes the root — either a literal traversal rejected
166
+ // BEFORE resolution (absolute, `..`, NUL, backslash, drive letter) or a
167
+ // resolution (a symlink or component) whose realpath lands outside — is
168
+ // read-text.escape; the message says which stage caught it.
169
+ "read-text.escape": "read-text.escape",
170
+ // The file is larger than the 10 MiB cap (checked via stat BEFORE the
171
+ // bytes are read). A file of EXACTLY the cap is legal.
172
+ "read-text.toobig": "read-text.toobig",
173
+ // The path stayed inside the root but is not a readable text file:
174
+ // missing, a directory, unreadable, or not valid UTF-8 — the message
175
+ // says which.
176
+ "read-text.failed": "read-text.failed",
177
+ // fence.* — the post-render document fence (chunk 3). Every violation is
178
+ // collected; finalizeDocument wraps them in one BuildError.
179
+ "fence.script-body": "fence.script-body",
180
+ "fence.style-body": "fence.style-body",
181
+ "fence.comment-value": "fence.comment-value",
182
+ "fence.dynamic-tag-name": "fence.dynamic-tag-name",
183
+ "fence.dynamic-attr-name": "fence.dynamic-attr-name",
184
+ "fence.event-handler": "fence.event-handler",
185
+ "fence.unquoted-attribute": "fence.unquoted-attribute",
186
+ "fence.unterminated": "fence.unterminated",
187
+ "fence.url-attribute": "fence.url-attribute",
188
+ "fence.ping-attr": "fence.ping-attr",
189
+ "fence.srcdoc-attr": "fence.srcdoc-attr",
190
+ // asset.* — the bundling pipeline (chunk 5, plan §4.2/§4.5). Exactly ONE
191
+ // emitted file per declared entrypoint is the invariant.
192
+ // entrypoint produced several files (imported assets, real chunks) — v1
193
+ // emits exactly one hashed file per entrypoint and refuses the rest.
194
+ "asset.entrypoint-chunked": "asset.entrypoint-chunked",
195
+ // Bun.build failed (thrown or returned failure) or emitted zero / an
196
+ // unrecognizable file; the bundler's own messages are folded in.
197
+ "asset.bundle-failed": "asset.bundle-failed",
198
+ // assets.publicDirectory is configured but unusable (absent, not a dir).
199
+ "asset.public-missing": "asset.public-missing",
200
+ // A symbolic link inside assets.publicDirectory. Never copied (a symlink
201
+ // could publish an arbitrary host tree or recurse forever — the package-wide
202
+ // "symlinks don't extend a boundary" rule) and never silently skipped (the
203
+ // author put the file there expecting it published — a silent skip is a
204
+ // false pass, crust rule 1). Always an error.
205
+ "asset.public-symlink": "asset.public-symlink",
206
+ // script()/stylesheet() name (or any manifest lookup) not declared in
207
+ // assets.scripts/assets.styles — a map-key typo is a build error, never a
208
+ // silently missing tag (plan §5).
209
+ "asset.unknown-entrypoint": "asset.unknown-entrypoint",
210
+ // A declared asset that no rendered page ever passed to script() or
211
+ // stylesheet() — declared but dead. A WARNING (not an error): the asset
212
+ // bundles and emits fine, the author simply never referenced it.
213
+ "asset.unused": "asset.unused",
214
+ // output.* — emit-time collisions (chunk 5 provides the detector, chunk 6
215
+ // runs it): a public file that would overwrite a generated file.
216
+ "output.collision": "output.collision",
217
+ // A discovered .md file could not be read at parse time (it vanished between
218
+ // discovery and reading, is unreadable, …). The file was FOUND by discovery,
219
+ // so silence here would be a false pass (crust rule 1) — always an error.
220
+ "content.read-failed": "content.read-failed",
221
+ // A throw that is NOT a read failure: the pre-pass already read the file
222
+ // before parseFrontmatter ran, or parsePage threw with the frontmatter
223
+ // already provided (renderMarkdown contains its own throws and parseData
224
+ // is caught inside it) — either way it is an engine bug, not a read
225
+ // problem. Labeled distinct from content.read-failed so the code stays
226
+ // true (crust rule 1).
227
+ "content.parse-failed": "content.parse-failed",
228
+ // Defense in depth (chunk 7): a resolved write path left the staging
229
+ // directory. Routes are normalized long before emit, so this can only fire
230
+ // on an internal bug — but a write outside staging would escape the atomic
231
+ // publish contract, so it is caught at the write itself, never trusted to
232
+ // the upstream normalization.
233
+ "output.escape": "output.escape",
234
+ // build.* — the per-output build lock (chunk 7, emit.ts): a concurrent
235
+ // build of the same output is REFUSED rather than interleaving its
236
+ // publish renames with the holder's (a measured false-pass race: the
237
+ // second build's output rolled back by the first's restore while the
238
+ // second reported success). The message names the live holder's pid;
239
+ // dead holders' locks are reclaimed automatically, so a killed build
240
+ // never blocks the output forever.
241
+ "build.busy": "build.busy",
242
+ // dev.* — the dev server (chunk 9). The configured port is already held
243
+ // by another process. v1 does NOT auto-increment: silently choosing a
244
+ // different port would serve the site somewhere the user is not looking
245
+ // (a false pass wearing a success exit) — the error names the port and
246
+ // the user picks (stop the other process, or set dev.port).
247
+ "dev.port-in-use": "dev.port-in-use",
248
+ // url.* — the URL policy (plan §1 url()): pre-parse rejects, scheme
249
+ // allowlist, host/userinfo rules. Thrown by validateUrl; the fence quotes
250
+ // the reason when a tracked value fails it (fence.url-attribute).
251
+ "url.control-char": "url.control-char",
252
+ "url.bad-char": "url.bad-char",
253
+ "url.entity-escape": "url.entity-escape",
254
+ "url.protocol-relative": "url.protocol-relative",
255
+ "url.scheme": "url.scheme",
256
+ "url.no-host": "url.no-host",
257
+ "url.userinfo": "url.userinfo",
258
+ } as const);
259
+
260
+ /** Every valid diagnostic code, as a union of the registry's strings. */
261
+ export type DiagnosticCode = (typeof DiagnosticCodes)[keyof typeof DiagnosticCodes];
262
+
263
+ /**
264
+ * One located problem. `sourcePath` is always posix and relative to the
265
+ * project root (plan, Windows table: "sourcePath in diagnostics always posix").
266
+ * `line`/`column` are 1-based and in the coordinates of the file named.
267
+ */
268
+ export interface Diagnostic {
269
+ code: DiagnosticCode;
270
+ message: string;
271
+ severity: Severity;
272
+ sourcePath?: string;
273
+ line?: number;
274
+ column?: number;
275
+ }
276
+
277
+ /** Runtime guard for values thrown/collected as diagnostics. */
278
+ export function isDiagnostic(value: unknown): value is Diagnostic {
279
+ if (typeof value !== "object" || value === null) return false;
280
+ const d = value as Record<string, unknown>;
281
+ return (
282
+ typeof d.code === "string" &&
283
+ Object.hasOwn(DiagnosticCodes, d.code) &&
284
+ typeof d.message === "string" &&
285
+ (d.severity === "error" || d.severity === "warning")
286
+ );
287
+ }
288
+
289
+ /**
290
+ * Code-unit lexicographic compare. Deliberately NOT `localeCompare`: that is
291
+ * locale COLLACTION (ICU data + the process's default locale), so two
292
+ * machines can order the same strings differently — measured: en collation
293
+ * orders "ab.md" before "aB.md" (case is a secondary key), while code units
294
+ * order "aB.md" (0x42) before "ab.md" (0x61). A locale-dependent order would
295
+ * break the byte-identical-rebuild guarantee (plan §4.6) across machines;
296
+ * code-unit order is the locale-free meaning of "lexicographic".
297
+ */
298
+ export function compareStrings(a: string, b: string): number {
299
+ if (a < b) return -1;
300
+ if (a > b) return 1;
301
+ return 0;
302
+ }
303
+
304
+ /**
305
+ * Deterministic order: sourcePath, then line, then code. Diagnostics that tie
306
+ * on all three keep their input order (Array#sort is stable), so a build's
307
+ * output is byte-reproducible (plan §4.6).
308
+ */
309
+ export function sortDiagnostics(diagnostics: readonly Diagnostic[]): Diagnostic[] {
310
+ return [...diagnostics].sort((a, b) => {
311
+ const p = compareStrings(a.sourcePath ?? "", b.sourcePath ?? "");
312
+ if (p !== 0) return p;
313
+ const l = (a.line ?? -1) - (b.line ?? -1);
314
+ if (l !== 0) return l;
315
+ return compareStrings(a.code, b.code);
316
+ });
317
+ }
318
+
319
+ function summarize(diagnostics: readonly Diagnostic[]): string {
320
+ const errors = diagnostics.filter((d) => d.severity === "error").length;
321
+ const warnings = diagnostics.length - errors;
322
+ const parts: string[] = [];
323
+ if (errors > 0) parts.push(`${errors} error${errors === 1 ? "" : "s"}`);
324
+ if (warnings > 0) parts.push(`${warnings} warning${warnings === 1 ? "" : "s"}`);
325
+ return `site build failed: ${parts.join(" and ") || "no diagnostics"}`;
326
+ }
327
+
328
+ /**
329
+ * The failed-build carrier (plan §5): a failed build rejects with a BuildError
330
+ * holding ALL collected diagnostics, already sorted. Construction sorts, so no
331
+ * call site can leak an unordered list.
332
+ */
333
+ export class BuildError extends Error {
334
+ readonly diagnostics: Diagnostic[];
335
+
336
+ constructor(diagnostics: readonly Diagnostic[], message?: string) {
337
+ const sorted = sortDiagnostics(diagnostics);
338
+ super(message ?? summarize(sorted));
339
+ this.name = "BuildError";
340
+ this.diagnostics = sorted;
341
+ }
342
+ }
343
+
344
+ // ---------------------------------------------------------------------------
345
+ // console formatting (CLI + dev server)
346
+ // ---------------------------------------------------------------------------
347
+
348
+ const RESET = "\x1b[0m";
349
+ const RED = "\x1b[31m";
350
+ const YELLOW = "\x1b[33m";
351
+
352
+ /**
353
+ * The one console format for diagnostics, shared by the CLI (build failure)
354
+ * and the dev server (failed rebuilds). One block per diagnostic:
355
+ *
356
+ * severity[code]: first message line
357
+ * --> sourcePath[:line[:column]]
358
+ * remaining message lines verbatim
359
+ *
360
+ * `color` (the caller checks `process.stdout.isTTY` / stderr) wraps
361
+ * `severity[code]` in red (error) or yellow (warning); plain output when
362
+ * false — the Windows table row "diagnostics degrade gracefully without
363
+ * ANSI" is satisfied by this single flag, never by sniffing the string.
364
+ */
365
+ export function formatDiagnostics(diags: readonly Diagnostic[], opts: { color: boolean }): string {
366
+ const blocks: string[] = [];
367
+ for (const d of diags) {
368
+ const paint = (s: string): string =>
369
+ opts.color ? `${d.severity === "error" ? RED : YELLOW}${s}${RESET}` : s;
370
+ const lines = d.message.split("\n");
371
+ const block = [`${paint(`${d.severity}[${d.code}]`)}: ${lines[0]}`];
372
+ if (d.sourcePath !== undefined && d.sourcePath !== "") {
373
+ let at = d.sourcePath;
374
+ if (d.line !== undefined) at = `${at}:${d.line}`;
375
+ if (d.column !== undefined) at = `${at}:${d.column}`;
376
+ block.push(` --> ${at}`);
377
+ }
378
+ block.push(...lines.slice(1));
379
+ blocks.push(block.join("\n"));
380
+ }
381
+ return blocks.join("\n\n");
382
+ }
package/src/emit.ts ADDED
@@ -0,0 +1,260 @@
1
+ // Staging, deterministic emitted files, and publication orchestration.
2
+ // Disk paths retain native roots; URL paths are handled by routes.ts.
3
+ //
4
+ // Publishing and startup recovery run under the SAME atomic output lock.
5
+ // publication.ts records backup/copy/commit state before destructive operations:
6
+ // incomplete copies never count as a committed output, and failed restores
7
+ // retain their last-good backup for another attempt. Legacy unjournaled backups
8
+ // remain recoverable too. All custodial trees are siblings of the output.
9
+
10
+ import { createHash, randomBytes } from "node:crypto";
11
+ import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
12
+ import { acquireOutputLock, pidAlive } from "./build-lock";
13
+ import type { RoutedPage } from "./content";
14
+ import { BuildError, compareStrings } from "./diagnostics";
15
+ import { isWindowsPath, pathContains, filesystemPath as posix, toPosix } from "./fs-path";
16
+ import { html } from "./html";
17
+ import {
18
+ adoptLegacyBackup,
19
+ type PublishFs,
20
+ publishOutput,
21
+ recoverTransactions,
22
+ TRANSACTION_RE,
23
+ } from "./publication";
24
+ import { canonicalUrl } from "./routes";
25
+ import type { RobotsConfig } from "./types";
26
+
27
+ export type { PublishFs } from "./publication";
28
+
29
+ function nonce(): string {
30
+ return randomBytes(6).toString("hex");
31
+ }
32
+
33
+ /** A fresh production staging directory on the output's filesystem. */
34
+ export function stagingDirFor(outputDir: string): string {
35
+ const out = posix.resolve(toPosix(outputDir));
36
+ return posix.join(posix.dirname(out), `.crust-staging-${process.pid}-${nonce()}`);
37
+ }
38
+
39
+ /**
40
+ * Dev staging has its own family: it is served in place, never published or
41
+ * restored over production. Dead dev staging is removable; live staging isn't.
42
+ */
43
+ export function devStagingDirFor(outputDir: string): string {
44
+ const out = posix.resolve(toPosix(outputDir));
45
+ return posix.join(posix.dirname(out), `.crust-dev-staging-${process.pid}-${nonce()}`);
46
+ }
47
+
48
+ /** Stable output identity, including slash/case equivalence on Windows. */
49
+ export function buildLockHash(outputDir: string): string {
50
+ const resolved = posix.resolve(toPosix(outputDir));
51
+ const identity = isWindowsPath(resolved) ? resolved.toLowerCase() : resolved;
52
+ return createHash("sha256").update(identity).digest("hex").slice(0, 16);
53
+ }
54
+
55
+ const STAGING_RE = /^\.crust-staging-(\d+)-([0-9a-f]+)$/;
56
+ const DEV_STAGING_RE = /^\.crust-dev-staging-(\d+)-([0-9a-f]+)$/;
57
+ const OUT_OLD_RE = /^\.crust-out-old-([0-9a-f]{16})-(\d+)-([0-9a-f]+)$/;
58
+ /** Legacy private claims are respected for on-disk compatibility. */
59
+ const LOCK_RE = /^\.crust-out-lock-([0-9a-f]{16})-(\d+)-([0-9a-f]+)$/;
60
+ const ATOMIC_LOCK_RE = /^\.crust-out-lock-[0-9a-f]{16}$/;
61
+ const OWNER_RE = /^\.crust-out-owner-[0-9a-f]{16}-(\d+)-[0-9a-f]{24}$/;
62
+ const RECLAIM_RE = /^\.crust-out-reclaim-[0-9a-f]{16}-[0-9a-f]{24}$/;
63
+
64
+ /** Watchers must ignore ALL of the builder's own filesystem traffic. */
65
+ export function isCustodianSibling(name: string): boolean {
66
+ return (
67
+ STAGING_RE.test(name) ||
68
+ DEV_STAGING_RE.test(name) ||
69
+ OUT_OLD_RE.test(name) ||
70
+ LOCK_RE.test(name) ||
71
+ ATOMIC_LOCK_RE.test(name) ||
72
+ OWNER_RE.test(name) ||
73
+ RECLAIM_RE.test(name) ||
74
+ TRANSACTION_RE.test(name)
75
+ );
76
+ }
77
+
78
+ /** Public cleanup acquires the output lock before inspecting recovery state. */
79
+ export async function cleanupStale(outputDir: string, fsDeps?: Partial<PublishFs>): Promise<void> {
80
+ const output = posix.resolve(toPosix(outputDir));
81
+ try {
82
+ await stat(posix.dirname(output));
83
+ } catch (error) {
84
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
85
+ throw error;
86
+ }
87
+ const release = await acquireBuildLock(output);
88
+ try {
89
+ await cleanupStaleLocked(output, fsDeps);
90
+ } finally {
91
+ await release();
92
+ }
93
+ }
94
+
95
+ /** Internal entry: caller MUST already hold this output's build lock. */
96
+ export async function cleanupStaleLocked(
97
+ outputDir: string,
98
+ fsDeps?: Partial<PublishFs>,
99
+ ): Promise<void> {
100
+ const output = posix.resolve(toPosix(outputDir));
101
+ const hash = buildLockHash(output);
102
+ const parent = posix.dirname(output);
103
+ const paired = await recoverTransactions(output, hash, fsDeps);
104
+ const orphans: { name: string; file: string; pid: number }[] = [];
105
+ for (const name of await readdir(parent)) {
106
+ const staging = STAGING_RE.exec(name) ?? DEV_STAGING_RE.exec(name) ?? OWNER_RE.exec(name);
107
+ const legacyLock = LOCK_RE.exec(name);
108
+ const pid = staging ? Number(staging[1]) : legacyLock ? Number(legacyLock[2]) : undefined;
109
+ if (pid !== undefined) {
110
+ if (!pidAlive(pid)) {
111
+ await rm(posix.join(parent, name), { recursive: true, force: true }).catch(() => {});
112
+ }
113
+ continue;
114
+ }
115
+ const old = OUT_OLD_RE.exec(name);
116
+ if (old?.[1] === hash && !paired.has(name)) {
117
+ orphans.push({ name, file: posix.join(parent, name), pid: Number(old[2]) });
118
+ }
119
+ // Shared claim/reclamation slots are removed ONLY by the lock protocol.
120
+ }
121
+ const dead = orphans
122
+ .filter((orphan) => !pidAlive(orphan.pid))
123
+ .sort((a, b) => compareStrings(a.name, b.name));
124
+ let outputExists: boolean;
125
+ try {
126
+ await stat(output);
127
+ outputExists = true;
128
+ } catch (error) {
129
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
130
+ outputExists = false;
131
+ }
132
+ if (!outputExists && dead.length > 0) {
133
+ // Adopt before a fallback copy can become partial. Only prune alternative
134
+ // legacy backups AFTER recovery succeeds; a failure must keep every copy.
135
+ await adoptLegacyBackup(dead[0].file, output, fsDeps);
136
+ dead.shift();
137
+ }
138
+ for (const orphan of dead) {
139
+ await rm(orphan.file, { recursive: true, force: true }).catch(() => {});
140
+ }
141
+ }
142
+
143
+ /** Dev cleanup never touches production output, backups, journals, or locks. */
144
+ export async function sweepDeadDevStaging(outputDir: string): Promise<void> {
145
+ const parent = posix.dirname(posix.resolve(toPosix(outputDir)));
146
+ let entries: string[];
147
+ try {
148
+ entries = await readdir(parent);
149
+ } catch {
150
+ return;
151
+ }
152
+ for (const name of entries) {
153
+ const match = DEV_STAGING_RE.exec(name);
154
+ if (match !== null && !pidAlive(Number(match[1]))) {
155
+ await rm(posix.join(parent, name), { recursive: true, force: true }).catch(() => {});
156
+ }
157
+ }
158
+ }
159
+
160
+ /** Atomically claim one shared output slot; always release in a finally. */
161
+ export async function acquireBuildLock(outputDir: string): Promise<() => Promise<void>> {
162
+ const output = posix.resolve(toPosix(outputDir));
163
+ return acquireOutputLock(output, buildLockHash(output));
164
+ }
165
+
166
+ export interface EmitFile {
167
+ readonly route: string;
168
+ readonly file: string;
169
+ readonly html: string;
170
+ }
171
+
172
+ /** Recheck containment on the resolved disk path before every staging write. */
173
+ export async function writePages(stagingDir: string, items: readonly EmitFile[]): Promise<void> {
174
+ const staging = posix.resolve(toPosix(stagingDir));
175
+ for (const item of items) {
176
+ const target = posix.resolve(staging, item.file);
177
+ if (!pathContains(staging, target)) {
178
+ throw new BuildError([
179
+ {
180
+ code: "output.escape",
181
+ severity: "error",
182
+ sourcePath: item.route,
183
+ message:
184
+ `refusing to write route ${JSON.stringify(item.route)}: the resolved path ` +
185
+ `${JSON.stringify(target)} is outside the staging directory ${JSON.stringify(staging)}`,
186
+ },
187
+ ]);
188
+ }
189
+ await mkdir(posix.dirname(target), { recursive: true });
190
+ await writeFile(target, item.html);
191
+ }
192
+ }
193
+
194
+ /** XML text escaping for <loc>: `&` FIRST, so inserted escapes aren't escaped. */
195
+ function xmlEscape(value: string): string {
196
+ return value
197
+ .replace(/&/g, "&amp;")
198
+ .replace(/</g, "&lt;")
199
+ .replace(/>/g, "&gt;")
200
+ .replace(/"/g, "&quot;")
201
+ .replace(/'/g, "&apos;");
202
+ }
203
+
204
+ /** Byte-pinned, sorted, canonical URLs; drafts and the generated 404 excluded. */
205
+ export function sitemapXml(pages: readonly RoutedPage[]): string {
206
+ const urls = pages
207
+ .filter((page) => !page.draft && page.route !== "/404")
208
+ .map((page) => page.canonicalUrl)
209
+ .sort(compareStrings);
210
+ const lines = [
211
+ '<?xml version="1.0" encoding="UTF-8"?>',
212
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
213
+ ...urls.map((url) => `<url><loc>${xmlEscape(url)}</loc></url>`),
214
+ "</urlset>",
215
+ ];
216
+ return `${lines.join("\n")}\n`;
217
+ }
218
+
219
+ /** Absent robots config means no robots.txt, not an empty emitted file. */
220
+ export function robotsTxt(
221
+ site: string,
222
+ robots: RobotsConfig | undefined,
223
+ sitemapEnabled: boolean,
224
+ ): string | null {
225
+ if (robots === undefined) return null;
226
+ if (!robots.indexable) return "User-agent: *\nDisallow: /\n";
227
+ const lines = ["User-agent: *", "Allow: /"];
228
+ if (sitemapEnabled) lines.push(`Sitemap: ${site}/sitemap.xml`);
229
+ return lines.map((line) => `${line}\n`).join("");
230
+ }
231
+
232
+ /** A synthetic page rendered through the site's default layout. */
233
+ export function notFoundPage(site: string, layout: string): RoutedPage {
234
+ return {
235
+ sourcePath: "<generated>",
236
+ relativePath: "404",
237
+ route: "/404",
238
+ layout,
239
+ title: "Not found",
240
+ description: "The requested page does not exist.",
241
+ headings: [],
242
+ data: {},
243
+ draft: false,
244
+ body: html`<p>The page you are looking for does not exist.</p>`,
245
+ links: [],
246
+ warnings: [],
247
+ diagnostics: [],
248
+ canonicalUrl: canonicalUrl(site, "/404"),
249
+ };
250
+ }
251
+
252
+ /** Lock required: swap staging into output or preserve the previous output. */
253
+ export async function publish(
254
+ stagingDir: string,
255
+ outputDir: string,
256
+ fsDeps?: Partial<PublishFs>,
257
+ ): Promise<void> {
258
+ const output = posix.resolve(toPosix(outputDir));
259
+ await publishOutput(posix.resolve(toPosix(stagingDir)), output, buildLockHash(output), fsDeps);
260
+ }