rosetack 0.1.2 → 0.1.3

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 (54) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/netlify/functions/rosetack.ts +38 -0
  4. package/deploy/netlify.toml +17 -0
  5. package/devtools/devtools.html +7 -0
  6. package/devtools/devtools.js +1 -0
  7. package/devtools/manifest.json +8 -0
  8. package/devtools/panel.html +28 -0
  9. package/devtools/panel.js +54 -0
  10. package/dist-cli/compiler.mjs +818 -445
  11. package/dist-cli/edge.mjs +115 -39
  12. package/dist-cli/rosetack.mjs +1078 -529
  13. package/dist-cli/runtime.mjs +115 -34
  14. package/dist-cli/test.mjs +875 -464
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/edge.ts +69 -61
  18. package/src/cli/index.ts +243 -328
  19. package/src/cli/prompt.ts +4 -1
  20. package/src/cli/shell.ts +67 -69
  21. package/src/cli/test.ts +9 -70
  22. package/src/compiler/index.ts +921 -851
  23. package/src/runtime/index.ts +155 -158
  24. package/src/types/rosetack.d.ts +16 -66
  25. package/templates/admin/package.json +14 -0
  26. package/templates/admin/rosetack.config.js +1 -0
  27. package/templates/admin/src/pages/_middleware.rose +33 -0
  28. package/templates/admin/src/pages/api/items.rose +37 -0
  29. package/templates/admin/src/pages/api/login.rose +25 -0
  30. package/templates/admin/src/pages/index.rose +79 -0
  31. package/templates/api/package.json +14 -0
  32. package/templates/api/rosetack.config.js +1 -0
  33. package/templates/api/src/pages/api/health.rose +7 -0
  34. package/templates/api/src/pages/api/items.rose +46 -0
  35. package/templates/api/src/pages/api/login.rose +24 -0
  36. package/templates/api/src/pages/index.rose +25 -0
  37. package/templates/blog/package.json +14 -0
  38. package/templates/blog/rosetack.config.js +1 -0
  39. package/templates/blog/src/pages/404.rose +2 -0
  40. package/templates/blog/src/pages/_layout.rose +42 -0
  41. package/templates/blog/src/pages/_middleware.rose +74 -0
  42. package/templates/blog/src/pages/admin.rose +85 -0
  43. package/templates/blog/src/pages/api/login.rose +46 -0
  44. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  45. package/templates/blog/src/pages/api/posts.rose +72 -0
  46. package/templates/blog/src/pages/index.rose +31 -0
  47. package/templates/blog/src/pages/post/[id].rose +36 -0
  48. package/templates/site/package.json +14 -0
  49. package/templates/site/rosetack.config.js +1 -0
  50. package/templates/site/src/pages/404.rose +2 -0
  51. package/templates/site/src/pages/_layout.rose +40 -0
  52. package/templates/site/src/pages/about.rose +6 -0
  53. package/templates/site/src/pages/index.rose +13 -0
  54. package/templates/site/src/pages/pricing.rose +8 -0
@@ -225,21 +225,50 @@ function skipTemplate(src, i) {
225
225
  }
226
226
  return j;
227
227
  }
228
+ function skipLiteral(src, i) {
229
+ const q = src[i];
230
+ if (q === '"' || q === "'") return skipQuoted(src, i);
231
+ if (q === "`") return skipTemplate(src, i);
232
+ if (q !== "/") return null;
233
+ if (src[i + 1] === "/" || src[i + 1] === "*") return null;
234
+ let b = i - 1;
235
+ while (b >= 0 && /\s/.test(src[b])) b--;
236
+ if (b >= 0) {
237
+ if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
238
+ const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
239
+ if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
240
+ }
241
+ }
242
+ let j = i + 1;
243
+ let inClass = false;
244
+ while (j < src.length) {
245
+ const c = src[j];
246
+ if (c === "\\") {
247
+ j += 2;
248
+ continue;
249
+ }
250
+ if (c === "\n") return null;
251
+ if (inClass) {
252
+ if (c === "]") inClass = false;
253
+ } else if (c === "[") inClass = true;
254
+ else if (c === "/") {
255
+ j++;
256
+ break;
257
+ }
258
+ j++;
259
+ }
260
+ if (j > src.length) return null;
261
+ while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
262
+ return j;
263
+ }
228
264
  function stripComments(src) {
229
265
  let out = "";
230
266
  let i = 0;
231
267
  while (i < src.length) {
232
- const q = src[i];
233
- if (q === '"' || q === "'") {
234
- const end = skipQuoted(src, i);
235
- out += src.slice(i, end);
236
- i = end;
237
- continue;
238
- }
239
- if (q === "`") {
240
- const end = skipTemplate(src, i);
241
- out += src.slice(i, end);
242
- i = end;
268
+ const lit = skipLiteral(src, i);
269
+ if (lit !== null) {
270
+ out += src.slice(i, lit);
271
+ i = lit;
243
272
  continue;
244
273
  }
245
274
  if (src.startsWith("//", i)) {
@@ -262,6 +291,167 @@ function stripComments(src) {
262
291
  }
263
292
  return out;
264
293
  }
294
+ function stripGuardedBranches(src) {
295
+ const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
296
+ const ws = (i2) => {
297
+ while (i2 < src.length && /\s/.test(src[i2])) i2++;
298
+ return i2;
299
+ };
300
+ const ternaryColon = (q) => {
301
+ let depth = 0;
302
+ let i2 = q + 1;
303
+ while (i2 < src.length) {
304
+ const c = src[i2];
305
+ const lit = skipLiteral(src, i2);
306
+ if (lit !== null) {
307
+ i2 = lit;
308
+ continue;
309
+ }
310
+ if (c === "(" || c === "[" || c === "{") depth++;
311
+ else if (c === ")" || c === "]" || c === "}") {
312
+ depth--;
313
+ if (depth < 0) return -1;
314
+ } else if (depth === 0 && c === ":") return i2;
315
+ else if (depth === 0 && c === "?") {
316
+ const inner = ternaryColon(i2);
317
+ if (inner < 0) return -1;
318
+ i2 = inner + 1;
319
+ continue;
320
+ }
321
+ i2++;
322
+ }
323
+ return -1;
324
+ };
325
+ const exprEnd = (i2) => {
326
+ let depth = 0;
327
+ while (i2 < src.length) {
328
+ const c = src[i2];
329
+ const lit = skipLiteral(src, i2);
330
+ if (lit !== null) {
331
+ i2 = lit;
332
+ continue;
333
+ }
334
+ if (c === "(" || c === "[" || c === "{") depth++;
335
+ else if (c === ")" || c === "]" || c === "}") {
336
+ if (depth === 0) return i2;
337
+ depth--;
338
+ } else if (depth === 0 && (c === "," || c === ";")) return i2;
339
+ else if (depth === 0 && c === "?") {
340
+ const inner = ternaryColon(i2);
341
+ if (inner < 0) return src.length;
342
+ i2 = inner + 1;
343
+ continue;
344
+ }
345
+ i2++;
346
+ }
347
+ return src.length;
348
+ };
349
+ const braceEnd = (b) => {
350
+ let depth = 0;
351
+ let i2 = b;
352
+ while (i2 < src.length) {
353
+ const c = src[i2];
354
+ const lit = skipLiteral(src, i2);
355
+ if (lit !== null) {
356
+ i2 = lit;
357
+ continue;
358
+ }
359
+ if (c === "{") depth++;
360
+ else if (c === "}") {
361
+ depth--;
362
+ if (depth === 0) return i2;
363
+ }
364
+ i2++;
365
+ }
366
+ return src.length;
367
+ };
368
+ const stmtEnd = (i2) => {
369
+ let depth = 0;
370
+ while (i2 < src.length) {
371
+ const c = src[i2];
372
+ const lit = skipLiteral(src, i2);
373
+ if (lit !== null) {
374
+ i2 = lit;
375
+ continue;
376
+ }
377
+ if (c === "(" || c === "[" || c === "{") depth++;
378
+ else if (c === ")" || c === "]" || c === "}") {
379
+ if (depth === 0) return i2;
380
+ depth--;
381
+ } else if (depth === 0 && (c === ";" || c === "\n")) return i2;
382
+ i2++;
383
+ }
384
+ return src.length;
385
+ };
386
+ const isIfGuard = (src2, at) => {
387
+ let b = at - 1;
388
+ while (b >= 0 && /\s/.test(src2[b])) b--;
389
+ if (b < 0 || src2[b] !== "(") return false;
390
+ b--;
391
+ while (b >= 0 && /\s/.test(src2[b])) b--;
392
+ return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
393
+ };
394
+ const blanks = [];
395
+ let i = 0;
396
+ while (i < src.length) {
397
+ const lit = skipLiteral(src, i);
398
+ if (lit !== null) {
399
+ i = lit;
400
+ continue;
401
+ }
402
+ GUARD.lastIndex = i;
403
+ const m = GUARD.exec(src);
404
+ if (!m) {
405
+ i++;
406
+ continue;
407
+ }
408
+ const browserAfter = m[1] === "!==";
409
+ const j = ws(i + m[0].length);
410
+ const two = src.slice(j, j + 2);
411
+ if (two === "&&" && browserAfter) {
412
+ blanks.push([j + 2, exprEnd(j + 2)]);
413
+ } else if (two === "||" && !browserAfter) {
414
+ blanks.push([j + 2, exprEnd(j + 2)]);
415
+ } else if (src[j] === "?") {
416
+ const colon = ternaryColon(j);
417
+ if (colon < 0) {
418
+ if (browserAfter) blanks.push([j + 1, src.length]);
419
+ } else if (browserAfter) {
420
+ blanks.push([j + 1, colon]);
421
+ } else {
422
+ blanks.push([colon + 1, exprEnd(colon + 1)]);
423
+ }
424
+ } else if (src[j] === ")" && isIfGuard(src, i)) {
425
+ let bodyEnd;
426
+ const k = ws(j + 1);
427
+ if (src[k] === "{") {
428
+ bodyEnd = braceEnd(k);
429
+ if (browserAfter) blanks.push([k + 1, bodyEnd]);
430
+ } else {
431
+ bodyEnd = stmtEnd(k);
432
+ if (browserAfter) blanks.push([k, bodyEnd]);
433
+ }
434
+ const after = ws(bodyEnd + 1);
435
+ if (src.startsWith("else", after)) {
436
+ const e = ws(after + 4);
437
+ if (src[e] === "{") {
438
+ const close = braceEnd(e);
439
+ if (!browserAfter) blanks.push([e + 1, close]);
440
+ } else {
441
+ const stop = stmtEnd(e);
442
+ if (!browserAfter) blanks.push([e, stop]);
443
+ }
444
+ }
445
+ }
446
+ i = j;
447
+ }
448
+ if (blanks.length === 0) return src;
449
+ const out = [...src];
450
+ for (const [a, b] of blanks) {
451
+ for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
452
+ }
453
+ return out.join("");
454
+ }
265
455
  function scriptOf(source) {
266
456
  return source.match(COMPONENT_RE)?.[1] ?? null;
267
457
  }
@@ -372,8 +562,9 @@ function scanSlotDecls(filePath) {
372
562
  } catch {
373
563
  return [];
374
564
  }
375
- const noBlocks = src.replace(STYLE_RE, "");
376
- const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
565
+ const noScript = src.replace(COMPONENT_RE, "");
566
+ const noBlocks = noScript.replace(STYLE_RE, "");
567
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
377
568
  const out = [];
378
569
  for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
379
570
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
@@ -441,6 +632,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
441
632
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
442
633
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
443
634
  const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
635
+ const ownRuntimeImports = new Set(
636
+ [...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
637
+ );
638
+ const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
639
+ const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
640
+ ` : "";
444
641
  return {
445
642
  ssr: "",
446
643
  client: "",
@@ -449,19 +646,19 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
449
646
  guardName: null,
450
647
  style: "",
451
648
  hasParams: false,
452
- api: `import { getContext, $query } from './runtime.js';
453
- ${rewriteRoseImports(`${hoisted.imports}
649
+ api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
454
650
  ${hoisted.rest}`, "ssr").trim()}`,
455
651
  apiMethods,
456
652
  hasPrerender,
457
653
  usesContext: usesContext2
458
654
  };
459
655
  }
460
- const sourceNoHead = source.replace(HEAD_RE, "");
656
+ const sourceNoScript = source.replace(COMPONENT_RE, "");
657
+ const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
461
658
  const styleMatch = sourceNoHead.match(STYLE_RE);
462
659
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
463
660
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
464
- const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
661
+ const scriptMatch = source.match(COMPONENT_RE);
465
662
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
466
663
  const rawScript = roseResolved.script;
467
664
  const roseImports = roseResolved.imports;
@@ -521,8 +718,11 @@ ${hoisted.rest}`, "ssr").trim()}`,
521
718
  }
522
719
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
523
720
  const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
721
+ const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
722
+ const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
524
723
  const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
525
724
  const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
725
+ const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
526
726
  if (csr === false) {
527
727
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
528
728
  if (dead) {
@@ -598,21 +798,22 @@ ${hoisted.rest}`, "ssr").trim()}`,
598
798
  if (!needsClient) {
599
799
  const codeOnly = stripComments(source);
600
800
  const scriptCodeOnly = stripComments(rawScript);
801
+ const scriptScannable = stripGuardedBranches(scriptCodeOnly);
601
802
  if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
602
803
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
603
804
  }
604
805
  if (/javascript:/i.test(codeOnly)) {
605
806
  jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
606
807
  }
607
- if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
808
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
608
809
  jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
609
810
  }
610
- if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(scriptCodeOnly)) {
811
+ if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(scriptScannable)) {
611
812
  jsWarnings.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true");
612
813
  }
613
814
  }
614
815
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
615
- const headContent = source.match(HEAD_RE)?.[1] ?? "";
816
+ const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
616
817
  const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
617
818
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
618
819
  const decls = extractDecls(script);
@@ -652,13 +853,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
652
853
  const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
653
854
  const wired = wireEventBindings(templateCalled, actionNames);
654
855
  const eventBindings = wired.bindings;
655
- const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
656
856
  const stateKeys = decls.map((d) => d.name);
657
857
  const comps = new Map(roseImports.map((r) => {
658
858
  const abs = path.resolve(path.dirname(filePath), r.specifier);
659
859
  const hit = registry.get(abs);
660
860
  return [r.name, { index: hit.index, slots: hit.slots }];
661
861
  }));
862
+ const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
863
+ assertKnownDirectives(ssrTemplate, filePath);
662
864
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
663
865
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
664
866
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -688,7 +890,9 @@ ${cleanScript}
688
890
  usesContext,
689
891
  revalidate,
690
892
  csr,
893
+ shell,
691
894
  buffer,
895
+ controlSignal,
692
896
  prefetch,
693
897
  vitals,
694
898
  bundle,
@@ -1042,6 +1246,108 @@ function compileHead(head) {
1042
1246
  flush();
1043
1247
  return out;
1044
1248
  }
1249
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
1250
+ function assertKnownDirectives(template, filePath) {
1251
+ const rawRanges = [];
1252
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
1253
+ let raw;
1254
+ while (raw = RAW_OPEN.exec(template)) {
1255
+ const tag = raw[1].toLowerCase();
1256
+ const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
1257
+ const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
1258
+ const end = gt < 0 ? template.length : gt + 1;
1259
+ rawRanges.push([raw.index, end]);
1260
+ RAW_OPEN.lastIndex = end;
1261
+ }
1262
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
1263
+ let note;
1264
+ while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
1265
+ rawRanges.sort((a, b) => a[0] - b[0]);
1266
+ const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
1267
+ const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
1268
+ let m;
1269
+ while (m = DIRECTIVE_RE.exec(template)) {
1270
+ if (inRaw(m.index)) continue;
1271
+ const [, sigil, word] = m;
1272
+ if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
1273
+ if (sigil === "/") {
1274
+ throw new RoseError(
1275
+ "E-TEMPLATE",
1276
+ `${filePath}: {/${word}} does not close anything`,
1277
+ { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
1278
+ );
1279
+ }
1280
+ if (word === "else") {
1281
+ throw new RoseError(
1282
+ "E-TEMPLATE",
1283
+ `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1284
+ { file: filePath, line: lineAt(template, m), hint: "nest a second {#if}: {#if cond}A{/if}{#if !cond}B{/if} - the negation of the first condition IS the else" }
1285
+ );
1286
+ }
1287
+ throw new RoseError(
1288
+ "E-TEMPLATE",
1289
+ `${filePath}: {:${word}} is not a rosetack directive`,
1290
+ { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary} - and there is no {:else}: nest a second {#if} with the negated condition" }
1291
+ );
1292
+ }
1293
+ const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
1294
+ while (m = OPENER_RE.exec(template)) {
1295
+ if (inRaw(m.index)) continue;
1296
+ const [, kind, head] = m;
1297
+ if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
1298
+ throw new RoseError(
1299
+ "E-TEMPLATE",
1300
+ `${filePath}: {#each ${head.trim()}} is missing its item name`,
1301
+ { file: filePath, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
1302
+ );
1303
+ }
1304
+ const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
1305
+ const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
1306
+ let depth = 1;
1307
+ let i = m.index + m[0].length;
1308
+ for (; ; ) {
1309
+ OPEN_RE.lastIndex = i;
1310
+ CLOSE_RE.lastIndex = i;
1311
+ const nextOpen = OPEN_RE.exec(template);
1312
+ const nextClose = CLOSE_RE.exec(template);
1313
+ if (!nextClose) break;
1314
+ if (nextOpen && nextOpen.index < nextClose.index) {
1315
+ i = nextOpen.index + nextOpen[0].length;
1316
+ continue;
1317
+ }
1318
+ i = nextClose.index + nextClose[0].length;
1319
+ if (--depth === 0) break;
1320
+ }
1321
+ if (depth !== 0) {
1322
+ throw new RoseError(
1323
+ "E-TEMPLATE",
1324
+ `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
1325
+ { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
1326
+ );
1327
+ }
1328
+ }
1329
+ }
1330
+ function rewriteQuotedExprAttrs(template, comps) {
1331
+ const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
1332
+ return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
1333
+ if (comps.has(name) || !/\{/.test(attrs)) return tag;
1334
+ const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
1335
+ if (!/\{/.test(value) || value.includes("`")) return whole;
1336
+ const spans = templateExprSpans(value);
1337
+ if (spans.length === 0) return whole;
1338
+ let expr = "";
1339
+ let last = 0;
1340
+ for (const s of spans) {
1341
+ if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
1342
+ expr += (expr ? " + " : "") + `(${s.expr})`;
1343
+ last = s.end + 1;
1344
+ }
1345
+ if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
1346
+ return `${attr}={${expr}}`;
1347
+ });
1348
+ return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
1349
+ });
1350
+ }
1045
1351
  function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
1046
1352
  let result = "";
1047
1353
  let remaining = template;
@@ -1061,6 +1367,25 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1061
1367
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
1062
1368
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
1063
1369
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
1370
+ const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
1371
+ const rawHit = rawOpenRe.exec(remaining);
1372
+ if (rawHit && earliest && rawHit.index < earliest.index) {
1373
+ const tag = rawHit[1].toLowerCase();
1374
+ const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
1375
+ const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
1376
+ const end = gt < 0 ? remaining.length : gt + 1;
1377
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1378
+ remaining = remaining.substring(end);
1379
+ continue;
1380
+ }
1381
+ const noteAt = remaining.indexOf("<!--");
1382
+ if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
1383
+ const noteEnd = remaining.indexOf("-->", noteAt + 4);
1384
+ const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
1385
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1386
+ remaining = remaining.substring(end);
1387
+ continue;
1388
+ }
1064
1389
  if (!earliest) {
1065
1390
  result += emitChunk(remaining, acc, closes, scope);
1066
1391
  break;
@@ -1452,7 +1777,8 @@ function compileSlot(acc) {
1452
1777
  return `${acc} += String(children);
1453
1778
  `;
1454
1779
  }
1455
- var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark } from './runtime.js';`;
1780
+ var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
1781
+ var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1456
1782
  function propsCode(props) {
1457
1783
  if (props.length === 0) return "";
1458
1784
  return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
@@ -1464,16 +1790,7 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1464
1790
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1465
1791
  return { o, fn };
1466
1792
  };
1467
- const __slotBlock = (closes, sl, name, pairs) => {
1468
- const hit = __slot(sl, name, pairs);
1469
- const idx = closes.length;
1470
- closes.push(() => {
1471
- if (!hit) return null;
1472
- const c = [];
1473
- return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
1474
- });
1475
- return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1476
- };`;
1793
+ const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
1477
1794
  function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1478
1795
  const headCode = headFn ? `
1479
1796
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -1498,9 +1815,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1498
1815
  ${script}
1499
1816
  ${stateDeclsCode}
1500
1817
  ${dataDeclsCode}
1501
- // The incremental patches of the action that produced THIS response,
1502
- // applied to the state the declarations above just established (a no-op on
1503
- // every path that is not a server action's re-render - see the runtime).
1818
+
1504
1819
  ${isComponent ? "" : "applyStateDeltas();"}
1505
1820
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1506
1821
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
@@ -1510,6 +1825,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1510
1825
  }
1511
1826
  function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1512
1827
  const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1828
+ const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
1513
1829
  const headCode = headFn ? `
1514
1830
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1515
1831
  __html += headMark(closes, __head);` : "";
@@ -1519,7 +1835,9 @@ ${RUNTIME_IMPORTS}
1519
1835
  ${imports}
1520
1836
 
1521
1837
  ${exports}
1522
-
1838
+ ${clientSetState ? `
1839
+ ${clientSetState}
1840
+ ` : ""}
1523
1841
  ${namedSlots ? SLOT_HELPER : ""}
1524
1842
 
1525
1843
  export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
@@ -1542,6 +1860,7 @@ var routeShipsNoJs = (infos, compiled, i) => {
1542
1860
  if (compiled[i].needsClient) return false;
1543
1861
  return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1544
1862
  };
1863
+ var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
1545
1864
  function buildReport(infos, compiled) {
1546
1865
  return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
1547
1866
  if (routeShipsNoJs(infos, compiled, i)) {
@@ -1552,6 +1871,48 @@ function buildReport(infos, compiled) {
1552
1871
  return `${info.routePath} client JS ${why}${forced}`;
1553
1872
  });
1554
1873
  }
1874
+ var MOUNT_ENTRY = `
1875
+ import { start, postForm } from '/client.js';
1876
+
1877
+ for (const el of document.querySelectorAll('[data-rosetack]')) {
1878
+ const route = el.getAttribute('data-rosetack');
1879
+ const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
1880
+ const parsed = new DOMParser().parseFromString(doc, 'text/html');
1881
+ // A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
1882
+ const app = parsed.getElementById('app');
1883
+ if (app) {
1884
+ el.innerHTML = app.innerHTML;
1885
+ } else {
1886
+ for (const node of Array.from(parsed.body.children)) {
1887
+ if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
1888
+ }
1889
+ }
1890
+ // start() resumes from #__rosetack_state (zero hydration), so the state
1891
+
1892
+ const state = parsed.getElementById('__rosetack_state');
1893
+ if (state) el.appendChild(state);
1894
+
1895
+ const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
1896
+ await start(el, route, rendered === route);
1897
+ if (state) state.remove();
1898
+
1899
+ el.addEventListener('click', (e) => {
1900
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
1901
+ if (!a || !el.contains(a)) return;
1902
+ e.preventDefault();
1903
+ el.setAttribute('data-rosetack', a.getAttribute('href'));
1904
+ start(el, a.getAttribute('href'), false);
1905
+ });
1906
+ // Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
1907
+ el.addEventListener('submit', (e) => {
1908
+ const f = e.target;
1909
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
1910
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
1911
+ e.preventDefault();
1912
+ postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
1913
+ });
1914
+ }
1915
+ `;
1555
1916
  async function buildProject(root, outDir) {
1556
1917
  await fs.promises.mkdir(outDir, { recursive: true });
1557
1918
  const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
@@ -1653,9 +2014,7 @@ async function buildProject(root, outDir) {
1653
2014
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1654
2015
  if (runtimePlugins.length > 0) {
1655
2016
  const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
1656
- await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
1657
- // Bundled into dist/server.js: these hooks run per request on every server
1658
- // (Node, dev/preview, edge). Transform hooks already ran at build time.
2017
+ await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
1659
2018
  import config from ${JSON.stringify(configRel)};
1660
2019
 
1661
2020
  const list = Array.isArray(config) ? config : [];
@@ -1684,8 +2043,34 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1684
2043
  await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1685
2044
  }
1686
2045
  }
1687
- const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1688
- const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi);
2046
+ const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).sort((a, b) => {
2047
+ const rank = (pattern) => {
2048
+ const segs = pattern.split("/");
2049
+ return [
2050
+ segs.filter((s) => s.startsWith("**")).length,
2051
+ segs.filter((s) => s.startsWith("*")).length,
2052
+ segs.filter((s) => s.startsWith(":")).length
2053
+ ];
2054
+ };
2055
+ const ra = rank(a.info.pattern);
2056
+ const rb = rank(b.info.pattern);
2057
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2058
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2059
+ });
2060
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
2061
+ const rank = (pattern) => {
2062
+ const segs = pattern.split("/");
2063
+ return [
2064
+ segs.filter((s) => s.startsWith("**")).length,
2065
+ segs.filter((s) => s.startsWith("*")).length,
2066
+ segs.filter((s) => s.startsWith(":")).length
2067
+ ];
2068
+ };
2069
+ const ra = rank(a.info.pattern);
2070
+ const rb = rank(b.info.pattern);
2071
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2072
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2073
+ });
1689
2074
  const compose = (idx) => {
1690
2075
  let expr = `render_${idx}`;
1691
2076
  for (const i of layoutsOf(infos, idx)) {
@@ -1716,8 +2101,16 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1716
2101
  const named = [actionImports, guardImport].filter(Boolean).join(", ");
1717
2102
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1718
2103
  }).join("\n");
1719
- const nfIdx = infos.findIndex((info) => info.isNotFound);
1720
- const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
2104
+ const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
2105
+ const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
2106
+ const dir = path.posix.dirname(rel);
2107
+ const prefix = dir === "." ? "/" : "/" + dir;
2108
+ const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
2109
+ return { prefix, render: split ? loaderOf(i) : compose(i), flags };
2110
+ }).sort((a, b) => b.prefix.length - a.prefix.length);
2111
+ const notFoundTable = `[
2112
+ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
2113
+ ]`;
1721
2114
  const errIdx = infos.findIndex((info) => info.isError);
1722
2115
  const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
1723
2116
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
@@ -1741,9 +2134,11 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1741
2134
  }
1742
2135
  }
1743
2136
  const csrFlag = routeNoJs(i) ? ", csr: false" : "";
2137
+ const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
1744
2138
  const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
2139
+ const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
1745
2140
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1746
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
2141
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
1747
2142
  }).join(",\n ");
1748
2143
  const serverEntry = `
1749
2144
  ${serverImports}
@@ -1755,12 +2150,7 @@ const __pluginHooks = [];
1755
2150
  const __hasRequestHooks = false;
1756
2151
  const __hasResponseHooks = false;`}
1757
2152
 
1758
- // The runtime plugin hooks. onRequest runs before routing and
1759
- // middleware and may short-circuit the request with its own Response; onResponse
1760
- // runs once the response exists and may replace it. Both are no-ops when the
1761
- // project declares no runtime hooks. A throwing hook is logged and skipped -
1762
- // the request continues - so a broken logging plugin can never take a site
1763
- // down (a build-time transform, by contrast, fails loudly).
2153
+
1764
2154
  export async function runRequestHooks(ctx) {
1765
2155
  for (const p of __pluginHooks) {
1766
2156
  if (!p.onRequest) continue;
@@ -1788,32 +2178,20 @@ export async function runResponseHooks(ctx, res) {
1788
2178
  return out;
1789
2179
  }
1790
2180
 
1791
- // The servers read these to skip building the hook context entirely when no
1792
- // hook exists - the hot path pays nothing for the feature.
2181
+
2182
+
1793
2183
  export const hasRequestHooks = __hasRequestHooks;
1794
2184
  export const hasResponseHooks = __hasResponseHooks;
1795
2185
 
1796
- // P0-1: the query of the request being rendered, for $query(). The servers
1797
- // call this before every render (stream, buffered, POST, api) with the parsed
1798
- // query string; routing itself matches the pathname, which is what fixed the
1799
- // query-404. A render with no query (the build's prerender, the ISR
1800
- // background pass) passes {} explicitly - the bag is per request, so a stale
1801
- // one must never leak into the next.
2186
+ // P0-1: the query of the request being rendered, for $query().
1802
2187
  export function setQuery(query) {
1803
2188
  setRequestQuery(query || {});
1804
2189
  }
1805
2190
 
1806
- // i18n: the dictionaries baked at build time from
1807
- // src/locales/*.json. A route segment named [lang] is the locale: the value
1808
- // must name one of these dictionaries, and $t resolves keys against it.
2191
+
1809
2192
  setLocales(${localesJson}, '${defaultLocale}');
1810
2193
 
1811
- // The store transport. Under "rosetack serve" every worker is its
1812
- // own process with its own dist/server.js module, so a $store write must
1813
- // travel: this worker -> primary -> every other worker. process.send exists
1814
- // only inside cluster workers, so a single-process runner (dev, preview,
1815
- // the edge adapter) keeps the transport null and $store stays plain
1816
- // per-process state - the documented boundary, not a bug.
2194
+
1817
2195
  if (typeof process !== 'undefined' && typeof process.send === 'function') {
1818
2196
  setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1819
2197
  process.on('message', (msg) => {
@@ -1821,76 +2199,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1821
2199
  });
1822
2200
  }
1823
2201
 
2202
+ // (the cross-machine seam): the cluster relay above covers ONE machine.
2203
+ export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
2204
+ setStoreTransport(send);
2205
+ }
2206
+ export function __deliverStorePatch(name: string, value: unknown): void {
2207
+ applyStorePatch(name, value);
2208
+ }
2209
+
1824
2210
  export { localeList };
1825
2211
  export const defaultLocale = '${defaultLocale}';
1826
2212
 
1827
- // Route params maps, re-exported for the build's prerender step: routePath
1828
- // -> the component's exported params (a static map or a function). Reading
1829
- // them through the server bundle keeps the deploy dir free of component
1830
- // modules - both bundles are self-contained, nothing else may ship. Only
1831
- // components that actually export params appear here (a missing export
1832
- // means the dynamic route renders on demand).
2213
+ // Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
1833
2214
  ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1834
2215
 
1835
2216
  export const routeParams = {
1836
2217
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1837
2218
  };
1838
2219
 
1839
- // Routes whose component reads the request context (getContext()), mutates a
1840
- // shared store ($store()), reads the query ($query(), P0-1), opted into
1841
- // nonce-based CSP or into the buffered path (buffer = true, P0-2):
1842
- // the bag is per-request, the store is per-process, a nonce is per-response,
1843
- // and a buffered route's hooks must run per request - so these are dynamic.
1844
- // The build never bakes them and the servers never answer them from a
1845
- // prerendered file. Public routes keep the static fast path (file cache,
1846
- // ETag/304, streaming) untouched.
2220
+ // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
1847
2221
  export const dynamicRoutes = [
1848
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
2222
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1849
2223
  ];
1850
2224
 
1851
- // Which api routes opt into build-time baking (export const prerender = true):
1852
- // routePath -> boolean. The build calls the GET handler once and writes the
1853
- // body to dist/, so the Go single binary serves read-only APIs without Node.
2225
+ // Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
1854
2226
  ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1855
2227
 
1856
2228
  export const apiPrerender = {
1857
2229
  ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1858
2230
  };
1859
2231
 
1860
- // Stale-while-revalidate windows (export const revalidate = N): the build
1861
- // bakes these routes like any other, and the preview server serves the
1862
- // baked file for up to N seconds - after which the next request is answered
1863
- // STALE (instant, from disk) while a background pass re-renders and swaps
1864
- // the file (ISR). Routes that read the request context are
1865
- // excluded: they render per request and have no baked file to revalidate.
1866
- // The dev server ignores the window (it rebuilds on change), the edge
1867
- // adapter renders live (always fresh), and the Go binary serves the baked
1868
- // file forever - the same static-half boundary as page POSTs.
2232
+
1869
2233
  export const revalidate = [
1870
2234
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1871
2235
  ];
1872
2236
 
1873
- // pages/_middleware.rose: a Web-standard request handler that runs before
1874
- // every render on the server (pages, POSTs, api calls alike). Returning a
1875
- // Response short-circuits the whole request - a redirect, an auth wall, a
1876
- // rewrite; returning nothing continues, and getContext() hands the
1877
- // per-request bag to $data, server actions and api handlers. Absent -> null,
1878
- // and the servers keep their static fast paths.
2237
+ // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
1879
2238
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1880
2239
 
1881
- // Routes whose DOCUMENTS ship without the client bundle (
1882
- // decided by the compiler since #29): HTML + CSS only - no runtime, no
1883
- // state script, zero JavaScript for whoever lands on them. The compiler
1884
- // picks these automatically: a route whose whole chain needs nothing from
1885
- // the client (no event wiring, no lifecycle, no action, no form) is a
1886
- // content route. An exported "csr = true" forces the bundle back in; an
1887
- // exported "csr = false" is the same decision, asserted. The route's render
1888
- // function still rides in the client bundle, so a client-side navigation
1889
- // from an interactive page paints it normally and a static deploy's SPA
1890
- // fallback can render it too; only the document is JS-free.
1891
- // isNoJs() lets the servers keep these routes on the buffered path: a
1892
- // streamed no-JS document would carry the shell's default <title> (the
1893
- // route head is applied client-side at boot, and there is no client).
2240
+ // Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
1894
2241
  export const noJsRoutes = [
1895
2242
  ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1896
2243
  ];
@@ -1899,21 +2246,12 @@ export function isNoJs(pathname) {
1899
2246
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1900
2247
  }
1901
2248
 
1902
- // P0-2 (bug report): routes that exported "buffer = true". The servers ask
1903
- // this BEFORE choosing a path: a streamed response commits its status and
1904
- // headers before the body exists, so its onResponse hooks cannot see the
1905
- // document and a render that throws mid-flight still answers 200. A buffered
1906
- // route keeps every capability and gives up the early flush - the trade is
1907
- // the route's to make, per route, not the framework's.
2249
+ // P0-2 (bug report): routes that exported "buffer = true".
1908
2250
  export function isBuffered(pathname) {
1909
- return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
2251
+ return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
1910
2252
  }
1911
2253
 
1912
- // Per-route response headers: a route exporting a headers
1913
- // map carries them into every response the servers write for it, merged
1914
- // OVER the framework defaults (the strict CSP) - so an app can tighten or
1915
- // relax the policy per route. Absent -> null, and the servers keep sending
1916
- // the defaults alone.
2254
+
1917
2255
  export const routeHeaders = [
1918
2256
  ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1919
2257
  ];
@@ -1923,14 +2261,7 @@ export function headersFor(pathname) {
1923
2261
  return hit ? hit.headers : null;
1924
2262
  }
1925
2263
 
1926
- // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
1927
- // ). The servers ask this BEFORE writing a document: when it is true they
1928
- // mint one random nonce per response, put it in the CSP header ('nonce-...'
1929
- // plus 'strict-dynamic', so the document's own code may load more code) and
1930
- // stamp the same value on the script tag. The default policy stays a hash -
1931
- // cspNonceRoutes is empty for an app that never asks, so the fast path is
1932
- // unchanged. The Go binary never sees this: these routes are dynamic, so it
1933
- // has no baked file for them to serve.
2264
+
1934
2265
  export const cspNonceRoutes = [
1935
2266
  ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1936
2267
  ];
@@ -1939,9 +2270,7 @@ export function cspNonce(pathname) {
1939
2270
  return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1940
2271
  }
1941
2272
 
1942
- // A Web-standard Request from whatever the host provides: the edge adapter
1943
- // passes one already; the Node server passes its IncomingMessage (plus the
1944
- // already-parsed FormData for POSTs, so middleware can read form fields).
2273
+ // A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
1945
2274
  function toWebRequest(raw, form) {
1946
2275
  if (raw instanceof Request) return raw;
1947
2276
  const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
@@ -1949,13 +2278,7 @@ function toWebRequest(raw, form) {
1949
2278
  return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1950
2279
  }
1951
2280
 
1952
- // Runs the middleware (if the project has one) for this request and returns
1953
- // its short-circuit Response, or null to continue. The servers call this
1954
- // EXACTLY ONCE per request, before anything else: it resets the per-request
1955
- // context bag and the middleware fills it via getContext(), which $data,
1956
- // server actions and api handlers then read while rendering. rawReq: the
1957
- // host's request (Node IncomingMessage or a Web-standard Request); form:
1958
- // the already-parsed FormData of a POST.
2281
+
1959
2282
  export async function runMiddleware(rawReq, form) {
1960
2283
  resetRequestContext();
1961
2284
  if (!middleware || !rawReq) return null;
@@ -1967,10 +2290,7 @@ const routes = [
1967
2290
  ${serverRoutes}
1968
2291
  ];
1969
2292
 
1970
- // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
1971
- // render HTML and never reach the client bundle. The middleware ran before
1972
- // this (the servers call runMiddleware() first), so handlers can read
1973
- // getContext() for auth without re-running anything.
2293
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
1974
2294
  const apiRoutes = [
1975
2295
  ${apiRoutes.map(({ info, i }) => {
1976
2296
  const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -1978,19 +2298,40 @@ const apiRoutes = [
1978
2298
  }).join(",\n ")}
1979
2299
  ];
1980
2300
 
1981
- // pages/404.rose (with its layouts) or null -> built-in plain 404
1982
- const notFound = ${notFoundRender};
2301
+ // Not-found pages, deepest segment first: the root 404.rose ('/') and any
2302
+ // pages/<seg>/_notfound.rose, each already composed with its layout chain.
2303
+ // notFoundFor picks the nearest one up the path - an /admin miss answers
2304
+ // the admin 404, a public miss the site's - and notFoundPage is the whole
2305
+ // answer (real 404 status, or the built-in plain 404 when the app has none).
2306
+ const notFoundRoutes = ${notFoundTable};
2307
+ const notFoundFor = (pathname) => {
2308
+ for (const [prefix, render] of notFoundRoutes) {
2309
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2310
+ }
2311
+ return null;
2312
+ };
2313
+
2314
+ const notFoundFlags = (pathname) => {
2315
+ for (const [prefix, render, flags] of notFoundRoutes) {
2316
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
2317
+ }
2318
+ return null;
2319
+ };
2320
+ const notFoundPage = async (pathname) => {
2321
+ const nf = notFoundFor(pathname);
2322
+ if (nf) {
2323
+ const page = await renderFallback(pathname, nf);
2324
+ // __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
2325
+ return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
2326
+ }
2327
+ return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
2328
+ };
2329
+
1983
2330
 
1984
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1985
2331
  // whose render throws degrades to this instead of failing the response.
1986
2332
  const errorPage = ${errorRender};
1987
2333
 
1988
- // The <html> attributes of the document for a pathname - the locale
1989
- // of its [lang] segment (the default when there is none, or when the segment
1990
- // names no dictionary: that request 404s in the default language) and the
1991
- // reading direction that locale implies. The buffered render returns the same
1992
- // pair; the streaming path needs it BEFORE the shell flushes, which is why
1993
- // the servers ask for it by pathname.
2334
+
1994
2335
  export function docAttrs(pathname) {
1995
2336
  for (const route of routes) {
1996
2337
  if (!matchRoute(route.pattern, pathname)) continue;
@@ -2000,7 +2341,7 @@ export function docAttrs(pathname) {
2000
2341
  const lang = pathname.split('/')[langIdx];
2001
2342
  if (isLocale(lang)) return { lang, dir: localeDir(lang) };
2002
2343
  }
2003
- break; // matched, but not a localized route (or a bogus locale): the default
2344
+ break;
2004
2345
  }
2005
2346
  return { lang: defaultLocale, dir: localeDir(defaultLocale) };
2006
2347
  }
@@ -2013,8 +2354,22 @@ async function renderFallback(pathname, render) {
2013
2354
  }
2014
2355
 
2015
2356
  export function matchRoute(pattern, pathname) {
2357
+ // Q0 (bug report): one canonical URL per route.
2358
+ pathname = pathname.replace(/\\/+$/, '') || '/';
2016
2359
  const patternParts = pattern.split('/');
2017
2360
  const pathParts = pathname.split('/');
2361
+
2362
+ const last = patternParts[patternParts.length - 1];
2363
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2364
+ const fixed = patternParts.slice(0, -1);
2365
+ if (pathParts.length < fixed.length) return false;
2366
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2367
+ for (let i = 0; i < fixed.length; i++) {
2368
+ if (fixed[i].startsWith(':')) continue;
2369
+ if (fixed[i] !== pathParts[i]) return false;
2370
+ }
2371
+ return true;
2372
+ }
2018
2373
  if (patternParts.length !== pathParts.length) return false;
2019
2374
  for (let i = 0; i < patternParts.length; i++) {
2020
2375
  if (patternParts[i].startsWith(':')) continue;
@@ -2023,13 +2378,7 @@ export function matchRoute(pattern, pathname) {
2023
2378
  return true;
2024
2379
  }
2025
2380
 
2026
- // Head blocks (one per component in the route chain) are pulled out of the
2027
- // page html: the shell injects them into <head>, and the client re-applies
2028
- // them on navigation. Document order is page-first, so the shell's keyed
2029
- // merge lets a page override its layouts. The EMPTY marker pair stays in the
2030
- // body so the client's wire() still finds the block: at boot it adopts the
2031
- // shell-injected elements in place (marked with the same keys, so no
2032
- // duplicates) and keeps the head reactive.
2381
+ // Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
2033
2382
  function extractHead(rendered) {
2034
2383
  const head = [];
2035
2384
  const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
@@ -2039,18 +2388,7 @@ function extractHead(rendered) {
2039
2388
  return { html, head };
2040
2389
  }
2041
2390
 
2042
- // form: the submitted FormData of a progressive-enhancement POST. The
2043
- // selected server action runs first and returns a state patch (e.g.
2044
- // { guests: [...] }); seeding those keys BEFORE the render makes state()
2045
- // adopt them, so the response is the page as it looks AFTER the action -
2046
- // with or without JS. A __action field picks the action by name (default
2047
- // 'action', the conventional <form method="POST"> target); a click handler
2048
- // bound to an action ($action('like')) sends the same field.
2049
- // A route whose render throws degrades to pages/500.rose (status 500) - or
2050
- // the built-in plain 500 - instead of failing the whole response.
2051
- // The middleware does NOT run here: the servers run it once per request via
2052
- // runMiddleware() (which also seeds the request context), so a page render
2053
- // never re-runs it.
2391
+ // Form: the submitted FormData of a progressive-enhancement POST.
2054
2392
  export async function renderPage(pathname, form) {
2055
2393
  clearRequestState();
2056
2394
  for (const route of routes) {
@@ -2058,31 +2396,21 @@ export async function renderPage(pathname, form) {
2058
2396
  const patternParts = route.pattern.split('/');
2059
2397
  const pathParts = pathname.split('/');
2060
2398
  for (let i = 0; i < patternParts.length; i++) {
2061
- if (patternParts[i].startsWith(':')) {
2062
- setState(patternParts[i].slice(1), pathParts[i]);
2063
- }
2399
+ const seg = patternParts[i];
2400
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2401
+
2402
+
2403
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2064
2404
  }
2065
- // i18n: a [lang] segment naming no dictionary is a
2066
- // 404 - the URL is the contract, and rendering the page with fallback
2067
- // strings would serve duplicate content under a bogus language
2405
+ // I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
2068
2406
  const langIdx = patternParts.indexOf(':lang');
2069
2407
  if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
2070
- if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
2071
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2408
+ return await notFoundPage(pathname);
2072
2409
  }
2073
- // The document's <html lang>/<dir> follow this route's locale
2074
- // (the default's when the route is not localized)
2410
+
2411
+
2075
2412
  const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
2076
- // The action dispatch. The page's guard (exported
2077
- // beforeAction) runs FIRST and vetoes with an ActionError - the
2078
- // action-level permission check. Then the selected action runs and its
2079
- // return value seeds this render's state, per key, so an incremental
2080
- // patch ($append and friends) grows a large list by one row instead of
2081
- // re-sending the whole thing. An ActionError from either half is a
2082
- // BUSINESS failure: it is seeded as the 'actionError' state, the
2083
- // response carries its status, and the page renders with the failure
2084
- // visible (a {#boundary} around the action's widget contains it).
2085
- // Anything else is a bug and keeps going to the 500 page.
2413
+ // The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
2086
2414
  let actionStatus = 0;
2087
2415
  if (form && route.actions) {
2088
2416
  const actionName = form.get('__action') || 'action';
@@ -2094,9 +2422,7 @@ export async function renderPage(pathname, form) {
2094
2422
  if (patch && typeof patch === 'object') {
2095
2423
  for (const key of Object.keys(patch)) {
2096
2424
  const v = patch[key];
2097
- // An incremental patch is RECORDED, not applied: the render's
2098
- // own state declarations apply it, so the delta is relative to
2099
- // the value the page was going to render anyway.
2425
+ // An incremental patch is RECORDED, not applied: the render's own state declarations apply.
2100
2426
  if (v instanceof StateDelta) setStateDelta(key, v);
2101
2427
  else setState(key, v);
2102
2428
  }
@@ -2105,6 +2431,11 @@ export async function renderPage(pathname, form) {
2105
2431
  if (err instanceof ActionError) {
2106
2432
  setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
2107
2433
  actionStatus = err.code;
2434
+ } else if (err && err.__rosetack === 'redirect') {
2435
+
2436
+ return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
2437
+ } else if (err && err.__rosetack === 'notFound') {
2438
+ return await notFoundPage(pathname);
2108
2439
  } else {
2109
2440
  throw err;
2110
2441
  }
@@ -2115,32 +2446,27 @@ export async function renderPage(pathname, form) {
2115
2446
  try {
2116
2447
  rendered = extractHead(await route.render([], ''));
2117
2448
  } catch (err) {
2449
+ // The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
2450
+ const signal = err && err.__rosetack;
2451
+ if (signal === 'redirect') {
2452
+ return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
2453
+ }
2454
+ if (signal === 'notFound') {
2455
+ return await notFoundPage(pathname);
2456
+ }
2118
2457
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2119
2458
  if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
2120
2459
  return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2121
2460
  }
2122
2461
  // __route tells the bootstrap which route this document was rendered for.
2123
- // A static-file server may serve another route's document (SPA fallback);
2124
- // the bootstrap then client-renders instead of adopting mismatched DOM.
2125
2462
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2126
- // csr ( auto since #29): false when the compiler found
2127
- // nothing in the route's chain that needs the client (or the route
2128
- // asserted csr = false) - the document ships no runtime, no state
2129
- // script, zero JavaScript. Every other route keeps the bundle. The
2130
- // caller passes this straight to the shell as js.
2131
- // Status is the failed action's code when one failed - the page
2132
- // rendered fine, so the body is the page with the failure visible, and
2133
- // the status says what happened (a 403 from the guard, a 422 from a
2134
- // validation action). 200 otherwise.
2135
- // Lang/dir are the document's <html> attributes - the locale
2136
- // this route rendered in, and its reading direction.
2137
- return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
2463
+ // Csr ( auto since #29): false when the compiler found nothing in the route's chain that needs the client (or the route asserted csr = false) .
2464
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
2138
2465
  }
2139
2466
  }
2140
- if (notFound) {
2141
- return { ...(await renderFallback(pathname, notFound)), status: 404 };
2142
- }
2143
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2467
+
2468
+
2469
+ return await notFoundPage(pathname);
2144
2470
  }
2145
2471
 
2146
2472
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -2148,21 +2474,20 @@ export async function renderPage(pathname, form) {
2148
2474
  export function canStream(pathname) {
2149
2475
  return routes.some((route) => {
2150
2476
  if (!matchRoute(route.pattern, pathname)) return false;
2151
- // i18n: an unknown locale must answer 404, and a
2152
- // streamed response cannot change its status - so it takes the buffered
2153
- // path (renderPage returns the real 404), never the streaming one
2477
+ // I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
2154
2478
  const langIdx = route.pattern.split('/').indexOf(':lang');
2155
2479
  return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
2156
2480
  });
2157
2481
  }
2158
2482
 
2159
- // === API routes ===
2160
- // The /api namespace answers JSON, never HTML: an API client that hits an
2161
- // unknown path must not receive the SPA shell. Handlers receive a
2162
- // Web-standard Request and return a plain object (serialized as JSON, 200),
2163
- // a Response (passed through), or nothing (204). A method the route does
2164
- // not export answers 405 with an Allow header. Same code path on the Node
2165
- // server and the edge adapter - Response is a global in both.
2483
+
2484
+ export function shellOff(pathname) {
2485
+ return routes.some(
2486
+ (route) => route.shell === false && matchRoute(route.pattern, pathname),
2487
+ );
2488
+ }
2489
+
2490
+ // === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
2166
2491
  export function isApi(pathname) {
2167
2492
  return pathname === '/api' || pathname.startsWith('/api/');
2168
2493
  }
@@ -2186,7 +2511,25 @@ export async function handleApi(method, pathname, request) {
2186
2511
  headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
2187
2512
  });
2188
2513
  }
2189
- return toResponse(await fn(request));
2514
+ try {
2515
+ return toResponse(await fn(request));
2516
+ } catch (err) {
2517
+
2518
+ const signal = err && err.__rosetack;
2519
+ if (signal === 'redirect') {
2520
+ return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
2521
+ status: err.status ?? 307,
2522
+ headers: { 'content-type': 'application/json', location: err.path },
2523
+ });
2524
+ }
2525
+ if (signal === 'notFound') {
2526
+ return new Response(JSON.stringify({ error: 'not found' }), {
2527
+ status: 404,
2528
+ headers: { 'content-type': 'application/json' },
2529
+ });
2530
+ }
2531
+ throw err;
2532
+ }
2190
2533
  }
2191
2534
  }
2192
2535
  return new Response(JSON.stringify({ error: 'not found' }), {
@@ -2195,18 +2538,7 @@ export async function handleApi(method, pathname, request) {
2195
2538
  });
2196
2539
  }
2197
2540
 
2198
- // === Streaming SSR ===
2199
- // The static shell (doctype, <head>, body + container open) flushes BEFORE
2200
- // the - possibly slow - render completes: the first byte leaves in
2201
- // microseconds instead of after every $data resolves. The route HTML, the
2202
- // state script, and the inlined bundle follow as later chunks of one chunked
2203
- // response - still exactly one request.
2204
- // The route's <head> tags are NOT in the streamed document: the client
2205
- // applies them at boot from the body's head markers, so JS users see the
2206
- // correct head immediately; no-JS consumers of streamed responses get the
2207
- // static shell head (prerendered files stay complete documents).
2208
- // Returns 200 (matched; a render throw degrades to the error-page body) or
2209
- // 404 (unmatched - nothing written, so the caller can still buffer).
2541
+ // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
2210
2542
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2211
2543
  clearRequestState();
2212
2544
  for (const route of routes) {
@@ -2214,9 +2546,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2214
2546
  const patternParts = route.pattern.split('/');
2215
2547
  const pathParts = pathname.split('/');
2216
2548
  for (let i = 0; i < patternParts.length; i++) {
2217
- if (patternParts[i].startsWith(':')) {
2218
- setState(patternParts[i].slice(1), pathParts[i]);
2219
- }
2549
+ const seg = patternParts[i];
2550
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2551
+
2552
+
2553
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2220
2554
  }
2221
2555
  // i18n: an unknown locale must 404 BEFORE the shell flushes - a
2222
2556
  // streamed response cannot change its status afterwards
@@ -2227,23 +2561,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2227
2561
  try {
2228
2562
  html = extractHead(await route.render([], '')).html;
2229
2563
  } catch (err) {
2230
- // the shell is already on the wire: degrade to the error page BODY
2231
- // (the status stays 200 - a real 500 needs the buffered path, which
2232
- // the server picks for routes known-broken at build time)
2564
+
2233
2565
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2234
2566
  html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
2235
2567
  }
2236
2568
  write(html);
2237
- // csr: false ( auto since #29): a no-JS route's document
2238
- // ends here - no state script, no inlined bundle. (The servers keep
2239
- // these routes off the streaming path so their <head> is complete;
2240
- // this is the correctness floor if one streams anyway.)
2569
+ // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
2241
2570
  if (route.csr === false) {
2242
2571
  write('</div>\\n</body>\\n</html>');
2243
2572
  return 200;
2244
2573
  }
2245
2574
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2246
- write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
2575
+ // P1-6 (bug report): the JSON data block is embedded in the document.
2576
+ const stateSafe = state.replace(/</g, '\\\\u003c');
2577
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
2247
2578
  return 200;
2248
2579
  }
2249
2580
  }
@@ -2267,7 +2598,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2267
2598
  const vitalsBlock = vitalsOn ? `
2268
2599
  // the app asked for web-vitals - measure once, at boot, and let the
2269
2600
  // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2270
- reportVitals;
2601
+ reportVitals();
2271
2602
  ` : "";
2272
2603
  const hasLang = infos.some((i) => i.pattern.includes(":lang"));
2273
2604
  const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
@@ -2275,26 +2606,24 @@ reportVitals;
2275
2606
  // logical properties both read it). A route with no [lang] segment
2276
2607
  // returns to the default locale, and a bogus segment falls back to it
2277
2608
  // too, exactly like the server's docAttrs.
2609
+ // Only when this container IS the document's app root. A mount
2610
+ // (dist/mount.js) renders into a foreign page, whose language and
2611
+ // direction belong to the host, not to the mounted route.
2278
2612
  const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
2279
2613
  const known = !seg || isLocale(seg);
2280
- const docLang = known && seg ? seg : __defLocale;
2281
- document.documentElement.lang = docLang;
2282
- const docDir = localeDir(docLang);
2283
- if (docDir) document.documentElement.setAttribute('dir', docDir);
2284
- else document.documentElement.removeAttribute('dir');
2614
+ if (container === document.getElementById('app')) {
2615
+ const docLang = known && seg ? seg : __defLocale;
2616
+ document.documentElement.lang = docLang;
2617
+ const docDir = localeDir(docLang);
2618
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
2619
+ else document.documentElement.removeAttribute('dir');
2620
+ }
2285
2621
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2286
2622
  const clientEntry = `
2287
2623
  ${clientImports}
2288
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
2624
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
2289
2625
 
2290
- // i18n: the dictionaries baked at build time - the client
2291
- // renders any PRELOADED locale from the bundle, so switching language costs
2292
- // zero requests (the same bet as the inlined route table). a locale
2293
- // the app left out of the preload (i18n.preload in rosetack.config.js) is a
2294
- // pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
2295
- // on first use - one request per language per session, then it renders from
2296
- // memory like any other. The default build preloads everything and ships no
2297
- // packs at all.
2626
+ // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
2298
2627
  setLocales(${clientLocalesJson}, '${defaultLocale}');
2299
2628
  setLocalePacks(${JSON.stringify(packed)});
2300
2629
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
@@ -2304,10 +2633,7 @@ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2304
2633
  // reportVitals alive through minification and tree-shaking; the call is one
2305
2634
  // statement at boot, before the first render.
2306
2635
  import { reportVitals } from './runtime.js';` : ""}
2307
- // The two pack doors, re-exported for an app that wants to warm a language
2308
- // before its visitor asks for it (ensureLocale) or to feed a dictionary it
2309
- // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
2310
- // is what applyParams calls - so the re-export costs the statement alone.
2636
+ // The two pack doors, re-exported for an app that wants to warm a language before its visitor asks for it (ensureLocale) or to feed a dictionary.
2311
2637
  export { ensureLocale, loadLocale } from './runtime.js';
2312
2638
  ${vitalsBlock}
2313
2639
 
@@ -2315,14 +2641,7 @@ const routes = [
2315
2641
  ${clientRoutes}
2316
2642
  ];
2317
2643
 
2318
- // === Mode B: lazy route chunks ===
2319
- // Split mode's registry entries arrive without a render function: loadChain
2320
- // loads the route's module graph (the page plus its layouts, one chunk per
2321
- // module, the shared runtime in its own vendor chunk) in parallel and
2322
- // composes it at runtime - the exact nesting compose() built at compile
2323
- // time for inline mode. getRender memoizes the composed function on the
2324
- // entry, so a chunk loads once per session; inline mode's entries are the
2325
- // render functions themselves, so the helper is a pass-through there.
2644
+ // === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
2326
2645
  const loadChain = async (loaders) => {
2327
2646
  const mods = await Promise.all(loaders.map((load) => load()));
2328
2647
  let expr = (closes, children) => mods[0].render(closes, children);
@@ -2338,36 +2657,62 @@ const getRender = async (route) => {
2338
2657
  return (route.render ??= (await route.load()).render);
2339
2658
  };
2340
2659
 
2341
- // pages/404.rose (with its layouts) or null -> built-in plain 404
2342
- const notFound = ${notFoundRender};
2660
+ // Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
2661
+ const notFoundRoutes = ${notFoundTable};
2662
+ const notFoundFor = (pathname) => {
2663
+ for (const [prefix, render] of notFoundRoutes) {
2664
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2665
+ }
2666
+ return null;
2667
+ };
2343
2668
 
2344
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
2345
- // whose render throws on the client degrades to this instead of breaking
2346
- // navigation.
2669
+ // Pages/500.rose (with its layouts) or null -> built-in plain 500: a route whose render throws on the client degrades to this instead of breaking.
2347
2670
  const errorPage = ${errorRender};
2348
2671
 
2349
2672
  // Paint a fallback page (404/500) into the container, wired like any render.
2350
- async function paintFallback(container, page, builtin) {
2351
- resetEffects();
2352
- clearRequestState();
2673
+ async function paintFallback(container, page, builtin, keepState = false) {
2674
+ if (!keepState) __navReset(container);
2353
2675
  clearMounts(); // a failed render leaves stale mounts behind
2354
2676
  // inline mode passes the render itself; split mode passes a loader
2355
2677
  const render = page ? await getRender(page) : null;
2356
2678
  if (render) {
2357
2679
  const closes = [];
2358
- const html = await render(closes, '');
2359
- container.innerHTML = html;
2360
- wire(container, closes);
2361
- bindEvents(container);
2362
- flushMounts();
2680
+ await __withOwner(container, async () => {
2681
+ const html = await render(closes, '');
2682
+ container.innerHTML = html;
2683
+ wire(container, closes);
2684
+ bindEvents(container);
2685
+ flushMounts();
2686
+ });
2363
2687
  return;
2364
2688
  }
2365
2689
  container.innerHTML = builtin;
2366
2690
  }
2367
2691
 
2692
+
2693
+ export async function startNotFound(container, pathname) {
2694
+ const el = document.getElementById('__rosetack_state');
2695
+ if (el) resumeState(el.textContent);
2696
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
2697
+ }
2698
+
2368
2699
  export function matchRoute(pattern, pathname) {
2700
+ // Q0 (bug report): one canonical URL per route.
2701
+ pathname = pathname.replace(/\\/+$/, '') || '/';
2369
2702
  const patternParts = pattern.split('/');
2370
2703
  const pathParts = pathname.split('/');
2704
+
2705
+ const last = patternParts[patternParts.length - 1];
2706
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2707
+ const fixed = patternParts.slice(0, -1);
2708
+ if (pathParts.length < fixed.length) return false;
2709
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2710
+ for (let i = 0; i < fixed.length; i++) {
2711
+ if (fixed[i].startsWith(':')) continue;
2712
+ if (fixed[i] !== pathParts[i]) return false;
2713
+ }
2714
+ return true;
2715
+ }
2371
2716
  if (patternParts.length !== pathParts.length) return false;
2372
2717
  for (let i = 0; i < patternParts.length; i++) {
2373
2718
  if (patternParts[i].startsWith(':')) continue;
@@ -2376,85 +2721,64 @@ export function matchRoute(pattern, pathname) {
2376
2721
  return true;
2377
2722
  }
2378
2723
 
2379
- // === Link prefetch ===
2380
- // Hover / focus / touch an internal link and the target route renders NOW -
2381
- // $data included - against a throwaway signal map. The click that follows
2382
- // paints from the cached HTML: no await, no request, no spinner. Other
2383
- // frameworks prefetch data only; rosetack prefetches the whole render because
2384
- // the inlined bundle already contains every route.
2385
- // Trade-off: the cache holds either a result or the in-flight promise (dedupes
2386
- // hover storms); one isolated render runs at a time so signal-map swapping
2387
- // stays correct without any merging logic. Entries are single-use: a consumed
2388
- // entry disappears from the cache, which is also how tests observe a hit.
2389
- // P1, three guards for link-heavy pages:
2390
- // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
2391
- // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
2392
- // Trade-off: app-global, not per-route - per-route would carry the mode
2393
- // in each document's shell.
2394
- // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
2395
- // the budget caps the QUEUE: a hover storm past it drops the excess
2396
- // instead of rendering fifty routes nobody clicks.
2397
- // 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
2398
- // is evicted first (Map iteration order; entries are single-use, so
2399
- // insertion order IS the recency order).
2724
+ // === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
2400
2725
  let prefetchMode = ${JSON.stringify(prefetchMode)};
2401
2726
  export function setPrefetchMode(mode) { prefetchMode = mode; }
2402
2727
  const PREFETCH_BUDGET = 8;
2403
2728
  const PREFETCH_MAX_CACHED = 4;
2404
- const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
2729
+ const prefetchCache = new Map();
2405
2730
  let prefetchQueue = Promise.resolve();
2406
2731
  let prefetchPending = 0;
2407
2732
 
2408
- // Applies the route's params to state. A [lang] segment whose dictionary is
2409
- // a runtime pack (i18n.preload) is awaited HERE - the one place every client
2410
- // render path goes through (navigation, prefetch, action adopt) - so a packed
2411
- // locale costs one request per session and then renders from memory. A
2412
- // preloaded locale (the default: every dictionary inline) resolves without
2413
- // touching the network, so the common path stays synchronous in spirit.
2733
+
2414
2734
  async function applyParams(route, pathname) {
2415
2735
  const patternParts = route.pattern.split('/');
2416
2736
  const pathParts = pathname.split('/');
2417
2737
  for (let i = 0; i < patternParts.length; i++) {
2418
- if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
2738
+ const seg = patternParts[i];
2739
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2740
+
2741
+
2742
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2419
2743
  }
2420
2744
  const langIdx = patternParts.indexOf(':lang');
2421
2745
  if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
2422
2746
  }
2423
2747
 
2748
+
2749
+ function __netOk() {
2750
+ const c = navigator.connection;
2751
+ if (!c) return true;
2752
+ if (c.saveData) return false;
2753
+ const t = c.effectiveType;
2754
+ return t !== 'slow-2g' && t !== '2g';
2755
+ }
2756
+
2424
2757
  export function prefetch(pathname, source = 'hover') {
2425
2758
  if (prefetchMode === 'off') return;
2426
2759
  if (prefetchMode === 'hover' && source !== 'hover') return;
2427
2760
  if (prefetchMode === 'viewport' && source !== 'viewport') return;
2761
+ if (!__netOk()) return; // save-data / 2g: no bytes before the click
2428
2762
  if (prefetchCache.has(pathname)) return;
2429
- if (pathname === location.pathname) return; // already here: nothing to prefetch
2763
+ if (pathname === location.pathname) return;
2430
2764
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
2431
2765
  if (!route) return;
2432
- if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
2433
- // P0-1: the link may carry a query (/search?q=cats). $query() reads the
2434
- // browser's own URL, which is the page being LEFT - so the prefetched
2435
- // render would see the wrong one. Override it for the duration and clear
2436
- // it after; the queue below serializes renders, so one slot is enough.
2766
+ if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
2437
2767
  const qi = pathname.indexOf('?');
2438
2768
  const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
2439
2769
  const p = prefetchQueue.then(async () => {
2440
2770
  try {
2441
2771
  setPrefetchOverride(qOverride);
2442
- // the isolated render also captures the onMount callbacks the route
2443
- // queued and the onCleanup disposers it registered: the paint that
2444
- // consumes this entry replays the mounts after wiring and adopts the
2445
- // cleanups, so the prefetched route's timers are disposed on the next
2446
- // navigation like any live route's
2772
+ // The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
2447
2773
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
2448
2774
  await applyParams(route, pathname); // a packed locale's dictionary lands before the render
2449
2775
  const closes = [];
2450
- const render = await getRender(route); // split mode: loads the route's chunk here
2776
+ const render = await getRender(route);
2451
2777
  const html = await render(closes, '');
2452
2778
  return { html, closes };
2453
2779
  });
2454
2780
  const entry = { ...result, state, mounts, cleanups };
2455
- prefetchCache.set(pathname, entry); // promise -> result
2456
- // evict oldest-first; in-flight promises are never evicted (evicting
2457
- // one would only force a duplicate render)
2781
+ prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
2458
2782
  while (prefetchCache.size > PREFETCH_MAX_CACHED) {
2459
2783
  const oldest = prefetchCache.keys().next().value;
2460
2784
  if (prefetchCache.get(oldest) instanceof Promise) break;
@@ -2462,7 +2786,7 @@ export function prefetch(pathname, source = 'hover') {
2462
2786
  }
2463
2787
  return entry;
2464
2788
  } catch {
2465
- prefetchCache.delete(pathname); // failed: the next hover retries
2789
+ prefetchCache.delete(pathname);
2466
2790
  return null;
2467
2791
  } finally {
2468
2792
  setPrefetchOverride(null);
@@ -2475,13 +2799,10 @@ export function prefetch(pathname, source = 'hover') {
2475
2799
  }
2476
2800
 
2477
2801
  export function prefetchStats() {
2478
- return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
2802
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
2479
2803
  }
2480
2804
 
2481
- // One delegated listener per event type on the app container: survives DOM
2482
- // swaps and cloned blocks, so handlers never need re-binding. A handler
2483
- // compiled from a server action (data-on-*="$action:name") dispatches to
2484
- // $action instead of the local handler registry.
2805
+ // One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
2485
2806
  const DELEGATED = ['click', 'input', 'change', 'submit'];
2486
2807
  function bindEvents(container) {
2487
2808
  if (container.__rosetack_bound) return;
@@ -2498,48 +2819,64 @@ function bindEvents(container) {
2498
2819
  }
2499
2820
  }
2500
2821
 
2501
- // === Server actions from any event ===
2502
- // POST the body to the current route and adopt the response in place: the
2503
- // server runs the selected action, seeds its state patch, and re-renders, so
2504
- // the swapped DOM is the page as it looks AFTER the action - one request, no
2505
- // reload, and wire() patches only the marked nodes (no re-render). The
2506
- // bootstrap's <form method="POST"> interception goes through the same door.
2507
- async function postForm(body) {
2508
- const res = await fetch(location.pathname, { method: 'POST', body });
2822
+ // === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
2823
+ async function postForm(body, container, pathname) {
2824
+
2825
+ const box = container || document.getElementById('app');
2826
+ const route = pathname || location.pathname;
2827
+ const res = await fetch(route, { method: 'POST', body });
2509
2828
  const html = await res.text();
2510
2829
  const doc = new DOMParser().parseFromString(html, 'text/html');
2511
2830
  const next = doc.getElementById('app');
2512
2831
  const st = doc.getElementById('__rosetack_state');
2513
2832
  const paint = () => {
2514
- const container = document.getElementById('app');
2515
- adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
2833
+ adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
2516
2834
  };
2517
2835
  if (document.startViewTransition) document.startViewTransition(paint);
2518
2836
  else paint();
2519
2837
  }
2520
2838
 
2521
- // Call a page's server action by name from any event handler:
2522
- // <button on:click={like}> compiles to $action('like'). Without JS the
2523
- // binding is inert - the progressive-enhancement story stays with forms.
2839
+ // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
2524
2840
  export async function $action(name, e) {
2525
2841
  if (e && e.preventDefault) e.preventDefault();
2526
2842
  const body = new FormData();
2527
2843
  body.append('__action', name);
2528
- return postForm(body);
2844
+ // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
2845
+ const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
2846
+ return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
2529
2847
  }
2530
2848
 
2531
2849
  export { postForm };
2532
2850
 
2533
- // The live signal graph as JSON - the same serializeState the zero-hydration
2534
- // resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
2535
- // can hand it to the dev server's reload bridge and to a devtools extension.
2536
- // A local re-export on purpose: it keeps the binding alive through minification
2537
- // for the bootstrap text appended after the bundle.
2851
+ // The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
2538
2852
  export { serializeState };
2539
2853
 
2540
- // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2541
- // the existing nodes and bind events. initial=false: client-side navigation -
2542
- // re-render the route chain from scratch and wire the fresh DOM.
2854
+ // Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
2855
+
2856
+
2857
+ function __ownsDoc(container) {
2858
+ return container === document.getElementById('app');
2859
+ }
2860
+ function __navReset(container) {
2861
+ if (__ownsDoc(container)) {
2862
+ resetEffects();
2863
+ clearRequestState();
2864
+ } else {
2865
+ resetContainerFx(container);
2866
+ }
2867
+ }
2868
+ // Attribute everything a render creates (state keys, effects, onCleanups) to
2869
+ // its container. The document path sets no owner and keeps the global sets.
2870
+ async function __withOwner(container, fn) {
2871
+ if (__ownsDoc(container)) return fn();
2872
+ setFxOwner(container);
2873
+ try {
2874
+ return await fn();
2875
+ } finally {
2876
+ setFxOwner(null);
2877
+ }
2878
+ }
2879
+
2543
2880
  export async function start(container, pathname, initial) {
2544
2881
  clearMounts(); // stale mounts from a failed render never fire
2545
2882
  if (initial) {
@@ -2548,104 +2885,110 @@ export async function start(container, pathname, initial) {
2548
2885
  }
2549
2886
  for (const route of routes) {
2550
2887
  if (matchRoute(route.pattern, pathname)) {
2551
- // i18n: an unknown locale paints the 404 page, same as the server
2552
- // (before the prefetch check: a cached entry for a bogus locale is
2553
- // discarded, never painted)
2888
+ // I18n: an unknown locale paints the 404 page, same as the server (before the prefetch check: a cached entry for a bogus locale is discarded).
2554
2889
  const langIdx = route.pattern.split('/').indexOf(':lang');
2555
2890
  ${langDirBlock}
2556
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2891
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2557
2892
  return;
2558
2893
  }
2559
- // Prefetched on hover/focus/touch: the render already ran, so paint its
2560
- // HTML and adopt its signal entries - events then patch the very nodes
2561
- // we wire, and no $data re-runs on click.
2894
+ // Prefetched on hover/focus/touch: the render already ran, so paint its HTML and adopt its signal entries - events then patch the very nodes we.
2562
2895
  let hit = initial ? undefined : prefetchCache.get(pathname);
2563
2896
  if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2564
2897
  if (hit) {
2565
- prefetchCache.delete(pathname); // single-use: the next hover refetches
2566
- resetEffects();
2898
+ prefetchCache.delete(pathname);
2899
+ __navReset(container);
2567
2900
  restoreState(hit.state);
2568
2901
  container.innerHTML = hit.html;
2569
- wire(container, hit.closes);
2902
+ await __withOwner(container, () => {
2903
+ wire(container, hit.closes);
2904
+ bindEvents(container);
2905
+ hit.mounts.forEach((fn) => fn());
2906
+ adoptCleanups(hit.cleanups);
2907
+ });
2908
+ return;
2909
+ }
2910
+ if (!initial) __navReset(container);
2911
+ let broken = false;
2912
+ let signal = null;
2913
+ await __withOwner(container, async () => {
2914
+ await applyParams(route, pathname);
2915
+ const closes = [];
2916
+ let html;
2917
+ try {
2918
+ const render = await getRender(route);
2919
+ html = await render(closes, '');
2920
+ } catch (err) {
2921
+
2922
+ if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
2923
+ if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
2924
+
2925
+
2926
+ broken = true;
2927
+ return;
2928
+ }
2929
+ if (!initial) container.innerHTML = html;
2930
+ wire(container, closes);
2570
2931
  bindEvents(container);
2571
- hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2572
- adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
2932
+ flushMounts();
2933
+ });
2934
+ if (signal === 'notFound') {
2935
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2573
2936
  return;
2574
2937
  }
2575
- if (!initial) {
2576
- resetEffects();
2577
- clearRequestState();
2938
+ if (signal) {
2939
+ location.href = signal;
2940
+ return;
2578
2941
  }
2579
- await applyParams(route, pathname);
2580
- const closes = [];
2581
- let html;
2582
- try {
2583
- const render = await getRender(route); // split mode: loads the route's chunk here
2584
- html = await render(closes, '');
2585
- } catch {
2586
- // the route itself is broken: degrade to pages/500.rose (or the
2587
- // built-in plain 500) instead of leaving the container empty
2942
+ if (broken) {
2588
2943
  await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2589
- return;
2590
2944
  }
2591
- if (!initial) container.innerHTML = html;
2592
- wire(container, closes);
2593
- bindEvents(container);
2594
- flushMounts();
2595
2945
  return;
2596
2946
  }
2597
2947
  }
2598
- // unmatched route: pages/404.rose renders (with its head + interactivity),
2599
- // else the built-in plain 404 - and an i18n app's document returns to the
2600
- // default locale, the same one the server stamps on its 404
2601
- ${hasLang ? ` document.documentElement.lang = __defLocale;
2602
- document.documentElement.removeAttribute('dir');` : ""}
2603
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2948
+ // Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
2949
+ ${hasLang ? ` // the same app-root gate as above - a mount never touches the
2950
+ // host document's language or direction.
2951
+ if (container === document.getElementById('app')) {
2952
+ document.documentElement.lang = __defLocale;
2953
+ document.documentElement.removeAttribute('dir');
2954
+ }` : ""}
2955
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2604
2956
  }
2605
2957
 
2606
- // Adopt a server-rendered response in place - the JS-enabled half of
2607
- // progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
2608
- // via fetch and hands the response here. The DOM is swapped and wired with
2609
- // the same zero-render trick as boot: re-run the route's render to rebuild
2610
- // the marker closures, wire them against the adopted nodes. The page never
2611
- // re-renders visibly, no hydration payload, no second request beyond the POST.
2612
- export async function adopt(container, html, stateJson) {
2613
- resetEffects();
2614
- clearRequestState();
2958
+ // Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
2959
+ export async function adopt(container, html, stateJson, pathname) {
2960
+
2961
+
2962
+ const route0 = pathname || location.pathname;
2963
+ __navReset(container);
2615
2964
  clearMounts(); // stale mounts from a failed render never fire
2616
2965
  resumeState(stateJson);
2617
2966
  container.innerHTML = html;
2618
- // keep the embedded state in sync so a later SPA-fallback check agrees
2967
+
2619
2968
  const st = document.getElementById('__rosetack_state');
2620
2969
  if (st) st.textContent = stateJson;
2621
2970
  for (const route of routes) {
2622
- if (matchRoute(route.pattern, location.pathname)) {
2623
- await applyParams(route, location.pathname);
2624
- const closes = [];
2625
- try {
2626
- const render = await getRender(route); // split mode: loads the route's chunk here
2627
- await render(closes, '');
2628
- } catch {
2629
- // the adopted response's route is broken (e.g. the action's page
2630
- // throws): keep the swapped DOM but skip wiring it
2631
- return;
2632
- }
2633
- wire(container, closes);
2634
- bindEvents(container);
2635
- flushMounts();
2971
+ if (matchRoute(route.pattern, route0)) {
2972
+ await __withOwner(container, async () => {
2973
+ await applyParams(route, route0);
2974
+ const closes = [];
2975
+ try {
2976
+ const render = await getRender(route);
2977
+ await render(closes, '');
2978
+ } catch {
2979
+
2980
+
2981
+ return;
2982
+ }
2983
+ wire(container, closes);
2984
+ bindEvents(container);
2985
+ flushMounts();
2986
+ });
2636
2987
  return;
2637
2988
  }
2638
2989
  }
2639
2990
  }
2640
- // === refresh() implementation ===
2641
- // Re-render the current route in place: the client half of router.refresh()
2642
- // (a router refresh) / (a full invalidation). Same machinery as a client-side
2643
- // navigation to the current path - $data re-runs, state re-seeds from the
2644
- // fresh render, wire() patches the marked nodes - but a refresh never lands
2645
- // a prefetch entry: a hover from a minute ago is exactly what it exists to
2646
- // bypass. Zero requests: the render (and its $data) runs in the page.
2647
- // Trade-off: state resets like navigation (no per-key retention); add
2648
- // retention when an app needs refresh-without-losing-input.
2991
+ // === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
2649
2992
  setRefreshHook(async () => {
2650
2993
  prefetchCache.delete(location.pathname);
2651
2994
  await start(document.getElementById('app'), location.pathname, false);
@@ -2679,26 +3022,44 @@ setRefreshHook(async () => {
2679
3022
  ...TS_LOADER
2680
3023
  });
2681
3024
  }
3025
+ await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
2682
3026
  await fs.promises.rm(buildDir, { recursive: true, force: true });
2683
3027
  const publicDir = path.join(root, "public");
2684
3028
  if (fs.existsSync(publicDir)) {
2685
- const outPublic = path.join(outDir, "public");
2686
- await fs.promises.mkdir(outPublic, { recursive: true });
2687
- const assets = await fs.promises.readdir(publicDir);
2688
- await Promise.all(
2689
- assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
2690
- );
3029
+ await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
3030
+ const favicon = path.join(publicDir, "favicon.ico");
3031
+ if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
2691
3032
  }
2692
3033
  console.log("rosetack zero-JS report:");
2693
3034
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
3035
+ const warnGroups = /* @__PURE__ */ new Map();
2694
3036
  for (const { info, i } of pages) {
2695
3037
  if (!routeShipsNoJs(infos, compiled, i)) continue;
2696
3038
  for (const ci of [i, ...layoutsOf(infos, i)]) {
2697
3039
  for (const w of compiled[ci].jsWarnings ?? []) {
2698
- console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
3040
+ let g = warnGroups.get(w);
3041
+ if (!g) {
3042
+ g = { why: w, files: /* @__PURE__ */ new Map() };
3043
+ warnGroups.set(w, g);
3044
+ }
3045
+ const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
3046
+ let routes = g.files.get(file);
3047
+ if (!routes) {
3048
+ routes = /* @__PURE__ */ new Set();
3049
+ g.files.set(file, routes);
3050
+ }
3051
+ routes.add(info.routePath);
2699
3052
  }
2700
3053
  }
2701
3054
  }
3055
+ for (const g of warnGroups.values()) {
3056
+ const allRoutes = /* @__PURE__ */ new Set();
3057
+ for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
3058
+ const parts = [...g.files.entries()].sort((a, b) => b[1].size - a[1].size).map(([file, routes]) => `${file} (${routes.size === 1 ? [...routes][0] : `${routes.size} routes`})`);
3059
+ const shown = parts.slice(0, 4).join(", ");
3060
+ const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
3061
+ console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
3062
+ }
2702
3063
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2703
3064
  }
2704
3065
  async function scanRoseFiles(root) {
@@ -2743,15 +3104,21 @@ function getRouteInfo(filePath, root) {
2743
3104
  const base = path.posix.basename(withoutExt);
2744
3105
  const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2745
3106
  const isLayout = !isComponent && base === "_layout";
2746
- const isNotFound = !isComponent && base === "404";
3107
+ const isNotFound = !isComponent && (base === "404" || base === "_notfound");
2747
3108
  const isError = !isComponent && base === "500";
2748
3109
  const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2749
3110
  const isMiddleware = !isComponent && withoutExt === "_middleware";
2750
- let parts = withoutExt.split("/").filter((p) => p !== "_layout");
3111
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
2751
3112
  if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
2752
- const routeParts = parts.map(
2753
- (part) => part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part
2754
- );
3113
+ const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
3114
+ const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
3115
+ const routeParts = parts.map((part) => {
3116
+ const optional = OPTIONAL_CATCH_ALL.exec(part);
3117
+ if (optional) return `**${optional[1]}`;
3118
+ const catchAll = CATCH_ALL.exec(part);
3119
+ if (catchAll) return `*${catchAll[1]}`;
3120
+ return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
3121
+ });
2755
3122
  let routePath;
2756
3123
  if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2757
3124
  routePath = "/";
@@ -2762,7 +3129,13 @@ function getRouteInfo(filePath, root) {
2762
3129
  filePath,
2763
3130
  routePath,
2764
3131
  pattern: routePath,
2765
- paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
3132
+ paramNames: parts.flatMap((p) => {
3133
+ const optional = OPTIONAL_CATCH_ALL.exec(p);
3134
+ if (optional) return [optional[1]];
3135
+ const catchAll = CATCH_ALL.exec(p);
3136
+ if (catchAll) return [catchAll[1]];
3137
+ return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
3138
+ }),
2766
3139
  isLayout,
2767
3140
  isNotFound,
2768
3141
  isError,
@@ -2813,7 +3186,25 @@ function getStyles() {
2813
3186
  }
2814
3187
  }
2815
3188
  var BOOTSTRAP = esbuild2.transformSync(`
2816
- const __app = document.getElementById('app');
3189
+ // shell = false: the document's SSR content sits directly in <body> - no
3190
+ // #app wrapper, no demo styles, so a real theme's CSS owns the document from
3191
+ // the first byte (and a JS-less visitor never sees either). The bundle still
3192
+ // runs, and it still needs its container: wrap the content once, here, before
3193
+ // any theme script executes (module scripts run before DOMContentLoaded). The
3194
+ // wrapper is a plain unstyled div, so the re-parent is visually inert; every
3195
+ // later path - adoption, navigation, forms - is then the ordinary one.
3196
+ let __app = document.getElementById('app');
3197
+ if (!__app) {
3198
+ __app = document.createElement('div');
3199
+ __app.id = 'app';
3200
+ // scripts stay outside the wrapper, exactly where the dressed document
3201
+ // keeps them: the state element and the running module must survive a
3202
+ // navigation's innerHTML swap (they are the document's, not the route's).
3203
+ for (const node of Array.from(document.body.children)) {
3204
+ if (node.tagName !== 'SCRIPT') __app.appendChild(node);
3205
+ }
3206
+ document.body.appendChild(__app);
3207
+ }
2817
3208
  // Native View Transitions around client-side navigation (progressive:
2818
3209
  // browsers without the API navigate normally, no polyfill, no CSS required).
2819
3210
  function __navigate(pathname) {
@@ -2876,13 +3267,15 @@ document.addEventListener('submit', (e) => {
2876
3267
  e.preventDefault();
2877
3268
  postForm(new FormData(f));
2878
3269
  });
2879
- // Dev seam: the live signal graph, readable as JSON. Two callers, one
3270
+ // Dev seam: the live signal graph, readable as JSON. Three callers, one
2880
3271
  // implementation: the dev server's reload bridge snapshots it before a
2881
3272
  // rebuild-triggered reload so the edit lands on the state the developer had,
2882
- // and a devtools extension reads it the same way. It is the same
2883
- // serializeState the zero-hydration resume already ships, so the only new
2884
- // bytes are the assignment.
2885
- window.__rosetack = { state: () => serializeState() };
3273
+ // and the devtools extension (devtools/) reads it the same way - the signal
3274
+ // graph plus the prefetch counters, which is the whole observable state of a
3275
+ // running page. Both are DIRECT references (no wrapper arrow): the names take
3276
+ // no arguments, so the call is identical and every document that carries the
3277
+ // bundle pays eleven bytes for the pair instead of forty.
3278
+ window.__rosetack = { state: serializeState, prefetch: prefetchStats };
2886
3279
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
2887
3280
  // If the document was rendered for a DIFFERENT route (a static-file server's
2888
3281
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
@@ -2901,7 +3294,14 @@ if (__resumed) {
2901
3294
  __state = Object.assign(__state, __resumed);
2902
3295
  __state.__route = __route;
2903
3296
  }
2904
- if (__resumed) {
3297
+ // A NOT-FOUND document (the server stamps __notFound onto its state) boots
3298
+ // into the app's own 404 route: the URL matches no route - or a catch-all
3299
+ // whose resolver threw notFound(), whose key sits null in the resumed state
3300
+ // and whose template would dereference it into a 500. startNotFound paints
3301
+ // the not-found route from the resumed state instead (zero requests).
3302
+ if (__state.__notFound) {
3303
+ startNotFound(__app, window.location.pathname);
3304
+ } else if (__resumed) {
2905
3305
  start(__app, window.location.pathname);
2906
3306
  } else if (__state.__route === window.location.pathname) {
2907
3307
  start(__app, window.location.pathname, true);
@@ -2909,10 +3309,10 @@ if (__resumed) {
2909
3309
  start(__app, window.location.pathname);
2910
3310
  }
2911
3311
  `, { minify: true }).code;
2912
- var CSP_TAIL = `style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
3312
+ var CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
2913
3313
  var cspCache = null;
2914
3314
  var EXTERNAL_BOOTSTRAP = `
2915
- import { start, prefetch, postForm } from '/client.js';
3315
+ import { start, prefetch, postForm, prefetchStats } from '/client.js';
2916
3316
  ${BOOTSTRAP}`;
2917
3317
  function inlineScript(client) {
2918
3318
  return `
@@ -2996,52 +3396,64 @@ function clientScriptTag(client, nonce = "") {
2996
3396
  return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
2997
3397
  <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
2998
3398
  }
2999
- function shellOpen(styles = getStyles(), lang = "en", dir = "") {
3399
+ function shellOpen(styles = getStyles(), lang = "en", dir = "", shell = true) {
3000
3400
  const styleTag = styles ? `
3001
3401
  <style>${styles}</style>` : "";
3402
+ const demoStyles = shell ? `
3403
+ <style>${STYLES_MIN}</style>` : "";
3404
+ const appOpen = shell ? `
3405
+ <div id="app">` : "";
3002
3406
  return `<!DOCTYPE html>
3003
3407
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
3004
3408
  <head>
3005
3409
  <meta charset="UTF-8">
3006
3410
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
3007
- <title>RoseTack</title>
3008
- <style>${STYLES_MIN}</style>${styleTag}
3411
+ <title>RoseTack</title>${demoStyles}${styleTag}
3009
3412
  ${FAVICON}
3010
3413
  </head>
3011
- <body>
3012
- <div id="app">`;
3414
+ <body>${appOpen}`;
3013
3415
  }
3014
- function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
3416
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
3015
3417
  const clientTag = clientScriptTag(client, nonce);
3016
3418
  const mergedHead = mergeHeadBlocks(head);
3419
+ const headStamped = nonce ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs) => /\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`) : mergedHead;
3420
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ""}`;
3421
+ let bodyAttrs = "";
3422
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag, attrs) => {
3423
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, "");
3424
+ if (tag === "html") htmlAttrs = clean;
3425
+ else bodyAttrs = clean;
3426
+ return "";
3427
+ });
3017
3428
  const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
3018
3429
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
3019
3430
  ${FAVICON}`;
3020
- const headTags = mergedHead ? `
3021
- ${mergedHead}` : "";
3431
+ const headTags = headClean ? `
3432
+ ${headClean}` : "";
3022
3433
  const styleTag = styles ? `
3023
3434
  <style>${styles}</style>` : "";
3435
+ const stateSafe = stateJson.replace(/</g, "\\u003c");
3024
3436
  const jsTail = js ? `
3025
- <script type="application/json" id="__rosetack_state">${stateJson}</script>
3437
+ <script type="application/json" id="__rosetack_state">${stateSafe}</script>
3026
3438
  ${clientTag}` : "";
3027
- const open = js ? '<div id="app">' : "";
3028
- const close = js ? "</div>" : "";
3029
- const shellStyles = js ? `
3439
+ const open = js && shell ? '<div id="app">' : "";
3440
+ const close = js && shell ? "</div>" : "";
3441
+ const shellStyles = js && shell ? `
3030
3442
  <style>${STYLES_MIN}</style>` : "";
3031
3443
  return `<!DOCTYPE html>
3032
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
3444
+ <html${htmlAttrs}>
3033
3445
  <head>
3034
3446
  <meta charset="UTF-8">
3035
3447
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
3036
3448
  ${titleTag}${shellStyles}${styleTag}
3037
3449
  </head>
3038
- <body>
3450
+ <body${bodyAttrs}>
3039
3451
  ${open}${ssrHtml}${close}${jsTail}
3040
3452
  </body>
3041
3453
  </html>`;
3042
3454
  }
3043
- function getHtmlShell(ssrHtml, stateJson, head = [], js = true, lang = "en", dir = "", nonce = "") {
3044
- return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce);
3455
+ function getHtmlShell(ssrHtml, stateJson, head = [], js = true, lang = "en", dir = "", nonce = "", shell = true) {
3456
+ return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce, shell);
3045
3457
  }
3046
3458
 
3047
3459
  // src/cli/prompt.ts
@@ -3080,7 +3492,7 @@ the smallest thing that works - the compiler decides what ships.
3080
3492
  <h1>Posts</h1>
3081
3493
  <p>Total: {total}</p>
3082
3494
  <button on:click={() => $setState('count', count() + 1)}>+1</button>
3083
- <form method="POST"><button formaction="?__action=like">Like</button></form>
3495
+ <form method="POST"><input type="hidden" name="__action" value="like"><button type="submit">Like</button></form>
3084
3496
  \`\`\`
3085
3497
 
3086
3498
  Rules the compiler enforces (breaking one fails the build):
@@ -3120,6 +3532,9 @@ Rules the compiler enforces (breaking one fails the build):
3120
3532
  (method="POST", no JS needed - progressive enhancement) or from any event
3121
3533
  (on:click={like} - one POST, in-place adopt). Its return value is an
3122
3534
  incremental patch: $append(row) / $prepend(row) / $merge({...}).
3535
+ - A form selects its action by the __action FIELD: name the function
3536
+ \`action\` (the default) or add <input type="hidden" name="__action"
3537
+ value="like">. The server reads the field, not the URL.
3123
3538
  - Business failures: throw new ActionError('message', 422, 'field'). It lands
3124
3539
  in ordinary state - $actionError() reads it back, a {#boundary} contains it.
3125
3540
  - beforeAction(name, form) is the per-page guard that vetoes an action.
@@ -3218,8 +3633,27 @@ async function sendWebResponse(web, res) {
3218
3633
  }
3219
3634
  async function sendPage(req, res, ssrModule, hookCtx, page, routePath) {
3220
3635
  let status = page.status ?? 200;
3636
+ if (page.redirect) {
3637
+ const body = `<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${page.redirect}">${page.redirect}</a>.</p>`;
3638
+ let headers2 = pageHeaders(ssrModule, routePath, "");
3639
+ if (hookCtx) {
3640
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(body, {
3641
+ status,
3642
+ headers: { "content-type": "text/html; charset=utf-8", location: page.redirect, ...headers2 }
3643
+ }));
3644
+ status = out.status;
3645
+ headers2 = webHeadersToNode(out);
3646
+ }
3647
+ headers2.location = page.redirect;
3648
+ res.statusCode = status;
3649
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
3650
+ res.setHeader("Location", page.redirect);
3651
+ for (const [k, v] of Object.entries(headers2)) if (k !== "location") res.setHeader(k, v);
3652
+ res.end(body);
3653
+ return;
3654
+ }
3221
3655
  const nonce = nonceFor(ssrModule, routePath);
3222
- let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
3656
+ let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
3223
3657
  let headers = pageHeaders(ssrModule, routePath, nonce);
3224
3658
  if (hookCtx) {
3225
3659
  const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
@@ -3273,6 +3707,20 @@ async function build2() {
3273
3707
  }));
3274
3708
  await writeBrotli(OUT_DIR2);
3275
3709
  await analyze(OUT_DIR2, ssrModule.dynamicRoutes ?? []);
3710
+ if (argv.includes("--static")) {
3711
+ const dyn = ssrModule.dynamicRoutes ?? [];
3712
+ const unbakedApi = Object.entries(ssrModule.apiPrerender ?? {}).filter(([, baked]) => !baked).map(([routePath]) => routePath);
3713
+ const paramless = routes.filter((r) => r.paramNames.length > 0 && !(ssrModule.routeParams ?? {})[r.routePath]).map((r) => r.routePath);
3714
+ const problems = [.../* @__PURE__ */ new Set([...dyn, ...unbakedApi, ...paramless, ...skipped])];
3715
+ if (problems.length > 0) {
3716
+ console.error("rosetack: --static export refused - these routes need a server:");
3717
+ for (const p of problems) console.error(` ${p}`);
3718
+ console.error("(getContext()/$store()/$query(), csp.nonce, buffer = true, an unbaked /api route, a param route with no export const params, or a route the middleware walled)");
3719
+ console.error("drop --static to build the normal dist (the dynamic half renders on demand on Node/edge)");
3720
+ process.exit(1);
3721
+ }
3722
+ console.log("rosetack: static export verified - every route is a baked file, no server needed");
3723
+ }
3276
3724
  }
3277
3725
  var BROTLI_EXT = /* @__PURE__ */ new Set([".html", ".js", ".css", ".json", ".svg", ".txt"]);
3278
3726
  async function writeBrotli(dir) {
@@ -3362,7 +3810,7 @@ async function prerender(routes) {
3362
3810
  }
3363
3811
  const routeDir = routePath === "/" ? OUT_DIR2 : path3.join(OUT_DIR2, routePath.slice(1));
3364
3812
  await fs3.promises.mkdir(routeDir, { recursive: true });
3365
- await fs3.promises.writeFile(path3.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
3813
+ await fs3.promises.writeFile(path3.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
3366
3814
  console.log(`prerendered ${routePath} -> ${path3.relative(process.cwd(), path3.join(routeDir, "index.html"))}`);
3367
3815
  };
3368
3816
  for (const info of routes) {
@@ -3418,7 +3866,11 @@ function enumerateParams(pattern, names, raw) {
3418
3866
  }
3419
3867
  return combos.map((values) => {
3420
3868
  let i = 0;
3421
- return pattern.split("/").map((seg) => seg.startsWith(":") ? encodeURIComponent(values[i++]) : seg).join("/");
3869
+ return pattern.split("/").map((seg) => {
3870
+ if (seg.startsWith(":")) return encodeURIComponent(values[i++]);
3871
+ if (seg.startsWith("*")) return values[i++].split("/").map(encodeURIComponent).join("/");
3872
+ return seg;
3873
+ }).join("/");
3422
3874
  });
3423
3875
  }
3424
3876
  var ASSET_EXT = /* @__PURE__ */ new Set([".js", ".css", ".json", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp", ".woff", ".woff2", ".txt", ".xml"]);
@@ -3442,7 +3894,7 @@ function revalidateInBackground(routePath, filePath) {
3442
3894
  ssrModule.setQuery?.({});
3443
3895
  const page = await ssrModule.renderPage(routePath);
3444
3896
  if (page.status === 200) {
3445
- await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
3897
+ await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
3446
3898
  fileCache.delete(filePath);
3447
3899
  console.log(`rosetack: revalidated ${routePath} in the background`);
3448
3900
  }
@@ -3577,6 +4029,29 @@ function devNotify() {
3577
4029
  }
3578
4030
  }
3579
4031
  }
4032
+ var devBuild = null;
4033
+ var devBuildPending = false;
4034
+ function startDevBuild() {
4035
+ if (!devBuild) {
4036
+ devBuild = (async () => {
4037
+ try {
4038
+ console.log("Rebuilding...");
4039
+ await build2();
4040
+ devNotify();
4041
+ } catch (err) {
4042
+ console.error("Build failed (server still running):", err instanceof Error ? err.message : String(err));
4043
+ } finally {
4044
+ devBuild = null;
4045
+ devBuildPending = false;
4046
+ }
4047
+ })();
4048
+ }
4049
+ return devBuild;
4050
+ }
4051
+ function settleDevBuild() {
4052
+ if (!devMode || !devBuild && !devBuildPending) return null;
4053
+ return startDevBuild();
4054
+ }
3580
4055
  function devWrap(inner) {
3581
4056
  devMode = true;
3582
4057
  return (req, res) => {
@@ -3593,7 +4068,7 @@ function devWrap(inner) {
3593
4068
  const at = s.indexOf("<head>");
3594
4069
  if (at < 0) return chunk;
3595
4070
  injected = true;
3596
- const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\//g, "<\\/")}</script>` : "";
4071
+ const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\/script>/g, "")}</script>` : "";
3597
4072
  const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
3598
4073
  return Buffer.isBuffer(chunk) ? Buffer.from(out, "utf8") : out;
3599
4074
  };
@@ -3616,7 +4091,24 @@ function serveStatic(dir, isr = false, dev2 = false) {
3616
4091
  res.end(blocked.body);
3617
4092
  return;
3618
4093
  }
3619
- loadServer().then(async (ssrModule) => {
4094
+ const want = pathnameOf(req.url || "/");
4095
+ const canonical = want.replace(/\/+$/, "") || "/";
4096
+ if (canonical !== want) {
4097
+ let search = "";
4098
+ try {
4099
+ search = new URL(req.url || "/", "http://localhost").search;
4100
+ } catch {
4101
+ }
4102
+ const to = canonical + search;
4103
+ res.statusCode = 308;
4104
+ res.setHeader("Location", to);
4105
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
4106
+ res.end(`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${to}">${to}</a>.</p>`);
4107
+ return;
4108
+ }
4109
+ const settled = settleDevBuild();
4110
+ const ready = settled ? settled.then(() => loadServer()) : loadServer();
4111
+ ready.then(async (ssrModule) => {
3620
4112
  const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true ? await hookContext(req) : null;
3621
4113
  if (hookCtx) {
3622
4114
  const short = await ssrModule.runRequestHooks(hookCtx);
@@ -3653,7 +4145,8 @@ function serveStatic(dir, isr = false, dev2 = false) {
3653
4145
  writeWebHeaders(apiRes, res);
3654
4146
  res.statusCode = apiRes.status;
3655
4147
  res.end(Buffer.from(await apiRes.arrayBuffer()));
3656
- } catch {
4148
+ } catch (err) {
4149
+ console.error(`rosetack: ${req.method} ${req.url} api handler failed:`, err instanceof Error ? err.stack ?? err.message : String(err));
3657
4150
  res.statusCode = 500;
3658
4151
  res.setHeader("Content-Type", "application/json");
3659
4152
  res.end('{"error":"api handler failed"}');
@@ -3715,8 +4208,6 @@ function serveStatic(dir, isr = false, dev2 = false) {
3715
4208
  entry = {
3716
4209
  mtimeMs: st.mtimeMs,
3717
4210
  raw,
3718
- // A file's compressed forms are computed ONCE and then served from this cache
3719
- // forever …
3720
4211
  br: zlib.brotliCompressSync(raw),
3721
4212
  gzip: zlib.gzipSync(raw, { level: 9 }),
3722
4213
  etag: `W/"${st.size}-${st.mtimeMs}"`
@@ -3808,7 +4299,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
3808
4299
  done = () => res.end();
3809
4300
  }
3810
4301
  const doc = ssrModule.docAttrs(safe2);
3811
- await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
4302
+ await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir, !ssrModule.shellOff(safe2)), clientScriptTag(getClientSource(), nonce));
3812
4303
  done();
3813
4304
  return;
3814
4305
  }
@@ -3876,17 +4367,27 @@ async function freePort(from) {
3876
4367
  return from;
3877
4368
  }
3878
4369
  function version() {
3879
- for (const rel of ["../../package.json", "../package.json"]) {
4370
+ for (const rel of ["../FRAMEWORK_VERSION", "../../FRAMEWORK_VERSION", "../../package.json", "../package.json"]) {
3880
4371
  try {
3881
- const v = JSON.parse(fs3.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8")).version;
4372
+ const raw = fs3.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8");
4373
+ const v = rel.endsWith("FRAMEWORK_VERSION") ? raw.trim() : JSON.parse(raw).version;
3882
4374
  if (v) return v;
3883
4375
  } catch {
3884
4376
  }
3885
4377
  }
3886
4378
  return "0.0.0";
3887
4379
  }
4380
+ function projectTag() {
4381
+ try {
4382
+ const pkg = JSON.parse(fs3.readFileSync(path3.join(process.cwd(), "package.json"), "utf-8"));
4383
+ if (!pkg.version || pkg.name === "rosetack") return "";
4384
+ return ` - project: ${pkg.name} v${pkg.version}`;
4385
+ } catch {
4386
+ return "";
4387
+ }
4388
+ }
3888
4389
  async function dev() {
3889
- console.log(`\u{1F339} RoseTack v${version()} dev server starting...`);
4390
+ console.log(`\u{1F339} RoseTack v${version()}${projectTag()} dev server starting...`);
3890
4391
  try {
3891
4392
  await build2();
3892
4393
  } catch (err) {
@@ -3894,15 +4395,10 @@ async function dev() {
3894
4395
  }
3895
4396
  let timeout;
3896
4397
  fs3.watch(SRC_DIR, { recursive: true }, () => {
4398
+ devBuildPending = true;
3897
4399
  clearTimeout(timeout);
3898
- timeout = setTimeout(async () => {
3899
- try {
3900
- console.log("Rebuilding...");
3901
- await build2();
3902
- devNotify();
3903
- } catch (err) {
3904
- console.error("Build failed (server still running):", err instanceof Error ? err.message : String(err));
3905
- }
4400
+ timeout = setTimeout(() => {
4401
+ void startDevBuild();
3906
4402
  }, 200);
3907
4403
  });
3908
4404
  const http = await import("http");
@@ -3916,7 +4412,7 @@ async function preview() {
3916
4412
  const http = await import("http");
3917
4413
  const server = http.createServer(serveStatic(OUT_DIR2, true));
3918
4414
  listenFree(server, PORT, (port) => {
3919
- console.log(`\u{1F339} RoseTack v${version()} preview at http://localhost:` + port);
4415
+ console.log(`\u{1F339} RoseTack v${version()}${projectTag()} preview at http://localhost:${port}`);
3920
4416
  });
3921
4417
  }
3922
4418
  async function serve() {
@@ -3947,7 +4443,7 @@ async function serve() {
3947
4443
  cluster.on("exit", () => {
3948
4444
  if (--live <= 0) process.exit(0);
3949
4445
  });
3950
- console.log(`\u{1F339} RoseTack v${version()} serve: ${workers} worker${workers > 1 ? "s" : ""} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
4446
+ console.log(`\u{1F339} RoseTack v${version()}${projectTag()} serve: ${workers} worker${workers > 1 ? "s" : ""} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
3951
4447
  return;
3952
4448
  }
3953
4449
  process.on("disconnect", () => process.exit(0));
@@ -3955,7 +4451,26 @@ async function serve() {
3955
4451
  try {
3956
4452
  servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
3957
4453
  } catch (err) {
3958
- console.error("rosetack: rosetack.config.js failed to load for the serve hooks:", err instanceof Error ? err.message : err);
4454
+ console.error("rosetack: rosetack.config.js failed to load for the serve hooks:", err instanceof Error ? err.message : String(err));
4455
+ }
4456
+ const storeBridge = {
4457
+ install: (send) => {
4458
+ try {
4459
+ serverModule?.__installStoreTransport?.(send);
4460
+ } catch {
4461
+ }
4462
+ },
4463
+ deliver: (name, value) => {
4464
+ try {
4465
+ serverModule?.__deliverStorePatch?.(name, value);
4466
+ } catch {
4467
+ }
4468
+ }
4469
+ };
4470
+ try {
4471
+ await loadServer();
4472
+ } catch (err) {
4473
+ console.error("rosetack: dist/server.js failed to load for the serve hooks:", err instanceof Error ? err.message : String(err));
3959
4474
  }
3960
4475
  const http = await import("node:http");
3961
4476
  const server = http.createServer(withAccessLog(serveStatic(OUT_DIR2, true), `w${process.pid}`));
@@ -3966,9 +4481,9 @@ async function serve() {
3966
4481
  console.log(`\u{1F339} RoseTack worker ${process.pid} listening on http://localhost:${port}`);
3967
4482
  for (const p of servicePlugins) {
3968
4483
  try {
3969
- await p.onServe({ port, workers });
4484
+ await p.onServe({ port, workers, store: storeBridge });
3970
4485
  } catch (err) {
3971
- console.error("rosetack: plugin", p.name, "onServe failed:", err instanceof Error ? err.message : err);
4486
+ console.error("rosetack: plugin", p.name, "onServe failed:", err instanceof Error ? err.message : String(err));
3972
4487
  }
3973
4488
  }
3974
4489
  });
@@ -3990,10 +4505,65 @@ async function serve() {
3990
4505
  process.on("SIGTERM", stop);
3991
4506
  process.on("SIGINT", stop);
3992
4507
  }
4508
+ function templatesDir() {
4509
+ for (const rel of ["../../templates", "../templates"]) {
4510
+ const p = fileURLToPath2(new URL(rel, import.meta.url));
4511
+ if (fs3.existsSync(p)) return p;
4512
+ }
4513
+ return null;
4514
+ }
4515
+ function writeTypeScriptReady(dir) {
4516
+ fs3.writeFileSync(path3.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
4517
+ `);
4518
+ fs3.writeFileSync(path3.join(dir, "tsconfig.json"), JSON.stringify({
4519
+ compilerOptions: {
4520
+ target: "ES2022",
4521
+ module: "ESNext",
4522
+ moduleResolution: "bundler",
4523
+ lib: ["ES2022", "DOM", "DOM.Iterable"],
4524
+ strict: true,
4525
+ noEmit: true,
4526
+ skipLibCheck: true
4527
+ },
4528
+ include: ["rosetack-env.d.ts", "src/**/*.ts"]
4529
+ }, null, 2) + "\n");
4530
+ }
4531
+ function copyTemplate(dir, name, display) {
4532
+ const base = templatesDir();
4533
+ const shipped = base ? path3.resolve(base, name) : "";
4534
+ const src = fs3.existsSync(shipped) ? shipped : path3.resolve(name);
4535
+ if (!fs3.existsSync(src) || !fs3.statSync(src).isDirectory()) {
4536
+ const available = base ? fs3.readdirSync(base).join(", ") : "(none found)";
4537
+ console.error(`rosetack: no template '${name}' - available: ${available} (or pass a path to any project directory)`);
4538
+ process.exit(1);
4539
+ }
4540
+ fs3.cpSync(src, dir, {
4541
+ recursive: true,
4542
+ filter: (s) => !/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(s)
4543
+ });
4544
+ const pkgFile = path3.join(dir, "package.json");
4545
+ if (fs3.existsSync(pkgFile)) {
4546
+ const pkg = JSON.parse(fs3.readFileSync(pkgFile, "utf8"));
4547
+ pkg.name = path3.basename(dir);
4548
+ if (pkg.dependencies?.rosetack) pkg.dependencies.rosetack = `^${version()}`;
4549
+ pkg.devDependencies = { ...pkg.devDependencies, typescript: "^5.6.0" };
4550
+ fs3.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
4551
+ }
4552
+ writeTypeScriptReady(dir);
4553
+ console.log(`\u{1F339} RoseTack new: ${display}/ from the '${path3.basename(src)}' template`);
4554
+ console.log(`
4555
+ cd ${display}`);
4556
+ console.log(` npm install && npm run dev`);
4557
+ console.log(` npm run build # then deploy dist/`);
4558
+ }
3993
4559
  async function scaffold() {
3994
- const name = process.argv[3];
3995
- if (!name || name.startsWith("-")) {
3996
- console.log("Usage: rosetack new <name> (creates <name>/ with a page that builds)");
4560
+ const args = argv.slice(1);
4561
+ const tplIdx = args.indexOf("--template");
4562
+ const template = tplIdx >= 0 ? args[tplIdx + 1] : null;
4563
+ const name = args.find((a, i) => !a.startsWith("-") && i !== (tplIdx >= 0 ? tplIdx + 1 : -1));
4564
+ if (!name || tplIdx >= 0 && !template) {
4565
+ const available = templatesDir() ? fs3.readdirSync(templatesDir()).join(", ") : "blog, api, admin, site";
4566
+ console.log(`Usage: rosetack new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${available} - or any project directory)`);
3997
4567
  return;
3998
4568
  }
3999
4569
  const dir = path3.resolve(name);
@@ -4001,6 +4571,10 @@ async function scaffold() {
4001
4571
  console.error(`rosetack: ${dir} already exists - pick another name`);
4002
4572
  process.exit(1);
4003
4573
  }
4574
+ if (template) {
4575
+ copyTemplate(dir, template, name);
4576
+ return;
4577
+ }
4004
4578
  const pages = path3.join(dir, "src", "pages");
4005
4579
  fs3.mkdirSync(pages, { recursive: true });
4006
4580
  fs3.writeFileSync(path3.join(dir, "package.json"), JSON.stringify({
@@ -4015,30 +4589,11 @@ async function scaffold() {
4015
4589
  check: "rosetack check"
4016
4590
  },
4017
4591
  dependencies: { rosetack: `^${version()}` },
4018
- // TypeScript is a first-class citizen: .rose scripts are typed, and `npm run check`
4019
- // type-checks every one of them with THIS project's TypeScript …
4020
4592
  devDependencies: { typescript: "^5.6.0" }
4021
4593
  }, null, 2) + "\n");
4022
- fs3.writeFileSync(path3.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
4023
- `);
4024
- fs3.writeFileSync(path3.join(dir, "tsconfig.json"), JSON.stringify({
4025
- compilerOptions: {
4026
- target: "ES2022",
4027
- module: "ESNext",
4028
- moduleResolution: "bundler",
4029
- lib: ["ES2022", "DOM", "DOM.Iterable"],
4030
- strict: true,
4031
- noEmit: true,
4032
- skipLibCheck: true
4033
- },
4034
- // the env file first (it is what makes the globals visible), then any
4035
- // .ts the project grows - .rose scripts are checked by `npm run check`
4036
- include: ["rosetack-env.d.ts", "src/**/*.ts"]
4037
- }, null, 2) + "\n");
4594
+ writeTypeScriptReady(dir);
4038
4595
  fs3.writeFileSync(path3.join(pages, "index.rose"), `<script>
4039
- // One file per route: markup, script and styles together.
4040
- // The script block is TypeScript - interfaces, annotations, generics and
4041
- // casts all compile, and \`npm run check\` type-checks them.
4596
+
4042
4597
  interface Item { label: string }
4043
4598
 
4044
4599
  let count = $state(0);
@@ -4047,8 +4602,8 @@ async function scaffold() {
4047
4602
 
4048
4603
  function increment() { $setState('count', count() + 1); }
4049
4604
  function toggleList() { $setState('showList', !showList()); }
4050
- // typed server data: the body runs per request on the server (and ships
4051
- // to the client, where it re-runs on a client-side navigation)
4605
+
4606
+
4052
4607
  let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
4053
4608
  </script>
4054
4609
 
@@ -4085,7 +4640,6 @@ npm run check # type-checks every .rose script
4085
4640
  Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
4086
4641
  \`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
4087
4642
  runs before every request, \`src/pages/api/*.rose\` answers JSON.
4088
- Full syntax: the README of the rosetack package.
4089
4643
  `);
4090
4644
  fs3.writeFileSync(path3.join(dir, ".gitignore"), "node_modules/\ndist/\n");
4091
4645
  console.log(`\u{1F339} Created ${dir}`);
@@ -4167,13 +4721,8 @@ async function check() {
4167
4721
  module: tsMod.ModuleKind.ESNext,
4168
4722
  moduleResolution: tsMod.ModuleResolutionKind.Bundler,
4169
4723
  lib: ["lib.es2022.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"],
4170
- // the virtual files are named after the .rose files (so a diagnostic points at the real
4171
- // path) …
4172
4724
  allowNonTsExtensions: true,
4173
- // the rewired './runtime.js' import points at a real .ts source
4174
4725
  allowImportingTsExtensions: true,
4175
- // `types` is deliberately NOT set: the project's own @types packages (@types/node for
4176
- // node:sqlite, say) load automatically, the way they do for the user's own .ts files.
4177
4726
  skipLibCheck: true
4178
4727
  };
4179
4728
  const host = tsMod.createCompilerHost(options);
@@ -4227,4 +4776,4 @@ else if (cmd === "serve") void serve().catch(reportFailure);
4227
4776
  else if (cmd === "new") void scaffold().catch(reportFailure);
4228
4777
  else if (cmd === "check") void check().catch(reportFailure);
4229
4778
  else if (cmd === "prompt") console.log(AI_PROMPT);
4230
- else console.log("Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON)");
4779
+ else console.log("Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] [--static] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON; --static verifies the build is deployable with no server at all; `new <name> [--template blog|api|admin|site]` scaffolds a project)");