saturndocs 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/{auth-OIEL34E4.js → auth-47SI6KTG.js} +4 -4
  2. package/dist/broken-links-EOEGVH4F.js +275 -0
  3. package/dist/build-OLTD5RJQ.js +139 -0
  4. package/dist/{chunk-32ATWMIS.js → chunk-27ARMXM2.js} +7 -6
  5. package/dist/{chunk-RKM7YWPD.js → chunk-33MGV73K.js} +11 -5
  6. package/dist/{chunk-BOWRQKXR.js → chunk-4MJYA6R5.js} +10 -8
  7. package/dist/{chunk-VDGVERLX.js → chunk-7QGSIPAS.js} +3 -3
  8. package/dist/{chunk-T3MCJYSF.js → chunk-ATM2LU6H.js} +1 -1
  9. package/dist/{chunk-WXLJZ7RD.js → chunk-C62AROBZ.js} +3 -3
  10. package/dist/chunk-CM2ONKCQ.js +1650 -0
  11. package/dist/{chunk-3KCCCMQY.js → chunk-F5G7PDQJ.js} +556 -117
  12. package/dist/{chunk-3EW6ZPL6.js → chunk-FIFAZLRQ.js} +19 -21
  13. package/dist/{chunk-5ZYUBLEH.js → chunk-GNR5NWNR.js} +2012 -1878
  14. package/dist/{chunk-3X2NBWZN.js → chunk-JFYMBFDW.js} +5 -25
  15. package/dist/{chunk-WMS6FUKK.js → chunk-JSKBT765.js} +86 -109
  16. package/dist/{chunk-IJOYWJVM.js → chunk-L6EE6XS2.js} +7 -7
  17. package/dist/chunk-LDE53VKA.js +146 -0
  18. package/dist/chunk-LLRWUKIR.js +62 -0
  19. package/dist/{chunk-E3G56DR2.js → chunk-MXJOVTOT.js} +606 -3
  20. package/dist/chunk-NE6SDXXB.js +52 -0
  21. package/dist/chunk-OWKBGNGZ.js +72 -0
  22. package/dist/{chunk-TEYHAN2L.js → chunk-RI5COFYL.js} +2 -2
  23. package/dist/{chunk-6EKGBIUR.js → chunk-RNRRFICE.js} +1 -1
  24. package/dist/{chunk-PU37LVIF.js → chunk-SDNJSBGO.js} +9 -5
  25. package/dist/{chunk-IWIVHHZI.js → chunk-SIGMRKFJ.js} +8 -7
  26. package/dist/{chunk-YPWPLIEZ.js → chunk-UJCRJ4XU.js} +3 -3
  27. package/dist/chunk-WDOLOQAV.js +259 -0
  28. package/dist/{chunk-FUZE54DG.js → chunk-X2YU7MAC.js} +26 -16
  29. package/dist/cli.js +3 -3
  30. package/dist/{coverage-SRIA65FT.js → coverage-I3FWCRWG.js} +4 -4
  31. package/dist/dev-PXZCETLB.js +243 -0
  32. package/dist/{dist-LJSALT4X.js → dist-RJ3HLSC7.js} +8 -3
  33. package/dist/index.d.ts +1 -1
  34. package/dist/index.js +60 -110
  35. package/dist/{init-Y3GDNDWW.js → init-GQELTILS.js} +4 -5
  36. package/dist/{lint-XM26WIGE.js → lint-MR7LHMLU.js} +2 -2
  37. package/dist/{login-HIXLPRUI.js → login-QW5GZLWK.js} +4 -4
  38. package/dist/{manage-3HEBB3EQ.js → manage-OTGX2SGZ.js} +4 -4
  39. package/dist/{nav-K43WZJ4J.js → nav-3GHG5U5B.js} +4 -4
  40. package/dist/{openapiCheck-CL2AH3YC.js → openapiCheck-XAZ6FOF2.js} +4 -6
  41. package/dist/pages-BA3MMNSL.js +16 -0
  42. package/dist/{read-RKT6HUZ7.js → read-6RAHFNPS.js} +25 -11
  43. package/dist/{read-DYGYUOFK.js → read-UCTHVWS2.js} +11 -10
  44. package/dist/renderer-76D7VFQ3.js +441 -0
  45. package/dist/requests-6OIP4LGE.js +13 -0
  46. package/dist/{schema-QMJMGD5P.js → schema-OEKCGF6Y.js} +3 -3
  47. package/dist/{sites-JKS25SEM.js → sites-L6DPTMX6.js} +5 -5
  48. package/dist/{status-FM2ALQUJ.js → status-PMVNHRK6.js} +4 -4
  49. package/dist/{suggestions-Z6XIHMFN.js → suggestions-WBWQP2UN.js} +29 -20
  50. package/dist/validate-LY3ZSHSV.js +12 -0
  51. package/package.json +10 -4
  52. package/dist/chunk-HBSJ4Z4S.js +0 -53
  53. package/dist/chunk-W3FZTCKV.js +0 -590
  54. package/dist/pages-4VWB7Z4S.js +0 -16
  55. package/dist/requests-CZYE6GI3.js +0 -13
  56. package/dist/unavailable-DVPNUO3J.js +0 -40
  57. package/dist/validate-X42T4TJ6.js +0 -12
@@ -0,0 +1,1650 @@
1
+ import {
2
+ collectOutsideRootFiles,
3
+ configLocator,
4
+ validateDocsReport
5
+ } from "./chunk-JSKBT765.js";
6
+ import {
7
+ SOURCE_ALLOWED_ROOTS,
8
+ SOURCE_LIMITS,
9
+ canonicalJson,
10
+ collectComponentCalls,
11
+ customerComponentRegistry,
12
+ frontmatterPolicy,
13
+ normalizeComponentMarkdown,
14
+ validateBundleStructure
15
+ } from "./chunk-GNR5NWNR.js";
16
+ import {
17
+ parseDocsConfig
18
+ } from "./chunk-MXJOVTOT.js";
19
+
20
+ // src/lib/preview/components.ts
21
+ import { spawn } from "child_process";
22
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs";
23
+ import { tmpdir } from "os";
24
+ import { finished } from "stream/promises";
25
+ import { basename, join } from "path";
26
+
27
+ // ../component-abi/dist/index.js
28
+ import { parseFragment } from "parse5";
29
+ var COMPONENT_PROTOCOL_VERSION = 1;
30
+ var COMPONENT_RUNTIME_REVISION = "r1";
31
+ var COMPONENT_REACT_VERSION = "19.3.0";
32
+ var RUNTIME_BASE = `/_saturndocs/runtime/${COMPONENT_RUNTIME_REVISION}-react-${COMPONENT_REACT_VERSION}`;
33
+ var COMPONENT_RUNTIME_PATHS = Object.freeze({
34
+ react: `${RUNTIME_BASE}/react.mjs`,
35
+ jsxRuntime: `${RUNTIME_BASE}/jsx-runtime.mjs`,
36
+ reactDomClient: `${RUNTIME_BASE}/react-dom-client.mjs`
37
+ });
38
+ var COMPONENT_RUNTIME_DIRECTORY = RUNTIME_BASE.slice(1);
39
+ var COMPONENT_LIMITS = Object.freeze({
40
+ maxCalls: 5e3,
41
+ maxPropsBytesPerCall: 524288,
42
+ maxPropsBytesTotal: 16777216,
43
+ maxHtmlBytesPerCall: 1048576,
44
+ maxMarkdownBytesPerCall: 262144,
45
+ maxMarkdownBytesTotal: 16777216,
46
+ maxChunkBytes: 524288,
47
+ maxOutputBytes: 33554432
48
+ });
49
+ var encoder = new TextEncoder();
50
+ function utf8Length(value) {
51
+ return encoder.encode(value).byteLength;
52
+ }
53
+ async function sha256Hex(value) {
54
+ const bytes = typeof value === "string" ? encoder.encode(value) : new Uint8Array(value);
55
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
56
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
57
+ }
58
+ function identifierPrefix(callId) {
59
+ let a = 2166136261;
60
+ let b = 16777619;
61
+ for (let index = 0; index < callId.length; index += 1) {
62
+ const code = callId.charCodeAt(index);
63
+ a = Math.imul(a ^ code, 16777619) >>> 0;
64
+ b = Math.imul(b ^ code, 1540483477) >>> 0;
65
+ }
66
+ return `c${a.toString(36)}${b.toString(36)}-`;
67
+ }
68
+ async function buildRenderInput(calls) {
69
+ if (calls.length > COMPONENT_LIMITS.maxCalls) {
70
+ throw new Error(`the site has ${calls.length} component calls; the limit is ${COMPONENT_LIMITS.maxCalls}`);
71
+ }
72
+ let totalProps = 0;
73
+ const seen = /* @__PURE__ */ new Set();
74
+ const input = [];
75
+ for (const call of calls) {
76
+ if (seen.has(call.id)) throw new Error(`duplicate component call id ${call.id}`);
77
+ seen.add(call.id);
78
+ const json = canonicalJson(call.props);
79
+ const bytes = utf8Length(json);
80
+ if (bytes > COMPONENT_LIMITS.maxPropsBytesPerCall) throw new Error(`${call.id}: props are ${bytes} bytes; the limit is ${COMPONENT_LIMITS.maxPropsBytesPerCall}`);
81
+ totalProps += bytes;
82
+ if (totalProps > COMPONENT_LIMITS.maxPropsBytesTotal) throw new Error(`component props total more than ${COMPONENT_LIMITS.maxPropsBytesTotal} bytes`);
83
+ input.push({
84
+ id: call.id,
85
+ component: call.component,
86
+ props: call.props,
87
+ propsDigest: await sha256Hex(json),
88
+ identifierPrefix: identifierPrefix(call.id)
89
+ });
90
+ }
91
+ return {
92
+ version: COMPONENT_PROTOCOL_VERSION,
93
+ runtime: { react: COMPONENT_RUNTIME_PATHS.react, jsxRuntime: COMPONENT_RUNTIME_PATHS.jsxRuntime },
94
+ calls: input
95
+ };
96
+ }
97
+ var HTML_NS = "http://www.w3.org/1999/xhtml";
98
+ var SVG_NS = "http://www.w3.org/2000/svg";
99
+ var PHRASING = /* @__PURE__ */ new Set([
100
+ "a",
101
+ "abbr",
102
+ "b",
103
+ "br",
104
+ "button",
105
+ "code",
106
+ "em",
107
+ "i",
108
+ "img",
109
+ "input",
110
+ "kbd",
111
+ "label",
112
+ "mark",
113
+ "s",
114
+ "select",
115
+ "small",
116
+ "span",
117
+ "strong",
118
+ "sub",
119
+ "sup",
120
+ "svg",
121
+ "textarea",
122
+ "time",
123
+ "u",
124
+ "wbr",
125
+ "option",
126
+ "optgroup"
127
+ ]);
128
+ var HTML_ELEMENTS = /* @__PURE__ */ new Set([
129
+ ...PHRASING,
130
+ "article",
131
+ "aside",
132
+ "blockquote",
133
+ "caption",
134
+ "col",
135
+ "colgroup",
136
+ "dd",
137
+ "details",
138
+ "div",
139
+ "dl",
140
+ "dt",
141
+ "fieldset",
142
+ "figcaption",
143
+ "figure",
144
+ "footer",
145
+ "header",
146
+ "hr",
147
+ "legend",
148
+ "li",
149
+ "nav",
150
+ "ol",
151
+ "p",
152
+ "pre",
153
+ "section",
154
+ "summary",
155
+ "table",
156
+ "tbody",
157
+ "td",
158
+ "tfoot",
159
+ "th",
160
+ "thead",
161
+ "tr",
162
+ "ul"
163
+ ]);
164
+ var SVG_ELEMENTS = /* @__PURE__ */ new Set([
165
+ "svg",
166
+ "g",
167
+ "path",
168
+ "circle",
169
+ "ellipse",
170
+ "rect",
171
+ "line",
172
+ "polyline",
173
+ "polygon",
174
+ "text",
175
+ "tspan",
176
+ "defs",
177
+ "marker",
178
+ "title",
179
+ "desc",
180
+ "lineargradient",
181
+ "radialgradient",
182
+ "stop",
183
+ "clippath",
184
+ "mask",
185
+ "symbol",
186
+ "use",
187
+ "animate",
188
+ "animatetransform",
189
+ "animatemotion",
190
+ "set"
191
+ ]);
192
+ var GLOBAL_ATTRIBUTES = /* @__PURE__ */ new Set(["class", "id", "title", "role", "lang", "dir", "tabindex", "hidden", "style"]);
193
+ var ELEMENT_ATTRIBUTES = {
194
+ a: /* @__PURE__ */ new Set(["href", "target", "rel"]),
195
+ img: /* @__PURE__ */ new Set(["src", "alt", "width", "height", "loading", "decoding"]),
196
+ input: /* @__PURE__ */ new Set(["type", "value", "checked", "disabled", "readonly", "placeholder", "name", "min", "max", "step", "autocomplete", "spellcheck", "maxlength", "size"]),
197
+ label: /* @__PURE__ */ new Set(["for"]),
198
+ select: /* @__PURE__ */ new Set(["name", "disabled", "multiple", "size"]),
199
+ option: /* @__PURE__ */ new Set(["value", "selected", "disabled", "label"]),
200
+ optgroup: /* @__PURE__ */ new Set(["label", "disabled"]),
201
+ textarea: /* @__PURE__ */ new Set(["name", "rows", "cols", "placeholder", "readonly", "disabled", "maxlength", "spellcheck"]),
202
+ button: /* @__PURE__ */ new Set(["type", "disabled", "name", "value"]),
203
+ td: /* @__PURE__ */ new Set(["colspan", "rowspan", "headers"]),
204
+ th: /* @__PURE__ */ new Set(["colspan", "rowspan", "headers", "scope", "abbr"]),
205
+ col: /* @__PURE__ */ new Set(["span"]),
206
+ colgroup: /* @__PURE__ */ new Set(["span"]),
207
+ ol: /* @__PURE__ */ new Set(["start", "reversed", "type"]),
208
+ li: /* @__PURE__ */ new Set(["value"]),
209
+ time: /* @__PURE__ */ new Set(["datetime"]),
210
+ details: /* @__PURE__ */ new Set(["open"]),
211
+ abbr: /* @__PURE__ */ new Set(["title"])
212
+ };
213
+ var SVG_ATTRIBUTES = /* @__PURE__ */ new Set([
214
+ "viewbox",
215
+ "xmlns",
216
+ "fill",
217
+ "stroke",
218
+ "stroke-width",
219
+ "stroke-linecap",
220
+ "stroke-linejoin",
221
+ "stroke-dasharray",
222
+ "stroke-dashoffset",
223
+ "stroke-miterlimit",
224
+ "d",
225
+ "cx",
226
+ "cy",
227
+ "r",
228
+ "rx",
229
+ "ry",
230
+ "x",
231
+ "y",
232
+ "x1",
233
+ "y1",
234
+ "x2",
235
+ "y2",
236
+ "width",
237
+ "height",
238
+ "points",
239
+ "transform",
240
+ "opacity",
241
+ "fill-opacity",
242
+ "stroke-opacity",
243
+ "fill-rule",
244
+ "clip-rule",
245
+ "font-size",
246
+ "font-family",
247
+ "font-weight",
248
+ "font-style",
249
+ "text-anchor",
250
+ "dominant-baseline",
251
+ "letter-spacing",
252
+ "offset",
253
+ "stop-color",
254
+ "stop-opacity",
255
+ "gradientunits",
256
+ "gradienttransform",
257
+ "markerwidth",
258
+ "markerheight",
259
+ "refx",
260
+ "refy",
261
+ "orient",
262
+ "markerunits",
263
+ "preserveaspectratio",
264
+ "clip-path",
265
+ "mask",
266
+ "marker-start",
267
+ "marker-mid",
268
+ "marker-end",
269
+ "dur",
270
+ "begin",
271
+ "end",
272
+ "repeatcount",
273
+ "repeatdur",
274
+ "values",
275
+ "keytimes",
276
+ "keysplines",
277
+ "calcmode",
278
+ "from",
279
+ "to",
280
+ "by",
281
+ "type",
282
+ "attributename",
283
+ "additive",
284
+ "accumulate",
285
+ "rotate",
286
+ "path",
287
+ "href",
288
+ "xlink:href",
289
+ "focusable",
290
+ "dx",
291
+ "dy",
292
+ "pathlength",
293
+ "vector-effect",
294
+ "shape-rendering",
295
+ "paint-order"
296
+ ]);
297
+ var ID_REFERENCE_ATTRIBUTES = ["for", "headers", "aria-labelledby", "aria-describedby", "aria-controls", "aria-owns", "aria-activedescendant", "aria-details", "aria-errormessage", "aria-flowto"];
298
+ var INPUT_TYPES = /* @__PURE__ */ new Set(["text", "color", "checkbox", "radio", "number", "search", "email", "url", "range", "tel"]);
299
+ var REACT_COMMENT = /^(?: |\$|\/\$|\$\?|\$!|&|\/&)?$/;
300
+ var RESERVED_TOKEN = /^(?:gs-|astro-|pagefind)/i;
301
+ var ID_PATTERN = /^[A-Za-z_«][^\s"'<>&]*$/u;
302
+ var LOCAL_REFERENCE = /^url\(\s*#([^)\s]+)\s*\)$/;
303
+ var MAX_DEPTH = 64;
304
+ var MAX_ELEMENTS = 2e4;
305
+ var Rejection = class extends Error {
306
+ };
307
+ function attributeName(attribute) {
308
+ return (attribute.prefix ? `${attribute.prefix}:${attribute.name}` : attribute.name).toLowerCase();
309
+ }
310
+ function isSafeComponentUrl(raw) {
311
+ if (raw.length === 0 || raw.trim() !== raw || /[\u0000-\u001f\u007f\s\\]/u.test(raw) || raw.startsWith("//")) return false;
312
+ if (raw.startsWith("/") || raw.startsWith("./") || raw.startsWith("../") || raw.startsWith("#") || raw.startsWith("?")) return true;
313
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(raw)?.[1]?.toLowerCase();
314
+ if (scheme !== void 0) return scheme === "http" || scheme === "https" || scheme === "mailto" || scheme === "tel";
315
+ return !raw.includes(":");
316
+ }
317
+ function checkStyle(value, where) {
318
+ if (/url\s*\(|expression\s*\(|javascript:|@import|\\|[<>]|behavior|binding/i.test(value)) {
319
+ throw new Rejection(`${where}: style uses a construct that can load or run content`);
320
+ }
321
+ for (const declaration of value.split(";")) {
322
+ if (declaration.trim() === "") continue;
323
+ const colon = declaration.indexOf(":");
324
+ if (colon <= 0) throw new Rejection(`${where}: style declaration "${declaration.trim()}" is malformed`);
325
+ const property = declaration.slice(0, colon).trim().toLowerCase();
326
+ const propertyValue = declaration.slice(colon + 1).trim().toLowerCase();
327
+ if (!/^-?[a-z][a-z0-9-]*$/.test(property)) throw new Rejection(`${where}: style property "${property}" is not allowed`);
328
+ if (property === "position" && propertyValue !== "static" && propertyValue !== "relative") {
329
+ throw new Rejection(`${where}: position: ${propertyValue} can cover platform controls`);
330
+ }
331
+ if (property === "z-index") throw new Rejection(`${where}: z-index can cover platform controls`);
332
+ }
333
+ }
334
+ function checkClass(value, where) {
335
+ for (const token of value.split(/\s+/)) {
336
+ if (token !== "" && RESERVED_TOKEN.test(token)) throw new Rejection(`${where}: class ${token} is reserved for the platform`);
337
+ }
338
+ }
339
+ function checkElement(element, state, depth) {
340
+ const name = element.tagName.toLowerCase();
341
+ const where = `<${name}>`;
342
+ state.elements += 1;
343
+ if (state.elements > MAX_ELEMENTS) throw new Rejection(`component output has more than ${MAX_ELEMENTS} elements`);
344
+ if (depth > MAX_DEPTH) throw new Rejection(`component output nests deeper than ${MAX_DEPTH} elements`);
345
+ if (element.namespaceURI === HTML_NS) {
346
+ if (!HTML_ELEMENTS.has(name)) throw new Rejection(`${where} is not allowed in component output`);
347
+ if (state.inline && depth === 0 && !PHRASING.has(name)) throw new Rejection(`${where} cannot appear in an inline component call`);
348
+ } else if (element.namespaceURI === SVG_NS) {
349
+ if (!SVG_ELEMENTS.has(name)) throw new Rejection(`SVG ${where} is not allowed in component output`);
350
+ } else {
351
+ throw new Rejection(`${where} uses a namespace that is not allowed`);
352
+ }
353
+ const allowed = element.namespaceURI === SVG_NS ? SVG_ATTRIBUTES : ELEMENT_ATTRIBUTES[name];
354
+ for (const attribute of element.attrs) {
355
+ const attr2 = attributeName(attribute);
356
+ const value = attribute.value;
357
+ if (attr2.startsWith("on")) throw new Rejection(`${where}: event handler attribute ${attr2} is not allowed`);
358
+ if (attr2.startsWith("data-")) {
359
+ if (/^data-(?:gs|astro|pagefind)/.test(attr2)) throw new Rejection(`${where}: attribute ${attr2} is reserved for the platform`);
360
+ continue;
361
+ }
362
+ if (attr2.startsWith("aria-")) {
363
+ if (ID_REFERENCE_ATTRIBUTES.includes(attr2)) {
364
+ for (const id of value.split(/\s+/)) if (id) state.references.push({ id, where: `${where} ${attr2}` });
365
+ }
366
+ continue;
367
+ }
368
+ if (!GLOBAL_ATTRIBUTES.has(attr2) && !(allowed?.has(attr2) ?? false)) throw new Rejection(`${where}: attribute ${attr2} is not allowed`);
369
+ if (attr2 === "style") checkStyle(value, where);
370
+ if (attr2 === "class") checkClass(value, where);
371
+ if (attr2 === "tabindex" && value !== "0" && value !== "-1") throw new Rejection(`${where}: tabindex must be 0 or -1`);
372
+ if (attr2 === "id") {
373
+ if (!ID_PATTERN.test(value) || RESERVED_TOKEN.test(value)) throw new Rejection(`${where}: id "${value}" is not allowed`);
374
+ if (!value.startsWith(state.prefix) && !value.startsWith(`_${state.prefix}`)) {
375
+ throw new Rejection(`${where}: id "${value}" must come from React useId so it cannot collide with other calls or the page`);
376
+ }
377
+ if (state.ids.has(value)) throw new Rejection(`${where}: id "${value}" appears twice`);
378
+ state.ids.add(value);
379
+ }
380
+ if (attr2 === "for" || attr2 === "headers") {
381
+ for (const id of value.split(/\s+/)) if (id) state.references.push({ id, where: `${where} ${attr2}` });
382
+ }
383
+ if (attr2 === "target" && value !== "_blank") throw new Rejection(`${where}: target must be _blank`);
384
+ if (name === "input" && attr2 === "type" && !INPUT_TYPES.has(value.toLowerCase())) throw new Rejection(`${where}: input type ${value} is not allowed`);
385
+ if (name === "button" && attr2 === "type" && value.toLowerCase() !== "button") throw new Rejection(`${where}: buttons must use type="button"`);
386
+ if (name === "input" && attr2 === "name" && !value.startsWith(state.prefix) && !value.startsWith(`_${state.prefix}`)) {
387
+ throw new Rejection(`${where}: input name "${value}" must come from React useId so radio groups in different calls stay separate`);
388
+ }
389
+ if ((attr2 === "href" || attr2 === "src") && element.namespaceURI === HTML_NS && !isSafeComponentUrl(value)) {
390
+ throw new Rejection(`${where}: ${attr2} "${value}" uses a scheme that is not allowed`);
391
+ }
392
+ if (element.namespaceURI === SVG_NS) {
393
+ if (attr2 === "href" || attr2 === "xlink:href") {
394
+ if (!value.startsWith("#")) throw new Rejection(`${where}: SVG ${attr2} must reference an element in the component`);
395
+ state.references.push({ id: value.slice(1), where: `${where} ${attr2}` });
396
+ }
397
+ if (attr2 === "attributename" && /href/i.test(value)) throw new Rejection(`${where}: animating ${value} is not allowed`);
398
+ if (/url\s*\(/i.test(value)) {
399
+ const local = LOCAL_REFERENCE.exec(value.trim());
400
+ if (local === null) throw new Rejection(`${where}: ${attr2} may reference only an element in the component`);
401
+ state.references.push({ id: local[1], where: `${where} ${attr2}` });
402
+ }
403
+ }
404
+ }
405
+ if (name === "button" && element.namespaceURI === HTML_NS && !element.attrs.some((attribute) => attributeName(attribute) === "type")) {
406
+ throw new Rejection(`${where}: buttons must use type="button"`);
407
+ }
408
+ walkChildren(element, state, depth + 1);
409
+ }
410
+ function walkChildren(parent, state, depth) {
411
+ const children2 = "content" in parent && parent.nodeName === "template" ? [] : parent.childNodes;
412
+ for (const child of children2) {
413
+ if (child.nodeName === "#text") continue;
414
+ if (child.nodeName === "#comment") {
415
+ if (!REACT_COMMENT.test(child.data)) throw new Rejection("comments other than React markers are not allowed");
416
+ continue;
417
+ }
418
+ if ("tagName" in child) {
419
+ checkElement(child, state, depth);
420
+ continue;
421
+ }
422
+ throw new Rejection(`node ${child.nodeName} is not allowed`);
423
+ }
424
+ }
425
+ function startTagCount(html) {
426
+ return html.match(/<[A-Za-z][A-Za-z0-9-]*/g)?.length ?? 0;
427
+ }
428
+ function contextElement(inline2) {
429
+ const holder = parseFragment(inline2 ? "<span></span>" : "<div></div>");
430
+ return holder.childNodes[0];
431
+ }
432
+ function approveComponentHtml(html, options) {
433
+ try {
434
+ const fragment = parseFragment(contextElement(options.inline), html, {});
435
+ const state = { prefix: options.identifierPrefix, inline: options.inline, ids: /* @__PURE__ */ new Set(), references: [], elements: 0 };
436
+ walkChildren(fragment, state, 0);
437
+ if (state.elements !== startTagCount(html)) {
438
+ throw new Rejection("the HTML parser had to repair this markup (for example a table row outside a table, or a block inside a paragraph); the browser would build a different tree and hydration would fail");
439
+ }
440
+ for (const reference of state.references) {
441
+ if (!state.ids.has(reference.id)) throw new Rejection(`${reference.where} references "${reference.id}", which is not in this component's output`);
442
+ }
443
+ return { ok: true, html, ids: [...state.ids] };
444
+ } catch (error) {
445
+ if (error instanceof Rejection) return { ok: false, reason: error.message };
446
+ throw error;
447
+ }
448
+ }
449
+ function parseApprovedHtml(html, inline2) {
450
+ return parseFragment(contextElement(inline2), html, {});
451
+ }
452
+ var BLOCKS = /* @__PURE__ */ new Set([
453
+ "article",
454
+ "aside",
455
+ "footer",
456
+ "header",
457
+ "nav",
458
+ "section",
459
+ "blockquote",
460
+ "dd",
461
+ "details",
462
+ "div",
463
+ "dl",
464
+ "dt",
465
+ "fieldset",
466
+ "figcaption",
467
+ "figure",
468
+ "hr",
469
+ "legend",
470
+ "li",
471
+ "ol",
472
+ "p",
473
+ "pre",
474
+ "summary",
475
+ "table",
476
+ "ul",
477
+ "tbody",
478
+ "thead",
479
+ "tfoot",
480
+ "tr",
481
+ "caption"
482
+ ]);
483
+ function attr(element, name) {
484
+ return element.attrs.find((attribute) => attribute.name.toLowerCase() === name)?.value;
485
+ }
486
+ function hidden(element) {
487
+ return attr(element, "hidden") !== void 0 || attr(element, "aria-hidden") === "true";
488
+ }
489
+ function escapeText(value) {
490
+ return value.replace(/([\\`*_[\]<>|])/g, "\\$1");
491
+ }
492
+ function codeSpan(value) {
493
+ const longest = Math.max(0, ...(value.match(/`+/g) ?? []).map((run) => run.length));
494
+ const fence = "`".repeat(longest + 1);
495
+ const pad = value.startsWith("`") || value.endsWith("`") ? " " : "";
496
+ return `${fence}${pad}${value}${pad}${fence}`;
497
+ }
498
+ function textContent(node) {
499
+ if (node.nodeName === "#text") return node.value;
500
+ if ("childNodes" in node) return node.childNodes.map(textContent).join("");
501
+ return "";
502
+ }
503
+ function children(node) {
504
+ return "childNodes" in node ? node.childNodes : [];
505
+ }
506
+ function inline(nodes) {
507
+ let out = "";
508
+ for (const node of nodes) {
509
+ if (node.nodeName === "#text") {
510
+ out += escapeText(node.value.replace(/\s+/g, " "));
511
+ continue;
512
+ }
513
+ if (!("tagName" in node) || hidden(node)) continue;
514
+ const name = node.tagName.toLowerCase();
515
+ switch (name) {
516
+ case "strong":
517
+ case "b": {
518
+ const inner = inline(node.childNodes).trim();
519
+ if (inner) out += `**${inner}**`;
520
+ break;
521
+ }
522
+ case "em":
523
+ case "i": {
524
+ const inner = inline(node.childNodes).trim();
525
+ if (inner) out += `*${inner}*`;
526
+ break;
527
+ }
528
+ case "code":
529
+ case "kbd":
530
+ out += codeSpan(textContent(node));
531
+ break;
532
+ case "a": {
533
+ const inner = inline(node.childNodes).trim() || attr(node, "aria-label") || "";
534
+ const href = attr(node, "href");
535
+ out += href !== void 0 && isSafeComponentUrl(href) && inner ? `[${inner}](${href})` : inner;
536
+ break;
537
+ }
538
+ case "img": {
539
+ const src = attr(node, "src");
540
+ const alt = (attr(node, "alt") ?? "").trim();
541
+ if (src !== void 0 && isSafeComponentUrl(src) && alt) out += `![${escapeText(alt)}](${src})`;
542
+ break;
543
+ }
544
+ case "br":
545
+ out += "\n";
546
+ break;
547
+ case "wbr":
548
+ break;
549
+ case "input": {
550
+ const value = attr(node, "value");
551
+ const type = (attr(node, "type") ?? "text").toLowerCase();
552
+ if (type === "checkbox" || type === "radio") out += attr(node, "checked") !== void 0 ? "[x]" : "[ ]";
553
+ else if (value) out += codeSpan(value);
554
+ break;
555
+ }
556
+ case "select": {
557
+ const options = node.childNodes.filter((child) => "tagName" in child);
558
+ const selected = options.find((option) => attr(option, "selected") !== void 0) ?? options[0];
559
+ if (selected) out += codeSpan(textContent(selected).trim());
560
+ break;
561
+ }
562
+ case "textarea": {
563
+ const value = textContent(node);
564
+ if (value) out += codeSpan(value);
565
+ break;
566
+ }
567
+ case "svg": {
568
+ const label = attr(node, "aria-label") ?? node.childNodes.filter((child) => "tagName" in child && child.tagName.toLowerCase() === "title").map(textContent).join(" ");
569
+ if (label?.trim()) out += escapeText(label.trim());
570
+ break;
571
+ }
572
+ default:
573
+ out += BLOCKS.has(name) ? ` ${inline(node.childNodes)} ` : inline(node.childNodes);
574
+ }
575
+ }
576
+ return out;
577
+ }
578
+ function tableMarkdown(table) {
579
+ const rows = [];
580
+ const collect = (node) => {
581
+ if (!("tagName" in node)) return;
582
+ if (node.tagName.toLowerCase() === "tr") rows.push(node);
583
+ else for (const child of node.childNodes) collect(child);
584
+ };
585
+ for (const child of table.childNodes) collect(child);
586
+ const cells = rows.map((row) => row.childNodes.filter((cell) => "tagName" in cell && /^t[dh]$/i.test(cell.tagName)).map((cell) => inline(cell.childNodes).replace(/\s+/g, " ").trim().replace(/\|/g, "\\|")));
587
+ if (cells.length === 0) return "";
588
+ const width = Math.max(...cells.map((row) => row.length));
589
+ if (width > 64 || cells.length * width > 1e5) throw new Error("component table is too large to convert to Markdown");
590
+ const pad = (row) => [...row, ...Array(width - row.length).fill("")];
591
+ const lines = [pad(cells[0]), Array(width).fill("---"), ...cells.slice(1).map(pad)];
592
+ return lines.map((row) => `| ${row.join(" | ")} |`).join("\n");
593
+ }
594
+ function blocks(nodes, out) {
595
+ let pending = [];
596
+ const flush = () => {
597
+ const text = inline(pending).replace(/[ \t]+/g, " ").replace(/ *\n */g, "\n").trim();
598
+ if (text) out.push(text);
599
+ pending = [];
600
+ };
601
+ for (const node of nodes) {
602
+ if (!("tagName" in node)) {
603
+ if (node.nodeName === "#text") pending.push(node);
604
+ continue;
605
+ }
606
+ const name = node.tagName.toLowerCase();
607
+ if (hidden(node)) continue;
608
+ if (!BLOCKS.has(name)) {
609
+ pending.push(node);
610
+ continue;
611
+ }
612
+ flush();
613
+ switch (name) {
614
+ case "pre": {
615
+ const code = textContent(node).replace(/\n$/, "");
616
+ const fence = "`".repeat(Math.max(3, Math.max(0, ...(code.match(/`+/g) ?? []).map((run) => run.length)) + 1));
617
+ out.push(`${fence}
618
+ ${code}
619
+ ${fence}`);
620
+ break;
621
+ }
622
+ case "ul":
623
+ case "ol": {
624
+ const ordered = name === "ol";
625
+ let index = Number(attr(node, "start") ?? "1") || 1;
626
+ const items = node.childNodes.filter((child) => "tagName" in child && child.tagName.toLowerCase() === "li" && !hidden(child));
627
+ const lines = items.map((item) => {
628
+ const inner = [];
629
+ blocks(item.childNodes, inner);
630
+ const marker = ordered ? `${index++}. ` : "- ";
631
+ return inner.join("\n\n").split("\n").map((line, position) => (position === 0 ? marker : " ".repeat(marker.length)) + line).join("\n");
632
+ });
633
+ if (lines.length > 0) out.push(lines.join("\n"));
634
+ break;
635
+ }
636
+ case "table": {
637
+ const table = tableMarkdown(node);
638
+ if (table) out.push(table);
639
+ break;
640
+ }
641
+ case "blockquote": {
642
+ const inner = [];
643
+ blocks(node.childNodes, inner);
644
+ if (inner.length > 0) out.push(inner.join("\n\n").split("\n").map((line) => line ? `> ${line}` : ">").join("\n"));
645
+ break;
646
+ }
647
+ case "hr":
648
+ out.push("* * *");
649
+ break;
650
+ case "summary":
651
+ case "legend":
652
+ case "dt":
653
+ case "caption": {
654
+ const text = inline(node.childNodes).trim();
655
+ if (text) out.push(`**${text}**`);
656
+ break;
657
+ }
658
+ default:
659
+ blocks(node.childNodes, out);
660
+ }
661
+ }
662
+ flush();
663
+ }
664
+ function componentHtmlToMarkdown(html, inlineCall) {
665
+ const fragment = parseApprovedHtml(html, inlineCall);
666
+ if (inlineCall) return inline(children(fragment)).replace(/\s+/g, " ").trim();
667
+ const out = [];
668
+ blocks(children(fragment), out);
669
+ return out.join("\n\n").trim();
670
+ }
671
+ var ComponentApprovalError = class extends Error {
672
+ constructor(problems) {
673
+ super(problems.slice(0, 20).join("\n"));
674
+ this.problems = problems;
675
+ this.name = "ComponentApprovalError";
676
+ }
677
+ problems;
678
+ };
679
+ var MODES = /* @__PURE__ */ new Set(["static", "hydrate", "client"]);
680
+ var SHA256 = /^[0-9a-f]{64}$/;
681
+ async function approveRenderResult(options) {
682
+ const { calls, input, result, chunks, hydrate } = options;
683
+ const problems = [];
684
+ if (result.version !== COMPONENT_PROTOCOL_VERSION) throw new ComponentApprovalError([`unsupported render result version ${String(result.version)}`]);
685
+ for (const error of result.errors ?? []) {
686
+ problems.push(`${error.id ?? error.component ?? "component"}: ${error.message}`);
687
+ }
688
+ const expected = new Map(input.calls.map((call) => [call.id, call]));
689
+ const byId = new Map(calls.map((call) => [call.id, call]));
690
+ if (expected.size !== calls.length || [...byId.keys()].some((id) => !expected.has(id))) {
691
+ throw new ComponentApprovalError(["render input does not match the verified source calls"]);
692
+ }
693
+ const seen = /* @__PURE__ */ new Set();
694
+ const approvedCalls = {};
695
+ const usedComponents = /* @__PURE__ */ new Set();
696
+ let markdownTotal = 0;
697
+ const componentInfo = (name) => {
698
+ const info = Object.prototype.hasOwnProperty.call(result.components ?? {}, name) ? result.components[name] : void 0;
699
+ if (info === void 0 || !MODES.has(info.render) || typeof info.decorative !== "boolean" || typeof info.hasToMarkdown !== "boolean") return null;
700
+ if (info.render === "static" ? info.chunk !== null : typeof info.chunk !== "string" || !SHA256.test(info.chunk)) return null;
701
+ return info;
702
+ };
703
+ for (const rendered of result.calls ?? []) {
704
+ if (seen.has(rendered.id)) {
705
+ problems.push(`${rendered.id}: rendered twice`);
706
+ continue;
707
+ }
708
+ seen.add(rendered.id);
709
+ const want = expected.get(rendered.id);
710
+ const call = byId.get(rendered.id);
711
+ if (want === void 0 || call === void 0) {
712
+ problems.push(`${rendered.id}: not a call in the verified source`);
713
+ continue;
714
+ }
715
+ if (rendered.component !== want.component || rendered.propsDigest !== want.propsDigest) {
716
+ problems.push(`${rendered.id}: result is bound to ${rendered.component} with different props than the source call`);
717
+ continue;
718
+ }
719
+ const info = componentInfo(want.component);
720
+ if (info === null) {
721
+ problems.push(`${rendered.id}: ${want.component} has no valid render metadata`);
722
+ continue;
723
+ }
724
+ usedComponents.add(want.component);
725
+ if (typeof rendered.html !== "string" || utf8Length(rendered.html) > COMPONENT_LIMITS.maxHtmlBytesPerCall) {
726
+ problems.push(`${rendered.id}: HTML is missing or larger than ${COMPONENT_LIMITS.maxHtmlBytesPerCall} bytes`);
727
+ continue;
728
+ }
729
+ if (info.render === "client" && rendered.html !== "") {
730
+ problems.push(`${rendered.id}: client components render no server HTML`);
731
+ continue;
732
+ }
733
+ const approval = approveComponentHtml(rendered.html, { inline: call.inline, identifierPrefix: want.identifierPrefix });
734
+ if (!approval.ok) {
735
+ problems.push(`${rendered.id} (${want.component}, line ${call.line}): ${approval.reason}`);
736
+ continue;
737
+ }
738
+ let markdown;
739
+ if (info.render === "static") {
740
+ markdown = normalizeComponentMarkdown(componentHtmlToMarkdown(approval.html, call.inline));
741
+ } else if (rendered.markdown !== null && rendered.markdown !== void 0) {
742
+ if (typeof rendered.markdown !== "string" || utf8Length(rendered.markdown) > COMPONENT_LIMITS.maxMarkdownBytesPerCall) {
743
+ problems.push(`${rendered.id}: Markdown is larger than ${COMPONENT_LIMITS.maxMarkdownBytesPerCall} bytes`);
744
+ continue;
745
+ }
746
+ markdown = normalizeComponentMarkdown(rendered.markdown);
747
+ } else {
748
+ markdown = "";
749
+ }
750
+ if (markdown.trim() === "" && !info.decorative && approval.html.replace(/<[^>]*>/g, "").trim() !== "") {
751
+ problems.push(`${rendered.id} (${want.component}): renders content but gives agents no Markdown; export toMarkdown or mark the component decorative`);
752
+ continue;
753
+ }
754
+ if (markdown.trim() === "" && !info.decorative && info.render !== "static") {
755
+ problems.push(`${rendered.id} (${want.component}): interactive components need toMarkdown unless they are decorative`);
756
+ continue;
757
+ }
758
+ markdownTotal += utf8Length(markdown);
759
+ approvedCalls[rendered.id] = {
760
+ component: want.component,
761
+ inline: call.inline,
762
+ propsDigest: want.propsDigest,
763
+ identifierPrefix: want.identifierPrefix,
764
+ html: approval.html,
765
+ markdown,
766
+ props: hydrate && info.render !== "static" ? call.props : null
767
+ };
768
+ }
769
+ for (const id of expected.keys()) if (!seen.has(id)) problems.push(`${id}: no render result`);
770
+ if (markdownTotal > COMPONENT_LIMITS.maxMarkdownBytesTotal) problems.push(`component Markdown totals more than ${COMPONENT_LIMITS.maxMarkdownBytesTotal} bytes`);
771
+ const approvedComponents = {};
772
+ for (const name of [...usedComponents].sort()) {
773
+ const info = componentInfo(name);
774
+ if (info.chunk !== null) {
775
+ const bytes = chunks.get(info.chunk);
776
+ if (bytes === void 0) {
777
+ problems.push(`${name}: client chunk ${info.chunk} is missing`);
778
+ } else if (bytes.byteLength > COMPONENT_LIMITS.maxChunkBytes) {
779
+ problems.push(`${name}: client chunk is larger than ${COMPONENT_LIMITS.maxChunkBytes} bytes`);
780
+ } else if (await sha256Hex(bytes) !== info.chunk) {
781
+ problems.push(`${name}: client chunk bytes do not match their digest`);
782
+ }
783
+ }
784
+ approvedComponents[name] = { render: info.render, chunk: hydrate ? info.chunk : null };
785
+ }
786
+ const referenced = new Set(Object.values(approvedComponents).map((component) => component.chunk).filter((chunk) => chunk !== null));
787
+ for (const digest of chunks.keys()) if (!referenced.has(digest) && hydrate) problems.push(`chunk ${digest} is not referenced by any called component`);
788
+ if (problems.length > 0) throw new ComponentApprovalError(problems);
789
+ return { version: COMPONENT_PROTOCOL_VERSION, hydrate, runtime: COMPONENT_RUNTIME_PATHS, components: approvedComponents, calls: approvedCalls };
790
+ }
791
+ var COMPONENT_RUNTIME_MANIFEST = Object.freeze([
792
+ Object.freeze({ path: "jsx-runtime.mjs", size: 906, sha256: "5846a7bf03494f06f657fc1c297421f46a1efb2b8d68be9a65624d9d6d79af9d" }),
793
+ Object.freeze({ path: "react-dom-client.mjs", size: 213978, sha256: "a182fdf30d39ddbb50c399742cbc40f94072546611d4a3e15a6f74c48c2e6775" }),
794
+ Object.freeze({ path: "react.mjs", size: 1695, sha256: "f0e8e682e8066cf5a8bc322da5344318b29a5b71f78c35f93b472a7ddeb4861e" }),
795
+ Object.freeze({ path: "shared-EGOFMTTA.mjs", size: 8250, sha256: "f493e0a1c622bb91758981b211b18006b82a971067fd97f66ff15c6f2633029c" }),
796
+ Object.freeze({ path: "shared-ER6OIO4S.mjs", size: 577, sha256: "11247d28c5c2fb3d976002c2b55fecb6ba19fd88153e11d2c7af5832fd6ff331" })
797
+ ]);
798
+
799
+ // ../../apps/ops/component-container/archive.mjs
800
+ var MiB = 1024 ** 2;
801
+ var archiveLimit = 36 * MiB;
802
+ var componentFile = /^components\/([A-Z][A-Za-z0-9]{0,63})\.(?:jsx|tsx)$/;
803
+ var helperFile = /^components\/[a-z][A-Za-z0-9_-]{0,63}\.(?:json|js|jsx|ts|tsx)$/;
804
+ var zeroBlock = Buffer.alloc(512);
805
+ function checksum(header) {
806
+ return header.reduce((sum, value, index) => sum + (index >= 148 && index < 156 ? 32 : value), 0);
807
+ }
808
+ function octal(header, start, length) {
809
+ const value = header.toString("latin1", start, start + length);
810
+ if (!/^[ ]*[0-7]+[\0 ]*$/.test(value)) throw Error("invalid tar number");
811
+ return parseInt(value, 8);
812
+ }
813
+ function unpack(buffer, input = true) {
814
+ if (buffer.length > (input ? archiveLimit : 100 * MiB) || buffer.length % 512) throw Error("invalid archive size");
815
+ const entries = /* @__PURE__ */ new Map();
816
+ let sourceBytes = 0;
817
+ let offset = 0;
818
+ while (offset + 512 <= buffer.length) {
819
+ const header = buffer.subarray(offset, offset += 512);
820
+ if (header.equals(zeroBlock)) {
821
+ if (offset + 512 > buffer.length || buffer.subarray(offset).some(Boolean)) throw Error("invalid tar end");
822
+ return entries;
823
+ }
824
+ if (header.toString("latin1", 257, 263) !== "ustar\0" || checksum(header) !== octal(header, 148, 8))
825
+ throw Error("invalid tar header");
826
+ if (![0, 48].includes(header[156]) || header.subarray(157, 257).some(Boolean) || header.subarray(345, 500).some(Boolean))
827
+ throw Error("only regular flat tar files allowed");
828
+ const name = header.toString("latin1", 0, 100).replace(/\0+$/, "");
829
+ const valid = input ? name === "calls.json" || componentFile.test(name) || helperFile.test(name) : name === "result.json" || /^chunks\/[a-f0-9]{64}\.js$/.test(name);
830
+ if (!valid || /[\r\n]/.test(name) || entries.has(name) || entries.size >= 257) throw Error("invalid or duplicate archive entry: " + name);
831
+ const size = octal(header, 124, 12);
832
+ if (input && name !== "calls.json") {
833
+ sourceBytes += size;
834
+ if (size > MiB || sourceBytes > 8 * MiB) throw Error("component source too large: " + name);
835
+ }
836
+ if (offset + size > buffer.length) throw Error("truncated tar entry");
837
+ const end = offset + Math.ceil(size / 512) * 512;
838
+ if (buffer.subarray(offset + size, end).some(Boolean)) throw Error("invalid tar padding");
839
+ entries.set(name, buffer.subarray(offset, offset + size));
840
+ offset += Math.ceil(size / 512) * 512;
841
+ }
842
+ throw Error("missing tar end");
843
+ }
844
+ function pack(entries) {
845
+ const blocks2 = [];
846
+ for (const [name, value] of entries) {
847
+ const data = Buffer.from(value);
848
+ const header = Buffer.alloc(512);
849
+ header.write(name);
850
+ for (const [offset, width, number] of [[100, 8, 420], [108, 8, 0], [116, 8, 0], [124, 12, data.length], [136, 12, 0]])
851
+ header.write(number.toString(8).padStart(width - 1, "0"), offset);
852
+ header.write("0", 156);
853
+ header.write("ustar\x0000", 257);
854
+ header.write(checksum(header).toString(8).padStart(6, "0") + "\0 ", 148);
855
+ blocks2.push(header, data, Buffer.alloc((512 - data.length % 512) % 512));
856
+ }
857
+ return Buffer.concat([...blocks2, zeroBlock, zeroBlock]);
858
+ }
859
+
860
+ // src/lib/preview/components.ts
861
+ async function runJob(script, cwd, signal) {
862
+ signal?.throwIfAborted();
863
+ const child = spawn(process.execPath, [script], {
864
+ cwd,
865
+ windowsHide: true,
866
+ detached: process.platform !== "win32",
867
+ env: process.platform === "win32" ? { SystemRoot: process.env.SystemRoot, TEMP: tmpdir() } : {},
868
+ stdio: ["ignore", "ignore", "pipe", "ipc"]
869
+ });
870
+ const cancel = () => {
871
+ if (child.connected) child.disconnect();
872
+ };
873
+ const timer = setTimeout(cancel, 65e3);
874
+ signal?.addEventListener("abort", cancel);
875
+ process.on("SIGINT", cancel);
876
+ process.on("SIGTERM", cancel);
877
+ let detail = "";
878
+ child.stderr.setEncoding("utf8").on("data", (text) => {
879
+ detail = (detail + text).slice(-8192);
880
+ });
881
+ try {
882
+ const exited = new Promise((resolve, reject) => {
883
+ child.once("error", reject);
884
+ child.once("exit", resolve);
885
+ });
886
+ const [code] = await Promise.all([exited, finished(child.stderr)]);
887
+ if (code !== 0) throw Error(detail || "component job exited");
888
+ signal?.throwIfAborted();
889
+ } finally {
890
+ clearTimeout(timer);
891
+ signal?.removeEventListener("abort", cancel);
892
+ process.off("SIGINT", cancel);
893
+ process.off("SIGTERM", cancel);
894
+ }
895
+ }
896
+ async function previewComponents(source, paths, dir, renderer, signal) {
897
+ const modules = paths.filter((file) => file.startsWith("components/"));
898
+ if (!modules.length) return;
899
+ const violations = [];
900
+ const registry = customerComponentRegistry(modules, violations);
901
+ if (violations.length) throw Error(violations[0].message);
902
+ const calls = [];
903
+ let propsBytes = 0;
904
+ for (const file of paths.filter((file2) => file2.startsWith("pages/"))) {
905
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(readFileSync(join(source, file)));
906
+ for (const call of collectComponentCalls(file, text, registry)) {
907
+ propsBytes += Buffer.byteLength(canonicalJson(call.props));
908
+ if (propsBytes > COMPONENT_LIMITS.maxPropsBytesTotal) throw Error(call.id + ": component props exceed the site byte limit");
909
+ calls.push(call);
910
+ }
911
+ if (calls.length > COMPONENT_LIMITS.maxCalls) throw Error(file + ": too many customer component calls");
912
+ }
913
+ if (!calls.length) return;
914
+ const script = join(renderer, "component-runtime/job.mjs");
915
+ if (!existsSync(script)) throw Error("The signed renderer lacks the customer component runtime. Update the preview renderer.");
916
+ const input = await buildRenderInput(calls);
917
+ const job = join(dir, "component-job");
918
+ mkdirSync(job, { mode: 448 });
919
+ const files = /* @__PURE__ */ new Map([["calls.json", JSON.stringify(input)]]);
920
+ for (const file of modules) files.set(file, readFileSync(join(source, file)));
921
+ try {
922
+ writeFileSync(join(job, "input.tar"), pack(files), { flag: "wx", mode: 384 });
923
+ console.error("Local preview runs this repository\u2019s custom components with your user permissions.");
924
+ await runJob(script, job, signal);
925
+ const output = join(job, "output.tar");
926
+ if (statSync(output).size > COMPONENT_LIMITS.maxOutputBytes) throw Error("Component output exceeds the byte limit");
927
+ const entries = unpack(readFileSync(output), false);
928
+ const metadata = entries.get("result.json");
929
+ if (!metadata) throw Error("Missing component result.json");
930
+ entries.delete("result.json");
931
+ const chunks = /* @__PURE__ */ new Map();
932
+ for (const [file, bytes] of entries) {
933
+ if (bytes.length > COMPONENT_LIMITS.maxChunkBytes) throw Error("Component chunk exceeds the byte limit");
934
+ chunks.set(file.slice(7, -3), bytes);
935
+ }
936
+ const result = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(metadata));
937
+ const approved = await approveRenderResult({ calls, input, result, chunks, hydrate: true });
938
+ approved.hydrate = chunks.size > 0;
939
+ const directory = join(dir, "approved-components");
940
+ mkdirSync(join(directory, "chunks"), { recursive: true, mode: 448 });
941
+ for (const { chunk } of Object.values(approved.components)) {
942
+ if (chunk) writeFileSync(join(directory, "chunks", chunk + ".js"), chunks.get(chunk), { mode: 384 });
943
+ }
944
+ writeFileSync(join(directory, "approved.json"), JSON.stringify(approved), { flag: "wx", mode: 384 });
945
+ return directory;
946
+ } catch (error) {
947
+ const reason = error instanceof Error ? error.message : String(error);
948
+ const module = modules.find((file) => reason.includes(file + ":"));
949
+ const call = calls.find((call2) => reason.startsWith(call2.id + ":") || reason.startsWith(call2.id + " ") || module && basename(module).split(".")[0] === call2.component) ?? calls[0];
950
+ throw Error(`Sandbox build failed: ${call.id} (${call.component}, line ${call.line}): ${reason}`, { cause: error });
951
+ } finally {
952
+ rmSync(job, { recursive: true, force: true });
953
+ }
954
+ }
955
+
956
+ // src/lib/preview/run-renderer.ts
957
+ import { spawn as spawn2, execFileSync } from "child_process";
958
+ import { join as join2 } from "path";
959
+ async function runRenderer(helper, options, cwd, signal, deadline = 3e5) {
960
+ signal?.throwIfAborted();
961
+ const windows = process.platform === "win32";
962
+ const child = spawn2(process.execPath, [
963
+ "--input-type=module",
964
+ "-e",
965
+ `import { execFileSync } from "node:child_process";
966
+ import { join } from "node:path";
967
+ function parentExited() {
968
+ if (process.platform === "win32") execFileSync(join(process.env.SystemRoot, "System32/taskkill.exe"), ["/F", "/T", "/PID", String(process.pid)]);
969
+ else process.kill(-process.pid, "SIGKILL");
970
+ }
971
+ process.once("disconnect", parentExited);
972
+ if (!process.connected) parentExited();
973
+ const { spawnRenderer } = await import(process.argv[1]);
974
+ try { await spawnRenderer(JSON.parse(process.argv[2])); }
975
+ finally { process.off("disconnect", parentExited); if (process.connected) process.disconnect(); }`,
976
+ helper,
977
+ JSON.stringify(options)
978
+ ], {
979
+ cwd,
980
+ env: windows ? { SystemRoot: process.env.SystemRoot } : {},
981
+ detached: !windows,
982
+ stdio: ["ignore", "ignore", "pipe", "ipc"],
983
+ windowsHide: true
984
+ });
985
+ let failure;
986
+ let detail = "";
987
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
988
+ detail = (detail + chunk).slice(-8192);
989
+ });
990
+ function stop(message) {
991
+ if (failure || !child.pid) return;
992
+ failure = new Error(message);
993
+ try {
994
+ if (windows) execFileSync(join2(process.env.SystemRoot, "System32", "taskkill.exe"), ["/F", "/T", "/PID", String(child.pid)], { windowsHide: true });
995
+ else process.kill(-child.pid, "SIGKILL");
996
+ } catch (error) {
997
+ if (error.code !== "ESRCH") failure = new Error("Cannot stop renderer process tree", { cause: error });
998
+ }
999
+ }
1000
+ const interrupt = () => stop("Renderer interrupted");
1001
+ const timer = setTimeout(() => stop("Renderer exceeded the build deadline"), deadline);
1002
+ process.on("SIGTERM", interrupt);
1003
+ process.on("SIGINT", interrupt);
1004
+ signal?.addEventListener("abort", interrupt);
1005
+ try {
1006
+ await new Promise((resolve, reject) => {
1007
+ child.once("error", reject);
1008
+ child.once("close", (code) => {
1009
+ if (failure) reject(failure);
1010
+ else if (code !== 0) reject(new Error(`Renderer exited with code ${code}: ${detail}`));
1011
+ else resolve();
1012
+ });
1013
+ });
1014
+ } finally {
1015
+ clearTimeout(timer);
1016
+ signal?.removeEventListener("abort", interrupt);
1017
+ process.off("SIGTERM", interrupt);
1018
+ process.off("SIGINT", interrupt);
1019
+ }
1020
+ }
1021
+
1022
+ // src/lib/preview/generation.ts
1023
+ import { createHash } from "crypto";
1024
+ import { readFileSync as readFileSync2, readdirSync } from "fs";
1025
+ import { join as join4, relative, sep } from "path";
1026
+ import { pathToFileURL } from "url";
1027
+
1028
+ // ../agent-surfaces/dist/index.js
1029
+ var MCP_SERVER_CARD_PATH = "/mcp/server-card";
1030
+ var MCP_SERVER_CARD_LEGACY_PATH = "/.well-known/mcp/server-card.json";
1031
+ var MCP_SERVER_CARD_CONTENT_TYPE = "application/mcp-server-card+json";
1032
+ var AI_CATALOG_PATH = "/.well-known/ai-catalog.json";
1033
+ var AI_CATALOG_CONTENT_TYPE = "application/ai-catalog+json";
1034
+ var DISCOVERY_DOCUMENT_PATHS = [
1035
+ MCP_SERVER_CARD_PATH,
1036
+ MCP_SERVER_CARD_LEGACY_PATH,
1037
+ AI_CATALOG_PATH
1038
+ ];
1039
+ function isAuthzManifest(value) {
1040
+ if (!isRecord(value)) return false;
1041
+ return value.version === 2 && isStringArray(value.public) && isStringArray(value.noindex) && Array.isArray(value.routes) && value.routes.every((route) => isRecord(route) && typeof route.path === "string" && isStringArray(route.groups)) && Array.isArray(value.redirects) && value.redirects.every((redirect) => isRecord(redirect) && typeof redirect.source === "string" && typeof redirect.destination === "string" && typeof redirect.permanent === "boolean") && (value.oidc === void 0 || isRecord(value.oidc) && typeof value.oidc.issuer === "string" && typeof value.oidc.client_id === "string" && (value.oidc.groups_claim === void 0 || typeof value.oidc.groups_claim === "string")) && (value.requireAuth === void 0 || typeof value.requireAuth === "boolean");
1042
+ }
1043
+ function isRecord(value) {
1044
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1045
+ }
1046
+ function isStringArray(value) {
1047
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
1048
+ }
1049
+ var RUNBOOK_KEYS = ["goal", "prerequisites", "steps", "expected", "verify", "target"];
1050
+ var RUNBOOK_KEY_SET = new Set(RUNBOOK_KEYS);
1051
+
1052
+ // ../../scripts/renderer-artifact/snapshot.mjs
1053
+ import fs from "fs";
1054
+ import path from "path";
1055
+ function requireSameEntry(expected, actual, label, expectedDevice = expected.dev) {
1056
+ if (actual.dev !== expectedDevice || actual.ino !== expected.ino || actual.birthtimeNs !== expected.birthtimeNs || process.platform === "win32" && actual.ino === 0n) {
1057
+ throw new Error(`Docs entry changed during snapshot: ${label}`);
1058
+ }
1059
+ }
1060
+ function snapshotDocs(source, dest, roots2, limits) {
1061
+ const work = process.cwd();
1062
+ let count = 0;
1063
+ let bytes = 0n;
1064
+ const stats = { bigint: true };
1065
+ const buffer = Buffer.allocUnsafe(64 * 1024);
1066
+ const { O_RDONLY, O_NOFOLLOW, O_NONBLOCK } = fs.constants;
1067
+ function copyFile(name, target, expected, label) {
1068
+ if (limits) {
1069
+ bytes += expected.size;
1070
+ if (++count > limits.maxFileCount || bytes > limits.maxTotalBytes || expected.size > limits.maxFileBytes) {
1071
+ throw new Error(`Source exceeds the preview limit: ${label}`);
1072
+ }
1073
+ }
1074
+ const input = fs.openSync(name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
1075
+ try {
1076
+ const opened = fs.fstatSync(input, stats);
1077
+ let expectedDevice = expected.dev;
1078
+ if (process.platform === "win32" && expected.dev !== opened.dev) {
1079
+ const parent = fs.openSync(".", O_RDONLY);
1080
+ try {
1081
+ const parentPath = fs.statSync(".", stats);
1082
+ if (parentPath.dev === expected.dev) expectedDevice = fs.fstatSync(parent, stats).dev;
1083
+ } finally {
1084
+ fs.closeSync(parent);
1085
+ }
1086
+ }
1087
+ requireSameEntry(expected, opened, label, expectedDevice);
1088
+ if (!opened.isFile() || opened.nlink !== 1n) throw new Error(`Unsupported docs entry: ${label}`);
1089
+ const output = fs.openSync(target, "wx", 384);
1090
+ try {
1091
+ let total = 0n;
1092
+ let length;
1093
+ while ((length = fs.readSync(input, buffer)) > 0) {
1094
+ total += BigInt(length);
1095
+ if (total > opened.size) throw new Error(`Docs file grew during snapshot: ${label}`);
1096
+ fs.writeFileSync(output, buffer.subarray(0, length));
1097
+ }
1098
+ const after = fs.fstatSync(input, stats);
1099
+ if (total !== opened.size || after.ctimeNs !== opened.ctimeNs || after.nlink !== 1n) {
1100
+ throw new Error(`Docs file changed during snapshot: ${label}`);
1101
+ }
1102
+ } finally {
1103
+ fs.closeSync(output);
1104
+ }
1105
+ } finally {
1106
+ fs.closeSync(input);
1107
+ }
1108
+ }
1109
+ function copyDirectory(name, target, expected, label, atRoot) {
1110
+ process.chdir(name);
1111
+ requireSameEntry(expected, fs.statSync(".", stats), label);
1112
+ fs.mkdirSync(target, { mode: 448 });
1113
+ for (const child of fs.readdirSync(".")) {
1114
+ if (atRoot && !roots2.has(child)) continue;
1115
+ const entry = fs.lstatSync(child, stats);
1116
+ const childLabel = path.join(label, child);
1117
+ const childTarget = path.join(target, child);
1118
+ if (atRoot && roots2.get(child) !== entry.isDirectory()) throw new Error(`Unsupported docs entry: ${childLabel}`);
1119
+ if (entry.isDirectory()) {
1120
+ copyDirectory(child, childTarget, entry, childLabel, false);
1121
+ process.chdir("..");
1122
+ requireSameEntry(expected, fs.statSync(".", stats), label);
1123
+ } else if (entry.isFile() && entry.nlink === 1n) {
1124
+ copyFile(child, childTarget, entry, childLabel);
1125
+ } else {
1126
+ throw new Error(`Unsupported docs entry: ${childLabel}`);
1127
+ }
1128
+ }
1129
+ }
1130
+ const root = fs.lstatSync(source, stats);
1131
+ if (!root.isDirectory()) throw new Error(`Expected a docs directory: ${source}`);
1132
+ try {
1133
+ copyDirectory(source, dest, root, source, true);
1134
+ } finally {
1135
+ process.chdir(work);
1136
+ }
1137
+ }
1138
+
1139
+ // src/lib/preview/fonts.ts
1140
+ import { randomUUID } from "crypto";
1141
+ import { mkdir, readFile, rename, rm, writeFile } from "fs/promises";
1142
+ import { dirname, join as join3 } from "path";
1143
+
1144
+ // ../source-abi/dist/fonts.js
1145
+ var CSS_HOST = "fonts.googleapis.com";
1146
+ var FILE_HOST = "fonts.gstatic.com";
1147
+ var DEFAULT_WEIGHTS = [400, 500, 600];
1148
+ var DEADLINE_MS = 25e3;
1149
+ var REQUEST_TIMEOUT_MS = 1e4;
1150
+ var MAX_REQUESTS = 32;
1151
+ var MAX_FILES = 24;
1152
+ var MAX_FILE_BYTES = 2097152;
1153
+ var MAX_TOTAL_BYTES = 16777216;
1154
+ var MAX_CSS_BYTES = 262144;
1155
+ var MAX_REDIRECTS = 3;
1156
+ var MAX_SLUG_LENGTH = 64;
1157
+ var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
1158
+ var SLOT_ORDER = ["body", "heading", "mono"];
1159
+ var SLOT_FALLBACK = { body: "sans-serif", heading: "sans-serif", mono: "monospace" };
1160
+ var FONT_FACE_PATTERN = /(?:\/\*([^*]*(?:\*(?!\/)[^*]*)*)\*\/\s*)?@font-face\s*\{([^}]*)\}/g;
1161
+ var encoder2 = new TextEncoder();
1162
+ var StagingFailure = class extends Error {
1163
+ constructor(reason, message) {
1164
+ super(message);
1165
+ this.reason = reason;
1166
+ }
1167
+ reason;
1168
+ };
1169
+ function normalizeWeights(values) {
1170
+ const source = values === void 0 ? DEFAULT_WEIGHTS : values;
1171
+ const unique = /* @__PURE__ */ new Set();
1172
+ for (const value of source) {
1173
+ if (!Number.isInteger(value) || value < 1 || value > 1e3) continue;
1174
+ unique.add(value);
1175
+ }
1176
+ return [...unique].sort((left, right) => left - right);
1177
+ }
1178
+ function normalizeFontRequests(docsConfig) {
1179
+ const merged = /* @__PURE__ */ new Map();
1180
+ for (const slot of SLOT_ORDER) {
1181
+ const spec = docsConfig.fonts?.[slot];
1182
+ if (spec === void 0) continue;
1183
+ const family = typeof spec === "string" ? spec : spec.family;
1184
+ const source = typeof spec === "string" ? "google" : spec.source ?? "google";
1185
+ if (source !== "google") continue;
1186
+ const weights = normalizeWeights(typeof spec === "string" ? void 0 : spec.weights);
1187
+ if (weights.length === 0) continue;
1188
+ const existing = merged.get(family);
1189
+ if (existing === void 0) {
1190
+ merged.set(family, { weights: new Set(weights), slots: [slot] });
1191
+ continue;
1192
+ }
1193
+ for (const weight of weights) existing.weights.add(weight);
1194
+ existing.slots.push(slot);
1195
+ }
1196
+ return [...merged].map(([family, value]) => ({
1197
+ family,
1198
+ weights: [...value.weights].sort((left, right) => left - right),
1199
+ slots: value.slots.slice().sort((left, right) => SLOT_ORDER.indexOf(left) - SLOT_ORDER.indexOf(right))
1200
+ })).sort((left, right) => left.family < right.family ? -1 : left.family > right.family ? 1 : 0);
1201
+ }
1202
+ async function sha256Hex2(bytes) {
1203
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
1204
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1205
+ }
1206
+ function familySlug(family) {
1207
+ const slug = family.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, MAX_SLUG_LENGTH).replace(/-+$/g, "");
1208
+ return slug.length === 0 ? "font" : slug;
1209
+ }
1210
+ function normalizeSubset(value) {
1211
+ const normalized = (value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32).replace(/-+$/g, "");
1212
+ return normalized.length === 0 ? "other" : normalized;
1213
+ }
1214
+ function stripQuotes(value) {
1215
+ const trimmed = value.trim();
1216
+ if (trimmed.length >= 2) {
1217
+ const first = trimmed[0];
1218
+ if ((first === '"' || first === "'") && trimmed[trimmed.length - 1] === first) return trimmed.slice(1, -1);
1219
+ }
1220
+ return trimmed;
1221
+ }
1222
+ function checkUrl(url, host) {
1223
+ if (url.protocol !== "https:" || url.hostname !== host) throw new StagingFailure("host", "url host rejected");
1224
+ }
1225
+ function contentTypeOf(response) {
1226
+ return (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
1227
+ }
1228
+ async function readCapped(response, maxBytes) {
1229
+ const declared = response.headers.get("content-length");
1230
+ if (declared !== null && /^[0-9]+$/.test(declared) && Number(declared) > maxBytes) throw new StagingFailure("size", "declared body exceeded the cap");
1231
+ if (response.body === null) {
1232
+ const buffer = await response.arrayBuffer();
1233
+ if (buffer.byteLength > maxBytes) throw new StagingFailure("size", "body exceeded the cap");
1234
+ return new Uint8Array(buffer);
1235
+ }
1236
+ const reader = response.body.getReader();
1237
+ const chunks = [];
1238
+ let total = 0;
1239
+ for (; ; ) {
1240
+ const next = await reader.read();
1241
+ if (next.done) break;
1242
+ if (next.value === void 0) continue;
1243
+ total += next.value.byteLength;
1244
+ if (total > maxBytes) {
1245
+ await reader.cancel().catch(() => void 0);
1246
+ throw new StagingFailure("size", "body exceeded the cap");
1247
+ }
1248
+ chunks.push(next.value);
1249
+ }
1250
+ const output = new Uint8Array(total);
1251
+ let offset = 0;
1252
+ for (const chunk of chunks) {
1253
+ output.set(chunk, offset);
1254
+ offset += chunk.byteLength;
1255
+ }
1256
+ return output;
1257
+ }
1258
+ async function requestOnce(context, url, accept) {
1259
+ if (context.now() >= context.deadlineAt) throw new StagingFailure("deadline", "staging deadline reached");
1260
+ if (context.requests >= MAX_REQUESTS) throw new StagingFailure("budget", "request budget exhausted");
1261
+ context.requests += 1;
1262
+ const controller = new AbortController();
1263
+ const abort = () => controller.abort();
1264
+ const timer = setTimeout(abort, Math.min(REQUEST_TIMEOUT_MS, Math.max(1, context.deadlineAt - context.now())));
1265
+ context.signal.addEventListener("abort", abort);
1266
+ try {
1267
+ const fetchImpl = context.fetchImpl;
1268
+ return await fetchImpl(url.toString(), {
1269
+ method: "GET",
1270
+ redirect: "manual",
1271
+ signal: controller.signal,
1272
+ headers: { "user-agent": USER_AGENT, accept }
1273
+ });
1274
+ } catch (error) {
1275
+ const detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1276
+ console.warn(`font staging fetch failed host=${url.hostname} error=${detail.replace(/https?:\/\/\S+/g, "<url>").slice(0, 160)}`);
1277
+ throw new StagingFailure(context.now() >= context.deadlineAt ? "deadline" : "timeout", "request failed");
1278
+ } finally {
1279
+ clearTimeout(timer);
1280
+ context.signal.removeEventListener("abort", abort);
1281
+ }
1282
+ }
1283
+ async function fetchAllowed(context, target, host, accept) {
1284
+ let url = target;
1285
+ checkUrl(url, host);
1286
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
1287
+ const response = await requestOnce(context, url, accept);
1288
+ const location = response.headers.get("location");
1289
+ if (response.status >= 300 && response.status < 400 && location !== null) {
1290
+ if (hop === MAX_REDIRECTS) throw new StagingFailure("host", "redirect limit exceeded");
1291
+ let next;
1292
+ try {
1293
+ next = new URL(location, url);
1294
+ } catch {
1295
+ throw new StagingFailure("host", "redirect target was not a url");
1296
+ }
1297
+ checkUrl(next, host);
1298
+ url = next;
1299
+ continue;
1300
+ }
1301
+ if (response.status !== 200) throw new StagingFailure("parse", `unexpected status ${response.status}`);
1302
+ return response;
1303
+ }
1304
+ throw new StagingFailure("host", "redirect limit exceeded");
1305
+ }
1306
+ function cssUrl(request) {
1307
+ const family = encodeURIComponent(request.family).replace(/%20/g, "+");
1308
+ return new URL(`https://${CSS_HOST}/css2?family=${family}:wght@${request.weights.join(";")}&display=swap`);
1309
+ }
1310
+ function parseFontFaceCss(css, request) {
1311
+ const blocks2 = [];
1312
+ const seen = /* @__PURE__ */ new Set();
1313
+ const weights = new Set(request.weights);
1314
+ FONT_FACE_PATTERN.lastIndex = 0;
1315
+ for (; ; ) {
1316
+ const match = FONT_FACE_PATTERN.exec(css);
1317
+ if (match === null) break;
1318
+ const subset = normalizeSubset(match[1]);
1319
+ if (subset !== "latin" && subset !== "latin-ext") continue;
1320
+ const declarations = /* @__PURE__ */ new Map();
1321
+ for (const part of match[2].split(";")) {
1322
+ const separator = part.indexOf(":");
1323
+ if (separator < 1) continue;
1324
+ const name = part.slice(0, separator).trim().toLowerCase();
1325
+ const value = part.slice(separator + 1).trim();
1326
+ const bucket = declarations.get(name);
1327
+ if (bucket === void 0) declarations.set(name, [value]);
1328
+ else bucket.push(value);
1329
+ }
1330
+ const family = declarations.get("font-family");
1331
+ if (family === void 0 || family.length !== 1 || stripQuotes(family[0]) !== request.family) continue;
1332
+ const style = declarations.get("font-style");
1333
+ if (style === void 0 || style.length !== 1 || style[0].trim().toLowerCase() !== "normal") continue;
1334
+ const weightValues = declarations.get("font-weight");
1335
+ if (weightValues === void 0 || weightValues.length !== 1 || !/^[0-9]{1,4}$/.test(weightValues[0].trim())) continue;
1336
+ const weight = Number(weightValues[0].trim());
1337
+ if (!weights.has(weight)) continue;
1338
+ const rangeValues = declarations.get("unicode-range");
1339
+ if (rangeValues === void 0 || rangeValues.length !== 1) continue;
1340
+ const unicodeRange = rangeValues[0].split(",").map((token) => token.trim()).filter((token) => token.length > 0);
1341
+ if (unicodeRange.length === 0) continue;
1342
+ const srcValues = declarations.get("src");
1343
+ if (srcValues === void 0 || srcValues.length !== 1) continue;
1344
+ const src = srcValues[0];
1345
+ if (src.split("url(").length !== 2) continue;
1346
+ const srcMatch = /^url\(([^)]*)\)\s*format\(([^)]*)\)$/.exec(src.trim());
1347
+ if (srcMatch === null) continue;
1348
+ if (stripQuotes(srcMatch[2]).toLowerCase() !== "woff2") continue;
1349
+ const raw = stripQuotes(srcMatch[1]);
1350
+ if (raw.includes("\\")) continue;
1351
+ let url;
1352
+ try {
1353
+ url = new URL(raw);
1354
+ } catch {
1355
+ continue;
1356
+ }
1357
+ if (url.protocol !== "https:" || url.hostname !== FILE_HOST) continue;
1358
+ const key = `${weight}:${subset}`;
1359
+ if (seen.has(key)) continue;
1360
+ seen.add(key);
1361
+ blocks2.push({ weight, subset, unicodeRange, url });
1362
+ }
1363
+ blocks2.sort((left, right) => left.weight - right.weight || (left.subset < right.subset ? -1 : left.subset > right.subset ? 1 : 0));
1364
+ return blocks2;
1365
+ }
1366
+ function descriptorKey(familyDigest, weights) {
1367
+ return `fonts/v1/families/${familyDigest}/${weights.join("-")}/family.json`;
1368
+ }
1369
+ function blobKey(blob) {
1370
+ return `fonts/v1/blobs/${blob}.woff2`;
1371
+ }
1372
+ function isValidDescriptor(value, request) {
1373
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1374
+ const candidate = value;
1375
+ if (candidate.version !== 1 || candidate.family !== request.family) return false;
1376
+ if (!Array.isArray(candidate.weights) || candidate.weights.length !== request.weights.length) return false;
1377
+ if (candidate.weights.some((weight, index) => weight !== request.weights[index])) return false;
1378
+ if (!Array.isArray(candidate.variants) || candidate.variants.length === 0) return false;
1379
+ for (const variant of candidate.variants) {
1380
+ if (typeof variant !== "object" || variant === null) return false;
1381
+ if (!Number.isInteger(variant.weight) || variant.style !== "normal") return false;
1382
+ if (typeof variant.subset !== "string" || !/^[a-z0-9-]{1,32}$/.test(variant.subset)) return false;
1383
+ if (!Array.isArray(variant.unicodeRange) || variant.unicodeRange.length === 0) return false;
1384
+ if (variant.unicodeRange.some((token) => typeof token !== "string" || token.length === 0)) return false;
1385
+ if (typeof variant.blob !== "string" || !/^sha256\/[0-9a-f]{64}$/.test(variant.blob)) return false;
1386
+ if (!Number.isInteger(variant.bytes) || variant.bytes <= 0) return false;
1387
+ }
1388
+ return true;
1389
+ }
1390
+ async function readCachedDescriptor(context, key, request) {
1391
+ try {
1392
+ const object = await context.staging.get(key);
1393
+ if (object === null) return null;
1394
+ const parsed = JSON.parse(new TextDecoder().decode(new Uint8Array(await object.arrayBuffer())));
1395
+ if (!isValidDescriptor(parsed, request)) return null;
1396
+ for (const variant of parsed.variants) {
1397
+ if (await context.staging.head(blobKey(variant.blob)) === null) return null;
1398
+ }
1399
+ return parsed;
1400
+ } catch {
1401
+ return null;
1402
+ }
1403
+ }
1404
+ async function downloadFamily(context, request) {
1405
+ const cssResponse = await fetchAllowed(context, cssUrl(request), CSS_HOST, "text/css,*/*;q=0.1");
1406
+ if (!contentTypeOf(cssResponse).startsWith("text/css")) throw new StagingFailure("parse", "css content type rejected");
1407
+ const css = new TextDecoder().decode(await readCapped(cssResponse, MAX_CSS_BYTES));
1408
+ const blocks2 = parseFontFaceCss(css, request);
1409
+ if (blocks2.length === 0) throw new StagingFailure("parse", "no acceptable font-face blocks");
1410
+ const latin = new Set(blocks2.filter((block) => block.subset === "latin").map((block) => block.weight));
1411
+ if (request.weights.some((weight) => !latin.has(weight))) throw new StagingFailure("parse", "latin coverage incomplete");
1412
+ const variants = [];
1413
+ const bodies = /* @__PURE__ */ new Map();
1414
+ for (const block of blocks2) {
1415
+ if (context.files >= MAX_FILES) throw new StagingFailure("budget", "file budget exhausted");
1416
+ const response = await fetchAllowed(context, block.url, FILE_HOST, "*/*");
1417
+ const contentType = contentTypeOf(response);
1418
+ if (contentType !== "font/woff2" && contentType !== "application/octet-stream") throw new StagingFailure("parse", "font content type rejected");
1419
+ const bytes = await readCapped(response, MAX_FILE_BYTES);
1420
+ context.files += 1;
1421
+ context.bytes += bytes.byteLength;
1422
+ if (context.bytes > MAX_TOTAL_BYTES) throw new StagingFailure("size", "total byte budget exhausted");
1423
+ if (bytes.byteLength < 4 || bytes[0] !== 119 || bytes[1] !== 79 || bytes[2] !== 70 || bytes[3] !== 50) throw new StagingFailure("parse", "font magic bytes rejected");
1424
+ const blob = `sha256/${await sha256Hex2(bytes)}`;
1425
+ bodies.set(blob, bytes);
1426
+ variants.push({ weight: block.weight, style: "normal", subset: block.subset, unicodeRange: block.unicodeRange, blob, bytes: bytes.byteLength });
1427
+ }
1428
+ const descriptor = { version: 1, family: request.family, weights: request.weights, variants };
1429
+ try {
1430
+ for (const [blob, bytes] of bodies) await context.staging.put(blobKey(blob), bytes);
1431
+ await context.staging.put(descriptorKey(await sha256Hex2(encoder2.encode(request.family)), request.weights), encoder2.encode(JSON.stringify(descriptor)));
1432
+ } catch {
1433
+ throw new StagingFailure("r2", "cache write failed");
1434
+ }
1435
+ return descriptor;
1436
+ }
1437
+ async function verifiedBlob(context, variant) {
1438
+ let bytes;
1439
+ try {
1440
+ const object = await context.staging.get(blobKey(variant.blob));
1441
+ if (object === null) throw new Error("missing");
1442
+ bytes = new Uint8Array(await object.arrayBuffer());
1443
+ } catch {
1444
+ throw new StagingFailure("r2", "blob read failed");
1445
+ }
1446
+ if (bytes.byteLength !== variant.bytes) throw new StagingFailure("verify", "blob size mismatch");
1447
+ if (`sha256/${await sha256Hex2(bytes)}` !== variant.blob) throw new StagingFailure("verify", "blob digest mismatch");
1448
+ return bytes;
1449
+ }
1450
+ function warn(family, reason) {
1451
+ console.warn(`font staging skipped family=${family} reason=${reason}`);
1452
+ }
1453
+ function failureReason(error) {
1454
+ return error instanceof StagingFailure ? error.reason : "parse";
1455
+ }
1456
+ async function stageFontFiles(options) {
1457
+ const requests = normalizeFontRequests(options.docsConfig);
1458
+ if (requests.length === 0) return null;
1459
+ const now = options.now ?? Date.now;
1460
+ const deadlineMs = options.deadlineMs ?? DEADLINE_MS;
1461
+ const controller = new AbortController();
1462
+ const timer = setTimeout(() => controller.abort(), deadlineMs);
1463
+ const context = {
1464
+ staging: options.staging,
1465
+ fetchImpl: options.fetchImpl ?? ((input, init) => fetch(input, init)),
1466
+ now,
1467
+ deadlineAt: now() + deadlineMs,
1468
+ signal: controller.signal,
1469
+ requests: 0,
1470
+ files: 0,
1471
+ bytes: 0
1472
+ };
1473
+ try {
1474
+ const resolved = [];
1475
+ for (const request of requests) {
1476
+ const key = descriptorKey(await sha256Hex2(encoder2.encode(request.family)), request.weights);
1477
+ const cached = await readCachedDescriptor(context, key, request);
1478
+ if (cached !== null) {
1479
+ resolved.push({ request, descriptor: cached });
1480
+ continue;
1481
+ }
1482
+ try {
1483
+ resolved.push({ request, descriptor: await downloadFamily(context, request) });
1484
+ } catch (error) {
1485
+ warn(request.family, failureReason(error));
1486
+ }
1487
+ }
1488
+ if (resolved.length === 0) return null;
1489
+ const slugs = /* @__PURE__ */ new Set();
1490
+ const families = [];
1491
+ const entries = [];
1492
+ for (const item of resolved) {
1493
+ const base = familySlug(item.request.family);
1494
+ let slug = base;
1495
+ for (let index = 2; slugs.has(slug); index += 1) slug = `${base}-${index}`;
1496
+ slugs.add(slug);
1497
+ const variants = [];
1498
+ for (const variant of item.descriptor.variants.slice().sort((left, right) => left.weight - right.weight || (left.subset < right.subset ? -1 : left.subset > right.subset ? 1 : 0))) {
1499
+ let bytes;
1500
+ try {
1501
+ bytes = await verifiedBlob(context, variant);
1502
+ } catch (error) {
1503
+ warn(item.request.family, failureReason(error));
1504
+ await context.staging.delete(descriptorKey(await sha256Hex2(encoder2.encode(item.request.family)), item.request.weights)).catch(() => void 0);
1505
+ return null;
1506
+ }
1507
+ const file = `${slug}/${variant.weight}-normal-${variant.subset}.woff2`;
1508
+ variants.push({ weight: variant.weight, style: "normal", subset: variant.subset, unicodeRange: variant.unicodeRange, file });
1509
+ entries.push({ path: file, bytes });
1510
+ }
1511
+ families.push({ slots: item.request.slots, family: item.request.family, fallback: SLOT_FALLBACK[item.request.slots[0] ?? "body"], variants });
1512
+ }
1513
+ const manifest = { version: 1, families };
1514
+ entries.push({ path: "fonts.json", bytes: encoder2.encode(JSON.stringify(manifest)) });
1515
+ return { entries, manifest };
1516
+ } catch (error) {
1517
+ warn("*", failureReason(error));
1518
+ return null;
1519
+ } finally {
1520
+ clearTimeout(timer);
1521
+ }
1522
+ }
1523
+
1524
+ // src/lib/preview/fonts.ts
1525
+ async function previewFonts(config, cache, directory, signal) {
1526
+ const requests = normalizeFontRequests(config);
1527
+ const bucket = {
1528
+ async get(key) {
1529
+ const bytes = await readFile(join3(cache, key)).catch(() => null);
1530
+ return bytes && { arrayBuffer: async () => Uint8Array.from(bytes).buffer };
1531
+ },
1532
+ async head(key) {
1533
+ return this.get(key);
1534
+ },
1535
+ async put(key, value) {
1536
+ if (!(value instanceof Uint8Array)) throw new Error("Invalid font bytes");
1537
+ const dest = join3(cache, key);
1538
+ const temp = dest + "." + randomUUID();
1539
+ await mkdir(dirname(dest), { recursive: true, mode: 448 });
1540
+ try {
1541
+ await writeFile(temp, value, { flag: "wx", mode: 384 });
1542
+ await rename(temp, dest);
1543
+ } finally {
1544
+ await rm(temp, { force: true });
1545
+ }
1546
+ },
1547
+ async delete(key) {
1548
+ await rm(join3(cache, key), { force: true });
1549
+ }
1550
+ };
1551
+ signal?.throwIfAborted();
1552
+ const staged = await stageFontFiles({
1553
+ docsConfig: config,
1554
+ staging: bucket,
1555
+ fetchImpl: signal ? (input, init) => fetch(input, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal }) : void 0
1556
+ });
1557
+ signal?.throwIfAborted();
1558
+ for (const entry of staged?.entries ?? []) {
1559
+ const target = join3(directory, entry.path);
1560
+ await mkdir(dirname(target), { recursive: true });
1561
+ await writeFile(target, entry.bytes, { flag: "wx" });
1562
+ }
1563
+ const warnings = requests.filter((r) => !staged?.manifest.families.some((f) => f.family === r.family)).map((r) => `Google font "${r.family}" could not be staged. The preview uses a fallback.`);
1564
+ return { fonts: staged ? directory : void 0, warnings };
1565
+ }
1566
+
1567
+ // src/lib/preview/generation.ts
1568
+ var roots = new Map(SOURCE_ALLOWED_ROOTS.map((pattern) => [pattern.split("/")[0], pattern.includes("/")]));
1569
+ var previewRoots = new Set(roots.keys());
1570
+ function checkConfig(text) {
1571
+ const config = parseDocsConfig(JSON.parse(text));
1572
+ if (config.type === "portal" || config.auth?.oidc) {
1573
+ const loc = configLocator(text)(config.type === "portal" ? ["type"] : ["auth", "oidc"]);
1574
+ throw new Error(`docs.json:${loc?.line ?? 1}:${loc?.column ?? 1}: Reader authentication requires a hosted preview.`);
1575
+ }
1576
+ return config;
1577
+ }
1578
+ function checkPage(file, bytes) {
1579
+ try {
1580
+ if (!frontmatterPolicy(bytes).grouped) return;
1581
+ } catch (error) {
1582
+ throw new Error(`${file}:1:1: Cannot read reader policy. Correct the page frontmatter. ${error}`);
1583
+ }
1584
+ const line = new TextDecoder().decode(bytes).split("\n").findIndex((l) => /^groups\s*:/.test(l));
1585
+ throw new Error(`${file}:${Math.max(1, line + 1)}:1: Reader groups require a hosted preview.`);
1586
+ }
1587
+ async function buildGeneration(docs, dir, cache, renderer, siteUrl, policyChecked, signal, linkCheck = "source") {
1588
+ const started = performance.now();
1589
+ const source = join4(dir, "source");
1590
+ snapshotDocs(docs, source, roots, SOURCE_LIMITS);
1591
+ const paths = readdirSync(source, { recursive: true, withFileTypes: true }).filter((e) => e.isFile()).map((e) => relative(source, join4(e.parentPath, e.name)).split(sep).join("/")).sort();
1592
+ let config;
1593
+ try {
1594
+ config = checkConfig(readFileSync2(join4(source, "docs.json"), "utf8"));
1595
+ } catch (error) {
1596
+ throw new Error(`Cannot admit docs.json. Check the site configuration. ${error}`);
1597
+ }
1598
+ for (const file of paths.filter((file2) => file2.startsWith("pages/"))) checkPage(file, readFileSync2(join4(source, file)));
1599
+ policyChecked?.(true);
1600
+ const hash = createHash("sha256");
1601
+ const inventory = await collectOutsideRootFiles(docs);
1602
+ for (const path2 of paths) {
1603
+ const bytes = readFileSync2(join4(source, path2));
1604
+ inventory.push({ path: path2, size: bytes.length });
1605
+ hash.update(JSON.stringify([path2, bytes.length])).update(bytes);
1606
+ }
1607
+ const invalid = validateBundleStructure(inventory).filter((v) => v.severity === "error");
1608
+ if (invalid.length) throw new Error(invalid.map((v) => `${v.path}: ${v.message}`).join("\n"));
1609
+ const errors = (await validateDocsReport(source, new Set(paths))).filter((e) => linkCheck === "source" || e.code !== "unresolved_link");
1610
+ if (errors.length) throw new Error(errors.map((e) => `${e.path ?? "bundle"}:${e.line ?? 1}:${e.column ?? 1}: ${e.message} ${e.fix ?? ""}`).join("\n"));
1611
+ const site = new URL(siteUrl ?? config.siteUrl ?? "http://localhost/");
1612
+ if (!["https:", "http:"].includes(site.protocol) || site.username || site.password) throw new Error("Expected an HTTP(S) site URL");
1613
+ const { fonts, warnings } = await previewFonts(config, cache, join4(dir, "fonts"), signal);
1614
+ signal?.throwIfAborted();
1615
+ const components = await previewComponents(source, paths, dir, renderer.root, signal);
1616
+ const out = join4(dir, "site");
1617
+ const worker = join4(dir, "worker");
1618
+ const helper = pathToFileURL(join4(renderer.root, "bin/spawn-renderer.mjs")).href;
1619
+ await runRenderer(helper, { docs: source, out, worker, fonts, components, siteUrl: site.href, scratchRoot: dir }, dir, signal);
1620
+ let policy;
1621
+ try {
1622
+ policy = JSON.parse(readFileSync2(join4(worker, "auth-manifest.json"), "utf8"));
1623
+ } catch {
1624
+ policyChecked?.(false);
1625
+ throw new Error("worker/auth-manifest.json:1:1: Cannot read reader policy. Use a hosted preview.");
1626
+ }
1627
+ if (!isAuthzManifest(policy) || policy.requireAuth || policy.routes.length || policy.oidc) {
1628
+ policyChecked?.(false);
1629
+ throw new Error("worker/auth-manifest.json:1:1: Missing or restricted reader policy. Use a hosted preview.");
1630
+ }
1631
+ return { out, worker, policy, report: {
1632
+ author_preview: true,
1633
+ renderer_identity: renderer.identity,
1634
+ input_digest: hash.digest("hex"),
1635
+ site_url: site.href,
1636
+ warnings,
1637
+ duration_ms: Math.round(performance.now() - started)
1638
+ } };
1639
+ }
1640
+
1641
+ export {
1642
+ MCP_SERVER_CARD_PATH,
1643
+ MCP_SERVER_CARD_LEGACY_PATH,
1644
+ MCP_SERVER_CARD_CONTENT_TYPE,
1645
+ AI_CATALOG_PATH,
1646
+ AI_CATALOG_CONTENT_TYPE,
1647
+ DISCOVERY_DOCUMENT_PATHS,
1648
+ previewRoots,
1649
+ buildGeneration
1650
+ };