@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/src/assets.ts ADDED
@@ -0,0 +1,875 @@
1
+ // The asset pipeline (plan §4.2, §4.5, §4.6): one Bun.build per declared
2
+ // entrypoint, hashing owned by the SSG, and the publicDirectory copied
3
+ // byte-for-byte to the staging root.
4
+ //
5
+ // Measured facts this design exists for (Bun 1.4.4; pinned by
6
+ // tests/assets.test.ts — do not re-litigate, do not "optimize" away):
7
+ // - `entrypoints` must be an ARRAY; a {name: path} map throws a TypeError.
8
+ // - Output names carry NO content hash we may rely on, and `outdir` is NOT
9
+ // cleared between builds — a stale file from an earlier build stays in the
10
+ // directory and a naive "collect the outdir" leaks it. Therefore: ONE
11
+ // Bun.build call per entrypoint into a FRESH mkdtemp directory, the SSG
12
+ // computes `sha256` over the final emitted bytes itself (first 16 hex),
13
+ // and every emitted name is hashed — a name is never copied from the
14
+ // bundler and an unhashed asset name is never emitted.
15
+ // - On success Bun.build RETURNS {success: true, outputs, logs}; on a
16
+ // bundling failure it THROWS an AggregateError ("Bundle failed") whose
17
+ // .errors are BuildMessage/ResolveMessage records. Both shapes are
18
+ // handled, and a throw never escapes as a raw exception (crust rule 1:
19
+ // the failure must be a located diagnostic, not a crash report).
20
+ // - `target: "browser"` INLINES dynamic import() — Bun 1.4.4 emits no extra
21
+ // chunk for it (pinned by a test). The multi-output guard is therefore
22
+ // about any entrypoint that really does emit several files (an imported
23
+ // asset like `import logo from "./x.svg"`, JS importing CSS, or real
24
+ // code-splitting by a future Bun) — one guard covers all of them.
25
+ // - The TRANSPILE drops EVERY source comment (leading, mid-file, trailing;
26
+ // `//` and `/* */`; CSS included) before the banner is prepended — the
27
+ // emitted code never contains a user comment line. It CAN, however,
28
+ // contain lines that merely LOOK like one: template-literal content is
29
+ // emitted verbatim, so a line of a backtick string starting with `// `
30
+ // sits in the output as a plain line (measured, pinned by a test). The
31
+ // banner strip below is therefore an EXACT match of the banner computed
32
+ // for the entry, never a pattern.
33
+ // - A file whose code is EMPTY after the transform (comments only, types
34
+ // only) emits no banner and zero bytes.
35
+ // - The output is PREFIXED with a path banner naming the bundled file
36
+ // relative to process.cwd() (Bun's "pretty" path: relative when the file
37
+ // is under the cwd, a `../`-prefixed path when it is not; never an
38
+ // absolute path — measured on Bun 1.4.4). The banner is part of the bytes
39
+ // Bun returns, so left alone it makes the hash cwd-dependent (measured:
40
+ // the same entry built from two differently-structured cwds produces
41
+ // different bytes; pinned by tests/assets.test.ts).
42
+ // - For a bundle of a SINGLE source file the banner sits at the head of the
43
+ // file (after a preserved hashbang + one blank line, when the entry starts
44
+ // with `#!`) and names the entry itself, so the exact match is
45
+ // unambiguous and it is stripped before hashing/writing — see
46
+ // stripBundlerBanner. A MULTI-file bundle (the entry imports other files,
47
+ // a CSS @imports, an npm package import) emits one such comment before
48
+ // EVERY bundled file, and the leading one names the first file (a
49
+ // dependency), not the entry. Those banners are stripped too (see
50
+ // stripMultiFileBanners): with `metafile: true` every input file of the
51
+ // build is enumerable, and each metafile key IS the cwd-relative path its
52
+ // banner carries (measured byte-identical), so the exact banner line is
53
+ // computable for EVERY bundled file — the strip removes any output line
54
+ // that is byte-identical to a computed banner, gated on the file's first
55
+ // line being one of them (a bannerless or changed-shape output is never
56
+ // touched; a future Bun that changed the banner shape silently degrades
57
+ // to the old cwd-sensitive behavior for that asset instead of
58
+ // pattern-stripping and corrupting code). One honest caveat (documented in
59
+ // docs/USAGE.md, Assets): a template-literal line that is byte-identical
60
+ // to a computed banner is stripped with it — the transpile drops every
61
+ // source comment, so a bare comment-shaped line in the output can only be
62
+ // a banner or string content, and stripping a string line changes string
63
+ // data, never parseability.
64
+ //
65
+ // Determinism (plan §4.6): entrypoints are iterated in sorted name order, the
66
+ // manifest is a Map in that insertion order, the public copy traverses sorted
67
+ // per directory, and all returned paths are posix (plan, Windows table).
68
+ // ALL assets — single-file and multi-file alike — have their per-file
69
+ // banners stripped before hashing, so emitted bytes are byte-identical
70
+ // across rebuilds from ANY working directory (the strip is an exact match of
71
+ // computed banners, never a pattern; see above).
72
+
73
+ import { createHash } from "node:crypto";
74
+ import {
75
+ copyFile,
76
+ lstat,
77
+ mkdir,
78
+ mkdtemp,
79
+ readdir,
80
+ readFile,
81
+ rm,
82
+ writeFile,
83
+ } from "node:fs/promises";
84
+ import { tmpdir } from "node:os";
85
+ import { posix, win32 } from "node:path";
86
+ import { compareStrings, type Diagnostic, sortDiagnostics } from "./diagnostics";
87
+ import { filesystemPath, isWindowsPath } from "./fs-path";
88
+ import type { ResolvedSite } from "./types";
89
+
90
+ const ASSETS_DIR = "assets";
91
+
92
+ function toPosix(p: string): string {
93
+ return p.replace(/\\/g, "/");
94
+ }
95
+
96
+ /** Locale-free case folding (toLowerCase, never toLocaleLowerCase — ICU). */
97
+ function foldCase(p: string): string {
98
+ return p.toLowerCase();
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // buildAssets
103
+ // ---------------------------------------------------------------------------
104
+
105
+ /** One manifest row: where the asset landed (posix, output-root-relative). */
106
+ export interface AssetManifestEntry {
107
+ /** `assets/<name>-<16 hex>.<ext>` — always hashed, never a bundler name. */
108
+ readonly file: string;
109
+ /** Byte length of the emitted file. */
110
+ readonly bytes: number;
111
+ }
112
+
113
+ /** name → entry. Iteration order is the sorted declaration order. */
114
+ export type AssetManifest = ReadonlyMap<string, AssetManifestEntry>;
115
+
116
+ export interface AssetsBuildResult {
117
+ /** Only successfully built assets; failed entrypoints are diagnostics. */
118
+ readonly manifest: AssetManifest;
119
+ readonly diagnostics: Diagnostic[];
120
+ }
121
+
122
+ interface DeclaredEntrypoint {
123
+ readonly name: string;
124
+ readonly key: string;
125
+ readonly path: string;
126
+ }
127
+
128
+ /** scripts + styles share ONE namespace (config.ts rejects a name in both). */
129
+ function declaredEntrypoints(resolvedSite: ResolvedSite): DeclaredEntrypoint[] {
130
+ const all: DeclaredEntrypoint[] = [
131
+ ...Object.entries(resolvedSite.assets.scripts).map(([name, path]) => ({
132
+ name,
133
+ key: `assets.scripts.${name}`,
134
+ path: toPosix(path),
135
+ })),
136
+ ...Object.entries(resolvedSite.assets.styles).map(([name, path]) => ({
137
+ name,
138
+ key: `assets.styles.${name}`,
139
+ path: toPosix(path),
140
+ })),
141
+ ];
142
+ return all.sort((a, b) => compareStrings(a.name, b.name));
143
+ }
144
+
145
+ /** A bundler message, reduced to what a Diagnostic can carry. */
146
+ interface BundlerMessage {
147
+ readonly message: string;
148
+ readonly file?: string;
149
+ readonly line?: number;
150
+ readonly column?: number;
151
+ }
152
+
153
+ function bundlerMessage(value: unknown): BundlerMessage {
154
+ if (typeof value === "object" && value !== null) {
155
+ const m = value as Record<string, unknown>;
156
+ const position = (m.position ?? m.location ?? undefined) as Record<string, unknown> | undefined;
157
+ if (typeof m.message === "string") {
158
+ return {
159
+ message: m.message,
160
+ ...(typeof position?.file === "string" ? { file: toPosix(position.file) } : {}),
161
+ ...(typeof position?.line === "number" ? { line: position.line } : {}),
162
+ ...(typeof position?.column === "number" ? { column: position.column } : {}),
163
+ };
164
+ }
165
+ }
166
+ return { message: value instanceof Error ? value.message : String(value) };
167
+ }
168
+
169
+ /**
170
+ * Flatten everything Bun.build can hand a failure into one honest list:
171
+ * the thrown AggregateError (.errors), a returned failure result (.logs /
172
+ * the legacy .messages), or any other thrown value.
173
+ */
174
+ function bundlerMessages(error: unknown): BundlerMessage[] {
175
+ const bag = error as { errors?: unknown; logs?: unknown; messages?: unknown };
176
+ const raw = Array.isArray(bag?.errors)
177
+ ? bag.errors
178
+ : Array.isArray(bag?.logs)
179
+ ? bag.logs
180
+ : Array.isArray(bag?.messages)
181
+ ? bag.messages
182
+ : undefined;
183
+ if (raw) return raw.map(bundlerMessage);
184
+ return [bundlerMessage(error)];
185
+ }
186
+
187
+ function bundleFailed(
188
+ entry: DeclaredEntrypoint,
189
+ messages: readonly BundlerMessage[],
190
+ ): Diagnostic[] {
191
+ return messages.map((m) => ({
192
+ code: "asset.bundle-failed" as const,
193
+ severity: "error" as const,
194
+ sourcePath: m.file ?? entry.path,
195
+ ...(m.line !== undefined ? { line: m.line } : {}),
196
+ ...(m.column !== undefined ? { column: m.column } : {}),
197
+ message: `bundling ${entry.key} "${entry.name}" failed: ${m.message}${
198
+ m.file !== undefined
199
+ ? ` (at ${m.file}${m.line !== undefined ? `:${m.line}` : ""}${m.column !== undefined ? `:${m.column}` : ""})`
200
+ : ""
201
+ }`,
202
+ }));
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Bundler banner strip (cross-cwd determinism)
207
+ // ---------------------------------------------------------------------------
208
+
209
+ /**
210
+ * The path banner Bun's bundler prepends to each bundled source file,
211
+ * measured through the real bundler on Bun 1.4.4 (pinned by
212
+ * tests/assets.test.ts, "Bun banner strip" block — do not re-litigate):
213
+ *
214
+ * - the path is the file's path RELATIVE TO PROCESS.CWD (Bun's "pretty"
215
+ * path), normalized with its platform-Loose rules: both `/` and `\`
216
+ * count as separators, output separators are always `/`, and the common
217
+ * prefix is compared byte-exact (even on Windows);
218
+ * - a JS chunk comments it `// <path>` on one line — but as a block
219
+ * comment when the path contains a newline or any byte > 0x7F; there,
220
+ * every star-slash pair (a `*` immediately followed by a `/`) is
221
+ * sanitized by replacing the `/` with `_`, looped until no star-slash
222
+ * remains, so the block comment cannot terminate early;
223
+ * - a CSS chunk always comments it as a block comment, escaping every
224
+ * star-slash pair by inserting a `\` before its `/` instead;
225
+ * - the banner for the FIRST file of a chunk sits at byte 0 — except that a
226
+ * hashbang on the entry's first source line (a leading BOM is dropped by
227
+ * Bun before hashbang detection, so BOM + hashbang still counts) is
228
+ * preserved first, followed by exactly one blank line, before the banner;
229
+ * - a file whose bundled code is empty gets NO banner at all, and a
230
+ * multi-file chunk gets one banner per file — in which case the LEADING
231
+ * banner names the first bundled file (a dependency), not the entry.
232
+ */
233
+ function bundlerBannerLine(pretty: string, ext: string): string {
234
+ if (ext === ".css") {
235
+ return `/* ${cssEscapeStarSlash(pretty)} */\n`;
236
+ }
237
+ if (hasNewlineOrNonAscii(pretty)) {
238
+ return `/* ${jsSanitizeStarSlash(pretty)} */\n`;
239
+ }
240
+ return `// ${pretty}\n`;
241
+ }
242
+
243
+ /** A newline (LF/CR) or a code point that encodes to bytes > 0x7F (UTF-8). */
244
+ function hasNewlineOrNonAscii(pretty: string): boolean {
245
+ for (let i = 0; i < pretty.length; i++) {
246
+ const cp = pretty.codePointAt(i) ?? 0; // unreachable for i < length; 0 matches no check below
247
+ if (cp === 0x0a || cp === 0x0d || cp > 0x7f) return true;
248
+ if (cp > 0xffff) i++; // consume the trailing surrogate of an astral pair
249
+ }
250
+ return false;
251
+ }
252
+
253
+ /** Bun's JS multiline sanitizer: every star-slash pair keeps its `*`, its `/` becomes `_`, looped. */
254
+ function jsSanitizeStarSlash(pretty: string): string {
255
+ let out = pretty;
256
+ let i = out.indexOf("*/");
257
+ while (i !== -1) {
258
+ out = `${out.slice(0, i + 1)}_${out.slice(i + 2)}`;
259
+ i = out.indexOf("*/");
260
+ }
261
+ return out;
262
+ }
263
+
264
+ /** Bun's CSS escape: a `\` is inserted before every `/` that follows a `*`. */
265
+ function cssEscapeStarSlash(pretty: string): string {
266
+ let out = "";
267
+ for (let i = 0; i < pretty.length; i++) {
268
+ if (pretty[i] === "/" && i > 0 && pretty[i - 1] === "*") out += "\\";
269
+ out += pretty[i];
270
+ }
271
+ return out;
272
+ }
273
+
274
+ /**
275
+ * The cwd-relative path forms the banner could carry, in match order. Bun's
276
+ * Loose platform differs from Node's in two measured corners, so this
277
+ * generates candidates instead of asserting one:
278
+ * - output separator: Loose always emits `/` (Node win32 emits `\`);
279
+ * - Windows drive-letter case: Node win32 uppercases drive letters while
280
+ * Bun preserves the case it was given, and the common-prefix compare is
281
+ * byte-exact (Node win32 is case-insensitive) — so same-drive paths whose
282
+ * drive letters disagree in case get their case folded per operand.
283
+ * Off-Platforms win32, Node's posix relative IS Bun's algorithm (same
284
+ * Node-derived relative, same separator) — one candidate. A candidate list
285
+ * can never match real content by accident: a match means the bytes literally
286
+ * are the banner we would have computed, and a NO-match (new Bun version,
287
+ * exotic path) simply means "leave the bytes alone" — never a corrupted strip.
288
+ */
289
+ export function bannerPathCandidates(absPath: string, cwd = process.cwd()): string[] {
290
+ const foldDrive = (p: string): string[] => {
291
+ if (!/^[A-Za-z]:/.test(p)) return [p];
292
+ const drive = p[0];
293
+ const folded =
294
+ (drive === drive.toUpperCase() ? drive.toLowerCase() : drive.toUpperCase()) + p.slice(1);
295
+ return [p, folded];
296
+ };
297
+ const out: string[] = [];
298
+ const push = (p: string): void => {
299
+ if (!out.includes(p)) out.push(p);
300
+ };
301
+ if (isWindowsPath(cwd) && isWindowsPath(absPath)) {
302
+ for (const from of foldDrive(toPosix(cwd))) {
303
+ for (const to of foldDrive(toPosix(absPath))) {
304
+ // Bun's Loose paths compare drive components byte-for-byte. In
305
+ // particular D:/cwd -> C:/tmp is ../../C:/tmp, not win32's C:/tmp.
306
+ push(posix.relative(`/${from}`, `/${to}`));
307
+ try {
308
+ push(win32.relative(from, to).replace(/\\/g, "/"));
309
+ } catch {
310
+ // mixed absolute/relative (should not happen: config paths are
311
+ // resolved against the config dir, cwd is absolute) — no candidate
312
+ }
313
+ }
314
+ }
315
+ } else {
316
+ if (!posix.isAbsolute(cwd) || !posix.isAbsolute(absPath)) return out;
317
+ push(posix.relative(cwd, absPath));
318
+ }
319
+ return out;
320
+ }
321
+
322
+ /**
323
+ * The byte offset of the banner when the entry's first source line is a
324
+ * hashbang (Bun keeps the hashbang line, adds its newline, then ONE blank
325
+ * line, then the banner), or -1 when the entry has no hashbang (or cannot be
326
+ * read, in which case the banner is simply not stripped).
327
+ */
328
+ async function hashbangBannerOffset(entryPath: string): Promise<number> {
329
+ let head: Buffer;
330
+ try {
331
+ head = await readFile(entryPath);
332
+ } catch {
333
+ return -1;
334
+ }
335
+ const isBom = head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf;
336
+ const line =
337
+ head
338
+ .subarray(isBom ? 3 : 0)
339
+ .toString("utf8")
340
+ .split("\n")[0] ?? "";
341
+ if (!line.startsWith("#!")) return -1;
342
+ return line.length + 1 /* the hashbang's own newline */ + 1 /* Bun's blank line */;
343
+ }
344
+
345
+ /**
346
+ * Strip the LEADING path banner from the emitted bytes of a SINGLE-input
347
+ * bundle (before hashing and before writing to staging), so the hash and the
348
+ * file are independent of the working directory the build ran from (plan
349
+ * §4.6, cross-cwd byte-identity). The strip is an EXACT match of the single
350
+ * banner line we would compute for THIS entrypoint, at the head of the file
351
+ * (or after a preserved hashbang + one blank line). It never pattern-matches:
352
+ * the transpiled code is comment-free, but template-literal content is
353
+ * emitted verbatim and can produce a line that merely looks like a banner —
354
+ * only an exact match of the computed banner is safe to remove. Returns the
355
+ * same bytes object unchanged when nothing matches (an entry whose code is
356
+ * empty after the transform, which emits no banner; a future Bun that
357
+ * changed the banner). Multi-file bundles route to stripMultiFileBanners.
358
+ */
359
+ export async function stripBundlerBanner(
360
+ bytes: Uint8Array,
361
+ entryPath: string,
362
+ ext: string,
363
+ ): Promise<Uint8Array> {
364
+ if (bytes.length === 0) return bytes;
365
+ const rels = bannerPathCandidates(entryPath);
366
+ if (rels.length === 0) return bytes;
367
+ const offsets: number[] = [0];
368
+ if (ext !== ".css") {
369
+ const off = await hashbangBannerOffset(entryPath);
370
+ if (off >= 0) offsets.push(off);
371
+ }
372
+ for (const rel of rels) {
373
+ const banner = new TextEncoder().encode(bundlerBannerLine(rel, ext));
374
+ for (const off of offsets) {
375
+ if (bytes.length < off + banner.length) continue;
376
+ let matches = true;
377
+ for (let i = 0; i < banner.length; i++) {
378
+ if (bytes[off + i] !== banner[i]) {
379
+ matches = false;
380
+ break;
381
+ }
382
+ }
383
+ if (!matches) continue;
384
+ const out = new Uint8Array(bytes.length - banner.length);
385
+ out.set(bytes.subarray(0, off), 0);
386
+ out.set(bytes.subarray(off + banner.length), off);
387
+ return out;
388
+ }
389
+ }
390
+ return bytes;
391
+ }
392
+
393
+ // ---------------------------------------------------------------------------
394
+ // Multi-file banner strip (cross-cwd determinism for bundles > 1 input)
395
+ // ---------------------------------------------------------------------------
396
+
397
+ /**
398
+ * Every exact banner line a multi-file bundle may carry (newline-stripped),
399
+ * in match form. Sources of candidates:
400
+ * - the entry's own cwd-relative candidates (bannerPathCandidates, same
401
+ * platform-Loose rules and drive-case folds as the single-file path) —
402
+ * the leading banner is the entry's when the entry is the first bundled
403
+ * file, and a dependency's otherwise;
404
+ * - each build input key from the metafile TWICE: the key itself — the
405
+ * metafile keys and the banner paths are measured byte-identical (both
406
+ * are Bun's cwd-relative "pretty" path, including the `../` form for
407
+ * files outside the cwd) — and the key resolved to an absolute path and
408
+ * re-derived through bannerPathCandidates (covers the case where the
409
+ * pretty form Bun used for the banner and the one in the metafile key
410
+ * differ in a platform corner, e.g. Windows drive-letter case).
411
+ * A candidate list can never match real content by accident: a match means
412
+ * the bytes literally are the banner we would have computed, and a no-match
413
+ * (new Bun version, exotic path) means "leave the bytes alone" — never a
414
+ * corrupted strip.
415
+ */
416
+ function multiFileBannerLines(
417
+ entryPath: string,
418
+ inputPaths: readonly string[],
419
+ ext: string,
420
+ ): Set<string> {
421
+ const lines = new Set<string>();
422
+ const add = (pretty: string): void => {
423
+ lines.add(bundlerBannerLine(pretty, ext).slice(0, -1)); // drop the line break
424
+ };
425
+ for (const pretty of bannerPathCandidates(entryPath)) add(pretty);
426
+ for (const key of inputPaths) {
427
+ add(key);
428
+ const abs =
429
+ process.platform === "win32"
430
+ ? win32.resolve(process.cwd(), toPosix(key))
431
+ : posix.resolve(process.cwd(), key);
432
+ for (const pretty of bannerPathCandidates(abs)) add(pretty);
433
+ }
434
+ return lines;
435
+ }
436
+
437
+ /** The line (as text) starting at byte offset `off`, or "" when off is at/past EOF. */
438
+ function lineAt(bytes: Uint8Array, off: number): string {
439
+ if (off >= bytes.length) return "";
440
+ let end = off;
441
+ while (end < bytes.length && bytes[end] !== 0x0a) end++;
442
+ return new TextDecoder("utf-8").decode(bytes.subarray(off, end));
443
+ }
444
+
445
+ /**
446
+ * Strip EVERY per-file path banner from a MULTI-file bundle (before hashing
447
+ * and before writing to staging), so the hash and the emitted file are
448
+ * independent of the working directory the build ran from (plan §4.6).
449
+ *
450
+ * Bun emits one banner line before EVERY bundled file, and the leading one
451
+ * names the first bundled file (a dependency), not the entry — so the
452
+ * single-file head-strip cannot identify it, and a pattern strip would eat
453
+ * template-literal lines that merely look like banners. The strip is
454
+ * therefore a two-stage EXACT match:
455
+ *
456
+ * 1. GATE — the line at the first banner position (byte 0, or after a
457
+ * preserved hashbang + one blank line when the entry starts with `#!`)
458
+ * must be byte-identical to the banner computed for ONE of the build's
459
+ * input files (the entry plus every metafile-enumerated import; see
460
+ * multiFileBannerLines). This proves the output really is a bannered
461
+ * bundle of THIS build. A bannerless output (code empty after the
462
+ * transform, a future Bun with a changed shape) never matches and the
463
+ * bytes are returned UNTOUCHED — the honest degradation is the old
464
+ * cwd-sensitive hash, never a corrupted file.
465
+ * 2. STRIP — once gated, every line in the output that is byte-identical to
466
+ * a computed banner is removed (in any position — the banners sit
467
+ * between the files' code, one per file). Blank lines are never removed:
468
+ * a stripped banner's line break stays, so a `code / blank / banner /
469
+ * code` seam becomes `code / blank / blank / code` — deterministic,
470
+ * and code whitespace is not part of the hash contract.
471
+ *
472
+ * Why the no-gate/no-pattern discipline is safe (measured, Bun 1.4.4): the
473
+ * transpile drops EVERY source comment, so a line of emitted code that is a
474
+ * bare comment-shaped line (`// …` or block-comment-shaped) can only be
475
+ * (a) a real banner, or (b)
476
+ * template-literal content emitted verbatim. Case (b) is the one honest
477
+ * caveat: if a line of string content is byte-identical to a computed
478
+ * banner, it is stripped with it — it changes one line of STRING DATA
479
+ * (the backtick boundaries stay, the code still parses), never code
480
+ * structure. Pinning both outcomes is the job of tests/assets.test.ts.
481
+ */
482
+ export async function stripMultiFileBanners(
483
+ bytes: Uint8Array,
484
+ entryPath: string,
485
+ ext: string,
486
+ inputPaths: readonly string[],
487
+ ): Promise<Uint8Array> {
488
+ if (bytes.length === 0) return bytes;
489
+ const lines = multiFileBannerLines(entryPath, inputPaths, ext);
490
+ const gateOffsets: number[] = [0];
491
+ if (ext !== ".css") {
492
+ const off = await hashbangBannerOffset(entryPath);
493
+ if (off >= 0) gateOffsets.push(off);
494
+ }
495
+ const gated = gateOffsets.some((off) => {
496
+ const line = lineAt(bytes, off);
497
+ return line !== "" && lines.has(line);
498
+ });
499
+ if (!gated) return bytes;
500
+ const out = new Uint8Array(bytes.length);
501
+ let n = 0;
502
+ for (let i = 0; i < bytes.length; ) {
503
+ let end = i;
504
+ while (end < bytes.length && bytes[end] !== 0x0a) end++;
505
+ const line = new TextDecoder("utf-8").decode(bytes.subarray(i, end));
506
+ if (!lines.has(line)) {
507
+ out.set(bytes.subarray(i, end), n);
508
+ n += end - i;
509
+ }
510
+ if (end < bytes.length) out[n++] = 0x0a; // every original line break survives
511
+ i = end + 1;
512
+ }
513
+ return out.subarray(0, n);
514
+ }
515
+
516
+ /**
517
+ * Bundle every declared script/style entrypoint into `stagingDir` and return
518
+ * the manifest (plan §4.2). One Bun.build per entrypoint into a fresh mkdtemp
519
+ * dir (stale-leak guard, see header); the build must emit EXACTLY ONE file,
520
+ * whose cwd-relative per-file path banners are stripped before hashing —
521
+ * single-input bundles through stripBundlerBanner (one leading banner),
522
+ * multi-input bundles through stripMultiFileBanners (one banner per bundled
523
+ * file, every one of them, gated on the first line being a computed banner) —
524
+ * then the final bytes are hashed (sha256, first 16 hex) and copied to
525
+ * `assets/<name>-<hash>.<ext>`. A failing entrypoint produces diagnostics
526
+ * and does NOT cancel its siblings — every problem is collected (config.ts
527
+ * convention), so one run reports every broken asset. All tmpdirs are removed
528
+ * in `finally`, on success and on failure alike.
529
+ */
530
+ export async function buildAssets(
531
+ resolvedSite: ResolvedSite,
532
+ stagingDir: string,
533
+ ): Promise<AssetsBuildResult> {
534
+ const staging = toPosix(stagingDir);
535
+ const manifest = new Map<string, AssetManifestEntry>();
536
+ const diagnostics: Diagnostic[] = [];
537
+ const tmpdirs: string[] = [];
538
+ try {
539
+ for (const entry of declaredEntrypoints(resolvedSite)) {
540
+ const outdir = await mkdtemp(filesystemPath.join(tmpdir(), "crust-site-asset-"));
541
+ tmpdirs.push(outdir);
542
+ let outputs: readonly Bun.BuildArtifact[];
543
+ // The build's input files as the bundler reports them — metafile keys,
544
+ // which are the cwd-relative "pretty" paths the per-file banners carry
545
+ // (measured byte-identical, Bun 1.4.4). The multi-file strip matches
546
+ // against them (stripMultiFileBanners). Absent metafile (a future Bun)
547
+ // → empty → the single-file strip degrades exactly as before.
548
+ let inputPaths: string[] = [];
549
+ try {
550
+ // entrypoints as an ARRAY (locked fact); outdir is fresh, so nothing
551
+ // but this build's own outputs can be collected from it.
552
+ // metafile: true — the input keys are the metafile's ONLY use here:
553
+ // they feed the multi-file banner strip above. They are never
554
+ // hashed or emitted, so they cannot leak into the output bytes.
555
+ const result = await Bun.build({
556
+ entrypoints: [entry.path],
557
+ outdir,
558
+ target: "browser",
559
+ metafile: true,
560
+ });
561
+ if (!result.success) {
562
+ diagnostics.push(...bundleFailed(entry, bundlerMessages(result)));
563
+ continue;
564
+ }
565
+ outputs = result.outputs;
566
+ inputPaths = Object.keys(result.metafile?.inputs ?? {});
567
+ } catch (error) {
568
+ diagnostics.push(...bundleFailed(entry, bundlerMessages(error)));
569
+ continue;
570
+ }
571
+ if (outputs.length === 0) {
572
+ diagnostics.push(
573
+ ...bundleFailed(entry, [{ message: "the bundler emitted zero output files" }]),
574
+ );
575
+ continue;
576
+ }
577
+ if (outputs.length > 1) {
578
+ const chunks = outputs.map((o) => posix.basename(toPosix(o.path))).sort(compareStrings);
579
+ diagnostics.push({
580
+ code: "asset.entrypoint-chunked",
581
+ severity: "error",
582
+ sourcePath: entry.path,
583
+ message:
584
+ `${entry.key} "${entry.name}" (${entry.path}) produced ${outputs.length} output files; ` +
585
+ `v1 emits exactly one hashed file per asset — imported asset files and code-splitting are not supported. Files: ${chunks.join(", ")}`,
586
+ });
587
+ continue;
588
+ }
589
+ const primary = outputs[0];
590
+ const emittedPath = toPosix(primary.path);
591
+ // v1 assets are JS (<script>) or CSS (<link>); anything else (an .svg
592
+ // declared as an entrypoint, say) has no honest ext and no honest tag.
593
+ const ext = posix.extname(emittedPath).toLowerCase();
594
+ if (ext !== ".js" && ext !== ".css") {
595
+ diagnostics.push(
596
+ ...bundleFailed(entry, [
597
+ {
598
+ message: `the bundler emitted "${posix.basename(emittedPath)}" (${primary.loader}); v1 assets must be JavaScript or CSS`,
599
+ },
600
+ ]),
601
+ );
602
+ continue;
603
+ }
604
+ const raw = await readFile(emittedPath);
605
+ // Strip the bundler's cwd-relative per-file path banners BEFORE the
606
+ // hash and before staging. A single-input bundle carries exactly one
607
+ // banner (the entry's, at the head or after a preserved hashbang), so
608
+ // its exact match is unambiguous — stripBundlerBanner. A multi-input
609
+ // bundle carries one banner per bundled file and its LEADING banner
610
+ // names a dependency, not the entry — stripMultiFileBanners removes
611
+ // every line that is an exact match of the banner computed for ANY
612
+ // build input (entry + metafile-enumerated imports), gated on the
613
+ // first line being such a banner. When the gate fails (bannerless
614
+ // output, a future Bun with a changed banner shape) the bytes are
615
+ // returned untouched: the honest degradation is the old
616
+ // cwd-sensitive hash, never a corrupted file.
617
+ const bytes =
618
+ inputPaths.length > 1
619
+ ? await stripMultiFileBanners(raw, entry.path, ext, inputPaths)
620
+ : await stripBundlerBanner(raw, entry.path, ext);
621
+ // Hash contract (plan §1): first 16 hex (64 bits) of sha256 over the
622
+ // FINAL emitted bytes (all per-file banners stripped —
623
+ // post-transform, so any input change moves the hash and the cwd
624
+ // never does). digest("hex") is lowercase by construction. Collision
625
+ // safety: the manifest is keyed by the DECLARED name and the emitted
626
+ // name embeds the hash, so two distinct assets can only overwrite
627
+ // each other if they share both name (config rejects that) and hash;
628
+ // a 64-bit preimage-free collision budget over a site's handful of
629
+ // assets is unreachable, so identical name+hash honestly implies
630
+ // identical content.
631
+ const hash = createHash("sha256").update(bytes).digest("hex").slice(0, 16);
632
+ const file = posix.join(ASSETS_DIR, `${entry.name}-${hash}.${ext.slice(1)}`);
633
+ await mkdir(filesystemPath.join(staging, ASSETS_DIR), { recursive: true });
634
+ await writeFile(filesystemPath.join(staging, file), bytes);
635
+ manifest.set(entry.name, { file, bytes: bytes.length });
636
+ }
637
+ } finally {
638
+ // Best effort, but ALWAYS: one build's tmpdirs must not linger, and a
639
+ // cleanup failure never masks the real result. force:true swallows the
640
+ // already-gone case; anything else (permissions) stays silent by design.
641
+ for (const dir of tmpdirs) {
642
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
643
+ }
644
+ }
645
+ return { manifest, diagnostics: sortDiagnostics(diagnostics) };
646
+ }
647
+
648
+ export type ManifestLookup =
649
+ | { readonly found: true; readonly entry: AssetManifestEntry }
650
+ | { readonly found: false; readonly diagnostic: Diagnostic };
651
+
652
+ /**
653
+ * The render-time lookup for script(name)/stylesheet(name) (chunk 6): the
654
+ * entry, or an asset.unknown-entrypoint diagnostic naming every declared
655
+ * name — a map-key typo is a build error, never a silently missing tag.
656
+ */
657
+ export function manifestLookup(manifest: AssetManifest, name: string): ManifestLookup {
658
+ const entry = manifest.get(name);
659
+ if (entry !== undefined) return { found: true, entry };
660
+ const known = [...manifest.keys()].sort(compareStrings);
661
+ return {
662
+ found: false,
663
+ diagnostic: {
664
+ code: "asset.unknown-entrypoint",
665
+ severity: "error",
666
+ sourcePath: "",
667
+ message:
668
+ `asset "${name}" is not in the build manifest` +
669
+ (known.length === 0 ? " (no assets were declared)" : ` (declared: ${known.join(", ")})`),
670
+ },
671
+ };
672
+ }
673
+
674
+ // ---------------------------------------------------------------------------
675
+ // copyPublicDir
676
+ // ---------------------------------------------------------------------------
677
+
678
+ export interface PublicCopyResult {
679
+ /**
680
+ * Every copied file, posix and relative to publicDirectory, sorted. The
681
+ * emitter (chunk 6) feeds this to publicCollisions. Directories are not
682
+ * listed — only files can collide.
683
+ */
684
+ readonly copied: string[];
685
+ readonly diagnostics: Diagnostic[];
686
+ }
687
+
688
+ function publicMissing(what: string, dir: string): Diagnostic {
689
+ return {
690
+ code: "asset.public-missing",
691
+ severity: "error",
692
+ sourcePath: dir,
693
+ message: `assets.publicDirectory "${dir}" ${what}`,
694
+ };
695
+ }
696
+
697
+ /**
698
+ * Sorted recursive copy: directories are created (empty ones too — it is the
699
+ * tree, preserved), files are copied byte-for-byte (no CRLF rewriting: these
700
+ * are opaque files — favicons, CNAMEs, robots alternates). File MODES are NOT
701
+ * a contract (copyFile copies content; executable bits etc. are meaningless
702
+ * for static hosting and are neither preserved nor normalized on purpose).
703
+ * Symlinks (file or directory) are an ERROR, never copied and never silently
704
+ * skipped: following them could publish an arbitrary host tree into the public
705
+ * output or recurse forever (the package-wide "symlinks don't extend a
706
+ * boundary" rule), but skipping quietly would be a false pass — the author
707
+ * put the file there expecting it to publish, and a green build with a missing
708
+ * file is exactly what crust rule 1 forbids. Raw I/O errors are NOT swallowed
709
+ * into diagnostics — a failed copy must reject the build, not half-emit.
710
+ */
711
+ async function walkCopy(
712
+ publicDir: string,
713
+ staging: string,
714
+ rel: string,
715
+ copied: string[],
716
+ diagnostics: Diagnostic[],
717
+ ): Promise<void> {
718
+ const entries = (
719
+ await readdir(filesystemPath.join(publicDir, rel), { withFileTypes: true })
720
+ ).sort((a, b) => compareStrings(a.name, b.name));
721
+ for (const d of entries) {
722
+ const childRel = rel === "" ? d.name : posix.join(rel, d.name);
723
+ if (d.isSymbolicLink()) {
724
+ diagnostics.push({
725
+ code: "asset.public-symlink",
726
+ severity: "error",
727
+ sourcePath: childRel,
728
+ message:
729
+ `the public entry "${childRel}" is a symbolic link; v1 never copies symlinks out of ` +
730
+ `assets.publicDirectory (one could publish an arbitrary host tree) — replace it with a real file or directory`,
731
+ });
732
+ continue;
733
+ }
734
+ if (d.isDirectory()) {
735
+ await mkdir(filesystemPath.join(staging, childRel), { recursive: true });
736
+ await walkCopy(publicDir, staging, childRel, copied, diagnostics);
737
+ } else if (d.isFile()) {
738
+ await mkdir(filesystemPath.join(staging, posix.dirname(childRel)), { recursive: true });
739
+ await copyFile(
740
+ filesystemPath.join(publicDir, childRel),
741
+ filesystemPath.join(staging, childRel),
742
+ );
743
+ copied.push(childRel);
744
+ }
745
+ // fifo/socket/device entries are not copied — they are not files.
746
+ }
747
+ }
748
+
749
+ /**
750
+ * Copy assets.publicDirectory to the staging ROOT, preserving relative paths,
751
+ * unhashed and unmodified (plan §2 — documented: public files get no cache
752
+ * busting). No publicDirectory configured → silent no-op; configured but
753
+ * absent/not-a-directory → asset.public-missing.
754
+ */
755
+ export async function copyPublicDir(
756
+ resolvedSite: ResolvedSite,
757
+ stagingDir: string,
758
+ ): Promise<PublicCopyResult> {
759
+ const configured = resolvedSite.assets.publicDirectory;
760
+ if (configured === undefined) return { copied: [], diagnostics: [] };
761
+ const publicDir = toPosix(configured);
762
+ const staging = toPosix(stagingDir);
763
+ let stat: Awaited<ReturnType<typeof lstat>>;
764
+ try {
765
+ stat = await lstat(publicDir);
766
+ } catch (error) {
767
+ const code = (error as NodeJS.ErrnoException).code;
768
+ const why = code === "ENOENT" ? "does not exist" : `is not readable (${code ?? String(error)})`;
769
+ return { copied: [], diagnostics: [publicMissing(why, publicDir)] };
770
+ }
771
+ if (!stat.isDirectory()) {
772
+ const why = stat.isSymbolicLink()
773
+ ? "is a symbolic link (v1 requires a real directory)"
774
+ : "is not a directory";
775
+ return { copied: [], diagnostics: [publicMissing(why, publicDir)] };
776
+ }
777
+ const copied: string[] = [];
778
+ const diagnostics: Diagnostic[] = [];
779
+ await walkCopy(publicDir, staging, "", copied, diagnostics);
780
+ return { copied: copied.sort(compareStrings), diagnostics: sortDiagnostics(diagnostics) };
781
+ }
782
+
783
+ // ---------------------------------------------------------------------------
784
+ // publicCollisions
785
+ // ---------------------------------------------------------------------------
786
+
787
+ /**
788
+ * Detect the copied public files that would clobber the emitted site.
789
+ * `generatedPaths` are the files the emitter is about to write (index.html,
790
+ * sitemap.xml, robots.txt, 404.html, every hashed assets/<name>-<hash>.<ext>)
791
+ * — all posix and output-root-relative, same coordinates as `copiedPaths`.
792
+ *
793
+ * Four rules, deterministic order (copied paths sorted):
794
+ * 1. the reserved prefix: `assets/` belongs to the generator whether an
795
+ * asset happens to be emitted right now or not — a public file there
796
+ * breaks the hashed-assets contract (the dev server serves assets/* as
797
+ * immutable; hashed names are the generator's namespace alone), so it is
798
+ * a collision even against an empty generated list (plan §2);
799
+ * 2. an exact path collision with a generated file;
800
+ * 3. a case-only collision with a generated file — the same file on
801
+ * case-insensitive filesystems (plan, Windows table: every path pass runs
802
+ * case-insensitive on top);
803
+ * 4. a case-only collision between TWO copied public files — on a
804
+ * case-insensitive filesystem the second silently overwrites the first in
805
+ * staging, so the same pass runs over the copied set itself (a Linux-only
806
+ * exception would make the same config pass here and half-emit on Windows
807
+ * — the route table takes the same unconditional stance).
808
+ * A file can trigger rule 1 AND rule 2/3 (it is both inside the reserved
809
+ * namespace and a specific collision) — both diagnostics are honest, so both
810
+ * are emitted; rules 2 and 3 are mutually exclusive.
811
+ *
812
+ * `sourcePath` is the copied file's public-relative posix path; the message
813
+ * names the generated counterpart.
814
+ */
815
+ export function publicCollisions(
816
+ copiedPaths: readonly string[],
817
+ generatedPaths: readonly string[],
818
+ ): Diagnostic[] {
819
+ const generatedExact = new Set<string>();
820
+ const generatedFolded = new Map<string, string>();
821
+ for (const g of [...generatedPaths].map(toPosix).sort(compareStrings)) {
822
+ generatedExact.add(g);
823
+ const folded = foldCase(g);
824
+ if (!generatedFolded.has(folded)) generatedFolded.set(folded, g);
825
+ }
826
+ const diagnostics: Diagnostic[] = [];
827
+ const copiedFolded = new Map<string, string>();
828
+ for (const p of [...copiedPaths].map(toPosix).sort(compareStrings)) {
829
+ const folded = foldCase(p);
830
+ const twin = copiedFolded.get(folded);
831
+ if (twin !== undefined && twin !== p) {
832
+ diagnostics.push({
833
+ code: "output.collision",
834
+ severity: "error",
835
+ sourcePath: p,
836
+ message:
837
+ `the public file "${p}" collides with the public file "${twin}" — ` +
838
+ `they differ only by case and collide on case-insensitive filesystems`,
839
+ });
840
+ } else if (twin === undefined) {
841
+ copiedFolded.set(folded, p);
842
+ }
843
+ if (folded.split("/")[0] === ASSETS_DIR) {
844
+ diagnostics.push({
845
+ code: "output.collision",
846
+ severity: "error",
847
+ sourcePath: p,
848
+ message:
849
+ `the public file "${p}" lands inside the reserved "${ASSETS_DIR}/" directory — ` +
850
+ `hashed assets are emitted there and public files must live outside it`,
851
+ });
852
+ }
853
+ if (generatedExact.has(p)) {
854
+ diagnostics.push({
855
+ code: "output.collision",
856
+ severity: "error",
857
+ sourcePath: p,
858
+ message: `the public file "${p}" collides with the generated file "${p}"`,
859
+ });
860
+ } else {
861
+ const foldedTarget = generatedFolded.get(folded);
862
+ if (foldedTarget !== undefined && foldedTarget !== p) {
863
+ diagnostics.push({
864
+ code: "output.collision",
865
+ severity: "error",
866
+ sourcePath: p,
867
+ message:
868
+ `the public file "${p}" collides with the generated file "${foldedTarget}" — ` +
869
+ `they differ only by case and collide on case-insensitive filesystems`,
870
+ });
871
+ }
872
+ }
873
+ }
874
+ return diagnostics;
875
+ }