@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,240 @@
1
+ // Frontmatter: a `---` YAML block at the top of every .md file, parsed with
2
+ // eemeli/yaml + LineCounter so every diagnostic lands in the FULL file's
3
+ // coordinates (Bun's built-in YAML gives no positions — plan §0). Strict:
4
+ // missing/unclosed block, non-mapping, duplicate keys, unknown keys and bad
5
+ // values are all ERRORS, collected into one BuildError. The delimiter is
6
+ // `---` at column 0 (trailing space/tab allowed) — an indented `---` is
7
+ // content, not a fence — and a leading BOM is stripped as input noise.
8
+
9
+ import { isMap, isNode, LineCounter, parseDocument } from "yaml";
10
+ import { BuildError, type Diagnostic, isDiagnostic } from "./diagnostics";
11
+ import { normalizeRoute } from "./routes";
12
+ import type { FrontmatterResult, PageFrontmatter } from "./types";
13
+
14
+ const KNOWN_KEYS = ["title", "description", "layout", "route", "draft", "data"] as const;
15
+ type KnownKey = (typeof KNOWN_KEYS)[number];
16
+
17
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
18
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
19
+ const proto = Object.getPrototypeOf(value);
20
+ return proto === Object.prototype || proto === null;
21
+ }
22
+
23
+ /**
24
+ * Parse a .md file's frontmatter. Throws `BuildError` (sorted) on ANY problem;
25
+ * on success returns the validated frontmatter, the body, and the body's
26
+ * first line so later chunks can locate markdown errors in file coordinates.
27
+ */
28
+ export function parseFrontmatter(text: string, sourcePath: string): FrontmatterResult {
29
+ // A single leading BOM is an input artifact (Windows editors write one);
30
+ // strip it, as eemeli/yaml does, and as the CRLF normalization below. A
31
+ // U+FEFF mid-file is content (a zero-width no-break space), not a BOM.
32
+ const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
33
+ // CRLF/CR → LF before counting: line COUNT is preserved, and every later
34
+ // chunk emits LF-only (plan, Windows table: "Normalize CRLF on input").
35
+ const lines = src.replace(/\r\n?/g, "\n").split("\n");
36
+
37
+ const structural = (message: string): never => {
38
+ throw new BuildError([
39
+ {
40
+ code: "frontmatter.missing",
41
+ message,
42
+ severity: "error",
43
+ sourcePath,
44
+ line: 1,
45
+ column: 1,
46
+ },
47
+ ]);
48
+ };
49
+
50
+ // The delimiter is `---` at column 0 with optional trailing whitespace:
51
+ // - leading whitespace is a Markdown code-block signal and must NOT
52
+ // delimit — a file that is an indented code block of dashes is body,
53
+ // not frontmatter (trailing space/tab is an editor artifact: allowed);
54
+ // - `----` is not a delimiter (it is horizontal-rule-ish content);
55
+ // - an indented `---` INSIDE the block is YAML content — a block scalar
56
+ // keeps it verbatim (eemeli/yaml only treats a column-0 marker as a
57
+ // document terminator) — so the closer must be column-0 or it would
58
+ // slice a scalar early and move the rest of the frontmatter into the
59
+ // body (a silent misparse, never a fix).
60
+ const DELIMITER = /^---[ \t]*$/;
61
+
62
+ if (!DELIMITER.test(lines[0] ?? "")) {
63
+ structural('file does not begin with a column-0 "---" frontmatter delimiter line');
64
+ }
65
+ let close = -1;
66
+ for (let i = 1; i < lines.length; i++) {
67
+ if (DELIMITER.test(lines[i])) {
68
+ close = i;
69
+ break;
70
+ }
71
+ }
72
+ if (close === -1) structural('frontmatter block is not closed (missing closing "---" line)');
73
+
74
+ // The YAML block occupies file lines 2..close; every position below is
75
+ // reported in FULL-FILE coordinates by adding this offset.
76
+ const lineOffset = 1;
77
+ const block = lines.slice(1, close).join("\n");
78
+ const lineCounter = new LineCounter();
79
+ const doc = parseDocument(block, { lineCounter, logLevel: "silent" });
80
+
81
+ const located = (offset: number): { line: number; column: number } => {
82
+ const pos = lineCounter.linePos(offset);
83
+ return { line: pos.line + lineOffset, column: pos.col };
84
+ };
85
+ const nodeOffset = (node: unknown, fallback: number): number => {
86
+ const range = isNode(node) ? node.range : undefined;
87
+ return range ? range[0] : fallback;
88
+ };
89
+
90
+ // Parse errors: duplicate keys are located and reported, and validation
91
+ // continues (yaml resolves duplicates to the last value, so the remaining
92
+ // keys are still checkable). Any other syntax error means the document
93
+ // cannot be trusted at all — report and stop, but report ALL syntax errors.
94
+ const errors: Diagnostic[] = [];
95
+ let fatal = false;
96
+ for (const err of doc.errors) {
97
+ const at = located(err.pos ? err.pos[0] : 0);
98
+ if (err.code === "DUPLICATE_KEY") {
99
+ errors.push({
100
+ code: "frontmatter.duplicate-key",
101
+ message: `duplicate frontmatter key: ${err.message.split("\n")[0]}`,
102
+ severity: "error",
103
+ sourcePath,
104
+ line: at.line,
105
+ column: at.column,
106
+ });
107
+ } else {
108
+ fatal = true;
109
+ errors.push({
110
+ code: "frontmatter.parse-error",
111
+ message: `frontmatter YAML is not parseable: ${err.message.split("\n")[0]}`,
112
+ severity: "error",
113
+ sourcePath,
114
+ line: at.line,
115
+ column: at.column,
116
+ });
117
+ }
118
+ }
119
+ if (fatal) throw new BuildError(errors);
120
+
121
+ if (!doc.contents || !isMap(doc.contents)) {
122
+ const at = doc.contents ? located(nodeOffset(doc.contents, 0)) : { line: 1, column: 1 };
123
+ errors.push({
124
+ code: "frontmatter.not-mapping",
125
+ message: "frontmatter must be a YAML mapping of key: value pairs",
126
+ severity: "error",
127
+ sourcePath,
128
+ line: at.line,
129
+ column: at.column,
130
+ });
131
+ throw new BuildError(errors);
132
+ }
133
+
134
+ const frontmatter: PageFrontmatter = { title: "" };
135
+ let hasTitle = false;
136
+ let dataLine: number | undefined;
137
+ const badValue = (at: { line: number; column: number }, key: KnownKey, why: string): void => {
138
+ errors.push({
139
+ code: "frontmatter.bad-value",
140
+ message: `frontmatter key "${key}": ${why}`,
141
+ severity: "error",
142
+ sourcePath,
143
+ line: at.line,
144
+ column: at.column,
145
+ });
146
+ };
147
+
148
+ for (const item of doc.contents.items) {
149
+ const keyPos = located(nodeOffset(item.key, 0));
150
+ const key = isNode(item.key) ? (item.key.toJS(doc) as unknown) : null;
151
+ if (typeof key !== "string") {
152
+ errors.push({
153
+ code: "frontmatter.unknown-key",
154
+ message: "frontmatter keys must be plain strings",
155
+ severity: "error",
156
+ sourcePath,
157
+ line: keyPos.line,
158
+ column: keyPos.column,
159
+ });
160
+ continue;
161
+ }
162
+ if (!(KNOWN_KEYS as readonly string[]).includes(key)) {
163
+ errors.push({
164
+ code: "frontmatter.unknown-key",
165
+ message: `unknown frontmatter key "${key}" (allowed: ${KNOWN_KEYS.join(", ")})`,
166
+ severity: "error",
167
+ sourcePath,
168
+ line: keyPos.line,
169
+ column: keyPos.column,
170
+ });
171
+ continue;
172
+ }
173
+ const value = isNode(item.value) ? item.value.toJS(doc) : undefined;
174
+ const valPos = located(nodeOffset(item.value, 0));
175
+
176
+ switch (key) {
177
+ case "title":
178
+ hasTitle = true;
179
+ if (typeof value !== "string" || value.trim() === "") {
180
+ badValue(valPos, "title", "must be a non-empty string");
181
+ } else {
182
+ frontmatter.title = value;
183
+ }
184
+ break;
185
+ case "description":
186
+ if (typeof value !== "string" || value === "") {
187
+ badValue(valPos, "description", "must be a non-empty string when present");
188
+ } else {
189
+ frontmatter.description = value;
190
+ }
191
+ break;
192
+ case "layout":
193
+ if (typeof value !== "string" || value === "") {
194
+ badValue(valPos, "layout", "must be a non-empty string");
195
+ } else {
196
+ frontmatter.layout = value;
197
+ }
198
+ break;
199
+ case "route":
200
+ try {
201
+ frontmatter.route = normalizeRoute(value, { sourcePath });
202
+ } catch (d) {
203
+ if (!isDiagnostic(d)) throw d;
204
+ // Keep the route.* code (codes are never repurposed) but locate the
205
+ // problem at the route KEY, which is what the author must fix.
206
+ errors.push({ ...d, line: keyPos.line, column: keyPos.column });
207
+ }
208
+ break;
209
+ case "draft":
210
+ if (typeof value !== "boolean") badValue(valPos, "draft", "must be a boolean");
211
+ else frontmatter.draft = value;
212
+ break;
213
+ case "data":
214
+ dataLine = keyPos.line;
215
+ if (!isPlainObject(value))
216
+ badValue(valPos, "data", "must be a plain object (a YAML mapping)");
217
+ else frontmatter.data = value;
218
+ break;
219
+ }
220
+ }
221
+
222
+ if (!hasTitle) {
223
+ errors.push({
224
+ code: "frontmatter.missing-title",
225
+ message: 'frontmatter is missing the required key "title"',
226
+ severity: "error",
227
+ sourcePath,
228
+ line: 1,
229
+ column: 1,
230
+ });
231
+ }
232
+ if (errors.length > 0) throw new BuildError(errors);
233
+
234
+ return {
235
+ frontmatter,
236
+ body: lines.slice(close + 1).join("\n"),
237
+ bodyStartLine: close + 2,
238
+ ...(dataLine !== undefined ? { dataLine } : {}),
239
+ };
240
+ }
package/src/fs-path.ts ADDED
@@ -0,0 +1,54 @@
1
+ import * as native from "node:path";
2
+ import { posix, win32 } from "node:path";
3
+
4
+ /** Disk paths are slash-normalized, but must retain their filesystem's roots. */
5
+ export function toPosix(path: string): string {
6
+ return path.replace(/\\/g, "/");
7
+ }
8
+
9
+ export function isWindowsPath(path: string): boolean {
10
+ return /^[A-Za-z]:[\\/]/.test(path) || /^[/\\]{2}[^/\\]+[/\\]+[^/\\]+/.test(path);
11
+ }
12
+
13
+ function implementation(paths: readonly string[]): typeof posix {
14
+ if (paths.some(isWindowsPath)) return win32;
15
+ // Explicit POSIX paths are also used by config validation on Windows.
16
+ if (paths.some((path) => posix.isAbsolute(path))) return posix;
17
+ return native;
18
+ }
19
+
20
+ export const filesystemPath = {
21
+ resolve(...paths: string[]): string {
22
+ // Unlike normalize, resolve addresses the host filesystem. On Windows,
23
+ // /dist and \dist need a drive/share before hashing, locking, or recovery.
24
+ const disk = paths.some(isWindowsPath) ? win32 : native;
25
+ return toPosix(disk.resolve(...paths.map(toPosix)));
26
+ },
27
+ join(...paths: string[]): string {
28
+ return toPosix(implementation(paths).join(...paths.map(toPosix)));
29
+ },
30
+ dirname(path: string): string {
31
+ return toPosix(implementation([path]).dirname(toPosix(path)));
32
+ },
33
+ basename(path: string): string {
34
+ return implementation([path]).basename(toPosix(path));
35
+ },
36
+ normalize(path: string): string {
37
+ return toPosix(implementation([path]).normalize(toPosix(path)));
38
+ },
39
+ relative(from: string, to: string): string {
40
+ return toPosix(implementation([from, to]).relative(toPosix(from), toPosix(to)));
41
+ },
42
+ isAbsolute(path: string): boolean {
43
+ return posix.isAbsolute(toPosix(path)) || isWindowsPath(path);
44
+ },
45
+ };
46
+
47
+ /** Component-aware, including Windows drive/case semantics; not a string prefix. */
48
+ export function pathContains(outer: string, inner: string): boolean {
49
+ const relative = filesystemPath.relative(outer, inner);
50
+ return (
51
+ relative === "" ||
52
+ (relative !== ".." && !relative.startsWith("../") && !filesystemPath.isAbsolute(relative))
53
+ );
54
+ }
package/src/html.ts ADDED
@@ -0,0 +1,400 @@
1
+ // The fenced template runtime (plan §1).
2
+ //
3
+ // A tagged template CANNOT enforce rules by inspecting the literal —
4
+ // `html\`<scr${"i"}pt>\`` defeats any literal check. The enforced design:
5
+ //
6
+ // 1. EVERY interpolated value is rendered through ONE escape function
7
+ // (& < > " ' → entities, ampersand first), so a value can never
8
+ // contribute a raw structural character to the document.
9
+ // 2. Each value's character range is recorded (recursively, through
10
+ // arbitrary template nesting — a value interpolated three levels deep
11
+ // is still tracked in the final document).
12
+ // 3. `finalizeDocument` runs the post-render fence (fence.ts) over
13
+ // (final markup, merged ranges) and throws a BuildError on any
14
+ // violation. The renderer (render chunk) calls it per page.
15
+ //
16
+ // Value semantics (render.bad-value, thrown BEFORE any toString/valueOf/
17
+ // toPrimitive is invoked — a hostile getter must never run):
18
+ // string → escaped
19
+ // finite number → String(n); `0` renders "0" (never falsy-dropped)
20
+ // null/undefined/ → nothing (no range: an empty emission crosses no
21
+ // false boundary)
22
+ // Html → the child's markup; its ranges are offset by the
23
+ // insertion point and merged in
24
+ // arrays → flattened recursively, joined with no separator
25
+ // EVERYTHING ELSE → render.bad-value: true, NaN, ±Infinity, Promises and
26
+ // (true, NaN, other thenables (detected WITHOUT letting a throwing
27
+ // Infinity, .then getter escape — the access is wrapped and a
28
+ // Promise, failure becomes the bad-value diagnostic), Symbol,
29
+ // Symbol, bigint, functions, class instances, plain objects.
30
+ // Cycles → a node that is its own ancestor in one render is a
31
+ // (per-render render.bad-value. A node used in TWO branches of the
32
+ // seen-set) same render (a diamond, e.g. an array rendered twice)
33
+ // is legal — values are resolved LIVE per render, so a
34
+ // shared array always shows its current contents.
35
+ // Depth → the root template is depth 0; a node at depth > 64
36
+ // is a render.bad-value.
37
+ //
38
+ // `trustedHtml(markup, ranges)` builds an Html from trusted internal markup
39
+ // (the markdown renderer, chunk 4, uses it to hand value ranges to the fence
40
+ // without re-escaping), and `isHtml` is the brand guard the render engine
41
+ // uses to recognize an Html. Both are exported from THIS module for
42
+ // internal use but deliberately NOT from index.ts.
43
+
44
+ import { BuildError, type Diagnostic } from "./diagnostics";
45
+ import { type Range, runFence } from "./fence";
46
+ import type { UrlPolicyOptions } from "./url";
47
+
48
+ /**
49
+ * The brand. A REAL unique symbol (a `declare const` would be type-only and
50
+ * vanish at runtime) that is never exported: a unique symbol is unnameable
51
+ * outside this module, so no other module can stamp or inspect this
52
+ * property, and a plain object cannot impersonate an Html.
53
+ */
54
+ const htmlBrand = Symbol("crust-site.Html");
55
+
56
+ /**
57
+ * The public opaque value type. Only `html` (and the internal `trustedHtml`)
58
+ * produce one. Consumers treat it as an opaque token: interpolate it into
59
+ * `html`, hand it to `renderToString`/`finalizeDocument`.
60
+ */
61
+ export interface Html {
62
+ readonly [htmlBrand]: never;
63
+ }
64
+
65
+ /** What template authors may interpolate. `true` is deliberately absent. */
66
+ export type HtmlValue = string | number | false | null | undefined | Html | readonly HtmlValue[];
67
+
68
+ /** The node behind an Html. `template` = a tagged-template capture; `trusted` = trustedHtml. */
69
+ type Node =
70
+ | {
71
+ readonly [htmlBrand]: true;
72
+ readonly kind: "template";
73
+ readonly literal: readonly string[];
74
+ readonly values: readonly unknown[];
75
+ }
76
+ | {
77
+ readonly [htmlBrand]: true;
78
+ readonly kind: "trusted";
79
+ readonly markup: string;
80
+ readonly ranges: readonly Range[];
81
+ };
82
+
83
+ /**
84
+ * The brand guard, exported for INTERNAL use (the render engine needs to
85
+ * tell an Html from any other value without touching it). Not exported from
86
+ * index.ts: like trustedHtml/renderToString/escapeHtml, it is module wiring,
87
+ * not author-facing surface.
88
+ */
89
+ export function isHtml(value: unknown): value is Html {
90
+ return typeof value === "object" && value !== null && Object.hasOwn(value, htmlBrand);
91
+ }
92
+
93
+ function nodeOf(html: Html): Node {
94
+ const node = html as Html & Node;
95
+ if (node.kind !== "template" && node.kind !== "trusted") {
96
+ throw badValue("an impersonated Html value (a plain object is not an Html)");
97
+ }
98
+ return node;
99
+ }
100
+
101
+ function makeTemplateNode(literal: readonly string[], values: readonly unknown[]): Html {
102
+ return { [htmlBrand]: true, kind: "template", literal, values } as unknown as Html;
103
+ }
104
+
105
+ function makeTrustedNode(markup: string, ranges: readonly Range[]): Html {
106
+ return { [htmlBrand]: true, kind: "trusted", markup, ranges } as unknown as Html;
107
+ }
108
+
109
+ /**
110
+ * The fenced template. Captures the literal and the RAW values; rendering
111
+ * (escaping, range tracking, cycle/depth checks) happens lazily on each
112
+ * top-level render, so a shared array always shows its current contents.
113
+ */
114
+ export function html(strings: TemplateStringsArray, ...values: HtmlValue[]): Html {
115
+ return makeTemplateNode(strings, values);
116
+ }
117
+
118
+ /**
119
+ * Escape the five HTML structural characters, in ONE pass. The single
120
+ * character-class replace is what makes it safe: `&` is replaced before any
121
+ * other character is touched, so the entities it emits are never re-escaped
122
+ * (input `&amp;` → `&amp;amp;`, never `&amp;amp;amp;`), and no other
123
+ * character can smuggle a raw `&` past the check.
124
+ */
125
+ export function escapeHtml(value: string): string {
126
+ // The map is the escape table: one entry per structural character. The
127
+ // fallback is unreachable (the character class admits exactly these five)
128
+ // but keeps the callback total.
129
+ const TABLE: Record<string, string> = {
130
+ "&": "&amp;",
131
+ "<": "&lt;",
132
+ ">": "&gt;",
133
+ '"': "&quot;",
134
+ "'": "&#x27;",
135
+ };
136
+ return value.replace(/[&<>"']/g, (ch) => TABLE[ch] ?? ch);
137
+ }
138
+
139
+ function badValue(message: string): Diagnostic {
140
+ return {
141
+ code: "render.bad-value",
142
+ severity: "error",
143
+ sourcePath: "",
144
+ message: `template value rejected: ${message}`,
145
+ };
146
+ }
147
+
148
+ function describe(value: unknown): string {
149
+ try {
150
+ if (value === null) return "null";
151
+ const t = typeof value;
152
+ if (t !== "object" && t !== "function") return `${t} ${JSON.stringify(value)}`;
153
+ const name = (value as { constructor?: { name?: unknown } }).constructor?.name;
154
+ return typeof name === "string" && name !== "" ? `an object of type ${name}` : "an object";
155
+ } catch {
156
+ return "an object";
157
+ }
158
+ }
159
+
160
+ interface Rendered {
161
+ markup: string;
162
+ ranges: Range[];
163
+ }
164
+
165
+ interface RenderCtx {
166
+ /**
167
+ * Nodes and arrays on the current render PATH (cycle detection). Path-based
168
+ * (not global): the same value in TWO branches of one render (a diamond,
169
+ * e.g. an array interpolated twice) is legal and rendered twice — only a
170
+ * value that is its own ANCESTOR is rejected. Arrays are tracked too: an
171
+ * array that contains itself (arr.push(arr)) must die with a diagnostic,
172
+ * not a raw stack overflow.
173
+ */
174
+ seen: Set<unknown>;
175
+ /** Per-render cache: a node is rendered at most once per top-level render. */
176
+ memo: Map<Html, Rendered>;
177
+ }
178
+
179
+ const MAX_DEPTH = 64;
180
+
181
+ function renderNode(node: Html, depth: number, ctx: RenderCtx): Rendered {
182
+ const memoized = ctx.memo.get(node);
183
+ if (memoized) return memoized;
184
+ if (ctx.seen.has(node)) {
185
+ throw badValue(
186
+ "a cycle in the Html value graph: a value is its own ancestor (shared arrays render live, cycles do not terminate)",
187
+ );
188
+ }
189
+ if (depth > MAX_DEPTH) {
190
+ throw badValue(`nesting depth ${depth} exceeds the cap of ${MAX_DEPTH}`);
191
+ }
192
+ ctx.seen.add(node);
193
+ let rendered: Rendered;
194
+ try {
195
+ const shape = nodeOf(node);
196
+ if (shape.kind === "trusted") {
197
+ rendered = { markup: shape.markup, ranges: [...shape.ranges] };
198
+ } else {
199
+ const parts: string[] = [];
200
+ const ranges: Range[] = [];
201
+ let pos = 0;
202
+ for (let i = 0; i < shape.values.length; i++) {
203
+ parts.push(shape.literal[i]);
204
+ pos += shape.literal[i].length;
205
+ const len = renderValue(shape.values[i], depth + 1, ctx, pos, parts, ranges);
206
+ pos += len;
207
+ }
208
+ parts.push(shape.literal[shape.values.length]);
209
+ rendered = { markup: parts.join(""), ranges };
210
+ }
211
+ } finally {
212
+ ctx.seen.delete(node);
213
+ }
214
+ ctx.memo.set(node, rendered);
215
+ return rendered;
216
+ }
217
+
218
+ /**
219
+ * Render one value. Appends its markup to `parts`, records its (escaped)
220
+ * range in `ranges`, and returns the markup's length. Throws a
221
+ * render.bad-value Diagnostic for anything that has no safe rendering.
222
+ */
223
+ function renderValue(
224
+ value: unknown,
225
+ depth: number,
226
+ ctx: RenderCtx,
227
+ pos: number,
228
+ parts: string[],
229
+ ranges: Range[],
230
+ ): number {
231
+ if (value === null || value === undefined || value === false) {
232
+ parts.push("");
233
+ return 0;
234
+ }
235
+ switch (typeof value) {
236
+ case "string": {
237
+ const escaped = escapeHtml(value);
238
+ parts.push(escaped);
239
+ if (escaped.length > 0) ranges.push([pos, pos + escaped.length]);
240
+ return escaped.length;
241
+ }
242
+ case "number": {
243
+ if (!Number.isFinite(value)) {
244
+ throw badValue(
245
+ `${value} is not renderable (non-finite numbers are rejected; render the number's meaning, not its type name)`,
246
+ );
247
+ }
248
+ const text = String(value);
249
+ parts.push(text);
250
+ ranges.push([pos, pos + text.length]);
251
+ return text.length;
252
+ }
253
+ case "boolean": {
254
+ // false is handled above; only true reaches here
255
+ throw badValue(
256
+ "true is not renderable (false/null/undefined render as nothing; everything else must be named)",
257
+ );
258
+ }
259
+ case "bigint":
260
+ throw badValue(
261
+ "a bigint is not renderable (convert it to a string or finite number explicitly)",
262
+ );
263
+ case "symbol":
264
+ throw badValue("a symbol is not renderable");
265
+ case "function":
266
+ throw badValue(`${describe(value)} is not renderable`);
267
+ case "object": {
268
+ if (isHtml(value)) {
269
+ const child = renderNode(value, depth, ctx);
270
+ parts.push(child.markup);
271
+ for (const r of child.ranges) ranges.push([pos + r[0], pos + r[1]]);
272
+ return child.markup.length;
273
+ }
274
+ if (Array.isArray(value)) {
275
+ // Flatten recursively, joined with no separator. Elements render at
276
+ // the ARRAY'S depth (grouping does not add template depth) — but a
277
+ // NESTED array does add one: without that increment, a pathological
278
+ // 50k-deep array nesting is a raw RangeError (stack overflow)
279
+ // instead of a render.bad-value diagnostic (crust rule 1: honest
280
+ // failure, never an uncatchable crash).
281
+ if (depth > MAX_DEPTH) {
282
+ throw badValue(`array nesting depth ${depth} exceeds the cap of ${MAX_DEPTH}`);
283
+ }
284
+ if (ctx.seen.has(value)) {
285
+ throw badValue(
286
+ "a cycle in the Html value graph: an array is its own ancestor (shared arrays render live, cycles do not terminate)",
287
+ );
288
+ }
289
+ ctx.seen.add(value);
290
+ let len = 0;
291
+ try {
292
+ for (const element of value) {
293
+ len += renderValue(
294
+ element,
295
+ Array.isArray(element) ? depth + 1 : depth,
296
+ ctx,
297
+ pos + len,
298
+ parts,
299
+ ranges,
300
+ );
301
+ }
302
+ } finally {
303
+ ctx.seen.delete(value);
304
+ }
305
+ return len;
306
+ }
307
+ // Thenable check WITHOUT letting a throwing getter escape: the .then
308
+ // access is wrapped, and a failure here means "we cannot prove this is
309
+ // safe" — the answer is the same bad-value diagnostic, never the
310
+ // getter's error leaking out.
311
+ let then: unknown;
312
+ try {
313
+ then = (value as { then?: unknown }).then;
314
+ } catch {
315
+ throw badValue(
316
+ "an object whose .then access throws; it cannot be proven safe and is treated as unrenderable",
317
+ );
318
+ }
319
+ if (typeof then === "function") {
320
+ throw badValue("a Promise/thenable is not renderable (values are never awaited)");
321
+ }
322
+ throw badValue(
323
+ `${describe(value)} is not renderable (only Html, strings, finite numbers, and arrays of those are)`,
324
+ );
325
+ }
326
+ default:
327
+ throw badValue("a value of an unsupported type");
328
+ }
329
+ }
330
+
331
+ function renderRoot(root: Html): Rendered {
332
+ const ctx: RenderCtx = { seen: new Set(), memo: new Map() };
333
+ return renderNode(root, 0, ctx);
334
+ }
335
+
336
+ /**
337
+ * Render an Html to its raw markup. INTERNAL (no fence) — exported for
338
+ * tests and for the render chunk; page output must go through
339
+ * `finalizeDocument` so the fence actually runs.
340
+ */
341
+ export function renderToString(root: Html): string {
342
+ return renderRoot(root).markup;
343
+ }
344
+
345
+ /**
346
+ * Render an Html AND run the fence over the result. This is what the
347
+ * renderer (render chunk) calls per page: a violation throws a BuildError
348
+ * carrying ALL fence diagnostics (never the first one only).
349
+ */
350
+ export function finalizeDocument(root: Html, opts: UrlPolicyOptions): string {
351
+ const rendered = renderRoot(root);
352
+ const diagnostics = runFence(rendered.markup, rendered.ranges, opts);
353
+ if (diagnostics.length > 0) throw new BuildError(diagnostics);
354
+ return rendered.markup;
355
+ }
356
+
357
+ /**
358
+ * Build an Html from TRUSTED internal markup plus explicit value ranges
359
+ * (the markdown renderer's escape output lands here: the markup is already
360
+ * escaped by the renderer, and the ranges mark where its tracked values are,
361
+ * so the fence polices them exactly like html-template values).
362
+ *
363
+ * Internal — exported from this module only, NOT from index.ts. Ranges must
364
+ * be well-formed (integers, 0 ≤ start ≤ end ≤ markup.length, sorted,
365
+ * non-overlapping — the invariants the fence's overlap tests rely on).
366
+ */
367
+ export function trustedHtml(markup: string, ranges: Range[] = []): Html {
368
+ if (typeof markup !== "string") {
369
+ throw badValue(
370
+ `trustedHtml markup must be a string, received ${markup === null ? "null" : typeof markup}`,
371
+ );
372
+ }
373
+ for (let i = 0; i < ranges.length; i++) {
374
+ const r = ranges[i];
375
+ if (
376
+ r.length !== 2 ||
377
+ !Number.isInteger(r[0]) ||
378
+ !Number.isInteger(r[1]) ||
379
+ r[0] < 0 ||
380
+ r[0] > r[1] ||
381
+ r[1] > markup.length
382
+ ) {
383
+ throw badValue(
384
+ `trustedHtml range ${JSON.stringify([...r])} is malformed (integers, 0 ≤ start ≤ end ≤ ${markup.length})`,
385
+ );
386
+ }
387
+ if (i > 0) {
388
+ const prev = ranges[i - 1];
389
+ if (r[0] < prev[1]) {
390
+ throw badValue(
391
+ `trustedHtml ranges are out of order or overlapping (${JSON.stringify([...prev])} before ${JSON.stringify([...r])})`,
392
+ );
393
+ }
394
+ }
395
+ }
396
+ return makeTrustedNode(markup, ranges);
397
+ }
398
+
399
+ // (rangesOverlap / Range live in fence.ts — tests and internal modules import
400
+ // them from there, so nothing is re-exported here.)