rosetack 0.1.1 → 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 (56) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/k8s/rosetack.yaml +107 -0
  4. package/deploy/netlify/functions/rosetack.ts +38 -0
  5. package/deploy/netlify.toml +17 -0
  6. package/devtools/devtools.html +7 -0
  7. package/devtools/devtools.js +1 -0
  8. package/devtools/manifest.json +8 -0
  9. package/devtools/panel.html +28 -0
  10. package/devtools/panel.js +54 -0
  11. package/dist-cli/compiler.mjs +1346 -492
  12. package/dist-cli/edge.mjs +152 -41
  13. package/dist-cli/rosetack.mjs +1974 -606
  14. package/dist-cli/runtime.mjs +205 -40
  15. package/dist-cli/test.mjs +1425 -508
  16. package/package.json +4 -3
  17. package/src/FRAMEWORK_VERSION +1 -1
  18. package/src/cli/edge.ts +76 -61
  19. package/src/cli/index.ts +516 -293
  20. package/src/cli/prompt.ts +130 -0
  21. package/src/cli/shell.ts +113 -65
  22. package/src/cli/test.ts +9 -70
  23. package/src/compiler/errors.ts +74 -0
  24. package/src/compiler/index.ts +1514 -839
  25. package/src/runtime/index.ts +255 -150
  26. package/src/types/rosetack.d.ts +18 -59
  27. package/templates/admin/package.json +14 -0
  28. package/templates/admin/rosetack.config.js +1 -0
  29. package/templates/admin/src/pages/_middleware.rose +33 -0
  30. package/templates/admin/src/pages/api/items.rose +37 -0
  31. package/templates/admin/src/pages/api/login.rose +25 -0
  32. package/templates/admin/src/pages/index.rose +79 -0
  33. package/templates/api/package.json +14 -0
  34. package/templates/api/rosetack.config.js +1 -0
  35. package/templates/api/src/pages/api/health.rose +7 -0
  36. package/templates/api/src/pages/api/items.rose +46 -0
  37. package/templates/api/src/pages/api/login.rose +24 -0
  38. package/templates/api/src/pages/index.rose +25 -0
  39. package/templates/blog/package.json +14 -0
  40. package/templates/blog/rosetack.config.js +1 -0
  41. package/templates/blog/src/pages/404.rose +2 -0
  42. package/templates/blog/src/pages/_layout.rose +42 -0
  43. package/templates/blog/src/pages/_middleware.rose +74 -0
  44. package/templates/blog/src/pages/admin.rose +85 -0
  45. package/templates/blog/src/pages/api/login.rose +46 -0
  46. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  47. package/templates/blog/src/pages/api/posts.rose +72 -0
  48. package/templates/blog/src/pages/index.rose +31 -0
  49. package/templates/blog/src/pages/post/[id].rose +36 -0
  50. package/templates/site/package.json +14 -0
  51. package/templates/site/rosetack.config.js +1 -0
  52. package/templates/site/src/pages/404.rose +2 -0
  53. package/templates/site/src/pages/_layout.rose +40 -0
  54. package/templates/site/src/pages/about.rose +6 -0
  55. package/templates/site/src/pages/index.rose +13 -0
  56. package/templates/site/src/pages/pricing.rose +8 -0
package/dist-cli/test.mjs CHANGED
@@ -9,6 +9,43 @@ import * as fs from "fs";
9
9
  import * as path from "path";
10
10
  import { pathToFileURL, fileURLToPath } from "url";
11
11
  import * as esbuild from "esbuild";
12
+
13
+ // src/compiler/errors.ts
14
+ var RoseError = class extends Error {
15
+ code;
16
+ file;
17
+ line;
18
+ hint;
19
+ constructor(code, message, opts = {}) {
20
+ super(message);
21
+ this.name = "RoseError";
22
+ this.code = code;
23
+ this.file = opts.file;
24
+ this.line = opts.line;
25
+ this.hint = opts.hint;
26
+ }
27
+ info() {
28
+ const info = { code: this.code };
29
+ if (this.file !== void 0) info.file = this.file;
30
+ if (this.line !== void 0) info.line = this.line;
31
+ info.message = this.message;
32
+ if (this.hint !== void 0) info.hint = this.hint;
33
+ return info;
34
+ }
35
+ };
36
+ function lineOf(src, index) {
37
+ let line = 1;
38
+ const end = Math.min(index, src.length);
39
+ for (let i = 0; i < end; i++) {
40
+ if (src[i] === "\n") line++;
41
+ }
42
+ return line;
43
+ }
44
+ function lineAt(src, match) {
45
+ return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
46
+ }
47
+
48
+ // src/compiler/index.ts
12
49
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
13
50
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
14
51
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
@@ -16,12 +53,11 @@ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
16
53
  var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
17
54
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
18
55
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
19
- var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
20
56
  var SLOT_RE = /<slot\s*\/?>/g;
21
57
  var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
22
58
  function encodeSlotCall(attrs) {
23
59
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
24
- if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
60
+ if (!name) throw new RoseError("E-TEMPLATE", '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
25
61
  const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
26
62
  return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
27
63
  }
@@ -108,7 +144,306 @@ function callifyStateReads(script, names) {
108
144
  }
109
145
  function callifyTemplateExprs(template, names) {
110
146
  if (names.length === 0) return template;
111
- return template.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${callifyStateReads(expr, names)}}`);
147
+ let out = "";
148
+ let last = 0;
149
+ for (const s of templateExprSpans(template)) {
150
+ out += template.slice(last, s.start) + "{" + callifyStateReads(s.expr, names) + "}";
151
+ last = s.end + 1;
152
+ }
153
+ return out + template.slice(last);
154
+ }
155
+ function templateExprSpans(src) {
156
+ const spans = [];
157
+ let i = 0;
158
+ while (i < src.length) {
159
+ if (src[i] === "{") {
160
+ const end = scanExprEnd(src, i);
161
+ if (end > i + 1) {
162
+ spans.push({ start: i, end, expr: src.slice(i + 1, end) });
163
+ i = end + 1;
164
+ continue;
165
+ }
166
+ }
167
+ i++;
168
+ }
169
+ return spans;
170
+ }
171
+ function scanExprEnd(src, open) {
172
+ let depth = 0;
173
+ let i = open;
174
+ while (i < src.length) {
175
+ const ch = src[i];
176
+ if (ch === "'" || ch === '"') {
177
+ i = skipQuoted(src, i);
178
+ continue;
179
+ }
180
+ if (ch === "`") {
181
+ i = skipTemplate(src, i);
182
+ continue;
183
+ }
184
+ if (ch === "{") depth++;
185
+ else if (ch === "}" && --depth === 0) return i;
186
+ i++;
187
+ }
188
+ return -1;
189
+ }
190
+ function skipQuoted(src, i) {
191
+ const q = src[i];
192
+ let j = i + 1;
193
+ while (j < src.length) {
194
+ if (src[j] === "\\") {
195
+ j += 2;
196
+ continue;
197
+ }
198
+ if (src[j] === q) return j + 1;
199
+ j++;
200
+ }
201
+ return j;
202
+ }
203
+ function skipTemplate(src, i) {
204
+ let j = i + 1;
205
+ while (j < src.length) {
206
+ const ch = src[j];
207
+ if (ch === "\\") {
208
+ j += 2;
209
+ continue;
210
+ }
211
+ if (ch === "`") return j + 1;
212
+ if (ch === "$" && src[j + 1] === "{") {
213
+ const end = scanExprEnd(src, j + 1);
214
+ j = end < 0 ? src.length : end + 1;
215
+ continue;
216
+ }
217
+ j++;
218
+ }
219
+ return j;
220
+ }
221
+ function skipLiteral(src, i) {
222
+ const q = src[i];
223
+ if (q === '"' || q === "'") return skipQuoted(src, i);
224
+ if (q === "`") return skipTemplate(src, i);
225
+ if (q !== "/") return null;
226
+ if (src[i + 1] === "/" || src[i + 1] === "*") return null;
227
+ let b = i - 1;
228
+ while (b >= 0 && /\s/.test(src[b])) b--;
229
+ if (b >= 0) {
230
+ if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
231
+ const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
232
+ if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
233
+ }
234
+ }
235
+ let j = i + 1;
236
+ let inClass = false;
237
+ while (j < src.length) {
238
+ const c = src[j];
239
+ if (c === "\\") {
240
+ j += 2;
241
+ continue;
242
+ }
243
+ if (c === "\n") return null;
244
+ if (inClass) {
245
+ if (c === "]") inClass = false;
246
+ } else if (c === "[") inClass = true;
247
+ else if (c === "/") {
248
+ j++;
249
+ break;
250
+ }
251
+ j++;
252
+ }
253
+ if (j > src.length) return null;
254
+ while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
255
+ return j;
256
+ }
257
+ function stripComments(src) {
258
+ let out = "";
259
+ let i = 0;
260
+ while (i < src.length) {
261
+ const lit = skipLiteral(src, i);
262
+ if (lit !== null) {
263
+ out += src.slice(i, lit);
264
+ i = lit;
265
+ continue;
266
+ }
267
+ if (src.startsWith("//", i)) {
268
+ while (i < src.length && src[i] !== "\n") i++;
269
+ continue;
270
+ }
271
+ if (src.startsWith("/*", i)) {
272
+ i += 2;
273
+ while (i < src.length && !src.startsWith("*/", i)) i++;
274
+ i = Math.min(i + 2, src.length);
275
+ continue;
276
+ }
277
+ if (src.startsWith("<!--", i)) {
278
+ i += 4;
279
+ while (i < src.length && !src.startsWith("-->", i)) i++;
280
+ i = Math.min(i + 3, src.length);
281
+ continue;
282
+ }
283
+ out += src[i++];
284
+ }
285
+ return out;
286
+ }
287
+ function stripGuardedBranches(src) {
288
+ const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
289
+ const ws = (i2) => {
290
+ while (i2 < src.length && /\s/.test(src[i2])) i2++;
291
+ return i2;
292
+ };
293
+ const ternaryColon = (q) => {
294
+ let depth = 0;
295
+ let i2 = q + 1;
296
+ while (i2 < src.length) {
297
+ const c = src[i2];
298
+ const lit = skipLiteral(src, i2);
299
+ if (lit !== null) {
300
+ i2 = lit;
301
+ continue;
302
+ }
303
+ if (c === "(" || c === "[" || c === "{") depth++;
304
+ else if (c === ")" || c === "]" || c === "}") {
305
+ depth--;
306
+ if (depth < 0) return -1;
307
+ } else if (depth === 0 && c === ":") return i2;
308
+ else if (depth === 0 && c === "?") {
309
+ const inner = ternaryColon(i2);
310
+ if (inner < 0) return -1;
311
+ i2 = inner + 1;
312
+ continue;
313
+ }
314
+ i2++;
315
+ }
316
+ return -1;
317
+ };
318
+ const exprEnd = (i2) => {
319
+ let depth = 0;
320
+ while (i2 < src.length) {
321
+ const c = src[i2];
322
+ const lit = skipLiteral(src, i2);
323
+ if (lit !== null) {
324
+ i2 = lit;
325
+ continue;
326
+ }
327
+ if (c === "(" || c === "[" || c === "{") depth++;
328
+ else if (c === ")" || c === "]" || c === "}") {
329
+ if (depth === 0) return i2;
330
+ depth--;
331
+ } else if (depth === 0 && (c === "," || c === ";")) return i2;
332
+ else if (depth === 0 && c === "?") {
333
+ const inner = ternaryColon(i2);
334
+ if (inner < 0) return src.length;
335
+ i2 = inner + 1;
336
+ continue;
337
+ }
338
+ i2++;
339
+ }
340
+ return src.length;
341
+ };
342
+ const braceEnd = (b) => {
343
+ let depth = 0;
344
+ let i2 = b;
345
+ while (i2 < src.length) {
346
+ const c = src[i2];
347
+ const lit = skipLiteral(src, i2);
348
+ if (lit !== null) {
349
+ i2 = lit;
350
+ continue;
351
+ }
352
+ if (c === "{") depth++;
353
+ else if (c === "}") {
354
+ depth--;
355
+ if (depth === 0) return i2;
356
+ }
357
+ i2++;
358
+ }
359
+ return src.length;
360
+ };
361
+ const stmtEnd = (i2) => {
362
+ let depth = 0;
363
+ while (i2 < src.length) {
364
+ const c = src[i2];
365
+ const lit = skipLiteral(src, i2);
366
+ if (lit !== null) {
367
+ i2 = lit;
368
+ continue;
369
+ }
370
+ if (c === "(" || c === "[" || c === "{") depth++;
371
+ else if (c === ")" || c === "]" || c === "}") {
372
+ if (depth === 0) return i2;
373
+ depth--;
374
+ } else if (depth === 0 && (c === ";" || c === "\n")) return i2;
375
+ i2++;
376
+ }
377
+ return src.length;
378
+ };
379
+ const isIfGuard = (src2, at) => {
380
+ let b = at - 1;
381
+ while (b >= 0 && /\s/.test(src2[b])) b--;
382
+ if (b < 0 || src2[b] !== "(") return false;
383
+ b--;
384
+ while (b >= 0 && /\s/.test(src2[b])) b--;
385
+ return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
386
+ };
387
+ const blanks = [];
388
+ let i = 0;
389
+ while (i < src.length) {
390
+ const lit = skipLiteral(src, i);
391
+ if (lit !== null) {
392
+ i = lit;
393
+ continue;
394
+ }
395
+ GUARD.lastIndex = i;
396
+ const m = GUARD.exec(src);
397
+ if (!m) {
398
+ i++;
399
+ continue;
400
+ }
401
+ const browserAfter = m[1] === "!==";
402
+ const j = ws(i + m[0].length);
403
+ const two = src.slice(j, j + 2);
404
+ if (two === "&&" && browserAfter) {
405
+ blanks.push([j + 2, exprEnd(j + 2)]);
406
+ } else if (two === "||" && !browserAfter) {
407
+ blanks.push([j + 2, exprEnd(j + 2)]);
408
+ } else if (src[j] === "?") {
409
+ const colon = ternaryColon(j);
410
+ if (colon < 0) {
411
+ if (browserAfter) blanks.push([j + 1, src.length]);
412
+ } else if (browserAfter) {
413
+ blanks.push([j + 1, colon]);
414
+ } else {
415
+ blanks.push([colon + 1, exprEnd(colon + 1)]);
416
+ }
417
+ } else if (src[j] === ")" && isIfGuard(src, i)) {
418
+ let bodyEnd;
419
+ const k = ws(j + 1);
420
+ if (src[k] === "{") {
421
+ bodyEnd = braceEnd(k);
422
+ if (browserAfter) blanks.push([k + 1, bodyEnd]);
423
+ } else {
424
+ bodyEnd = stmtEnd(k);
425
+ if (browserAfter) blanks.push([k, bodyEnd]);
426
+ }
427
+ const after = ws(bodyEnd + 1);
428
+ if (src.startsWith("else", after)) {
429
+ const e = ws(after + 4);
430
+ if (src[e] === "{") {
431
+ const close = braceEnd(e);
432
+ if (!browserAfter) blanks.push([e + 1, close]);
433
+ } else {
434
+ const stop = stmtEnd(e);
435
+ if (!browserAfter) blanks.push([e, stop]);
436
+ }
437
+ }
438
+ }
439
+ i = j;
440
+ }
441
+ if (blanks.length === 0) return src;
442
+ const out = [...src];
443
+ for (const [a, b] of blanks) {
444
+ for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
445
+ }
446
+ return out.join("");
112
447
  }
113
448
  async function loadConfig(root) {
114
449
  const file = path.join(root, "rosetack.config.js");
@@ -121,21 +456,29 @@ async function loadConfig(root) {
121
456
  }
122
457
  function resolveRoseImports(script, fromFile, registry) {
123
458
  const imports = [];
124
- const resolve3 = (spec) => {
459
+ const resolve3 = (spec, at) => {
125
460
  const abs = path.resolve(path.dirname(fromFile), spec);
126
461
  const hit = registry.get(abs);
127
462
  if (!hit) {
128
- throw new Error(`${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`);
463
+ throw new RoseError(
464
+ "E-IMPORT",
465
+ `${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
466
+ {
467
+ file: fromFile,
468
+ line: lineOf(script, at),
469
+ hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`
470
+ }
471
+ );
129
472
  }
130
473
  return hit;
131
474
  };
132
- let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
133
- const hit = resolve3(spec);
475
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at) => {
476
+ const hit = resolve3(spec, at);
134
477
  imports.push({ name, specifier: spec, index: hit.index });
135
478
  return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
136
479
  });
137
- rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
138
- const hit = resolve3(spec);
480
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at) => {
481
+ const hit = resolve3(spec, at);
139
482
  const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
140
483
  imports.push({ name: alias, specifier: spec, index: hit.index });
141
484
  return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
@@ -145,6 +488,60 @@ function resolveRoseImports(script, fromFile, registry) {
145
488
  function rewriteRoseImports(script, kind) {
146
489
  return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
147
490
  }
491
+ var NODE_ONLY_SPEC = /^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream|child_process|worker_threads|dns|cluster|better-sqlite3|sqlite3|pg|mysql2|mongodb|redis|ioredis)$)/;
492
+ function nodeOnlyImports(importStmts) {
493
+ const out = [];
494
+ for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
495
+ if (m[1]) continue;
496
+ if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
497
+ }
498
+ return out;
499
+ }
500
+ function wireEventBindings(template, actionNames) {
501
+ const bindings = [];
502
+ let out = "";
503
+ let rest = template;
504
+ for (; ; ) {
505
+ const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
506
+ if (!m) {
507
+ out += rest;
508
+ break;
509
+ }
510
+ out += rest.slice(0, m.index);
511
+ let i = m.index + m[0].length;
512
+ let depth = 1;
513
+ while (i < rest.length) {
514
+ const ch = rest[i];
515
+ if (ch === '"' || ch === "'") {
516
+ i = skipQuoted(rest, i);
517
+ continue;
518
+ }
519
+ if (ch === "`") {
520
+ i = skipTemplate(rest, i);
521
+ continue;
522
+ }
523
+ if (ch === "{") depth++;
524
+ else if (ch === "}") {
525
+ depth--;
526
+ if (depth === 0) break;
527
+ }
528
+ i++;
529
+ }
530
+ const expr = rest.slice(m.index + m[0].length, i).trim();
531
+ if (actionNames.has(expr)) {
532
+ out += `data-on-${m[1]}="$action:${expr}"`;
533
+ } else if (/^\w+$/.test(expr)) {
534
+ out += `data-on-${m[1]}="${expr}"`;
535
+ bindings.push({ event: m[1], fn: expr });
536
+ } else {
537
+ const name = `__h${bindings.length}`;
538
+ out += `data-on-${m[1]}="${name}"`;
539
+ bindings.push({ event: m[1], fn: `${name}: ${expr}` });
540
+ }
541
+ rest = rest.slice(i + 1);
542
+ }
543
+ return { template: out, bindings };
544
+ }
148
545
  function scanSlotDecls(filePath) {
149
546
  let src;
150
547
  try {
@@ -152,8 +549,9 @@ function scanSlotDecls(filePath) {
152
549
  } catch {
153
550
  return [];
154
551
  }
155
- const noBlocks = src.replace(STYLE_RE, "");
156
- const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
552
+ const noScript = src.replace(COMPONENT_RE, "");
553
+ const noBlocks = noScript.replace(STYLE_RE, "");
554
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
157
555
  const out = [];
158
556
  for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
159
557
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
@@ -207,7 +605,11 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
207
605
  try {
208
606
  source = await p.transform(source, filePath);
209
607
  } catch (err) {
210
- throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
608
+ throw new RoseError(
609
+ "E-PLUGIN",
610
+ `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
611
+ { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
612
+ );
211
613
  }
212
614
  }
213
615
  if (isApi) {
@@ -217,6 +619,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
217
619
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
218
620
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
219
621
  const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
622
+ const ownRuntimeImports = new Set(
623
+ [...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))
624
+ );
625
+ const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
626
+ const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
627
+ ` : "";
220
628
  return {
221
629
  ssr: "",
222
630
  client: "",
@@ -225,49 +633,95 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
225
633
  guardName: null,
226
634
  style: "",
227
635
  hasParams: false,
228
- api: `import { getContext } from './runtime.js';
229
- ${rewriteRoseImports(`${hoisted.imports}
636
+ api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
230
637
  ${hoisted.rest}`, "ssr").trim()}`,
231
638
  apiMethods,
232
639
  hasPrerender,
233
640
  usesContext: usesContext2
234
641
  };
235
642
  }
236
- const styleMatch = source.match(STYLE_RE);
643
+ const sourceNoScript = source.replace(COMPONENT_RE, "");
644
+ const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
645
+ const styleMatch = sourceNoHead.match(STYLE_RE);
237
646
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
238
- const sourceNoBlocks = source.replace(STYLE_RE, "");
239
- const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
647
+ const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
648
+ const scriptMatch = source.match(COMPONENT_RE);
240
649
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
241
650
  const rawScript = roseResolved.script;
242
651
  const roseImports = roseResolved.imports;
243
652
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
653
+ if (path.basename(filePath) !== "_middleware.rose") {
654
+ for (const spec of nodeOnlyImports(importStmts)) {
655
+ const at = importStmts.indexOf(spec);
656
+ throw new RoseError(
657
+ "E-NODE-ONLY",
658
+ `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
659
+ {
660
+ file: filePath,
661
+ line: at >= 0 ? lineOf(importStmts, at) : void 0,
662
+ hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`
663
+ }
664
+ );
665
+ }
666
+ }
244
667
  const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
245
668
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
246
- throw new Error(
247
- `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`
669
+ throw new RoseError(
670
+ "E-EXPORT",
671
+ `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
672
+ { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
248
673
  );
249
674
  }
250
- const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
675
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
251
676
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
252
677
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
253
678
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
254
679
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
255
680
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
256
681
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
257
- throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
682
+ throw new RoseError(
683
+ "E-EXPORT",
684
+ `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
685
+ { file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
686
+ );
687
+ }
688
+ const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
689
+ const vitals = vitalsMatch ? vitalsMatch[1].trim() === "true" : void 0;
690
+ if (vitalsMatch && !vitals) {
691
+ throw new RoseError(
692
+ "E-EXPORT",
693
+ `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
694
+ { file: filePath, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
695
+ );
258
696
  }
259
697
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
260
698
  const bundle = bundleMatch ? bundleMatch[1] : void 0;
261
699
  if (bundle && !["inline", "split"].includes(bundle)) {
262
- throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
700
+ throw new RoseError(
701
+ "E-EXPORT",
702
+ `${filePath}: export const bundle must be 'inline' or 'split'`,
703
+ { file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
704
+ );
263
705
  }
264
706
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
265
707
  const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
708
+ const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
709
+ const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
710
+ const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
711
+ const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
712
+ const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
266
713
  if (csr === false) {
267
714
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
268
715
  if (dead) {
269
- throw new Error(
270
- `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`
716
+ const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
717
+ throw new RoseError(
718
+ "E-EXPORT",
719
+ `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
720
+ {
721
+ file: filePath,
722
+ line: lineAt(deadSrc, dead),
723
+ hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'
724
+ }
271
725
  );
272
726
  }
273
727
  }
@@ -278,10 +732,18 @@ ${hoisted.rest}`, "ssr").trim()}`,
278
732
  try {
279
733
  value = new Function(`return ${headersLiteral}`)();
280
734
  } catch {
281
- throw new Error(`${filePath}: export const headers must be an object literal`);
735
+ throw new RoseError(
736
+ "E-EXPORT",
737
+ `${filePath}: export const headers must be an object literal`,
738
+ { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
739
+ );
282
740
  }
283
741
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
284
- throw new Error(`${filePath}: export const headers must be a flat map of string -> string`);
742
+ throw new RoseError(
743
+ "E-EXPORT",
744
+ `${filePath}: export const headers must be a flat map of string -> string`,
745
+ { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
746
+ );
285
747
  }
286
748
  headers = value;
287
749
  }
@@ -292,11 +754,19 @@ ${hoisted.rest}`, "ssr").trim()}`,
292
754
  try {
293
755
  value = new Function(`return ${cspLiteral}`)();
294
756
  } catch {
295
- throw new Error(`${filePath}: export const csp must be an object literal`);
757
+ throw new RoseError(
758
+ "E-EXPORT",
759
+ `${filePath}: export const csp must be an object literal`,
760
+ { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
761
+ );
296
762
  }
297
763
  const nonce = value?.nonce;
298
764
  if (nonce !== void 0 && typeof nonce !== "boolean") {
299
- throw new Error(`${filePath}: csp.nonce must be a boolean`);
765
+ throw new RoseError(
766
+ "E-EXPORT",
767
+ `${filePath}: csp.nonce must be a boolean`,
768
+ { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
769
+ );
300
770
  }
301
771
  cspNonce = nonce === true;
302
772
  }
@@ -305,54 +775,39 @@ ${hoisted.rest}`, "ssr").trim()}`,
305
775
  const actionNames = new Set(actions.map((a) => a.name));
306
776
  const clientReasons = [];
307
777
  if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
308
- if (/<form[\s>]/.test(source)) clientReasons.push("a <form> (its in-place adopt is the enhancement)");
778
+ if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
779
+ clientReasons.push("a form bound to a client dispatch ($action)");
780
+ }
309
781
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
310
782
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
311
- if (actionNames.size > 0) {
312
- clientReasons.push(`server action${actionNames.size > 1 ? "s" : ""} (${[...actionNames].join(", ")})`);
313
- }
314
783
  const needsClient = clientReasons.length > 0;
315
784
  const jsWarnings = [];
316
785
  if (!needsClient) {
317
- if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
786
+ const codeOnly = stripComments(source);
787
+ const scriptCodeOnly = stripComments(rawScript);
788
+ const scriptScannable = stripGuardedBranches(scriptCodeOnly);
789
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
318
790
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
319
791
  }
320
- if (/javascript:/i.test(source)) {
792
+ if (/javascript:/i.test(codeOnly)) {
321
793
  jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
322
794
  }
323
- if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
795
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
324
796
  jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
325
797
  }
326
- 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(rawScript)) {
798
+ 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)) {
327
799
  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");
328
800
  }
329
801
  }
330
802
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
331
- const headMatch = sourceNoBlocks.match(HEAD_RE);
332
- const headContent = headMatch?.[1] ?? "";
333
- const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, "");
334
- const rawTemplate = templateMatch ? templateMatch[1] : sourceNoHead.replace(COMPONENT_RE, "").trim();
803
+ const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
804
+ const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
335
805
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
336
806
  const decls = extractDecls(script);
337
807
  const stateDecls = decls.filter((d) => d.kind === "state");
338
808
  const setterNames = /* @__PURE__ */ new Map();
339
809
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
340
- const eventBindings = [];
341
- let em;
342
- EVENT_RE.lastIndex = 0;
343
- while (em = EVENT_RE.exec(template)) {
344
- if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
345
- }
346
- let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end]));
347
- cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
348
- const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
349
- const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
350
- return `${setter}(${val})`;
351
- });
352
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
353
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
354
- const ssrTemplate = templateCalled.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}").replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) => actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
355
- const stateDeclsCode = decls.map((d) => {
810
+ const declCode = (d) => {
356
811
  const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
357
812
  if (d.kind === "state") {
358
813
  return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
@@ -362,15 +817,39 @@ ${hoisted.rest}`, "ssr").trim()}`,
362
817
  return `const __had_${d.name} = hasState(${JSON.stringify(key)});
363
818
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
364
819
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
365
- }).join("\n");
820
+ };
821
+ const nestedDecls = [];
822
+ let spliced = "";
823
+ let pos = 0;
824
+ decls.forEach((d, i) => {
825
+ const top = braceDepthAt(script, d.start) === 0;
826
+ if (!top) nestedDecls.push(d);
827
+ spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
828
+ pos = d.end;
829
+ });
830
+ spliced += script.slice(pos);
831
+ let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
832
+ const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
833
+ const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
834
+ return `${setter}(${val})`;
835
+ });
836
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
837
+ cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
838
+ const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
839
+ const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
840
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
841
+ const wired = wireEventBindings(templateCalled, actionNames);
842
+ const eventBindings = wired.bindings;
366
843
  const stateKeys = decls.map((d) => d.name);
367
844
  const comps = new Map(roseImports.map((r) => {
368
845
  const abs = path.resolve(path.dirname(filePath), r.specifier);
369
846
  const hit = registry.get(abs);
370
847
  return [r.name, { index: hit.index, slots: hit.slots }];
371
848
  }));
849
+ const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
850
+ assertKnownDirectives(ssrTemplate, filePath);
372
851
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
373
- const compiledHead = headContent.trim() ? compileTemplate(headContent, "__hd", "__hc", null, 0, false) : "";
852
+ const compiledHead = headContent.trim() ? compileHead(headContent) : "";
374
853
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
375
854
  const ssrExports = actions.length > 0 ? `${exportStmts}
376
855
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
@@ -385,8 +864,8 @@ ${ssrExports}
385
864
  ${ssrGuard}
386
865
 
387
866
  ${cleanScript}
388
- ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
389
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
867
+ ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
868
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
390
869
  return {
391
870
  ssr: rewriteRoseImports(ssr, "ssr"),
392
871
  client: rewriteRoseImports(client, "client"),
@@ -398,7 +877,11 @@ ${cleanScript}
398
877
  usesContext,
399
878
  revalidate,
400
879
  csr,
880
+ shell,
881
+ buffer,
882
+ controlSignal,
401
883
  prefetch,
884
+ vitals,
402
885
  bundle,
403
886
  needsClient,
404
887
  clientReasons,
@@ -633,31 +1116,236 @@ function extractDecls(script) {
633
1116
  }
634
1117
  return decls;
635
1118
  }
636
- function removeRanges(text, ranges) {
637
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
638
- let out = "";
639
- let pos = 0;
640
- for (const [start, end] of sorted) {
641
- out += text.slice(pos, start);
642
- pos = end;
1119
+ function braceDepthAt(src, index) {
1120
+ let depth = 0;
1121
+ let i = 0;
1122
+ while (i < index) {
1123
+ const ch = src[i];
1124
+ if (ch === "'" || ch === '"' || ch === "`") {
1125
+ const quote = ch;
1126
+ i++;
1127
+ while (i < index) {
1128
+ if (src[i] === "\\") {
1129
+ i += 2;
1130
+ continue;
1131
+ }
1132
+ if (src[i] === quote) {
1133
+ i++;
1134
+ break;
1135
+ }
1136
+ if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
1137
+ let d = 1;
1138
+ i += 2;
1139
+ while (i < index && d > 0) {
1140
+ if (src[i] === "{") d++;
1141
+ else if (src[i] === "}") d--;
1142
+ i++;
1143
+ }
1144
+ continue;
1145
+ }
1146
+ i++;
1147
+ }
1148
+ continue;
1149
+ }
1150
+ if (ch === "/" && src[i + 1] === "/") {
1151
+ const nl = src.indexOf("\n", i);
1152
+ i = nl === -1 ? src.length : nl;
1153
+ continue;
1154
+ }
1155
+ if (ch === "/" && src[i + 1] === "*") {
1156
+ const close = src.indexOf("*/", i + 2);
1157
+ i = close === -1 ? src.length : close + 2;
1158
+ continue;
1159
+ }
1160
+ if (ch === "{") depth++;
1161
+ else if (ch === "}") depth--;
1162
+ i++;
643
1163
  }
644
- out += text.slice(pos);
645
- return out;
1164
+ return depth;
646
1165
  }
647
1166
  function autoCall(expr) {
648
1167
  const e = expr.trim();
649
1168
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
650
1169
  }
1170
+ function findBlock(src, kind) {
1171
+ const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
1172
+ const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1173
+ let open;
1174
+ while (open = head.exec(src)) {
1175
+ const start = open.index;
1176
+ const afterOpen = start + open[0].length;
1177
+ let depth = 1;
1178
+ let i = afterOpen;
1179
+ for (; ; ) {
1180
+ head.lastIndex = i;
1181
+ closeRe.lastIndex = i;
1182
+ const nextOpen = head.exec(src);
1183
+ const nextClose = closeRe.exec(src);
1184
+ if (!nextClose) break;
1185
+ if (nextOpen && nextOpen.index < nextClose.index) {
1186
+ depth++;
1187
+ i = nextOpen.index + nextOpen[0].length;
1188
+ continue;
1189
+ }
1190
+ i = nextClose.index + nextClose[0].length;
1191
+ if (--depth === 0) {
1192
+ const content = src.slice(afterOpen, nextClose.index);
1193
+ const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
1194
+ const arr = [src.slice(start, i), ...groups];
1195
+ arr.index = start;
1196
+ return arr;
1197
+ }
1198
+ }
1199
+ head.lastIndex = afterOpen;
1200
+ }
1201
+ return null;
1202
+ }
1203
+ function compileHead(head) {
1204
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
1205
+ let out = "";
1206
+ let buf = "";
1207
+ let seg = 0;
1208
+ let i = 0;
1209
+ const flush = () => {
1210
+ if (buf.trim()) out += compileTemplate(buf, "__hd", "__hc", null, seg++, false);
1211
+ buf = "";
1212
+ };
1213
+ while (i < head.length) {
1214
+ if (head.startsWith("<!--", i)) {
1215
+ const end = head.indexOf("-->", i + 4);
1216
+ i = end < 0 ? head.length : end + 3;
1217
+ continue;
1218
+ }
1219
+ RAW_OPEN.lastIndex = i;
1220
+ const open = RAW_OPEN.exec(head);
1221
+ if (open) {
1222
+ const tag = open[1].toLowerCase();
1223
+ const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
1224
+ const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
1225
+ const end = gt < 0 ? head.length : gt + 1;
1226
+ flush();
1227
+ out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
1228
+ i = end;
1229
+ continue;
1230
+ }
1231
+ buf += head[i++];
1232
+ }
1233
+ flush();
1234
+ return out;
1235
+ }
1236
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
1237
+ function assertKnownDirectives(template, filePath) {
1238
+ const rawRanges = [];
1239
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
1240
+ let raw;
1241
+ while (raw = RAW_OPEN.exec(template)) {
1242
+ const tag = raw[1].toLowerCase();
1243
+ const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
1244
+ const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
1245
+ const end = gt < 0 ? template.length : gt + 1;
1246
+ rawRanges.push([raw.index, end]);
1247
+ RAW_OPEN.lastIndex = end;
1248
+ }
1249
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
1250
+ let note;
1251
+ while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
1252
+ rawRanges.sort((a, b) => a[0] - b[0]);
1253
+ const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
1254
+ const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
1255
+ let m;
1256
+ while (m = DIRECTIVE_RE.exec(template)) {
1257
+ if (inRaw(m.index)) continue;
1258
+ const [, sigil, word] = m;
1259
+ if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
1260
+ if (sigil === "/") {
1261
+ throw new RoseError(
1262
+ "E-TEMPLATE",
1263
+ `${filePath}: {/${word}} does not close anything`,
1264
+ { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
1265
+ );
1266
+ }
1267
+ if (word === "else") {
1268
+ throw new RoseError(
1269
+ "E-TEMPLATE",
1270
+ `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1271
+ { 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" }
1272
+ );
1273
+ }
1274
+ throw new RoseError(
1275
+ "E-TEMPLATE",
1276
+ `${filePath}: {:${word}} is not a rosetack directive`,
1277
+ { 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" }
1278
+ );
1279
+ }
1280
+ const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
1281
+ while (m = OPENER_RE.exec(template)) {
1282
+ if (inRaw(m.index)) continue;
1283
+ const [, kind, head] = m;
1284
+ if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
1285
+ throw new RoseError(
1286
+ "E-TEMPLATE",
1287
+ `${filePath}: {#each ${head.trim()}} is missing its item name`,
1288
+ { 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)" }
1289
+ );
1290
+ }
1291
+ const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
1292
+ const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
1293
+ let depth = 1;
1294
+ let i = m.index + m[0].length;
1295
+ for (; ; ) {
1296
+ OPEN_RE.lastIndex = i;
1297
+ CLOSE_RE.lastIndex = i;
1298
+ const nextOpen = OPEN_RE.exec(template);
1299
+ const nextClose = CLOSE_RE.exec(template);
1300
+ if (!nextClose) break;
1301
+ if (nextOpen && nextOpen.index < nextClose.index) {
1302
+ i = nextOpen.index + nextOpen[0].length;
1303
+ continue;
1304
+ }
1305
+ i = nextClose.index + nextClose[0].length;
1306
+ if (--depth === 0) break;
1307
+ }
1308
+ if (depth !== 0) {
1309
+ throw new RoseError(
1310
+ "E-TEMPLATE",
1311
+ `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
1312
+ { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
1313
+ );
1314
+ }
1315
+ }
1316
+ }
1317
+ function rewriteQuotedExprAttrs(template, comps) {
1318
+ const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
1319
+ return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
1320
+ if (comps.has(name) || !/\{/.test(attrs)) return tag;
1321
+ const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
1322
+ if (!/\{/.test(value) || value.includes("`")) return whole;
1323
+ const spans = templateExprSpans(value);
1324
+ if (spans.length === 0) return whole;
1325
+ let expr = "";
1326
+ let last = 0;
1327
+ for (const s of spans) {
1328
+ if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
1329
+ expr += (expr ? " + " : "") + `(${s.expr})`;
1330
+ last = s.end + 1;
1331
+ }
1332
+ if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
1333
+ return `${attr}={${expr}}`;
1334
+ });
1335
+ return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
1336
+ });
1337
+ }
651
1338
  function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
652
1339
  let result = "";
653
1340
  let remaining = template;
654
1341
  let blockId = 0;
655
1342
  const nextId = () => `${depth}_${blockId++}`;
656
1343
  while (remaining.length > 0) {
657
- const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/);
658
- const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/);
659
- const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/);
660
- const exprMatch = remaining.match(/\{([^{}]+)\}/);
1344
+ const ifMatch = findBlock(remaining, "if");
1345
+ const eachMatch = findBlock(remaining, "each");
1346
+ const boundaryMatch = findBlock(remaining, "boundary");
1347
+ const firstExpr = templateExprSpans(remaining)[0];
1348
+ const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
661
1349
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
662
1350
  const candidates = [];
663
1351
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
@@ -666,6 +1354,25 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
666
1354
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
667
1355
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
668
1356
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
1357
+ const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
1358
+ const rawHit = rawOpenRe.exec(remaining);
1359
+ if (rawHit && earliest && rawHit.index < earliest.index) {
1360
+ const tag = rawHit[1].toLowerCase();
1361
+ const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
1362
+ const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
1363
+ const end = gt < 0 ? remaining.length : gt + 1;
1364
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1365
+ remaining = remaining.substring(end);
1366
+ continue;
1367
+ }
1368
+ const noteAt = remaining.indexOf("<!--");
1369
+ if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
1370
+ const noteEnd = remaining.indexOf("-->", noteAt + 4);
1371
+ const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
1372
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1373
+ remaining = remaining.substring(end);
1374
+ continue;
1375
+ }
669
1376
  if (!earliest) {
670
1377
  result += emitChunk(remaining, acc, closes, scope);
671
1378
  break;
@@ -695,7 +1402,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
695
1402
  const call = autoCall(items);
696
1403
  const id = nextId();
697
1404
  const itemRe = new RegExp(`\\b${item}\\b`, "g");
698
- const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(itemRe, "__s")}}`);
1405
+ let scoped = "";
1406
+ let lastSpan = 0;
1407
+ for (const s of templateExprSpans(content.trim())) {
1408
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
1409
+ lastSpan = s.end + 1;
1410
+ }
1411
+ scoped += content.trim().slice(lastSpan);
699
1412
  const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
700
1413
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
701
1414
  `;
@@ -735,7 +1448,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
735
1448
  rest = remaining.substring(tag.end);
736
1449
  } else {
737
1450
  const closeIdx = findClose(remaining, tag.end, tag.name);
738
- if (closeIdx < 0) throw new Error(`unclosed <${tag.name}> - every component tag needs its matching close tag`);
1451
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${tag.name}> - every component tag needs its matching close tag`, { hint: `add the matching </${tag.name}> (or close the tag with /> when it takes no children)` });
739
1452
  childrenSrc = remaining.substring(tag.end, closeIdx);
740
1453
  rest = remaining.substring(closeIdx + tag.name.length + 3);
741
1454
  }
@@ -749,7 +1462,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
749
1462
  const decl = entry.slots.find((s) => s.name === nm);
750
1463
  let content = src;
751
1464
  for (const p of decl?.props ?? []) {
752
- content = content.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(new RegExp(`\\b${p}\\b`, "g"), `__s.${p}`)}}`);
1465
+ const pRe = new RegExp(`\\b${p}\\b`, "g");
1466
+ let out = "";
1467
+ let lastSpan = 0;
1468
+ for (const s of templateExprSpans(content)) {
1469
+ out += content.slice(lastSpan, s.start) + "{" + s.expr.replace(pRe, `__s.${p}`) + "}";
1470
+ lastSpan = s.end + 1;
1471
+ }
1472
+ content = out + content.slice(lastSpan);
753
1473
  }
754
1474
  return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
755
1475
  });
@@ -780,6 +1500,21 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
780
1500
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
781
1501
  continue;
782
1502
  }
1503
+ const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
1504
+ if (rawMatch) {
1505
+ if (before) result += emitChunk(before, acc, closes, scope);
1506
+ const expr2 = rawMatch[1].trim();
1507
+ if (!markers) {
1508
+ result += `${acc} += String(${expr2} ?? '');
1509
+ `;
1510
+ } else {
1511
+ const fn = scope ? `(${scope}) => (${expr2})` : `() => (${expr2})`;
1512
+ result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ""});
1513
+ `;
1514
+ }
1515
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1516
+ continue;
1517
+ }
783
1518
  const attrMatch = before.match(/([\w-]+)=\s*$/);
784
1519
  if (attrMatch) {
785
1520
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -891,7 +1626,7 @@ function rejectNestedSlot(src, outer) {
891
1626
  if (end < 0) return;
892
1627
  const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
893
1628
  if (hit && nm[1] !== "/") {
894
- throw new Error(`slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`);
1629
+ throw new RoseError("E-TEMPLATE", `slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`, { hint: "move the inner <slot> out of the outer one - a slot is a direct child of the component tag, never nested in another slot" });
895
1630
  }
896
1631
  i = end;
897
1632
  }
@@ -945,7 +1680,7 @@ function splitSlots(src) {
945
1680
  if (!selfClosing && !isVoid) elemDepth++;
946
1681
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
947
1682
  if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
948
- throw new Error(`slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`);
1683
+ throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
949
1684
  }
950
1685
  if (slotName) {
951
1686
  const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
@@ -953,7 +1688,7 @@ function splitSlots(src) {
953
1688
  named.set(slotName, (named.get(slotName) ?? "") + stripped);
954
1689
  } else {
955
1690
  const closeIdx = findClose(src, end, nm[2]);
956
- if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
1691
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
957
1692
  const tail = `</${nm[2]}>`;
958
1693
  const inner = src.slice(end, closeIdx);
959
1694
  rejectNestedSlot(inner, slotName);
@@ -1029,7 +1764,8 @@ function compileSlot(acc) {
1029
1764
  return `${acc} += String(children);
1030
1765
  `;
1031
1766
  }
1032
- var RUNTIME_IMPORTS = `import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark } from './runtime.js';`;
1767
+ 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';`;
1768
+ var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1033
1769
  function propsCode(props) {
1034
1770
  if (props.length === 0) return "";
1035
1771
  return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
@@ -1041,20 +1777,13 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1041
1777
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1042
1778
  return { o, fn };
1043
1779
  };
1044
- const __slotBlock = (closes, sl, name, pairs) => {
1045
- const hit = __slot(sl, name, pairs);
1046
- const idx = closes.length;
1047
- closes.push(() => {
1048
- if (!hit) return null;
1049
- const c = [];
1050
- return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
1051
- });
1052
- return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1053
- };`;
1054
- function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "") {
1780
+ const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
1781
+ function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1055
1782
  const headCode = headFn ? `
1056
1783
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1057
1784
  __html += headMark(closes, __head);` : "";
1785
+ const actionState = hasActions ? `
1786
+ const $setState = (key, value) => setState(key, value);` : "";
1058
1787
  return `
1059
1788
  ${RUNTIME_IMPORTS}
1060
1789
 
@@ -1062,6 +1791,7 @@ ${imports}
1062
1791
 
1063
1792
  ${exports}
1064
1793
  ${guard}
1794
+ ${actionState}
1065
1795
 
1066
1796
  ${namedSlots ? SLOT_HELPER : ""}
1067
1797
 
@@ -1069,20 +1799,20 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1069
1799
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1070
1800
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1071
1801
  ${propsCode(props)}
1802
+ ${script}
1072
1803
  ${stateDeclsCode}
1073
- // The incremental patches of the action that produced THIS response,
1074
- // applied to the state the declarations above just established (a no-op on
1075
- // every path that is not a server action's re-render - see the runtime).
1804
+ ${dataDeclsCode}
1805
+
1076
1806
  ${isComponent ? "" : "applyStateDeltas();"}
1077
- ${script}
1078
1807
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1079
1808
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1080
1809
  return __html;
1081
1810
  }
1082
1811
  `;
1083
1812
  }
1084
- function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
1813
+ function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1085
1814
  const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1815
+ const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
1086
1816
  const headCode = headFn ? `
1087
1817
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1088
1818
  __html += headMark(closes, __head);` : "";
@@ -1092,15 +1822,18 @@ ${RUNTIME_IMPORTS}
1092
1822
  ${imports}
1093
1823
 
1094
1824
  ${exports}
1095
-
1825
+ ${clientSetState ? `
1826
+ ${clientSetState}
1827
+ ` : ""}
1096
1828
  ${namedSlots ? SLOT_HELPER : ""}
1097
1829
 
1098
1830
  export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1099
1831
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1100
1832
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1101
1833
  ${propsCode(props)}
1102
- ${stateDeclsCode}
1103
1834
  ${script}
1835
+ ${stateDeclsCode}
1836
+ ${dataDeclsCode}
1104
1837
  ${handlerRegistry}
1105
1838
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1106
1839
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
@@ -1114,6 +1847,7 @@ var routeShipsNoJs = (infos, compiled, i) => {
1114
1847
  if (compiled[i].needsClient) return false;
1115
1848
  return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1116
1849
  };
1850
+ var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
1117
1851
  function buildReport(infos, compiled) {
1118
1852
  return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
1119
1853
  if (routeShipsNoJs(infos, compiled, i)) {
@@ -1124,6 +1858,48 @@ function buildReport(infos, compiled) {
1124
1858
  return `${info.routePath} client JS ${why}${forced}`;
1125
1859
  });
1126
1860
  }
1861
+ var MOUNT_ENTRY = `
1862
+ import { start, postForm } from '/client.js';
1863
+
1864
+ for (const el of document.querySelectorAll('[data-rosetack]')) {
1865
+ const route = el.getAttribute('data-rosetack');
1866
+ const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
1867
+ const parsed = new DOMParser().parseFromString(doc, 'text/html');
1868
+ // A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
1869
+ const app = parsed.getElementById('app');
1870
+ if (app) {
1871
+ el.innerHTML = app.innerHTML;
1872
+ } else {
1873
+ for (const node of Array.from(parsed.body.children)) {
1874
+ if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
1875
+ }
1876
+ }
1877
+ // start() resumes from #__rosetack_state (zero hydration), so the state
1878
+
1879
+ const state = parsed.getElementById('__rosetack_state');
1880
+ if (state) el.appendChild(state);
1881
+
1882
+ const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
1883
+ await start(el, route, rendered === route);
1884
+ if (state) state.remove();
1885
+
1886
+ el.addEventListener('click', (e) => {
1887
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
1888
+ if (!a || !el.contains(a)) return;
1889
+ e.preventDefault();
1890
+ el.setAttribute('data-rosetack', a.getAttribute('href'));
1891
+ start(el, a.getAttribute('href'), false);
1892
+ });
1893
+ // Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
1894
+ el.addEventListener('submit', (e) => {
1895
+ const f = e.target;
1896
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
1897
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
1898
+ e.preventDefault();
1899
+ postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
1900
+ });
1901
+ }
1902
+ `;
1127
1903
  async function buildProject(root, outDir) {
1128
1904
  await fs.promises.mkdir(outDir, { recursive: true });
1129
1905
  const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
@@ -1132,7 +1908,11 @@ async function buildProject(root, outDir) {
1132
1908
  const compFiles = await scanComponentFiles(root);
1133
1909
  const files = [...pageFiles, ...compFiles];
1134
1910
  if (pageFiles.length === 0) {
1135
- throw new Error(`no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`);
1911
+ throw new RoseError(
1912
+ "E-ROUTE",
1913
+ `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1914
+ { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1915
+ );
1136
1916
  }
1137
1917
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1138
1918
  const config = await loadConfig(root);
@@ -1221,9 +2001,7 @@ async function buildProject(root, outDir) {
1221
2001
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1222
2002
  if (runtimePlugins.length > 0) {
1223
2003
  const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
1224
- await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
1225
- // Bundled into dist/server.js: these hooks run per request on every server
1226
- // (Node, dev/preview, edge). Transform hooks already ran at build time.
2004
+ await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
1227
2005
  import config from ${JSON.stringify(configRel)};
1228
2006
 
1229
2007
  const list = Array.isArray(config) ? config : [];
@@ -1236,7 +2014,7 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1236
2014
  `);
1237
2015
  }
1238
2016
  const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
1239
- if (!runtimeEntry) throw new Error("rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler");
2017
+ if (!runtimeEntry) throw new RoseError("E-INTERNAL", "rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler", { hint: "the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout" });
1240
2018
  await esbuild.build({
1241
2019
  entryPoints: [runtimeEntry],
1242
2020
  bundle: true,
@@ -1252,8 +2030,34 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1252
2030
  await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1253
2031
  }
1254
2032
  }
1255
- const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1256
- const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi);
2033
+ 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) => {
2034
+ const rank = (pattern) => {
2035
+ const segs = pattern.split("/");
2036
+ return [
2037
+ segs.filter((s) => s.startsWith("**")).length,
2038
+ segs.filter((s) => s.startsWith("*")).length,
2039
+ segs.filter((s) => s.startsWith(":")).length
2040
+ ];
2041
+ };
2042
+ const ra = rank(a.info.pattern);
2043
+ const rb = rank(b.info.pattern);
2044
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2045
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2046
+ });
2047
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
2048
+ const rank = (pattern) => {
2049
+ const segs = pattern.split("/");
2050
+ return [
2051
+ segs.filter((s) => s.startsWith("**")).length,
2052
+ segs.filter((s) => s.startsWith("*")).length,
2053
+ segs.filter((s) => s.startsWith(":")).length
2054
+ ];
2055
+ };
2056
+ const ra = rank(a.info.pattern);
2057
+ const rb = rank(b.info.pattern);
2058
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2059
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2060
+ });
1257
2061
  const compose = (idx) => {
1258
2062
  let expr = `render_${idx}`;
1259
2063
  for (const i of layoutsOf(infos, idx)) {
@@ -1284,33 +2088,48 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1284
2088
  const named = [actionImports, guardImport].filter(Boolean).join(", ");
1285
2089
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1286
2090
  }).join("\n");
1287
- const nfIdx = infos.findIndex((info) => info.isNotFound);
1288
- const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
2091
+ const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
2092
+ const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
2093
+ const dir = path.posix.dirname(rel);
2094
+ const prefix = dir === "." ? "/" : "/" + dir;
2095
+ const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
2096
+ return { prefix, render: split ? loaderOf(i) : compose(i), flags };
2097
+ }).sort((a, b) => b.prefix.length - a.prefix.length);
2098
+ const notFoundTable = `[
2099
+ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
2100
+ ]`;
1289
2101
  const errIdx = infos.findIndex((info) => info.isError);
1290
2102
  const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
1291
2103
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
1292
2104
  const serverRoutes = pages.map(({ info, i }) => {
1293
2105
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
1294
2106
  if (compiled[i].csr === false && compiled[i].needsClient) {
1295
- throw new Error(
1296
- `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`
2107
+ throw new RoseError(
2108
+ "E-EXPORT",
2109
+ `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`,
2110
+ { file: info.filePath, hint: "remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above" }
1297
2111
  );
1298
2112
  }
1299
2113
  if (compiled[i].csr === false) {
1300
2114
  const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1301
2115
  if (needy !== void 0) {
1302
- throw new Error(
1303
- `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`
2116
+ throw new RoseError(
2117
+ "E-EXPORT",
2118
+ `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`,
2119
+ { file: info.filePath, hint: "a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only" }
1304
2120
  );
1305
2121
  }
1306
2122
  }
1307
2123
  const csrFlag = routeNoJs(i) ? ", csr: false" : "";
2124
+ const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
2125
+ const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
2126
+ const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
1308
2127
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1309
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag} }`;
2128
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
1310
2129
  }).join(",\n ");
1311
2130
  const serverEntry = `
1312
2131
  ${serverImports}
1313
- import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
2132
+ import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1314
2133
  ${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
1315
2134
  // module to import - the runners below stay no-ops and the servers call them
1316
2135
  // unconditionally (one code path, no flags to keep in sync).
@@ -1318,12 +2137,7 @@ const __pluginHooks = [];
1318
2137
  const __hasRequestHooks = false;
1319
2138
  const __hasResponseHooks = false;`}
1320
2139
 
1321
- // The runtime plugin hooks. onRequest runs before routing and
1322
- // middleware and may short-circuit the request with its own Response; onResponse
1323
- // runs once the response exists and may replace it. Both are no-ops when the
1324
- // project declares no runtime hooks. A throwing hook is logged and skipped -
1325
- // the request continues - so a broken logging plugin can never take a site
1326
- // down (a build-time transform, by contrast, fails loudly).
2140
+
1327
2141
  export async function runRequestHooks(ctx) {
1328
2142
  for (const p of __pluginHooks) {
1329
2143
  if (!p.onRequest) continue;
@@ -1351,22 +2165,20 @@ export async function runResponseHooks(ctx, res) {
1351
2165
  return out;
1352
2166
  }
1353
2167
 
1354
- // The servers read these to skip building the hook context entirely when no
1355
- // hook exists - the hot path pays nothing for the feature.
2168
+
2169
+
1356
2170
  export const hasRequestHooks = __hasRequestHooks;
1357
2171
  export const hasResponseHooks = __hasResponseHooks;
1358
2172
 
1359
- // i18n: the dictionaries baked at build time from
1360
- // src/locales/*.json. A route segment named [lang] is the locale: the value
1361
- // must name one of these dictionaries, and $t resolves keys against it.
2173
+ // P0-1: the query of the request being rendered, for $query().
2174
+ export function setQuery(query) {
2175
+ setRequestQuery(query || {});
2176
+ }
2177
+
2178
+
1362
2179
  setLocales(${localesJson}, '${defaultLocale}');
1363
2180
 
1364
- // The store transport. Under "rosetack serve" every worker is its
1365
- // own process with its own dist/server.js module, so a $store write must
1366
- // travel: this worker -> primary -> every other worker. process.send exists
1367
- // only inside cluster workers, so a single-process runner (dev, preview,
1368
- // the edge adapter) keeps the transport null and $store stays plain
1369
- // per-process state - the documented boundary, not a bug.
2181
+
1370
2182
  if (typeof process !== 'undefined' && typeof process.send === 'function') {
1371
2183
  setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1372
2184
  process.on('message', (msg) => {
@@ -1374,74 +2186,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1374
2186
  });
1375
2187
  }
1376
2188
 
2189
+ // (the cross-machine seam): the cluster relay above covers ONE machine.
2190
+ export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
2191
+ setStoreTransport(send);
2192
+ }
2193
+ export function __deliverStorePatch(name: string, value: unknown): void {
2194
+ applyStorePatch(name, value);
2195
+ }
2196
+
1377
2197
  export { localeList };
1378
2198
  export const defaultLocale = '${defaultLocale}';
1379
2199
 
1380
- // Route params maps, re-exported for the build's prerender step: routePath
1381
- // -> the component's exported params (a static map or a function). Reading
1382
- // them through the server bundle keeps the deploy dir free of component
1383
- // modules - both bundles are self-contained, nothing else may ship. Only
1384
- // components that actually export params appear here (a missing export
1385
- // means the dynamic route renders on demand).
2200
+ // Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
1386
2201
  ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1387
2202
 
1388
2203
  export const routeParams = {
1389
2204
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1390
2205
  };
1391
2206
 
1392
- // Routes whose component reads the request context (getContext()), mutates a
1393
- // shared store ($store), or opted into nonce-based CSP: the bag is
1394
- // per-request, the store is per-process, and a nonce is per-response, so
1395
- // these are dynamic - the build never bakes them and the servers never
1396
- // answer them from a prerendered file. Public routes keep the static fast
1397
- // path (file cache, ETag/304, streaming) untouched.
2207
+ // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
1398
2208
  export const dynamicRoutes = [
1399
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
2209
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1400
2210
  ];
1401
2211
 
1402
- // Which api routes opt into build-time baking (export const prerender = true):
1403
- // routePath -> boolean. The build calls the GET handler once and writes the
1404
- // body to dist/, so the Go single binary serves read-only APIs without Node.
2212
+ // Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
1405
2213
  ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1406
2214
 
1407
2215
  export const apiPrerender = {
1408
2216
  ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1409
2217
  };
1410
2218
 
1411
- // Stale-while-revalidate windows (export const revalidate = N): the build
1412
- // bakes these routes like any other, and the preview server serves the
1413
- // baked file for up to N seconds - after which the next request is answered
1414
- // STALE (instant, from disk) while a background pass re-renders and swaps
1415
- // the file (ISR). Routes that read the request context are
1416
- // excluded: they render per request and have no baked file to revalidate.
1417
- // The dev server ignores the window (it rebuilds on change), the edge
1418
- // adapter renders live (always fresh), and the Go binary serves the baked
1419
- // file forever - the same static-half boundary as page POSTs.
2219
+
1420
2220
  export const revalidate = [
1421
2221
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1422
2222
  ];
1423
2223
 
1424
- // pages/_middleware.rose: a Web-standard request handler that runs before
1425
- // every render on the server (pages, POSTs, api calls alike). Returning a
1426
- // Response short-circuits the whole request - a redirect, an auth wall, a
1427
- // rewrite; returning nothing continues, and getContext() hands the
1428
- // per-request bag to $data, server actions and api handlers. Absent -> null,
1429
- // and the servers keep their static fast paths.
2224
+ // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
1430
2225
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1431
2226
 
1432
- // Routes whose DOCUMENTS ship without the client bundle (
1433
- // decided by the compiler since #29): HTML + CSS only - no runtime, no
1434
- // state script, zero JavaScript for whoever lands on them. The compiler
1435
- // picks these automatically: a route whose whole chain needs nothing from
1436
- // the client (no event wiring, no lifecycle, no action, no form) is a
1437
- // content route. An exported "csr = true" forces the bundle back in; an
1438
- // exported "csr = false" is the same decision, asserted. The route's render
1439
- // function still rides in the client bundle, so a client-side navigation
1440
- // from an interactive page paints it normally and a static deploy's SPA
1441
- // fallback can render it too; only the document is JS-free.
1442
- // isNoJs() lets the servers keep these routes on the buffered path: a
1443
- // streamed no-JS document would carry the shell's default <title> (the
1444
- // route head is applied client-side at boot, and there is no client).
2227
+ // Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
1445
2228
  export const noJsRoutes = [
1446
2229
  ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1447
2230
  ];
@@ -1450,11 +2233,12 @@ export function isNoJs(pathname) {
1450
2233
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1451
2234
  }
1452
2235
 
1453
- // Per-route response headers: a route exporting a headers
1454
- // map carries them into every response the servers write for it, merged
1455
- // OVER the framework defaults (the strict CSP) - so an app can tighten or
1456
- // relax the policy per route. Absent -> null, and the servers keep sending
1457
- // the defaults alone.
2236
+ // P0-2 (bug report): routes that exported "buffer = true".
2237
+ export function isBuffered(pathname) {
2238
+ return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
2239
+ }
2240
+
2241
+
1458
2242
  export const routeHeaders = [
1459
2243
  ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1460
2244
  ];
@@ -1464,14 +2248,7 @@ export function headersFor(pathname) {
1464
2248
  return hit ? hit.headers : null;
1465
2249
  }
1466
2250
 
1467
- // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
1468
- // ). The servers ask this BEFORE writing a document: when it is true they
1469
- // mint one random nonce per response, put it in the CSP header ('nonce-...'
1470
- // plus 'strict-dynamic', so the document's own code may load more code) and
1471
- // stamp the same value on the script tag. The default policy stays a hash -
1472
- // cspNonceRoutes is empty for an app that never asks, so the fast path is
1473
- // unchanged. The Go binary never sees this: these routes are dynamic, so it
1474
- // has no baked file for them to serve.
2251
+
1475
2252
  export const cspNonceRoutes = [
1476
2253
  ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1477
2254
  ];
@@ -1480,9 +2257,7 @@ export function cspNonce(pathname) {
1480
2257
  return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1481
2258
  }
1482
2259
 
1483
- // A Web-standard Request from whatever the host provides: the edge adapter
1484
- // passes one already; the Node server passes its IncomingMessage (plus the
1485
- // already-parsed FormData for POSTs, so middleware can read form fields).
2260
+ // A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
1486
2261
  function toWebRequest(raw, form) {
1487
2262
  if (raw instanceof Request) return raw;
1488
2263
  const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
@@ -1490,13 +2265,7 @@ function toWebRequest(raw, form) {
1490
2265
  return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1491
2266
  }
1492
2267
 
1493
- // Runs the middleware (if the project has one) for this request and returns
1494
- // its short-circuit Response, or null to continue. The servers call this
1495
- // EXACTLY ONCE per request, before anything else: it resets the per-request
1496
- // context bag and the middleware fills it via getContext(), which $data,
1497
- // server actions and api handlers then read while rendering. rawReq: the
1498
- // host's request (Node IncomingMessage or a Web-standard Request); form:
1499
- // the already-parsed FormData of a POST.
2268
+
1500
2269
  export async function runMiddleware(rawReq, form) {
1501
2270
  resetRequestContext();
1502
2271
  if (!middleware || !rawReq) return null;
@@ -1508,10 +2277,7 @@ const routes = [
1508
2277
  ${serverRoutes}
1509
2278
  ];
1510
2279
 
1511
- // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
1512
- // render HTML and never reach the client bundle. The middleware ran before
1513
- // this (the servers call runMiddleware() first), so handlers can read
1514
- // getContext() for auth without re-running anything.
2280
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
1515
2281
  const apiRoutes = [
1516
2282
  ${apiRoutes.map(({ info, i }) => {
1517
2283
  const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -1519,19 +2285,40 @@ const apiRoutes = [
1519
2285
  }).join(",\n ")}
1520
2286
  ];
1521
2287
 
1522
- // pages/404.rose (with its layouts) or null -> built-in plain 404
1523
- const notFound = ${notFoundRender};
2288
+ // Not-found pages, deepest segment first: the root 404.rose ('/') and any
2289
+ // pages/<seg>/_notfound.rose, each already composed with its layout chain.
2290
+ // notFoundFor picks the nearest one up the path - an /admin miss answers
2291
+ // the admin 404, a public miss the site's - and notFoundPage is the whole
2292
+ // answer (real 404 status, or the built-in plain 404 when the app has none).
2293
+ const notFoundRoutes = ${notFoundTable};
2294
+ const notFoundFor = (pathname) => {
2295
+ for (const [prefix, render] of notFoundRoutes) {
2296
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2297
+ }
2298
+ return null;
2299
+ };
2300
+
2301
+ const notFoundFlags = (pathname) => {
2302
+ for (const [prefix, render, flags] of notFoundRoutes) {
2303
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
2304
+ }
2305
+ return null;
2306
+ };
2307
+ const notFoundPage = async (pathname) => {
2308
+ const nf = notFoundFor(pathname);
2309
+ if (nf) {
2310
+ const page = await renderFallback(pathname, nf);
2311
+ // __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
2312
+ return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
2313
+ }
2314
+ return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
2315
+ };
2316
+
1524
2317
 
1525
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1526
2318
  // whose render throws degrades to this instead of failing the response.
1527
2319
  const errorPage = ${errorRender};
1528
2320
 
1529
- // The <html> attributes of the document for a pathname - the locale
1530
- // of its [lang] segment (the default when there is none, or when the segment
1531
- // names no dictionary: that request 404s in the default language) and the
1532
- // reading direction that locale implies. The buffered render returns the same
1533
- // pair; the streaming path needs it BEFORE the shell flushes, which is why
1534
- // the servers ask for it by pathname.
2321
+
1535
2322
  export function docAttrs(pathname) {
1536
2323
  for (const route of routes) {
1537
2324
  if (!matchRoute(route.pattern, pathname)) continue;
@@ -1541,7 +2328,7 @@ export function docAttrs(pathname) {
1541
2328
  const lang = pathname.split('/')[langIdx];
1542
2329
  if (isLocale(lang)) return { lang, dir: localeDir(lang) };
1543
2330
  }
1544
- break; // matched, but not a localized route (or a bogus locale): the default
2331
+ break;
1545
2332
  }
1546
2333
  return { lang: defaultLocale, dir: localeDir(defaultLocale) };
1547
2334
  }
@@ -1554,8 +2341,22 @@ async function renderFallback(pathname, render) {
1554
2341
  }
1555
2342
 
1556
2343
  export function matchRoute(pattern, pathname) {
2344
+ // Q0 (bug report): one canonical URL per route.
2345
+ pathname = pathname.replace(/\\/+$/, '') || '/';
1557
2346
  const patternParts = pattern.split('/');
1558
2347
  const pathParts = pathname.split('/');
2348
+
2349
+ const last = patternParts[patternParts.length - 1];
2350
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2351
+ const fixed = patternParts.slice(0, -1);
2352
+ if (pathParts.length < fixed.length) return false;
2353
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2354
+ for (let i = 0; i < fixed.length; i++) {
2355
+ if (fixed[i].startsWith(':')) continue;
2356
+ if (fixed[i] !== pathParts[i]) return false;
2357
+ }
2358
+ return true;
2359
+ }
1559
2360
  if (patternParts.length !== pathParts.length) return false;
1560
2361
  for (let i = 0; i < patternParts.length; i++) {
1561
2362
  if (patternParts[i].startsWith(':')) continue;
@@ -1564,13 +2365,7 @@ export function matchRoute(pattern, pathname) {
1564
2365
  return true;
1565
2366
  }
1566
2367
 
1567
- // Head blocks (one per component in the route chain) are pulled out of the
1568
- // page html: the shell injects them into <head>, and the client re-applies
1569
- // them on navigation. Document order is page-first, so the shell's keyed
1570
- // merge lets a page override its layouts. The EMPTY marker pair stays in the
1571
- // body so the client's wire() still finds the block: at boot it adopts the
1572
- // shell-injected elements in place (marked with the same keys, so no
1573
- // duplicates) and keeps the head reactive.
2368
+ // Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
1574
2369
  function extractHead(rendered) {
1575
2370
  const head = [];
1576
2371
  const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
@@ -1580,18 +2375,7 @@ function extractHead(rendered) {
1580
2375
  return { html, head };
1581
2376
  }
1582
2377
 
1583
- // form: the submitted FormData of a progressive-enhancement POST. The
1584
- // selected server action runs first and returns a state patch (e.g.
1585
- // { guests: [...] }); seeding those keys BEFORE the render makes state()
1586
- // adopt them, so the response is the page as it looks AFTER the action -
1587
- // with or without JS. A __action field picks the action by name (default
1588
- // 'action', the conventional <form method="POST"> target); a click handler
1589
- // bound to an action ($action('like')) sends the same field.
1590
- // A route whose render throws degrades to pages/500.rose (status 500) - or
1591
- // the built-in plain 500 - instead of failing the whole response.
1592
- // The middleware does NOT run here: the servers run it once per request via
1593
- // runMiddleware() (which also seeds the request context), so a page render
1594
- // never re-runs it.
2378
+ // Form: the submitted FormData of a progressive-enhancement POST.
1595
2379
  export async function renderPage(pathname, form) {
1596
2380
  clearRequestState();
1597
2381
  for (const route of routes) {
@@ -1599,31 +2383,21 @@ export async function renderPage(pathname, form) {
1599
2383
  const patternParts = route.pattern.split('/');
1600
2384
  const pathParts = pathname.split('/');
1601
2385
  for (let i = 0; i < patternParts.length; i++) {
1602
- if (patternParts[i].startsWith(':')) {
1603
- setState(patternParts[i].slice(1), pathParts[i]);
1604
- }
2386
+ const seg = patternParts[i];
2387
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2388
+
2389
+
2390
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
1605
2391
  }
1606
- // i18n: a [lang] segment naming no dictionary is a
1607
- // 404 - the URL is the contract, and rendering the page with fallback
1608
- // strings would serve duplicate content under a bogus language
2392
+ // I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
1609
2393
  const langIdx = patternParts.indexOf(':lang');
1610
2394
  if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
1611
- if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
1612
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2395
+ return await notFoundPage(pathname);
1613
2396
  }
1614
- // The document's <html lang>/<dir> follow this route's locale
1615
- // (the default's when the route is not localized)
2397
+
2398
+
1616
2399
  const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
1617
- // The action dispatch. The page's guard (exported
1618
- // beforeAction) runs FIRST and vetoes with an ActionError - the
1619
- // action-level permission check. Then the selected action runs and its
1620
- // return value seeds this render's state, per key, so an incremental
1621
- // patch ($append and friends) grows a large list by one row instead of
1622
- // re-sending the whole thing. An ActionError from either half is a
1623
- // BUSINESS failure: it is seeded as the 'actionError' state, the
1624
- // response carries its status, and the page renders with the failure
1625
- // visible (a {#boundary} around the action's widget contains it).
1626
- // Anything else is a bug and keeps going to the 500 page.
2400
+ // The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
1627
2401
  let actionStatus = 0;
1628
2402
  if (form && route.actions) {
1629
2403
  const actionName = form.get('__action') || 'action';
@@ -1635,9 +2409,7 @@ export async function renderPage(pathname, form) {
1635
2409
  if (patch && typeof patch === 'object') {
1636
2410
  for (const key of Object.keys(patch)) {
1637
2411
  const v = patch[key];
1638
- // An incremental patch is RECORDED, not applied: the render's
1639
- // own state declarations apply it, so the delta is relative to
1640
- // the value the page was going to render anyway.
2412
+ // An incremental patch is RECORDED, not applied: the render's own state declarations apply.
1641
2413
  if (v instanceof StateDelta) setStateDelta(key, v);
1642
2414
  else setState(key, v);
1643
2415
  }
@@ -1646,6 +2418,11 @@ export async function renderPage(pathname, form) {
1646
2418
  if (err instanceof ActionError) {
1647
2419
  setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
1648
2420
  actionStatus = err.code;
2421
+ } else if (err && err.__rosetack === 'redirect') {
2422
+
2423
+ return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
2424
+ } else if (err && err.__rosetack === 'notFound') {
2425
+ return await notFoundPage(pathname);
1649
2426
  } else {
1650
2427
  throw err;
1651
2428
  }
@@ -1656,32 +2433,27 @@ export async function renderPage(pathname, form) {
1656
2433
  try {
1657
2434
  rendered = extractHead(await route.render([], ''));
1658
2435
  } catch (err) {
2436
+ // The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
2437
+ const signal = err && err.__rosetack;
2438
+ if (signal === 'redirect') {
2439
+ return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
2440
+ }
2441
+ if (signal === 'notFound') {
2442
+ return await notFoundPage(pathname);
2443
+ }
1659
2444
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1660
2445
  if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
1661
2446
  return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
1662
2447
  }
1663
2448
  // __route tells the bootstrap which route this document was rendered for.
1664
- // A static-file server may serve another route's document (SPA fallback);
1665
- // the bootstrap then client-renders instead of adopting mismatched DOM.
1666
2449
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1667
- // csr ( auto since #29): false when the compiler found
1668
- // nothing in the route's chain that needs the client (or the route
1669
- // asserted csr = false) - the document ships no runtime, no state
1670
- // script, zero JavaScript. Every other route keeps the bundle. The
1671
- // caller passes this straight to the shell as js.
1672
- // Status is the failed action's code when one failed - the page
1673
- // rendered fine, so the body is the page with the failure visible, and
1674
- // the status says what happened (a 403 from the guard, a 422 from a
1675
- // validation action). 200 otherwise.
1676
- // Lang/dir are the document's <html> attributes - the locale
1677
- // this route rendered in, and its reading direction.
1678
- return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
2450
+ // 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) .
2451
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
1679
2452
  }
1680
2453
  }
1681
- if (notFound) {
1682
- return { ...(await renderFallback(pathname, notFound)), status: 404 };
1683
- }
1684
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2454
+
2455
+
2456
+ return await notFoundPage(pathname);
1685
2457
  }
1686
2458
 
1687
2459
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -1689,21 +2461,20 @@ export async function renderPage(pathname, form) {
1689
2461
  export function canStream(pathname) {
1690
2462
  return routes.some((route) => {
1691
2463
  if (!matchRoute(route.pattern, pathname)) return false;
1692
- // i18n: an unknown locale must answer 404, and a
1693
- // streamed response cannot change its status - so it takes the buffered
1694
- // path (renderPage returns the real 404), never the streaming one
2464
+ // I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
1695
2465
  const langIdx = route.pattern.split('/').indexOf(':lang');
1696
2466
  return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
1697
2467
  });
1698
2468
  }
1699
2469
 
1700
- // === API routes ===
1701
- // The /api namespace answers JSON, never HTML: an API client that hits an
1702
- // unknown path must not receive the SPA shell. Handlers receive a
1703
- // Web-standard Request and return a plain object (serialized as JSON, 200),
1704
- // a Response (passed through), or nothing (204). A method the route does
1705
- // not export answers 405 with an Allow header. Same code path on the Node
1706
- // server and the edge adapter - Response is a global in both.
2470
+
2471
+ export function shellOff(pathname) {
2472
+ return routes.some(
2473
+ (route) => route.shell === false && matchRoute(route.pattern, pathname),
2474
+ );
2475
+ }
2476
+
2477
+ // === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
1707
2478
  export function isApi(pathname) {
1708
2479
  return pathname === '/api' || pathname.startsWith('/api/');
1709
2480
  }
@@ -1727,7 +2498,25 @@ export async function handleApi(method, pathname, request) {
1727
2498
  headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
1728
2499
  });
1729
2500
  }
1730
- return toResponse(await fn(request));
2501
+ try {
2502
+ return toResponse(await fn(request));
2503
+ } catch (err) {
2504
+
2505
+ const signal = err && err.__rosetack;
2506
+ if (signal === 'redirect') {
2507
+ return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
2508
+ status: err.status ?? 307,
2509
+ headers: { 'content-type': 'application/json', location: err.path },
2510
+ });
2511
+ }
2512
+ if (signal === 'notFound') {
2513
+ return new Response(JSON.stringify({ error: 'not found' }), {
2514
+ status: 404,
2515
+ headers: { 'content-type': 'application/json' },
2516
+ });
2517
+ }
2518
+ throw err;
2519
+ }
1731
2520
  }
1732
2521
  }
1733
2522
  return new Response(JSON.stringify({ error: 'not found' }), {
@@ -1736,18 +2525,7 @@ export async function handleApi(method, pathname, request) {
1736
2525
  });
1737
2526
  }
1738
2527
 
1739
- // === Streaming SSR ===
1740
- // The static shell (doctype, <head>, body + container open) flushes BEFORE
1741
- // the - possibly slow - render completes: the first byte leaves in
1742
- // microseconds instead of after every $data resolves. The route HTML, the
1743
- // state script, and the inlined bundle follow as later chunks of one chunked
1744
- // response - still exactly one request.
1745
- // The route's <head> tags are NOT in the streamed document: the client
1746
- // applies them at boot from the body's head markers, so JS users see the
1747
- // correct head immediately; no-JS consumers of streamed responses get the
1748
- // static shell head (prerendered files stay complete documents).
1749
- // Returns 200 (matched; a render throw degrades to the error-page body) or
1750
- // 404 (unmatched - nothing written, so the caller can still buffer).
2528
+ // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
1751
2529
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1752
2530
  clearRequestState();
1753
2531
  for (const route of routes) {
@@ -1755,9 +2533,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1755
2533
  const patternParts = route.pattern.split('/');
1756
2534
  const pathParts = pathname.split('/');
1757
2535
  for (let i = 0; i < patternParts.length; i++) {
1758
- if (patternParts[i].startsWith(':')) {
1759
- setState(patternParts[i].slice(1), pathParts[i]);
1760
- }
2536
+ const seg = patternParts[i];
2537
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2538
+
2539
+
2540
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
1761
2541
  }
1762
2542
  // i18n: an unknown locale must 404 BEFORE the shell flushes - a
1763
2543
  // streamed response cannot change its status afterwards
@@ -1768,23 +2548,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1768
2548
  try {
1769
2549
  html = extractHead(await route.render([], '')).html;
1770
2550
  } catch (err) {
1771
- // the shell is already on the wire: degrade to the error page BODY
1772
- // (the status stays 200 - a real 500 needs the buffered path, which
1773
- // the server picks for routes known-broken at build time)
2551
+
1774
2552
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1775
2553
  html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
1776
2554
  }
1777
2555
  write(html);
1778
- // csr: false ( auto since #29): a no-JS route's document
1779
- // ends here - no state script, no inlined bundle. (The servers keep
1780
- // these routes off the streaming path so their <head> is complete;
1781
- // this is the correctness floor if one streams anyway.)
2556
+ // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
1782
2557
  if (route.csr === false) {
1783
2558
  write('</div>\\n</body>\\n</html>');
1784
2559
  return 200;
1785
2560
  }
1786
2561
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1787
- write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
2562
+ // P1-6 (bug report): the JSON data block is embedded in the document.
2563
+ const stateSafe = state.replace(/</g, '\\\\u003c');
2564
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
1788
2565
  return 200;
1789
2566
  }
1790
2567
  }
@@ -1804,55 +2581,54 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1804
2581
  const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
1805
2582
  const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
1806
2583
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
2584
+ const vitalsOn = compiled.some((c) => c.vitals === true);
2585
+ const vitalsBlock = vitalsOn ? `
2586
+ // the app asked for web-vitals - measure once, at boot, and let the
2587
+ // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2588
+ reportVitals();
2589
+ ` : "";
1807
2590
  const hasLang = infos.some((i) => i.pattern.includes(":lang"));
1808
2591
  const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
1809
2592
  // client-side navigation cannot leave stale (screen readers and CSS
1810
2593
  // logical properties both read it). A route with no [lang] segment
1811
2594
  // returns to the default locale, and a bogus segment falls back to it
1812
2595
  // too, exactly like the server's docAttrs.
2596
+ // Only when this container IS the document's app root. A mount
2597
+ // (dist/mount.js) renders into a foreign page, whose language and
2598
+ // direction belong to the host, not to the mounted route.
1813
2599
  const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
1814
2600
  const known = !seg || isLocale(seg);
1815
- const docLang = known && seg ? seg : __defLocale;
1816
- document.documentElement.lang = docLang;
1817
- const docDir = localeDir(docLang);
1818
- if (docDir) document.documentElement.setAttribute('dir', docDir);
1819
- else document.documentElement.removeAttribute('dir');
2601
+ if (container === document.getElementById('app')) {
2602
+ const docLang = known && seg ? seg : __defLocale;
2603
+ document.documentElement.lang = docLang;
2604
+ const docDir = localeDir(docLang);
2605
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
2606
+ else document.documentElement.removeAttribute('dir');
2607
+ }
1820
2608
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
1821
2609
  const clientEntry = `
1822
2610
  ${clientImports}
1823
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
1824
-
1825
- // i18n: the dictionaries baked at build time - the client
1826
- // renders any PRELOADED locale from the bundle, so switching language costs
1827
- // zero requests (the same bet as the inlined route table). a locale
1828
- // the app left out of the preload (i18n.preload in rosetack.config.js) is a
1829
- // pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
1830
- // on first use - one request per language per session, then it renders from
1831
- // memory like any other. The default build preloads everything and ships no
1832
- // packs at all.
2611
+ 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';
2612
+
2613
+ // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
1833
2614
  setLocales(${clientLocalesJson}, '${defaultLocale}');
1834
2615
  setLocalePacks(${JSON.stringify(packed)});
1835
2616
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
1836
2617
  // follow a route that carries no [lang] segment (a non-i18n page)
1837
2618
  const __defLocale = '${defaultLocale}';` : ""}
1838
- // The two pack doors, re-exported for an app that wants to warm a language
1839
- // before its visitor asks for it (ensureLocale) or to feed a dictionary it
1840
- // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
1841
- // is what applyParams calls - so the re-export costs the statement alone.
2619
+ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2620
+ // reportVitals alive through minification and tree-shaking; the call is one
2621
+ // statement at boot, before the first render.
2622
+ import { reportVitals } from './runtime.js';` : ""}
2623
+ // 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.
1842
2624
  export { ensureLocale, loadLocale } from './runtime.js';
2625
+ ${vitalsBlock}
1843
2626
 
1844
2627
  const routes = [
1845
2628
  ${clientRoutes}
1846
2629
  ];
1847
2630
 
1848
- // === Mode B: lazy route chunks ===
1849
- // Split mode's registry entries arrive without a render function: loadChain
1850
- // loads the route's module graph (the page plus its layouts, one chunk per
1851
- // module, the shared runtime in its own vendor chunk) in parallel and
1852
- // composes it at runtime - the exact nesting compose() built at compile
1853
- // time for inline mode. getRender memoizes the composed function on the
1854
- // entry, so a chunk loads once per session; inline mode's entries are the
1855
- // render functions themselves, so the helper is a pass-through there.
2631
+ // === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
1856
2632
  const loadChain = async (loaders) => {
1857
2633
  const mods = await Promise.all(loaders.map((load) => load()));
1858
2634
  let expr = (closes, children) => mods[0].render(closes, children);
@@ -1868,36 +2644,62 @@ const getRender = async (route) => {
1868
2644
  return (route.render ??= (await route.load()).render);
1869
2645
  };
1870
2646
 
1871
- // pages/404.rose (with its layouts) or null -> built-in plain 404
1872
- const notFound = ${notFoundRender};
2647
+ // Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
2648
+ const notFoundRoutes = ${notFoundTable};
2649
+ const notFoundFor = (pathname) => {
2650
+ for (const [prefix, render] of notFoundRoutes) {
2651
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2652
+ }
2653
+ return null;
2654
+ };
1873
2655
 
1874
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1875
- // whose render throws on the client degrades to this instead of breaking
1876
- // navigation.
2656
+ // 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.
1877
2657
  const errorPage = ${errorRender};
1878
2658
 
1879
2659
  // Paint a fallback page (404/500) into the container, wired like any render.
1880
- async function paintFallback(container, page, builtin) {
1881
- resetEffects();
1882
- clearRequestState();
2660
+ async function paintFallback(container, page, builtin, keepState = false) {
2661
+ if (!keepState) __navReset(container);
1883
2662
  clearMounts(); // a failed render leaves stale mounts behind
1884
2663
  // inline mode passes the render itself; split mode passes a loader
1885
2664
  const render = page ? await getRender(page) : null;
1886
2665
  if (render) {
1887
2666
  const closes = [];
1888
- const html = await render(closes, '');
1889
- container.innerHTML = html;
1890
- wire(container, closes);
1891
- bindEvents(container);
1892
- flushMounts();
2667
+ await __withOwner(container, async () => {
2668
+ const html = await render(closes, '');
2669
+ container.innerHTML = html;
2670
+ wire(container, closes);
2671
+ bindEvents(container);
2672
+ flushMounts();
2673
+ });
1893
2674
  return;
1894
2675
  }
1895
2676
  container.innerHTML = builtin;
1896
2677
  }
1897
2678
 
2679
+
2680
+ export async function startNotFound(container, pathname) {
2681
+ const el = document.getElementById('__rosetack_state');
2682
+ if (el) resumeState(el.textContent);
2683
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
2684
+ }
2685
+
1898
2686
  export function matchRoute(pattern, pathname) {
2687
+ // Q0 (bug report): one canonical URL per route.
2688
+ pathname = pathname.replace(/\\/+$/, '') || '/';
1899
2689
  const patternParts = pattern.split('/');
1900
2690
  const pathParts = pathname.split('/');
2691
+
2692
+ const last = patternParts[patternParts.length - 1];
2693
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2694
+ const fixed = patternParts.slice(0, -1);
2695
+ if (pathParts.length < fixed.length) return false;
2696
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2697
+ for (let i = 0; i < fixed.length; i++) {
2698
+ if (fixed[i].startsWith(':')) continue;
2699
+ if (fixed[i] !== pathParts[i]) return false;
2700
+ }
2701
+ return true;
2702
+ }
1901
2703
  if (patternParts.length !== pathParts.length) return false;
1902
2704
  for (let i = 0; i < patternParts.length; i++) {
1903
2705
  if (patternParts[i].startsWith(':')) continue;
@@ -1906,78 +2708,64 @@ export function matchRoute(pattern, pathname) {
1906
2708
  return true;
1907
2709
  }
1908
2710
 
1909
- // === Link prefetch ===
1910
- // Hover / focus / touch an internal link and the target route renders NOW -
1911
- // $data included - against a throwaway signal map. The click that follows
1912
- // paints from the cached HTML: no await, no request, no spinner. Other
1913
- // frameworks prefetch data only; rosetack prefetches the whole render because
1914
- // the inlined bundle already contains every route.
1915
- // Trade-off: the cache holds either a result or the in-flight promise (dedupes
1916
- // hover storms); one isolated render runs at a time so signal-map swapping
1917
- // stays correct without any merging logic. Entries are single-use: a consumed
1918
- // entry disappears from the cache, which is also how tests observe a hit.
1919
- // P1, three guards for link-heavy pages:
1920
- // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
1921
- // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
1922
- // Trade-off: app-global, not per-route - per-route would carry the mode
1923
- // in each document's shell.
1924
- // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
1925
- // the budget caps the QUEUE: a hover storm past it drops the excess
1926
- // instead of rendering fifty routes nobody clicks.
1927
- // 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
1928
- // is evicted first (Map iteration order; entries are single-use, so
1929
- // insertion order IS the recency order).
2711
+ // === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
1930
2712
  let prefetchMode = ${JSON.stringify(prefetchMode)};
1931
2713
  export function setPrefetchMode(mode) { prefetchMode = mode; }
1932
2714
  const PREFETCH_BUDGET = 8;
1933
2715
  const PREFETCH_MAX_CACHED = 4;
1934
- const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
2716
+ const prefetchCache = new Map();
1935
2717
  let prefetchQueue = Promise.resolve();
1936
2718
  let prefetchPending = 0;
1937
2719
 
1938
- // Applies the route's params to state. A [lang] segment whose dictionary is
1939
- // a runtime pack (i18n.preload) is awaited HERE - the one place every client
1940
- // render path goes through (navigation, prefetch, action adopt) - so a packed
1941
- // locale costs one request per session and then renders from memory. A
1942
- // preloaded locale (the default: every dictionary inline) resolves without
1943
- // touching the network, so the common path stays synchronous in spirit.
2720
+
1944
2721
  async function applyParams(route, pathname) {
1945
2722
  const patternParts = route.pattern.split('/');
1946
2723
  const pathParts = pathname.split('/');
1947
2724
  for (let i = 0; i < patternParts.length; i++) {
1948
- if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
2725
+ const seg = patternParts[i];
2726
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2727
+
2728
+
2729
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
1949
2730
  }
1950
2731
  const langIdx = patternParts.indexOf(':lang');
1951
2732
  if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
1952
2733
  }
1953
2734
 
2735
+
2736
+ function __netOk() {
2737
+ const c = navigator.connection;
2738
+ if (!c) return true;
2739
+ if (c.saveData) return false;
2740
+ const t = c.effectiveType;
2741
+ return t !== 'slow-2g' && t !== '2g';
2742
+ }
2743
+
1954
2744
  export function prefetch(pathname, source = 'hover') {
1955
2745
  if (prefetchMode === 'off') return;
1956
2746
  if (prefetchMode === 'hover' && source !== 'hover') return;
1957
2747
  if (prefetchMode === 'viewport' && source !== 'viewport') return;
2748
+ if (!__netOk()) return; // save-data / 2g: no bytes before the click
1958
2749
  if (prefetchCache.has(pathname)) return;
1959
- if (pathname === location.pathname) return; // already here: nothing to prefetch
2750
+ if (pathname === location.pathname) return;
1960
2751
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
1961
2752
  if (!route) return;
1962
- if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
2753
+ if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
2754
+ const qi = pathname.indexOf('?');
2755
+ const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
1963
2756
  const p = prefetchQueue.then(async () => {
1964
2757
  try {
1965
- // the isolated render also captures the onMount callbacks the route
1966
- // queued and the onCleanup disposers it registered: the paint that
1967
- // consumes this entry replays the mounts after wiring and adopts the
1968
- // cleanups, so the prefetched route's timers are disposed on the next
1969
- // navigation like any live route's
2758
+ setPrefetchOverride(qOverride);
2759
+ // The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
1970
2760
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
1971
2761
  await applyParams(route, pathname); // a packed locale's dictionary lands before the render
1972
2762
  const closes = [];
1973
- const render = await getRender(route); // split mode: loads the route's chunk here
2763
+ const render = await getRender(route);
1974
2764
  const html = await render(closes, '');
1975
2765
  return { html, closes };
1976
2766
  });
1977
2767
  const entry = { ...result, state, mounts, cleanups };
1978
- prefetchCache.set(pathname, entry); // promise -> result
1979
- // evict oldest-first; in-flight promises are never evicted (evicting
1980
- // one would only force a duplicate render)
2768
+ prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
1981
2769
  while (prefetchCache.size > PREFETCH_MAX_CACHED) {
1982
2770
  const oldest = prefetchCache.keys().next().value;
1983
2771
  if (prefetchCache.get(oldest) instanceof Promise) break;
@@ -1985,9 +2773,10 @@ export function prefetch(pathname, source = 'hover') {
1985
2773
  }
1986
2774
  return entry;
1987
2775
  } catch {
1988
- prefetchCache.delete(pathname); // failed: the next hover retries
2776
+ prefetchCache.delete(pathname);
1989
2777
  return null;
1990
2778
  } finally {
2779
+ setPrefetchOverride(null);
1991
2780
  prefetchPending--;
1992
2781
  }
1993
2782
  });
@@ -1997,13 +2786,10 @@ export function prefetch(pathname, source = 'hover') {
1997
2786
  }
1998
2787
 
1999
2788
  export function prefetchStats() {
2000
- return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
2789
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
2001
2790
  }
2002
2791
 
2003
- // One delegated listener per event type on the app container: survives DOM
2004
- // swaps and cloned blocks, so handlers never need re-binding. A handler
2005
- // compiled from a server action (data-on-*="$action:name") dispatches to
2006
- // $action instead of the local handler registry.
2792
+ // One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
2007
2793
  const DELEGATED = ['click', 'input', 'change', 'submit'];
2008
2794
  function bindEvents(container) {
2009
2795
  if (container.__rosetack_bound) return;
@@ -2020,41 +2806,64 @@ function bindEvents(container) {
2020
2806
  }
2021
2807
  }
2022
2808
 
2023
- // === Server actions from any event ===
2024
- // POST the body to the current route and adopt the response in place: the
2025
- // server runs the selected action, seeds its state patch, and re-renders, so
2026
- // the swapped DOM is the page as it looks AFTER the action - one request, no
2027
- // reload, and wire() patches only the marked nodes (no re-render). The
2028
- // bootstrap's <form method="POST"> interception goes through the same door.
2029
- async function postForm(body) {
2030
- const res = await fetch(location.pathname, { method: 'POST', body });
2809
+ // === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
2810
+ async function postForm(body, container, pathname) {
2811
+
2812
+ const box = container || document.getElementById('app');
2813
+ const route = pathname || location.pathname;
2814
+ const res = await fetch(route, { method: 'POST', body });
2031
2815
  const html = await res.text();
2032
2816
  const doc = new DOMParser().parseFromString(html, 'text/html');
2033
2817
  const next = doc.getElementById('app');
2034
2818
  const st = doc.getElementById('__rosetack_state');
2035
2819
  const paint = () => {
2036
- const container = document.getElementById('app');
2037
- adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
2820
+ adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
2038
2821
  };
2039
2822
  if (document.startViewTransition) document.startViewTransition(paint);
2040
2823
  else paint();
2041
2824
  }
2042
2825
 
2043
- // Call a page's server action by name from any event handler:
2044
- // <button on:click={like}> compiles to $action('like'). Without JS the
2045
- // binding is inert - the progressive-enhancement story stays with forms.
2826
+ // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
2046
2827
  export async function $action(name, e) {
2047
2828
  if (e && e.preventDefault) e.preventDefault();
2048
2829
  const body = new FormData();
2049
2830
  body.append('__action', name);
2050
- return postForm(body);
2831
+ // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
2832
+ const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
2833
+ return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
2051
2834
  }
2052
2835
 
2053
2836
  export { postForm };
2054
2837
 
2055
- // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2056
- // the existing nodes and bind events. initial=false: client-side navigation -
2057
- // re-render the route chain from scratch and wire the fresh DOM.
2838
+ // The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
2839
+ export { serializeState };
2840
+
2841
+ // Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
2842
+
2843
+
2844
+ function __ownsDoc(container) {
2845
+ return container === document.getElementById('app');
2846
+ }
2847
+ function __navReset(container) {
2848
+ if (__ownsDoc(container)) {
2849
+ resetEffects();
2850
+ clearRequestState();
2851
+ } else {
2852
+ resetContainerFx(container);
2853
+ }
2854
+ }
2855
+ // Attribute everything a render creates (state keys, effects, onCleanups) to
2856
+ // its container. The document path sets no owner and keeps the global sets.
2857
+ async function __withOwner(container, fn) {
2858
+ if (__ownsDoc(container)) return fn();
2859
+ setFxOwner(container);
2860
+ try {
2861
+ return await fn();
2862
+ } finally {
2863
+ setFxOwner(null);
2864
+ }
2865
+ }
2866
+
2058
2867
  export async function start(container, pathname, initial) {
2059
2868
  clearMounts(); // stale mounts from a failed render never fire
2060
2869
  if (initial) {
@@ -2063,104 +2872,110 @@ export async function start(container, pathname, initial) {
2063
2872
  }
2064
2873
  for (const route of routes) {
2065
2874
  if (matchRoute(route.pattern, pathname)) {
2066
- // i18n: an unknown locale paints the 404 page, same as the server
2067
- // (before the prefetch check: a cached entry for a bogus locale is
2068
- // discarded, never painted)
2875
+ // 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).
2069
2876
  const langIdx = route.pattern.split('/').indexOf(':lang');
2070
2877
  ${langDirBlock}
2071
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2878
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2072
2879
  return;
2073
2880
  }
2074
- // Prefetched on hover/focus/touch: the render already ran, so paint its
2075
- // HTML and adopt its signal entries - events then patch the very nodes
2076
- // we wire, and no $data re-runs on click.
2881
+ // 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.
2077
2882
  let hit = initial ? undefined : prefetchCache.get(pathname);
2078
2883
  if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2079
2884
  if (hit) {
2080
- prefetchCache.delete(pathname); // single-use: the next hover refetches
2081
- resetEffects();
2885
+ prefetchCache.delete(pathname);
2886
+ __navReset(container);
2082
2887
  restoreState(hit.state);
2083
2888
  container.innerHTML = hit.html;
2084
- wire(container, hit.closes);
2889
+ await __withOwner(container, () => {
2890
+ wire(container, hit.closes);
2891
+ bindEvents(container);
2892
+ hit.mounts.forEach((fn) => fn());
2893
+ adoptCleanups(hit.cleanups);
2894
+ });
2895
+ return;
2896
+ }
2897
+ if (!initial) __navReset(container);
2898
+ let broken = false;
2899
+ let signal = null;
2900
+ await __withOwner(container, async () => {
2901
+ await applyParams(route, pathname);
2902
+ const closes = [];
2903
+ let html;
2904
+ try {
2905
+ const render = await getRender(route);
2906
+ html = await render(closes, '');
2907
+ } catch (err) {
2908
+
2909
+ if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
2910
+ if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
2911
+
2912
+
2913
+ broken = true;
2914
+ return;
2915
+ }
2916
+ if (!initial) container.innerHTML = html;
2917
+ wire(container, closes);
2085
2918
  bindEvents(container);
2086
- hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2087
- adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
2919
+ flushMounts();
2920
+ });
2921
+ if (signal === 'notFound') {
2922
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2088
2923
  return;
2089
2924
  }
2090
- if (!initial) {
2091
- resetEffects();
2092
- clearRequestState();
2925
+ if (signal) {
2926
+ location.href = signal;
2927
+ return;
2093
2928
  }
2094
- await applyParams(route, pathname);
2095
- const closes = [];
2096
- let html;
2097
- try {
2098
- const render = await getRender(route); // split mode: loads the route's chunk here
2099
- html = await render(closes, '');
2100
- } catch {
2101
- // the route itself is broken: degrade to pages/500.rose (or the
2102
- // built-in plain 500) instead of leaving the container empty
2929
+ if (broken) {
2103
2930
  await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2104
- return;
2105
2931
  }
2106
- if (!initial) container.innerHTML = html;
2107
- wire(container, closes);
2108
- bindEvents(container);
2109
- flushMounts();
2110
2932
  return;
2111
2933
  }
2112
2934
  }
2113
- // unmatched route: pages/404.rose renders (with its head + interactivity),
2114
- // else the built-in plain 404 - and an i18n app's document returns to the
2115
- // default locale, the same one the server stamps on its 404
2116
- ${hasLang ? ` document.documentElement.lang = __defLocale;
2117
- document.documentElement.removeAttribute('dir');` : ""}
2118
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2935
+ // Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
2936
+ ${hasLang ? ` // the same app-root gate as above - a mount never touches the
2937
+ // host document's language or direction.
2938
+ if (container === document.getElementById('app')) {
2939
+ document.documentElement.lang = __defLocale;
2940
+ document.documentElement.removeAttribute('dir');
2941
+ }` : ""}
2942
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2119
2943
  }
2120
2944
 
2121
- // Adopt a server-rendered response in place - the JS-enabled half of
2122
- // progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
2123
- // via fetch and hands the response here. The DOM is swapped and wired with
2124
- // the same zero-render trick as boot: re-run the route's render to rebuild
2125
- // the marker closures, wire them against the adopted nodes. The page never
2126
- // re-renders visibly, no hydration payload, no second request beyond the POST.
2127
- export async function adopt(container, html, stateJson) {
2128
- resetEffects();
2129
- clearRequestState();
2945
+ // Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
2946
+ export async function adopt(container, html, stateJson, pathname) {
2947
+
2948
+
2949
+ const route0 = pathname || location.pathname;
2950
+ __navReset(container);
2130
2951
  clearMounts(); // stale mounts from a failed render never fire
2131
2952
  resumeState(stateJson);
2132
2953
  container.innerHTML = html;
2133
- // keep the embedded state in sync so a later SPA-fallback check agrees
2954
+
2134
2955
  const st = document.getElementById('__rosetack_state');
2135
2956
  if (st) st.textContent = stateJson;
2136
2957
  for (const route of routes) {
2137
- if (matchRoute(route.pattern, location.pathname)) {
2138
- await applyParams(route, location.pathname);
2139
- const closes = [];
2140
- try {
2141
- const render = await getRender(route); // split mode: loads the route's chunk here
2142
- await render(closes, '');
2143
- } catch {
2144
- // the adopted response's route is broken (e.g. the action's page
2145
- // throws): keep the swapped DOM but skip wiring it
2146
- return;
2147
- }
2148
- wire(container, closes);
2149
- bindEvents(container);
2150
- flushMounts();
2958
+ if (matchRoute(route.pattern, route0)) {
2959
+ await __withOwner(container, async () => {
2960
+ await applyParams(route, route0);
2961
+ const closes = [];
2962
+ try {
2963
+ const render = await getRender(route);
2964
+ await render(closes, '');
2965
+ } catch {
2966
+
2967
+
2968
+ return;
2969
+ }
2970
+ wire(container, closes);
2971
+ bindEvents(container);
2972
+ flushMounts();
2973
+ });
2151
2974
  return;
2152
2975
  }
2153
2976
  }
2154
2977
  }
2155
- // === refresh() implementation ===
2156
- // Re-render the current route in place: the client half of router.refresh()
2157
- // (a router refresh) / (a full invalidation). Same machinery as a client-side
2158
- // navigation to the current path - $data re-runs, state re-seeds from the
2159
- // fresh render, wire() patches the marked nodes - but a refresh never lands
2160
- // a prefetch entry: a hover from a minute ago is exactly what it exists to
2161
- // bypass. Zero requests: the render (and its $data) runs in the page.
2162
- // Trade-off: state resets like navigation (no per-key retention); add
2163
- // retention when an app needs refresh-without-losing-input.
2978
+ // === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
2164
2979
  setRefreshHook(async () => {
2165
2980
  prefetchCache.delete(location.pathname);
2166
2981
  await start(document.getElementById('app'), location.pathname, false);
@@ -2194,26 +3009,44 @@ setRefreshHook(async () => {
2194
3009
  ...TS_LOADER
2195
3010
  });
2196
3011
  }
3012
+ await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
2197
3013
  await fs.promises.rm(buildDir, { recursive: true, force: true });
2198
3014
  const publicDir = path.join(root, "public");
2199
3015
  if (fs.existsSync(publicDir)) {
2200
- const outPublic = path.join(outDir, "public");
2201
- await fs.promises.mkdir(outPublic, { recursive: true });
2202
- const assets = await fs.promises.readdir(publicDir);
2203
- await Promise.all(
2204
- assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
2205
- );
3016
+ await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
3017
+ const favicon = path.join(publicDir, "favicon.ico");
3018
+ if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
2206
3019
  }
2207
3020
  console.log("rosetack zero-JS report:");
2208
3021
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
3022
+ const warnGroups = /* @__PURE__ */ new Map();
2209
3023
  for (const { info, i } of pages) {
2210
3024
  if (!routeShipsNoJs(infos, compiled, i)) continue;
2211
3025
  for (const ci of [i, ...layoutsOf(infos, i)]) {
2212
3026
  for (const w of compiled[ci].jsWarnings ?? []) {
2213
- console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
3027
+ let g = warnGroups.get(w);
3028
+ if (!g) {
3029
+ g = { why: w, files: /* @__PURE__ */ new Map() };
3030
+ warnGroups.set(w, g);
3031
+ }
3032
+ const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
3033
+ let routes = g.files.get(file);
3034
+ if (!routes) {
3035
+ routes = /* @__PURE__ */ new Set();
3036
+ g.files.set(file, routes);
3037
+ }
3038
+ routes.add(info.routePath);
2214
3039
  }
2215
3040
  }
2216
3041
  }
3042
+ for (const g of warnGroups.values()) {
3043
+ const allRoutes = /* @__PURE__ */ new Set();
3044
+ for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
3045
+ 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`})`);
3046
+ const shown = parts.slice(0, 4).join(", ");
3047
+ const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
3048
+ console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
3049
+ }
2217
3050
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2218
3051
  }
2219
3052
  async function scanRoseFiles(root) {
@@ -2258,15 +3091,21 @@ function getRouteInfo(filePath, root) {
2258
3091
  const base = path.posix.basename(withoutExt);
2259
3092
  const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2260
3093
  const isLayout = !isComponent && base === "_layout";
2261
- const isNotFound = !isComponent && base === "404";
3094
+ const isNotFound = !isComponent && (base === "404" || base === "_notfound");
2262
3095
  const isError = !isComponent && base === "500";
2263
3096
  const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2264
3097
  const isMiddleware = !isComponent && withoutExt === "_middleware";
2265
- let parts = withoutExt.split("/").filter((p) => p !== "_layout");
3098
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
2266
3099
  if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
2267
- const routeParts = parts.map(
2268
- (part) => part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part
2269
- );
3100
+ const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
3101
+ const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
3102
+ const routeParts = parts.map((part) => {
3103
+ const optional = OPTIONAL_CATCH_ALL.exec(part);
3104
+ if (optional) return `**${optional[1]}`;
3105
+ const catchAll = CATCH_ALL.exec(part);
3106
+ if (catchAll) return `*${catchAll[1]}`;
3107
+ return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
3108
+ });
2270
3109
  let routePath;
2271
3110
  if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2272
3111
  routePath = "/";
@@ -2277,7 +3116,13 @@ function getRouteInfo(filePath, root) {
2277
3116
  filePath,
2278
3117
  routePath,
2279
3118
  pattern: routePath,
2280
- paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
3119
+ paramNames: parts.flatMap((p) => {
3120
+ const optional = OPTIONAL_CATCH_ALL.exec(p);
3121
+ if (optional) return [optional[1]];
3122
+ const catchAll = CATCH_ALL.exec(p);
3123
+ if (catchAll) return [catchAll[1]];
3124
+ return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
3125
+ }),
2281
3126
  isLayout,
2282
3127
  isNotFound,
2283
3128
  isError,
@@ -2309,7 +3154,25 @@ function getStyles() {
2309
3154
  }
2310
3155
  }
2311
3156
  var BOOTSTRAP = esbuild2.transformSync(`
2312
- const __app = document.getElementById('app');
3157
+ // shell = false: the document's SSR content sits directly in <body> - no
3158
+ // #app wrapper, no demo styles, so a real theme's CSS owns the document from
3159
+ // the first byte (and a JS-less visitor never sees either). The bundle still
3160
+ // runs, and it still needs its container: wrap the content once, here, before
3161
+ // any theme script executes (module scripts run before DOMContentLoaded). The
3162
+ // wrapper is a plain unstyled div, so the re-parent is visually inert; every
3163
+ // later path - adoption, navigation, forms - is then the ordinary one.
3164
+ let __app = document.getElementById('app');
3165
+ if (!__app) {
3166
+ __app = document.createElement('div');
3167
+ __app.id = 'app';
3168
+ // scripts stay outside the wrapper, exactly where the dressed document
3169
+ // keeps them: the state element and the running module must survive a
3170
+ // navigation's innerHTML swap (they are the document's, not the route's).
3171
+ for (const node of Array.from(document.body.children)) {
3172
+ if (node.tagName !== 'SCRIPT') __app.appendChild(node);
3173
+ }
3174
+ document.body.appendChild(__app);
3175
+ }
2313
3176
  // Native View Transitions around client-side navigation (progressive:
2314
3177
  // browsers without the API navigate normally, no polyfill, no CSS required).
2315
3178
  function __navigate(pathname) {
@@ -2372,20 +3235,50 @@ document.addEventListener('submit', (e) => {
2372
3235
  e.preventDefault();
2373
3236
  postForm(new FormData(f));
2374
3237
  });
3238
+ // Dev seam: the live signal graph, readable as JSON. Three callers, one
3239
+ // implementation: the dev server's reload bridge snapshots it before a
3240
+ // rebuild-triggered reload so the edit lands on the state the developer had,
3241
+ // and the devtools extension (devtools/) reads it the same way - the signal
3242
+ // graph plus the prefetch counters, which is the whole observable state of a
3243
+ // running page. Both are DIRECT references (no wrapper arrow): the names take
3244
+ // no arguments, so the call is identical and every document that carries the
3245
+ // bundle pays eleven bytes for the pair instead of forty.
3246
+ window.__rosetack = { state: serializeState, prefetch: prefetchStats };
2375
3247
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
2376
3248
  // If the document was rendered for a DIFFERENT route (a static-file server's
2377
3249
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
2378
3250
  // client router render the requested route from scratch.
2379
3251
  const __st = document.getElementById('__rosetack_state');
2380
- const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
2381
- if (__state.__route === window.location.pathname) {
3252
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
3253
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
3254
+ // the next document (window.__rosetack_resume). The resumed values win over the
3255
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
3256
+ // the route renders client-side from the bundle rather than adopting the SSR
3257
+ // DOM, because a resumed list can be longer than the document's rows and
3258
+ // adoption could not add them. Absent in every non-dev document.
3259
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
3260
+ if (__resumed) {
3261
+ const __route = __state.__route;
3262
+ __state = Object.assign(__state, __resumed);
3263
+ __state.__route = __route;
3264
+ }
3265
+ // A NOT-FOUND document (the server stamps __notFound onto its state) boots
3266
+ // into the app's own 404 route: the URL matches no route - or a catch-all
3267
+ // whose resolver threw notFound(), whose key sits null in the resumed state
3268
+ // and whose template would dereference it into a 500. startNotFound paints
3269
+ // the not-found route from the resumed state instead (zero requests).
3270
+ if (__state.__notFound) {
3271
+ startNotFound(__app, window.location.pathname);
3272
+ } else if (__resumed) {
3273
+ start(__app, window.location.pathname);
3274
+ } else if (__state.__route === window.location.pathname) {
2382
3275
  start(__app, window.location.pathname, true);
2383
3276
  } else {
2384
3277
  start(__app, window.location.pathname);
2385
3278
  }
2386
3279
  `, { minify: true }).code;
2387
3280
  var EXTERNAL_BOOTSTRAP = `
2388
- import { start, prefetch, postForm } from '/client.js';
3281
+ import { start, prefetch, postForm, prefetchStats } from '/client.js';
2389
3282
  ${BOOTSTRAP}`;
2390
3283
  function inlineScript(client) {
2391
3284
  return `
@@ -2418,6 +3311,7 @@ var STYLES_MIN = STYLES.replace(
2418
3311
  function mergeHeadBlocks(blocks) {
2419
3312
  const byKey = /* @__PURE__ */ new Map();
2420
3313
  const order = [];
3314
+ const positional = /* @__PURE__ */ new Map();
2421
3315
  const put = (key, html) => {
2422
3316
  if (!byKey.has(key)) {
2423
3317
  byKey.set(key, html);
@@ -2426,11 +3320,20 @@ function mergeHeadBlocks(blocks) {
2426
3320
  };
2427
3321
  for (const block of blocks) {
2428
3322
  for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
2429
- for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
3323
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
2430
3324
  const tag = m[1].toLowerCase();
2431
- const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
2432
- const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
2433
- const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
3325
+ if (tag === "title") continue;
3326
+ const attrs = m[2];
3327
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
3328
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
3329
+ let key;
3330
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
3331
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
3332
+ else {
3333
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
3334
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
3335
+ }
3336
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
2434
3337
  put(key, marked);
2435
3338
  }
2436
3339
  }
@@ -2441,29 +3344,42 @@ function clientScriptTag(client, nonce = "") {
2441
3344
  return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
2442
3345
  <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
2443
3346
  }
2444
- function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
3347
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
2445
3348
  const clientTag = clientScriptTag(client, nonce);
2446
3349
  const mergedHead = mergeHeadBlocks(head);
3350
+ const headStamped = nonce ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs) => /\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`) : mergedHead;
3351
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ""}`;
3352
+ let bodyAttrs = "";
3353
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag, attrs) => {
3354
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, "");
3355
+ if (tag === "html") htmlAttrs = clean;
3356
+ else bodyAttrs = clean;
3357
+ return "";
3358
+ });
2447
3359
  const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
2448
3360
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
2449
3361
  ${FAVICON}`;
2450
- const headTags = mergedHead ? `
2451
- ${mergedHead}` : "";
3362
+ const headTags = headClean ? `
3363
+ ${headClean}` : "";
2452
3364
  const styleTag = styles ? `
2453
3365
  <style>${styles}</style>` : "";
3366
+ const stateSafe = stateJson.replace(/</g, "\\u003c");
2454
3367
  const jsTail = js ? `
2455
- <script type="application/json" id="__rosetack_state">${stateJson}</script>
3368
+ <script type="application/json" id="__rosetack_state">${stateSafe}</script>
2456
3369
  ${clientTag}` : "";
3370
+ const open = js && shell ? '<div id="app">' : "";
3371
+ const close = js && shell ? "</div>" : "";
3372
+ const shellStyles = js && shell ? `
3373
+ <style>${STYLES_MIN}</style>` : "";
2457
3374
  return `<!DOCTYPE html>
2458
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
3375
+ <html${htmlAttrs}>
2459
3376
  <head>
2460
3377
  <meta charset="UTF-8">
2461
3378
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
2462
- ${titleTag}
2463
- <style>${STYLES_MIN}</style>${styleTag}
3379
+ ${titleTag}${shellStyles}${styleTag}
2464
3380
  </head>
2465
- <body>
2466
- <div id="app">${ssrHtml}</div>${jsTail}
3381
+ <body${bodyAttrs}>
3382
+ ${open}${ssrHtml}${close}${jsTail}
2467
3383
  </body>
2468
3384
  </html>`;
2469
3385
  }
@@ -2555,15 +3471,16 @@ async function test(file, opts = {}) {
2555
3471
  state: page.state ? JSON.parse(page.state) : {},
2556
3472
  head: page.head ?? [],
2557
3473
  csr: page.csr,
3474
+ shell: page.shell,
2558
3475
  lang: page.lang ?? "en",
2559
3476
  dir: page.dir ?? "",
2560
- document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? ""),
3477
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? "", "", page.shell !== false),
2561
3478
  redirect
2562
3479
  });
2563
3480
  const toRequest = (pathname, req = {}, body) => {
2564
3481
  const headers = new Headers(req.headers ?? {});
2565
3482
  for (const [k, v] of Object.entries(req.cookies ?? {})) headers.append("cookie", `${k}=${v}`);
2566
- return new Request(`http://localhost${pathname}`, { method: body ? "POST" : "GET", headers, body });
3483
+ return new Request(`http://localhost${pathname}`, { method: req.method ?? "GET", headers, body: body ?? void 0 });
2567
3484
  };
2568
3485
  const request = async (pathname, req, body) => {
2569
3486
  if (mod.middleware) {