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
@@ -3,6 +3,47 @@ import * as fs from "fs";
3
3
  import * as path from "path";
4
4
  import { pathToFileURL, fileURLToPath } from "url";
5
5
  import * as esbuild from "esbuild";
6
+
7
+ // src/compiler/errors.ts
8
+ var RoseError = class extends Error {
9
+ code;
10
+ file;
11
+ line;
12
+ hint;
13
+ constructor(code, message, opts = {}) {
14
+ super(message);
15
+ this.name = "RoseError";
16
+ this.code = code;
17
+ this.file = opts.file;
18
+ this.line = opts.line;
19
+ this.hint = opts.hint;
20
+ }
21
+ info() {
22
+ const info = { code: this.code };
23
+ if (this.file !== void 0) info.file = this.file;
24
+ if (this.line !== void 0) info.line = this.line;
25
+ info.message = this.message;
26
+ if (this.hint !== void 0) info.hint = this.hint;
27
+ return info;
28
+ }
29
+ };
30
+ function lineOf(src, index) {
31
+ let line = 1;
32
+ const end = Math.min(index, src.length);
33
+ for (let i = 0; i < end; i++) {
34
+ if (src[i] === "\n") line++;
35
+ }
36
+ return line;
37
+ }
38
+ function lineAt(src, match) {
39
+ return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
40
+ }
41
+ function errorInfo(err) {
42
+ if (err instanceof RoseError) return err.info();
43
+ return { code: "E-UNKNOWN", message: err instanceof Error ? err.message : String(err) };
44
+ }
45
+
46
+ // src/compiler/index.ts
6
47
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
7
48
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
8
49
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
@@ -10,12 +51,11 @@ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
10
51
  var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
11
52
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
12
53
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
13
- var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
14
54
  var SLOT_RE = /<slot\s*\/?>/g;
15
55
  var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
16
56
  function encodeSlotCall(attrs) {
17
57
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
18
- if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
58
+ 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} />' });
19
59
  const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
20
60
  return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
21
61
  }
@@ -102,7 +142,306 @@ function callifyStateReads(script, names) {
102
142
  }
103
143
  function callifyTemplateExprs(template, names) {
104
144
  if (names.length === 0) return template;
105
- return template.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${callifyStateReads(expr, names)}}`);
145
+ let out = "";
146
+ let last = 0;
147
+ for (const s of templateExprSpans(template)) {
148
+ out += template.slice(last, s.start) + "{" + callifyStateReads(s.expr, names) + "}";
149
+ last = s.end + 1;
150
+ }
151
+ return out + template.slice(last);
152
+ }
153
+ function templateExprSpans(src) {
154
+ const spans = [];
155
+ let i = 0;
156
+ while (i < src.length) {
157
+ if (src[i] === "{") {
158
+ const end = scanExprEnd(src, i);
159
+ if (end > i + 1) {
160
+ spans.push({ start: i, end, expr: src.slice(i + 1, end) });
161
+ i = end + 1;
162
+ continue;
163
+ }
164
+ }
165
+ i++;
166
+ }
167
+ return spans;
168
+ }
169
+ function scanExprEnd(src, open) {
170
+ let depth = 0;
171
+ let i = open;
172
+ while (i < src.length) {
173
+ const ch = src[i];
174
+ if (ch === "'" || ch === '"') {
175
+ i = skipQuoted(src, i);
176
+ continue;
177
+ }
178
+ if (ch === "`") {
179
+ i = skipTemplate(src, i);
180
+ continue;
181
+ }
182
+ if (ch === "{") depth++;
183
+ else if (ch === "}" && --depth === 0) return i;
184
+ i++;
185
+ }
186
+ return -1;
187
+ }
188
+ function skipQuoted(src, i) {
189
+ const q = src[i];
190
+ let j = i + 1;
191
+ while (j < src.length) {
192
+ if (src[j] === "\\") {
193
+ j += 2;
194
+ continue;
195
+ }
196
+ if (src[j] === q) return j + 1;
197
+ j++;
198
+ }
199
+ return j;
200
+ }
201
+ function skipTemplate(src, i) {
202
+ let j = i + 1;
203
+ while (j < src.length) {
204
+ const ch = src[j];
205
+ if (ch === "\\") {
206
+ j += 2;
207
+ continue;
208
+ }
209
+ if (ch === "`") return j + 1;
210
+ if (ch === "$" && src[j + 1] === "{") {
211
+ const end = scanExprEnd(src, j + 1);
212
+ j = end < 0 ? src.length : end + 1;
213
+ continue;
214
+ }
215
+ j++;
216
+ }
217
+ return j;
218
+ }
219
+ function skipLiteral(src, i) {
220
+ const q = src[i];
221
+ if (q === '"' || q === "'") return skipQuoted(src, i);
222
+ if (q === "`") return skipTemplate(src, i);
223
+ if (q !== "/") return null;
224
+ if (src[i + 1] === "/" || src[i + 1] === "*") return null;
225
+ let b = i - 1;
226
+ while (b >= 0 && /\s/.test(src[b])) b--;
227
+ if (b >= 0) {
228
+ if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
229
+ const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
230
+ if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
231
+ }
232
+ }
233
+ let j = i + 1;
234
+ let inClass = false;
235
+ while (j < src.length) {
236
+ const c = src[j];
237
+ if (c === "\\") {
238
+ j += 2;
239
+ continue;
240
+ }
241
+ if (c === "\n") return null;
242
+ if (inClass) {
243
+ if (c === "]") inClass = false;
244
+ } else if (c === "[") inClass = true;
245
+ else if (c === "/") {
246
+ j++;
247
+ break;
248
+ }
249
+ j++;
250
+ }
251
+ if (j > src.length) return null;
252
+ while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
253
+ return j;
254
+ }
255
+ function stripComments(src) {
256
+ let out = "";
257
+ let i = 0;
258
+ while (i < src.length) {
259
+ const lit = skipLiteral(src, i);
260
+ if (lit !== null) {
261
+ out += src.slice(i, lit);
262
+ i = lit;
263
+ continue;
264
+ }
265
+ if (src.startsWith("//", i)) {
266
+ while (i < src.length && src[i] !== "\n") i++;
267
+ continue;
268
+ }
269
+ if (src.startsWith("/*", i)) {
270
+ i += 2;
271
+ while (i < src.length && !src.startsWith("*/", i)) i++;
272
+ i = Math.min(i + 2, src.length);
273
+ continue;
274
+ }
275
+ if (src.startsWith("<!--", i)) {
276
+ i += 4;
277
+ while (i < src.length && !src.startsWith("-->", i)) i++;
278
+ i = Math.min(i + 3, src.length);
279
+ continue;
280
+ }
281
+ out += src[i++];
282
+ }
283
+ return out;
284
+ }
285
+ function stripGuardedBranches(src) {
286
+ const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
287
+ const ws = (i2) => {
288
+ while (i2 < src.length && /\s/.test(src[i2])) i2++;
289
+ return i2;
290
+ };
291
+ const ternaryColon = (q) => {
292
+ let depth = 0;
293
+ let i2 = q + 1;
294
+ while (i2 < src.length) {
295
+ const c = src[i2];
296
+ const lit = skipLiteral(src, i2);
297
+ if (lit !== null) {
298
+ i2 = lit;
299
+ continue;
300
+ }
301
+ if (c === "(" || c === "[" || c === "{") depth++;
302
+ else if (c === ")" || c === "]" || c === "}") {
303
+ depth--;
304
+ if (depth < 0) return -1;
305
+ } else if (depth === 0 && c === ":") return i2;
306
+ else if (depth === 0 && c === "?") {
307
+ const inner = ternaryColon(i2);
308
+ if (inner < 0) return -1;
309
+ i2 = inner + 1;
310
+ continue;
311
+ }
312
+ i2++;
313
+ }
314
+ return -1;
315
+ };
316
+ const exprEnd = (i2) => {
317
+ let depth = 0;
318
+ while (i2 < src.length) {
319
+ const c = src[i2];
320
+ const lit = skipLiteral(src, i2);
321
+ if (lit !== null) {
322
+ i2 = lit;
323
+ continue;
324
+ }
325
+ if (c === "(" || c === "[" || c === "{") depth++;
326
+ else if (c === ")" || c === "]" || c === "}") {
327
+ if (depth === 0) return i2;
328
+ depth--;
329
+ } else if (depth === 0 && (c === "," || c === ";")) return i2;
330
+ else if (depth === 0 && c === "?") {
331
+ const inner = ternaryColon(i2);
332
+ if (inner < 0) return src.length;
333
+ i2 = inner + 1;
334
+ continue;
335
+ }
336
+ i2++;
337
+ }
338
+ return src.length;
339
+ };
340
+ const braceEnd = (b) => {
341
+ let depth = 0;
342
+ let i2 = b;
343
+ while (i2 < src.length) {
344
+ const c = src[i2];
345
+ const lit = skipLiteral(src, i2);
346
+ if (lit !== null) {
347
+ i2 = lit;
348
+ continue;
349
+ }
350
+ if (c === "{") depth++;
351
+ else if (c === "}") {
352
+ depth--;
353
+ if (depth === 0) return i2;
354
+ }
355
+ i2++;
356
+ }
357
+ return src.length;
358
+ };
359
+ const stmtEnd = (i2) => {
360
+ let depth = 0;
361
+ while (i2 < src.length) {
362
+ const c = src[i2];
363
+ const lit = skipLiteral(src, i2);
364
+ if (lit !== null) {
365
+ i2 = lit;
366
+ continue;
367
+ }
368
+ if (c === "(" || c === "[" || c === "{") depth++;
369
+ else if (c === ")" || c === "]" || c === "}") {
370
+ if (depth === 0) return i2;
371
+ depth--;
372
+ } else if (depth === 0 && (c === ";" || c === "\n")) return i2;
373
+ i2++;
374
+ }
375
+ return src.length;
376
+ };
377
+ const isIfGuard = (src2, at) => {
378
+ let b = at - 1;
379
+ while (b >= 0 && /\s/.test(src2[b])) b--;
380
+ if (b < 0 || src2[b] !== "(") return false;
381
+ b--;
382
+ while (b >= 0 && /\s/.test(src2[b])) b--;
383
+ return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
384
+ };
385
+ const blanks = [];
386
+ let i = 0;
387
+ while (i < src.length) {
388
+ const lit = skipLiteral(src, i);
389
+ if (lit !== null) {
390
+ i = lit;
391
+ continue;
392
+ }
393
+ GUARD.lastIndex = i;
394
+ const m = GUARD.exec(src);
395
+ if (!m) {
396
+ i++;
397
+ continue;
398
+ }
399
+ const browserAfter = m[1] === "!==";
400
+ const j = ws(i + m[0].length);
401
+ const two = src.slice(j, j + 2);
402
+ if (two === "&&" && browserAfter) {
403
+ blanks.push([j + 2, exprEnd(j + 2)]);
404
+ } else if (two === "||" && !browserAfter) {
405
+ blanks.push([j + 2, exprEnd(j + 2)]);
406
+ } else if (src[j] === "?") {
407
+ const colon = ternaryColon(j);
408
+ if (colon < 0) {
409
+ if (browserAfter) blanks.push([j + 1, src.length]);
410
+ } else if (browserAfter) {
411
+ blanks.push([j + 1, colon]);
412
+ } else {
413
+ blanks.push([colon + 1, exprEnd(colon + 1)]);
414
+ }
415
+ } else if (src[j] === ")" && isIfGuard(src, i)) {
416
+ let bodyEnd;
417
+ const k = ws(j + 1);
418
+ if (src[k] === "{") {
419
+ bodyEnd = braceEnd(k);
420
+ if (browserAfter) blanks.push([k + 1, bodyEnd]);
421
+ } else {
422
+ bodyEnd = stmtEnd(k);
423
+ if (browserAfter) blanks.push([k, bodyEnd]);
424
+ }
425
+ const after = ws(bodyEnd + 1);
426
+ if (src.startsWith("else", after)) {
427
+ const e = ws(after + 4);
428
+ if (src[e] === "{") {
429
+ const close = braceEnd(e);
430
+ if (!browserAfter) blanks.push([e + 1, close]);
431
+ } else {
432
+ const stop = stmtEnd(e);
433
+ if (!browserAfter) blanks.push([e, stop]);
434
+ }
435
+ }
436
+ }
437
+ i = j;
438
+ }
439
+ if (blanks.length === 0) return src;
440
+ const out = [...src];
441
+ for (const [a, b] of blanks) {
442
+ for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
443
+ }
444
+ return out.join("");
106
445
  }
107
446
  function scriptOf(source) {
108
447
  return source.match(COMPONENT_RE)?.[1] ?? null;
@@ -121,21 +460,29 @@ async function loadPlugins(root) {
121
460
  }
122
461
  function resolveRoseImports(script, fromFile, registry) {
123
462
  const imports = [];
124
- const resolve2 = (spec) => {
463
+ const resolve2 = (spec, at) => {
125
464
  const abs = path.resolve(path.dirname(fromFile), spec);
126
465
  const hit = registry.get(abs);
127
466
  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.`);
467
+ throw new RoseError(
468
+ "E-IMPORT",
469
+ `${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.`,
470
+ {
471
+ file: fromFile,
472
+ line: lineOf(script, at),
473
+ hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`
474
+ }
475
+ );
129
476
  }
130
477
  return hit;
131
478
  };
132
- let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
133
- const hit = resolve2(spec);
479
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at) => {
480
+ const hit = resolve2(spec, at);
134
481
  imports.push({ name, specifier: spec, index: hit.index });
135
482
  return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
136
483
  });
137
- rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
138
- const hit = resolve2(spec);
484
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at) => {
485
+ const hit = resolve2(spec, at);
139
486
  const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
140
487
  imports.push({ name: alias, specifier: spec, index: hit.index });
141
488
  return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
@@ -145,6 +492,60 @@ function resolveRoseImports(script, fromFile, registry) {
145
492
  function rewriteRoseImports(script, kind) {
146
493
  return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
147
494
  }
495
+ 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)$)/;
496
+ function nodeOnlyImports(importStmts) {
497
+ const out = [];
498
+ for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
499
+ if (m[1]) continue;
500
+ if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
501
+ }
502
+ return out;
503
+ }
504
+ function wireEventBindings(template, actionNames) {
505
+ const bindings = [];
506
+ let out = "";
507
+ let rest = template;
508
+ for (; ; ) {
509
+ const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
510
+ if (!m) {
511
+ out += rest;
512
+ break;
513
+ }
514
+ out += rest.slice(0, m.index);
515
+ let i = m.index + m[0].length;
516
+ let depth = 1;
517
+ while (i < rest.length) {
518
+ const ch = rest[i];
519
+ if (ch === '"' || ch === "'") {
520
+ i = skipQuoted(rest, i);
521
+ continue;
522
+ }
523
+ if (ch === "`") {
524
+ i = skipTemplate(rest, i);
525
+ continue;
526
+ }
527
+ if (ch === "{") depth++;
528
+ else if (ch === "}") {
529
+ depth--;
530
+ if (depth === 0) break;
531
+ }
532
+ i++;
533
+ }
534
+ const expr = rest.slice(m.index + m[0].length, i).trim();
535
+ if (actionNames.has(expr)) {
536
+ out += `data-on-${m[1]}="$action:${expr}"`;
537
+ } else if (/^\w+$/.test(expr)) {
538
+ out += `data-on-${m[1]}="${expr}"`;
539
+ bindings.push({ event: m[1], fn: expr });
540
+ } else {
541
+ const name = `__h${bindings.length}`;
542
+ out += `data-on-${m[1]}="${name}"`;
543
+ bindings.push({ event: m[1], fn: `${name}: ${expr}` });
544
+ }
545
+ rest = rest.slice(i + 1);
546
+ }
547
+ return { template: out, bindings };
548
+ }
148
549
  function scanSlotDecls(filePath) {
149
550
  let src;
150
551
  try {
@@ -152,8 +553,9 @@ function scanSlotDecls(filePath) {
152
553
  } catch {
153
554
  return [];
154
555
  }
155
- const noBlocks = src.replace(STYLE_RE, "");
156
- const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
556
+ const noScript = src.replace(COMPONENT_RE, "");
557
+ const noBlocks = noScript.replace(STYLE_RE, "");
558
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
157
559
  const out = [];
158
560
  for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
159
561
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
@@ -207,7 +609,11 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
207
609
  try {
208
610
  source = await p.transform(source, filePath);
209
611
  } catch (err) {
210
- throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
612
+ throw new RoseError(
613
+ "E-PLUGIN",
614
+ `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
615
+ { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
616
+ );
211
617
  }
212
618
  }
213
619
  if (isApi) {
@@ -217,6 +623,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
217
623
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
218
624
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
219
625
  const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
626
+ const ownRuntimeImports = new Set(
627
+ [...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))
628
+ );
629
+ const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
630
+ const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
631
+ ` : "";
220
632
  return {
221
633
  ssr: "",
222
634
  client: "",
@@ -225,49 +637,95 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
225
637
  guardName: null,
226
638
  style: "",
227
639
  hasParams: false,
228
- api: `import { getContext } from './runtime.js';
229
- ${rewriteRoseImports(`${hoisted.imports}
640
+ api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
230
641
  ${hoisted.rest}`, "ssr").trim()}`,
231
642
  apiMethods,
232
643
  hasPrerender,
233
644
  usesContext: usesContext2
234
645
  };
235
646
  }
236
- const styleMatch = source.match(STYLE_RE);
647
+ const sourceNoScript = source.replace(COMPONENT_RE, "");
648
+ const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
649
+ const styleMatch = sourceNoHead.match(STYLE_RE);
237
650
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
238
- const sourceNoBlocks = source.replace(STYLE_RE, "");
239
- const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
651
+ const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
652
+ const scriptMatch = source.match(COMPONENT_RE);
240
653
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
241
654
  const rawScript = roseResolved.script;
242
655
  const roseImports = roseResolved.imports;
243
656
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
657
+ if (path.basename(filePath) !== "_middleware.rose") {
658
+ for (const spec of nodeOnlyImports(importStmts)) {
659
+ const at = importStmts.indexOf(spec);
660
+ throw new RoseError(
661
+ "E-NODE-ONLY",
662
+ `${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.`,
663
+ {
664
+ file: filePath,
665
+ line: at >= 0 ? lineOf(importStmts, at) : void 0,
666
+ 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`
667
+ }
668
+ );
669
+ }
670
+ }
244
671
  const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
245
672
  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()}>.`
673
+ throw new RoseError(
674
+ "E-EXPORT",
675
+ `${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()}>.`,
676
+ { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
248
677
  );
249
678
  }
250
- const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
679
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
251
680
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
252
681
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
253
682
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
254
683
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
255
684
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
256
685
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
257
- throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
686
+ throw new RoseError(
687
+ "E-EXPORT",
688
+ `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
689
+ { 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'" }
690
+ );
691
+ }
692
+ const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
693
+ const vitals = vitalsMatch ? vitalsMatch[1].trim() === "true" : void 0;
694
+ if (vitalsMatch && !vitals) {
695
+ throw new RoseError(
696
+ "E-EXPORT",
697
+ `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
698
+ { 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" }
699
+ );
258
700
  }
259
701
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
260
702
  const bundle = bundleMatch ? bundleMatch[1] : void 0;
261
703
  if (bundle && !["inline", "split"].includes(bundle)) {
262
- throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
704
+ throw new RoseError(
705
+ "E-EXPORT",
706
+ `${filePath}: export const bundle must be 'inline' or 'split'`,
707
+ { 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" }
708
+ );
263
709
  }
264
710
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
265
711
  const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
712
+ const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
713
+ const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
714
+ const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
715
+ const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
716
+ const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
266
717
  if (csr === false) {
267
718
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
268
719
  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.)`
720
+ const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
721
+ throw new RoseError(
722
+ "E-EXPORT",
723
+ `${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.)`,
724
+ {
725
+ file: filePath,
726
+ line: lineAt(deadSrc, dead),
727
+ 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'
728
+ }
271
729
  );
272
730
  }
273
731
  }
@@ -278,10 +736,18 @@ ${hoisted.rest}`, "ssr").trim()}`,
278
736
  try {
279
737
  value = new Function(`return ${headersLiteral}`)();
280
738
  } catch {
281
- throw new Error(`${filePath}: export const headers must be an object literal`);
739
+ throw new RoseError(
740
+ "E-EXPORT",
741
+ `${filePath}: export const headers must be an object literal`,
742
+ { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
743
+ );
282
744
  }
283
745
  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`);
746
+ throw new RoseError(
747
+ "E-EXPORT",
748
+ `${filePath}: export const headers must be a flat map of string -> string`,
749
+ { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
750
+ );
285
751
  }
286
752
  headers = value;
287
753
  }
@@ -292,11 +758,19 @@ ${hoisted.rest}`, "ssr").trim()}`,
292
758
  try {
293
759
  value = new Function(`return ${cspLiteral}`)();
294
760
  } catch {
295
- throw new Error(`${filePath}: export const csp must be an object literal`);
761
+ throw new RoseError(
762
+ "E-EXPORT",
763
+ `${filePath}: export const csp must be an object literal`,
764
+ { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
765
+ );
296
766
  }
297
767
  const nonce = value?.nonce;
298
768
  if (nonce !== void 0 && typeof nonce !== "boolean") {
299
- throw new Error(`${filePath}: csp.nonce must be a boolean`);
769
+ throw new RoseError(
770
+ "E-EXPORT",
771
+ `${filePath}: csp.nonce must be a boolean`,
772
+ { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
773
+ );
300
774
  }
301
775
  cspNonce = nonce === true;
302
776
  }
@@ -305,54 +779,39 @@ ${hoisted.rest}`, "ssr").trim()}`,
305
779
  const actionNames = new Set(actions.map((a) => a.name));
306
780
  const clientReasons = [];
307
781
  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)");
782
+ if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
783
+ clientReasons.push("a form bound to a client dispatch ($action)");
784
+ }
309
785
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
310
786
  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
787
  const needsClient = clientReasons.length > 0;
315
788
  const jsWarnings = [];
316
789
  if (!needsClient) {
317
- if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
790
+ const codeOnly = stripComments(source);
791
+ const scriptCodeOnly = stripComments(rawScript);
792
+ const scriptScannable = stripGuardedBranches(scriptCodeOnly);
793
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
318
794
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
319
795
  }
320
- if (/javascript:/i.test(source)) {
796
+ if (/javascript:/i.test(codeOnly)) {
321
797
  jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
322
798
  }
323
- if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
799
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
324
800
  jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
325
801
  }
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)) {
802
+ 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
803
  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
804
  }
329
805
  }
330
806
  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();
807
+ const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
808
+ const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
335
809
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
336
810
  const decls = extractDecls(script);
337
811
  const stateDecls = decls.filter((d) => d.kind === "state");
338
812
  const setterNames = /* @__PURE__ */ new Map();
339
813
  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) => {
814
+ const declCode = (d) => {
356
815
  const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
357
816
  if (d.kind === "state") {
358
817
  return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
@@ -362,15 +821,39 @@ ${hoisted.rest}`, "ssr").trim()}`,
362
821
  return `const __had_${d.name} = hasState(${JSON.stringify(key)});
363
822
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
364
823
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
365
- }).join("\n");
824
+ };
825
+ const nestedDecls = [];
826
+ let spliced = "";
827
+ let pos = 0;
828
+ decls.forEach((d, i) => {
829
+ const top = braceDepthAt(script, d.start) === 0;
830
+ if (!top) nestedDecls.push(d);
831
+ spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
832
+ pos = d.end;
833
+ });
834
+ spliced += script.slice(pos);
835
+ let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
836
+ const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
837
+ const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
838
+ return `${setter}(${val})`;
839
+ });
840
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
841
+ cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
842
+ const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
843
+ const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
844
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
845
+ const wired = wireEventBindings(templateCalled, actionNames);
846
+ const eventBindings = wired.bindings;
366
847
  const stateKeys = decls.map((d) => d.name);
367
848
  const comps = new Map(roseImports.map((r) => {
368
849
  const abs = path.resolve(path.dirname(filePath), r.specifier);
369
850
  const hit = registry.get(abs);
370
851
  return [r.name, { index: hit.index, slots: hit.slots }];
371
852
  }));
853
+ const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
854
+ assertKnownDirectives(ssrTemplate, filePath);
372
855
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
373
- const compiledHead = headContent.trim() ? compileTemplate(headContent, "__hd", "__hc", null, 0, false) : "";
856
+ const compiledHead = headContent.trim() ? compileHead(headContent) : "";
374
857
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
375
858
  const ssrExports = actions.length > 0 ? `${exportStmts}
376
859
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
@@ -385,8 +868,8 @@ ${ssrExports}
385
868
  ${ssrGuard}
386
869
 
387
870
  ${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);
871
+ ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
872
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
390
873
  return {
391
874
  ssr: rewriteRoseImports(ssr, "ssr"),
392
875
  client: rewriteRoseImports(client, "client"),
@@ -398,7 +881,11 @@ ${cleanScript}
398
881
  usesContext,
399
882
  revalidate,
400
883
  csr,
884
+ shell,
885
+ buffer,
886
+ controlSignal,
401
887
  prefetch,
888
+ vitals,
402
889
  bundle,
403
890
  needsClient,
404
891
  clientReasons,
@@ -633,31 +1120,236 @@ function extractDecls(script) {
633
1120
  }
634
1121
  return decls;
635
1122
  }
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;
1123
+ function braceDepthAt(src, index) {
1124
+ let depth = 0;
1125
+ let i = 0;
1126
+ while (i < index) {
1127
+ const ch = src[i];
1128
+ if (ch === "'" || ch === '"' || ch === "`") {
1129
+ const quote = ch;
1130
+ i++;
1131
+ while (i < index) {
1132
+ if (src[i] === "\\") {
1133
+ i += 2;
1134
+ continue;
1135
+ }
1136
+ if (src[i] === quote) {
1137
+ i++;
1138
+ break;
1139
+ }
1140
+ if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
1141
+ let d = 1;
1142
+ i += 2;
1143
+ while (i < index && d > 0) {
1144
+ if (src[i] === "{") d++;
1145
+ else if (src[i] === "}") d--;
1146
+ i++;
1147
+ }
1148
+ continue;
1149
+ }
1150
+ i++;
1151
+ }
1152
+ continue;
1153
+ }
1154
+ if (ch === "/" && src[i + 1] === "/") {
1155
+ const nl = src.indexOf("\n", i);
1156
+ i = nl === -1 ? src.length : nl;
1157
+ continue;
1158
+ }
1159
+ if (ch === "/" && src[i + 1] === "*") {
1160
+ const close = src.indexOf("*/", i + 2);
1161
+ i = close === -1 ? src.length : close + 2;
1162
+ continue;
1163
+ }
1164
+ if (ch === "{") depth++;
1165
+ else if (ch === "}") depth--;
1166
+ i++;
643
1167
  }
644
- out += text.slice(pos);
645
- return out;
1168
+ return depth;
646
1169
  }
647
1170
  function autoCall(expr) {
648
1171
  const e = expr.trim();
649
1172
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
650
1173
  }
1174
+ function findBlock(src, kind) {
1175
+ const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
1176
+ const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1177
+ let open;
1178
+ while (open = head.exec(src)) {
1179
+ const start = open.index;
1180
+ const afterOpen = start + open[0].length;
1181
+ let depth = 1;
1182
+ let i = afterOpen;
1183
+ for (; ; ) {
1184
+ head.lastIndex = i;
1185
+ closeRe.lastIndex = i;
1186
+ const nextOpen = head.exec(src);
1187
+ const nextClose = closeRe.exec(src);
1188
+ if (!nextClose) break;
1189
+ if (nextOpen && nextOpen.index < nextClose.index) {
1190
+ depth++;
1191
+ i = nextOpen.index + nextOpen[0].length;
1192
+ continue;
1193
+ }
1194
+ i = nextClose.index + nextClose[0].length;
1195
+ if (--depth === 0) {
1196
+ const content = src.slice(afterOpen, nextClose.index);
1197
+ const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
1198
+ const arr = [src.slice(start, i), ...groups];
1199
+ arr.index = start;
1200
+ return arr;
1201
+ }
1202
+ }
1203
+ head.lastIndex = afterOpen;
1204
+ }
1205
+ return null;
1206
+ }
1207
+ function compileHead(head) {
1208
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
1209
+ let out = "";
1210
+ let buf = "";
1211
+ let seg = 0;
1212
+ let i = 0;
1213
+ const flush = () => {
1214
+ if (buf.trim()) out += compileTemplate(buf, "__hd", "__hc", null, seg++, false);
1215
+ buf = "";
1216
+ };
1217
+ while (i < head.length) {
1218
+ if (head.startsWith("<!--", i)) {
1219
+ const end = head.indexOf("-->", i + 4);
1220
+ i = end < 0 ? head.length : end + 3;
1221
+ continue;
1222
+ }
1223
+ RAW_OPEN.lastIndex = i;
1224
+ const open = RAW_OPEN.exec(head);
1225
+ if (open) {
1226
+ const tag = open[1].toLowerCase();
1227
+ const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
1228
+ const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
1229
+ const end = gt < 0 ? head.length : gt + 1;
1230
+ flush();
1231
+ out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
1232
+ i = end;
1233
+ continue;
1234
+ }
1235
+ buf += head[i++];
1236
+ }
1237
+ flush();
1238
+ return out;
1239
+ }
1240
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
1241
+ function assertKnownDirectives(template, filePath) {
1242
+ const rawRanges = [];
1243
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
1244
+ let raw;
1245
+ while (raw = RAW_OPEN.exec(template)) {
1246
+ const tag = raw[1].toLowerCase();
1247
+ const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
1248
+ const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
1249
+ const end = gt < 0 ? template.length : gt + 1;
1250
+ rawRanges.push([raw.index, end]);
1251
+ RAW_OPEN.lastIndex = end;
1252
+ }
1253
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
1254
+ let note;
1255
+ while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
1256
+ rawRanges.sort((a, b) => a[0] - b[0]);
1257
+ const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
1258
+ const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
1259
+ let m;
1260
+ while (m = DIRECTIVE_RE.exec(template)) {
1261
+ if (inRaw(m.index)) continue;
1262
+ const [, sigil, word] = m;
1263
+ if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
1264
+ if (sigil === "/") {
1265
+ throw new RoseError(
1266
+ "E-TEMPLATE",
1267
+ `${filePath}: {/${word}} does not close anything`,
1268
+ { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
1269
+ );
1270
+ }
1271
+ if (word === "else") {
1272
+ throw new RoseError(
1273
+ "E-TEMPLATE",
1274
+ `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1275
+ { 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" }
1276
+ );
1277
+ }
1278
+ throw new RoseError(
1279
+ "E-TEMPLATE",
1280
+ `${filePath}: {:${word}} is not a rosetack directive`,
1281
+ { 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" }
1282
+ );
1283
+ }
1284
+ const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
1285
+ while (m = OPENER_RE.exec(template)) {
1286
+ if (inRaw(m.index)) continue;
1287
+ const [, kind, head] = m;
1288
+ if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
1289
+ throw new RoseError(
1290
+ "E-TEMPLATE",
1291
+ `${filePath}: {#each ${head.trim()}} is missing its item name`,
1292
+ { 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)" }
1293
+ );
1294
+ }
1295
+ const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
1296
+ const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
1297
+ let depth = 1;
1298
+ let i = m.index + m[0].length;
1299
+ for (; ; ) {
1300
+ OPEN_RE.lastIndex = i;
1301
+ CLOSE_RE.lastIndex = i;
1302
+ const nextOpen = OPEN_RE.exec(template);
1303
+ const nextClose = CLOSE_RE.exec(template);
1304
+ if (!nextClose) break;
1305
+ if (nextOpen && nextOpen.index < nextClose.index) {
1306
+ i = nextOpen.index + nextOpen[0].length;
1307
+ continue;
1308
+ }
1309
+ i = nextClose.index + nextClose[0].length;
1310
+ if (--depth === 0) break;
1311
+ }
1312
+ if (depth !== 0) {
1313
+ throw new RoseError(
1314
+ "E-TEMPLATE",
1315
+ `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
1316
+ { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
1317
+ );
1318
+ }
1319
+ }
1320
+ }
1321
+ function rewriteQuotedExprAttrs(template, comps) {
1322
+ const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
1323
+ return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
1324
+ if (comps.has(name) || !/\{/.test(attrs)) return tag;
1325
+ const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
1326
+ if (!/\{/.test(value) || value.includes("`")) return whole;
1327
+ const spans = templateExprSpans(value);
1328
+ if (spans.length === 0) return whole;
1329
+ let expr = "";
1330
+ let last = 0;
1331
+ for (const s of spans) {
1332
+ if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
1333
+ expr += (expr ? " + " : "") + `(${s.expr})`;
1334
+ last = s.end + 1;
1335
+ }
1336
+ if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
1337
+ return `${attr}={${expr}}`;
1338
+ });
1339
+ return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
1340
+ });
1341
+ }
651
1342
  function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
652
1343
  let result = "";
653
1344
  let remaining = template;
654
1345
  let blockId = 0;
655
1346
  const nextId = () => `${depth}_${blockId++}`;
656
1347
  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(/\{([^{}]+)\}/);
1348
+ const ifMatch = findBlock(remaining, "if");
1349
+ const eachMatch = findBlock(remaining, "each");
1350
+ const boundaryMatch = findBlock(remaining, "boundary");
1351
+ const firstExpr = templateExprSpans(remaining)[0];
1352
+ const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
661
1353
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
662
1354
  const candidates = [];
663
1355
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
@@ -666,6 +1358,25 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
666
1358
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
667
1359
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
668
1360
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
1361
+ const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
1362
+ const rawHit = rawOpenRe.exec(remaining);
1363
+ if (rawHit && earliest && rawHit.index < earliest.index) {
1364
+ const tag = rawHit[1].toLowerCase();
1365
+ const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
1366
+ const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
1367
+ const end = gt < 0 ? remaining.length : gt + 1;
1368
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1369
+ remaining = remaining.substring(end);
1370
+ continue;
1371
+ }
1372
+ const noteAt = remaining.indexOf("<!--");
1373
+ if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
1374
+ const noteEnd = remaining.indexOf("-->", noteAt + 4);
1375
+ const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
1376
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1377
+ remaining = remaining.substring(end);
1378
+ continue;
1379
+ }
669
1380
  if (!earliest) {
670
1381
  result += emitChunk(remaining, acc, closes, scope);
671
1382
  break;
@@ -695,7 +1406,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
695
1406
  const call = autoCall(items);
696
1407
  const id = nextId();
697
1408
  const itemRe = new RegExp(`\\b${item}\\b`, "g");
698
- const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(itemRe, "__s")}}`);
1409
+ let scoped = "";
1410
+ let lastSpan = 0;
1411
+ for (const s of templateExprSpans(content.trim())) {
1412
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
1413
+ lastSpan = s.end + 1;
1414
+ }
1415
+ scoped += content.trim().slice(lastSpan);
699
1416
  const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
700
1417
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
701
1418
  `;
@@ -735,7 +1452,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
735
1452
  rest = remaining.substring(tag.end);
736
1453
  } else {
737
1454
  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`);
1455
+ 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
1456
  childrenSrc = remaining.substring(tag.end, closeIdx);
740
1457
  rest = remaining.substring(closeIdx + tag.name.length + 3);
741
1458
  }
@@ -749,7 +1466,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
749
1466
  const decl = entry.slots.find((s) => s.name === nm);
750
1467
  let content = src;
751
1468
  for (const p of decl?.props ?? []) {
752
- content = content.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(new RegExp(`\\b${p}\\b`, "g"), `__s.${p}`)}}`);
1469
+ const pRe = new RegExp(`\\b${p}\\b`, "g");
1470
+ let out = "";
1471
+ let lastSpan = 0;
1472
+ for (const s of templateExprSpans(content)) {
1473
+ out += content.slice(lastSpan, s.start) + "{" + s.expr.replace(pRe, `__s.${p}`) + "}";
1474
+ lastSpan = s.end + 1;
1475
+ }
1476
+ content = out + content.slice(lastSpan);
753
1477
  }
754
1478
  return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
755
1479
  });
@@ -780,6 +1504,21 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
780
1504
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
781
1505
  continue;
782
1506
  }
1507
+ const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
1508
+ if (rawMatch) {
1509
+ if (before) result += emitChunk(before, acc, closes, scope);
1510
+ const expr2 = rawMatch[1].trim();
1511
+ if (!markers) {
1512
+ result += `${acc} += String(${expr2} ?? '');
1513
+ `;
1514
+ } else {
1515
+ const fn = scope ? `(${scope}) => (${expr2})` : `() => (${expr2})`;
1516
+ result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ""});
1517
+ `;
1518
+ }
1519
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1520
+ continue;
1521
+ }
783
1522
  const attrMatch = before.match(/([\w-]+)=\s*$/);
784
1523
  if (attrMatch) {
785
1524
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -891,7 +1630,7 @@ function rejectNestedSlot(src, outer) {
891
1630
  if (end < 0) return;
892
1631
  const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
893
1632
  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`);
1633
+ 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
1634
  }
896
1635
  i = end;
897
1636
  }
@@ -945,7 +1684,7 @@ function splitSlots(src) {
945
1684
  if (!selfClosing && !isVoid) elemDepth++;
946
1685
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
947
1686
  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`);
1687
+ 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
1688
  }
950
1689
  if (slotName) {
951
1690
  const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
@@ -953,7 +1692,7 @@ function splitSlots(src) {
953
1692
  named.set(slotName, (named.get(slotName) ?? "") + stripped);
954
1693
  } else {
955
1694
  const closeIdx = findClose(src, end, nm[2]);
956
- if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
1695
+ 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
1696
  const tail = `</${nm[2]}>`;
958
1697
  const inner = src.slice(end, closeIdx);
959
1698
  rejectNestedSlot(inner, slotName);
@@ -1029,7 +1768,8 @@ function compileSlot(acc) {
1029
1768
  return `${acc} += String(children);
1030
1769
  `;
1031
1770
  }
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';`;
1771
+ 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';`;
1772
+ var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1033
1773
  function propsCode(props) {
1034
1774
  if (props.length === 0) return "";
1035
1775
  return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
@@ -1041,20 +1781,13 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1041
1781
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1042
1782
  return { o, fn };
1043
1783
  };
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 = "") {
1784
+ const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
1785
+ function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1055
1786
  const headCode = headFn ? `
1056
1787
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1057
1788
  __html += headMark(closes, __head);` : "";
1789
+ const actionState = hasActions ? `
1790
+ const $setState = (key, value) => setState(key, value);` : "";
1058
1791
  return `
1059
1792
  ${RUNTIME_IMPORTS}
1060
1793
 
@@ -1062,6 +1795,7 @@ ${imports}
1062
1795
 
1063
1796
  ${exports}
1064
1797
  ${guard}
1798
+ ${actionState}
1065
1799
 
1066
1800
  ${namedSlots ? SLOT_HELPER : ""}
1067
1801
 
@@ -1069,20 +1803,20 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1069
1803
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1070
1804
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1071
1805
  ${propsCode(props)}
1806
+ ${script}
1072
1807
  ${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).
1808
+ ${dataDeclsCode}
1809
+
1076
1810
  ${isComponent ? "" : "applyStateDeltas();"}
1077
- ${script}
1078
1811
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1079
1812
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1080
1813
  return __html;
1081
1814
  }
1082
1815
  `;
1083
1816
  }
1084
- function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
1817
+ function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1085
1818
  const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1819
+ const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
1086
1820
  const headCode = headFn ? `
1087
1821
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1088
1822
  __html += headMark(closes, __head);` : "";
@@ -1092,15 +1826,18 @@ ${RUNTIME_IMPORTS}
1092
1826
  ${imports}
1093
1827
 
1094
1828
  ${exports}
1095
-
1829
+ ${clientSetState ? `
1830
+ ${clientSetState}
1831
+ ` : ""}
1096
1832
  ${namedSlots ? SLOT_HELPER : ""}
1097
1833
 
1098
1834
  export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1099
1835
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1100
1836
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1101
1837
  ${propsCode(props)}
1102
- ${stateDeclsCode}
1103
1838
  ${script}
1839
+ ${stateDeclsCode}
1840
+ ${dataDeclsCode}
1104
1841
  ${handlerRegistry}
1105
1842
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1106
1843
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
@@ -1114,6 +1851,7 @@ var routeShipsNoJs = (infos, compiled, i) => {
1114
1851
  if (compiled[i].needsClient) return false;
1115
1852
  return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1116
1853
  };
1854
+ var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
1117
1855
  function buildReport(infos, compiled) {
1118
1856
  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
1857
  if (routeShipsNoJs(infos, compiled, i)) {
@@ -1124,6 +1862,48 @@ function buildReport(infos, compiled) {
1124
1862
  return `${info.routePath} client JS ${why}${forced}`;
1125
1863
  });
1126
1864
  }
1865
+ var MOUNT_ENTRY = `
1866
+ import { start, postForm } from '/client.js';
1867
+
1868
+ for (const el of document.querySelectorAll('[data-rosetack]')) {
1869
+ const route = el.getAttribute('data-rosetack');
1870
+ const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
1871
+ const parsed = new DOMParser().parseFromString(doc, 'text/html');
1872
+ // A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
1873
+ const app = parsed.getElementById('app');
1874
+ if (app) {
1875
+ el.innerHTML = app.innerHTML;
1876
+ } else {
1877
+ for (const node of Array.from(parsed.body.children)) {
1878
+ if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
1879
+ }
1880
+ }
1881
+ // start() resumes from #__rosetack_state (zero hydration), so the state
1882
+
1883
+ const state = parsed.getElementById('__rosetack_state');
1884
+ if (state) el.appendChild(state);
1885
+
1886
+ const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
1887
+ await start(el, route, rendered === route);
1888
+ if (state) state.remove();
1889
+
1890
+ el.addEventListener('click', (e) => {
1891
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
1892
+ if (!a || !el.contains(a)) return;
1893
+ e.preventDefault();
1894
+ el.setAttribute('data-rosetack', a.getAttribute('href'));
1895
+ start(el, a.getAttribute('href'), false);
1896
+ });
1897
+ // Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
1898
+ el.addEventListener('submit', (e) => {
1899
+ const f = e.target;
1900
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
1901
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
1902
+ e.preventDefault();
1903
+ postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
1904
+ });
1905
+ }
1906
+ `;
1127
1907
  async function buildProject(root, outDir) {
1128
1908
  await fs.promises.mkdir(outDir, { recursive: true });
1129
1909
  const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
@@ -1132,7 +1912,11 @@ async function buildProject(root, outDir) {
1132
1912
  const compFiles = await scanComponentFiles(root);
1133
1913
  const files = [...pageFiles, ...compFiles];
1134
1914
  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>`);
1915
+ throw new RoseError(
1916
+ "E-ROUTE",
1917
+ `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1918
+ { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1919
+ );
1136
1920
  }
1137
1921
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1138
1922
  const config = await loadConfig(root);
@@ -1221,9 +2005,7 @@ async function buildProject(root, outDir) {
1221
2005
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1222
2006
  if (runtimePlugins.length > 0) {
1223
2007
  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.
2008
+ await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
1227
2009
  import config from ${JSON.stringify(configRel)};
1228
2010
 
1229
2011
  const list = Array.isArray(config) ? config : [];
@@ -1236,7 +2018,7 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1236
2018
  `);
1237
2019
  }
1238
2020
  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");
2021
+ 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
2022
  await esbuild.build({
1241
2023
  entryPoints: [runtimeEntry],
1242
2024
  bundle: true,
@@ -1252,8 +2034,34 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1252
2034
  await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1253
2035
  }
1254
2036
  }
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);
2037
+ 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) => {
2038
+ const rank = (pattern) => {
2039
+ const segs = pattern.split("/");
2040
+ return [
2041
+ segs.filter((s) => s.startsWith("**")).length,
2042
+ segs.filter((s) => s.startsWith("*")).length,
2043
+ segs.filter((s) => s.startsWith(":")).length
2044
+ ];
2045
+ };
2046
+ const ra = rank(a.info.pattern);
2047
+ const rb = rank(b.info.pattern);
2048
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2049
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2050
+ });
2051
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
2052
+ const rank = (pattern) => {
2053
+ const segs = pattern.split("/");
2054
+ return [
2055
+ segs.filter((s) => s.startsWith("**")).length,
2056
+ segs.filter((s) => s.startsWith("*")).length,
2057
+ segs.filter((s) => s.startsWith(":")).length
2058
+ ];
2059
+ };
2060
+ const ra = rank(a.info.pattern);
2061
+ const rb = rank(b.info.pattern);
2062
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2063
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2064
+ });
1257
2065
  const compose = (idx) => {
1258
2066
  let expr = `render_${idx}`;
1259
2067
  for (const i of layoutsOf(infos, idx)) {
@@ -1284,33 +2092,48 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1284
2092
  const named = [actionImports, guardImport].filter(Boolean).join(", ");
1285
2093
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1286
2094
  }).join("\n");
1287
- const nfIdx = infos.findIndex((info) => info.isNotFound);
1288
- const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
2095
+ const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
2096
+ const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
2097
+ const dir = path.posix.dirname(rel);
2098
+ const prefix = dir === "." ? "/" : "/" + dir;
2099
+ const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
2100
+ return { prefix, render: split ? loaderOf(i) : compose(i), flags };
2101
+ }).sort((a, b) => b.prefix.length - a.prefix.length);
2102
+ const notFoundTable = `[
2103
+ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
2104
+ ]`;
1289
2105
  const errIdx = infos.findIndex((info) => info.isError);
1290
2106
  const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
1291
2107
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
1292
2108
  const serverRoutes = pages.map(({ info, i }) => {
1293
2109
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
1294
2110
  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(" + ")}).`
2111
+ throw new RoseError(
2112
+ "E-EXPORT",
2113
+ `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`,
2114
+ { file: info.filePath, hint: "remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above" }
1297
2115
  );
1298
2116
  }
1299
2117
  if (compiled[i].csr === false) {
1300
2118
  const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1301
2119
  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).`
2120
+ throw new RoseError(
2121
+ "E-EXPORT",
2122
+ `${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).`,
2123
+ { 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
2124
  );
1305
2125
  }
1306
2126
  }
1307
2127
  const csrFlag = routeNoJs(i) ? ", csr: false" : "";
2128
+ const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
2129
+ const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
2130
+ const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
1308
2131
  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} }`;
2132
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
1310
2133
  }).join(",\n ");
1311
2134
  const serverEntry = `
1312
2135
  ${serverImports}
1313
- import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
2136
+ import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1314
2137
  ${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
2138
  // module to import - the runners below stay no-ops and the servers call them
1316
2139
  // unconditionally (one code path, no flags to keep in sync).
@@ -1318,12 +2141,7 @@ const __pluginHooks = [];
1318
2141
  const __hasRequestHooks = false;
1319
2142
  const __hasResponseHooks = false;`}
1320
2143
 
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).
2144
+
1327
2145
  export async function runRequestHooks(ctx) {
1328
2146
  for (const p of __pluginHooks) {
1329
2147
  if (!p.onRequest) continue;
@@ -1351,22 +2169,20 @@ export async function runResponseHooks(ctx, res) {
1351
2169
  return out;
1352
2170
  }
1353
2171
 
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.
2172
+
2173
+
1356
2174
  export const hasRequestHooks = __hasRequestHooks;
1357
2175
  export const hasResponseHooks = __hasResponseHooks;
1358
2176
 
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.
2177
+ // P0-1: the query of the request being rendered, for $query().
2178
+ export function setQuery(query) {
2179
+ setRequestQuery(query || {});
2180
+ }
2181
+
2182
+
1362
2183
  setLocales(${localesJson}, '${defaultLocale}');
1363
2184
 
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.
2185
+
1370
2186
  if (typeof process !== 'undefined' && typeof process.send === 'function') {
1371
2187
  setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1372
2188
  process.on('message', (msg) => {
@@ -1374,74 +2190,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1374
2190
  });
1375
2191
  }
1376
2192
 
2193
+ // (the cross-machine seam): the cluster relay above covers ONE machine.
2194
+ export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
2195
+ setStoreTransport(send);
2196
+ }
2197
+ export function __deliverStorePatch(name: string, value: unknown): void {
2198
+ applyStorePatch(name, value);
2199
+ }
2200
+
1377
2201
  export { localeList };
1378
2202
  export const defaultLocale = '${defaultLocale}';
1379
2203
 
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).
2204
+ // Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
1386
2205
  ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1387
2206
 
1388
2207
  export const routeParams = {
1389
2208
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1390
2209
  };
1391
2210
 
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.
2211
+ // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
1398
2212
  export const dynamicRoutes = [
1399
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
2213
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1400
2214
  ];
1401
2215
 
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.
2216
+ // Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
1405
2217
  ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1406
2218
 
1407
2219
  export const apiPrerender = {
1408
2220
  ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1409
2221
  };
1410
2222
 
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.
2223
+
1420
2224
  export const revalidate = [
1421
2225
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1422
2226
  ];
1423
2227
 
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.
2228
+ // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
1430
2229
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1431
2230
 
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).
2231
+ // Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
1445
2232
  export const noJsRoutes = [
1446
2233
  ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1447
2234
  ];
@@ -1450,11 +2237,12 @@ export function isNoJs(pathname) {
1450
2237
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1451
2238
  }
1452
2239
 
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.
2240
+ // P0-2 (bug report): routes that exported "buffer = true".
2241
+ export function isBuffered(pathname) {
2242
+ return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
2243
+ }
2244
+
2245
+
1458
2246
  export const routeHeaders = [
1459
2247
  ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1460
2248
  ];
@@ -1464,14 +2252,7 @@ export function headersFor(pathname) {
1464
2252
  return hit ? hit.headers : null;
1465
2253
  }
1466
2254
 
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.
2255
+
1475
2256
  export const cspNonceRoutes = [
1476
2257
  ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1477
2258
  ];
@@ -1480,9 +2261,7 @@ export function cspNonce(pathname) {
1480
2261
  return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1481
2262
  }
1482
2263
 
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).
2264
+ // A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
1486
2265
  function toWebRequest(raw, form) {
1487
2266
  if (raw instanceof Request) return raw;
1488
2267
  const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
@@ -1490,13 +2269,7 @@ function toWebRequest(raw, form) {
1490
2269
  return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1491
2270
  }
1492
2271
 
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.
2272
+
1500
2273
  export async function runMiddleware(rawReq, form) {
1501
2274
  resetRequestContext();
1502
2275
  if (!middleware || !rawReq) return null;
@@ -1508,10 +2281,7 @@ const routes = [
1508
2281
  ${serverRoutes}
1509
2282
  ];
1510
2283
 
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.
2284
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
1515
2285
  const apiRoutes = [
1516
2286
  ${apiRoutes.map(({ info, i }) => {
1517
2287
  const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -1519,19 +2289,40 @@ const apiRoutes = [
1519
2289
  }).join(",\n ")}
1520
2290
  ];
1521
2291
 
1522
- // pages/404.rose (with its layouts) or null -> built-in plain 404
1523
- const notFound = ${notFoundRender};
2292
+ // Not-found pages, deepest segment first: the root 404.rose ('/') and any
2293
+ // pages/<seg>/_notfound.rose, each already composed with its layout chain.
2294
+ // notFoundFor picks the nearest one up the path - an /admin miss answers
2295
+ // the admin 404, a public miss the site's - and notFoundPage is the whole
2296
+ // answer (real 404 status, or the built-in plain 404 when the app has none).
2297
+ const notFoundRoutes = ${notFoundTable};
2298
+ const notFoundFor = (pathname) => {
2299
+ for (const [prefix, render] of notFoundRoutes) {
2300
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2301
+ }
2302
+ return null;
2303
+ };
2304
+
2305
+ const notFoundFlags = (pathname) => {
2306
+ for (const [prefix, render, flags] of notFoundRoutes) {
2307
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
2308
+ }
2309
+ return null;
2310
+ };
2311
+ const notFoundPage = async (pathname) => {
2312
+ const nf = notFoundFor(pathname);
2313
+ if (nf) {
2314
+ const page = await renderFallback(pathname, nf);
2315
+ // __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
2316
+ return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
2317
+ }
2318
+ return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
2319
+ };
2320
+
1524
2321
 
1525
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1526
2322
  // whose render throws degrades to this instead of failing the response.
1527
2323
  const errorPage = ${errorRender};
1528
2324
 
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.
2325
+
1535
2326
  export function docAttrs(pathname) {
1536
2327
  for (const route of routes) {
1537
2328
  if (!matchRoute(route.pattern, pathname)) continue;
@@ -1541,7 +2332,7 @@ export function docAttrs(pathname) {
1541
2332
  const lang = pathname.split('/')[langIdx];
1542
2333
  if (isLocale(lang)) return { lang, dir: localeDir(lang) };
1543
2334
  }
1544
- break; // matched, but not a localized route (or a bogus locale): the default
2335
+ break;
1545
2336
  }
1546
2337
  return { lang: defaultLocale, dir: localeDir(defaultLocale) };
1547
2338
  }
@@ -1554,8 +2345,22 @@ async function renderFallback(pathname, render) {
1554
2345
  }
1555
2346
 
1556
2347
  export function matchRoute(pattern, pathname) {
2348
+ // Q0 (bug report): one canonical URL per route.
2349
+ pathname = pathname.replace(/\\/+$/, '') || '/';
1557
2350
  const patternParts = pattern.split('/');
1558
2351
  const pathParts = pathname.split('/');
2352
+
2353
+ const last = patternParts[patternParts.length - 1];
2354
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2355
+ const fixed = patternParts.slice(0, -1);
2356
+ if (pathParts.length < fixed.length) return false;
2357
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2358
+ for (let i = 0; i < fixed.length; i++) {
2359
+ if (fixed[i].startsWith(':')) continue;
2360
+ if (fixed[i] !== pathParts[i]) return false;
2361
+ }
2362
+ return true;
2363
+ }
1559
2364
  if (patternParts.length !== pathParts.length) return false;
1560
2365
  for (let i = 0; i < patternParts.length; i++) {
1561
2366
  if (patternParts[i].startsWith(':')) continue;
@@ -1564,13 +2369,7 @@ export function matchRoute(pattern, pathname) {
1564
2369
  return true;
1565
2370
  }
1566
2371
 
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.
2372
+ // Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
1574
2373
  function extractHead(rendered) {
1575
2374
  const head = [];
1576
2375
  const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
@@ -1580,18 +2379,7 @@ function extractHead(rendered) {
1580
2379
  return { html, head };
1581
2380
  }
1582
2381
 
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.
2382
+ // Form: the submitted FormData of a progressive-enhancement POST.
1595
2383
  export async function renderPage(pathname, form) {
1596
2384
  clearRequestState();
1597
2385
  for (const route of routes) {
@@ -1599,31 +2387,21 @@ export async function renderPage(pathname, form) {
1599
2387
  const patternParts = route.pattern.split('/');
1600
2388
  const pathParts = pathname.split('/');
1601
2389
  for (let i = 0; i < patternParts.length; i++) {
1602
- if (patternParts[i].startsWith(':')) {
1603
- setState(patternParts[i].slice(1), pathParts[i]);
1604
- }
2390
+ const seg = patternParts[i];
2391
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2392
+
2393
+
2394
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
1605
2395
  }
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
2396
+ // I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
1609
2397
  const langIdx = patternParts.indexOf(':lang');
1610
2398
  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) };
2399
+ return await notFoundPage(pathname);
1613
2400
  }
1614
- // The document's <html lang>/<dir> follow this route's locale
1615
- // (the default's when the route is not localized)
2401
+
2402
+
1616
2403
  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.
2404
+ // The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
1627
2405
  let actionStatus = 0;
1628
2406
  if (form && route.actions) {
1629
2407
  const actionName = form.get('__action') || 'action';
@@ -1635,9 +2413,7 @@ export async function renderPage(pathname, form) {
1635
2413
  if (patch && typeof patch === 'object') {
1636
2414
  for (const key of Object.keys(patch)) {
1637
2415
  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.
2416
+ // An incremental patch is RECORDED, not applied: the render's own state declarations apply.
1641
2417
  if (v instanceof StateDelta) setStateDelta(key, v);
1642
2418
  else setState(key, v);
1643
2419
  }
@@ -1646,6 +2422,11 @@ export async function renderPage(pathname, form) {
1646
2422
  if (err instanceof ActionError) {
1647
2423
  setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
1648
2424
  actionStatus = err.code;
2425
+ } else if (err && err.__rosetack === 'redirect') {
2426
+
2427
+ return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
2428
+ } else if (err && err.__rosetack === 'notFound') {
2429
+ return await notFoundPage(pathname);
1649
2430
  } else {
1650
2431
  throw err;
1651
2432
  }
@@ -1656,32 +2437,27 @@ export async function renderPage(pathname, form) {
1656
2437
  try {
1657
2438
  rendered = extractHead(await route.render([], ''));
1658
2439
  } catch (err) {
2440
+ // The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
2441
+ const signal = err && err.__rosetack;
2442
+ if (signal === 'redirect') {
2443
+ return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
2444
+ }
2445
+ if (signal === 'notFound') {
2446
+ return await notFoundPage(pathname);
2447
+ }
1659
2448
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1660
2449
  if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
1661
2450
  return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
1662
2451
  }
1663
2452
  // __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
2453
  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) };
2454
+ // 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) .
2455
+ 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
2456
  }
1680
2457
  }
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) };
2458
+
2459
+
2460
+ return await notFoundPage(pathname);
1685
2461
  }
1686
2462
 
1687
2463
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -1689,21 +2465,20 @@ export async function renderPage(pathname, form) {
1689
2465
  export function canStream(pathname) {
1690
2466
  return routes.some((route) => {
1691
2467
  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
2468
+ // I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
1695
2469
  const langIdx = route.pattern.split('/').indexOf(':lang');
1696
2470
  return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
1697
2471
  });
1698
2472
  }
1699
2473
 
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.
2474
+
2475
+ export function shellOff(pathname) {
2476
+ return routes.some(
2477
+ (route) => route.shell === false && matchRoute(route.pattern, pathname),
2478
+ );
2479
+ }
2480
+
2481
+ // === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
1707
2482
  export function isApi(pathname) {
1708
2483
  return pathname === '/api' || pathname.startsWith('/api/');
1709
2484
  }
@@ -1727,7 +2502,25 @@ export async function handleApi(method, pathname, request) {
1727
2502
  headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
1728
2503
  });
1729
2504
  }
1730
- return toResponse(await fn(request));
2505
+ try {
2506
+ return toResponse(await fn(request));
2507
+ } catch (err) {
2508
+
2509
+ const signal = err && err.__rosetack;
2510
+ if (signal === 'redirect') {
2511
+ return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
2512
+ status: err.status ?? 307,
2513
+ headers: { 'content-type': 'application/json', location: err.path },
2514
+ });
2515
+ }
2516
+ if (signal === 'notFound') {
2517
+ return new Response(JSON.stringify({ error: 'not found' }), {
2518
+ status: 404,
2519
+ headers: { 'content-type': 'application/json' },
2520
+ });
2521
+ }
2522
+ throw err;
2523
+ }
1731
2524
  }
1732
2525
  }
1733
2526
  return new Response(JSON.stringify({ error: 'not found' }), {
@@ -1736,18 +2529,7 @@ export async function handleApi(method, pathname, request) {
1736
2529
  });
1737
2530
  }
1738
2531
 
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).
2532
+ // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
1751
2533
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1752
2534
  clearRequestState();
1753
2535
  for (const route of routes) {
@@ -1755,9 +2537,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1755
2537
  const patternParts = route.pattern.split('/');
1756
2538
  const pathParts = pathname.split('/');
1757
2539
  for (let i = 0; i < patternParts.length; i++) {
1758
- if (patternParts[i].startsWith(':')) {
1759
- setState(patternParts[i].slice(1), pathParts[i]);
1760
- }
2540
+ const seg = patternParts[i];
2541
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2542
+
2543
+
2544
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
1761
2545
  }
1762
2546
  // i18n: an unknown locale must 404 BEFORE the shell flushes - a
1763
2547
  // streamed response cannot change its status afterwards
@@ -1768,23 +2552,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1768
2552
  try {
1769
2553
  html = extractHead(await route.render([], '')).html;
1770
2554
  } 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)
2555
+
1774
2556
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1775
2557
  html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
1776
2558
  }
1777
2559
  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.)
2560
+ // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
1782
2561
  if (route.csr === false) {
1783
2562
  write('</div>\\n</body>\\n</html>');
1784
2563
  return 200;
1785
2564
  }
1786
2565
  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>');
2566
+ // P1-6 (bug report): the JSON data block is embedded in the document.
2567
+ const stateSafe = state.replace(/</g, '\\\\u003c');
2568
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
1788
2569
  return 200;
1789
2570
  }
1790
2571
  }
@@ -1804,55 +2585,54 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1804
2585
  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
2586
  const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
1806
2587
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
2588
+ const vitalsOn = compiled.some((c) => c.vitals === true);
2589
+ const vitalsBlock = vitalsOn ? `
2590
+ // the app asked for web-vitals - measure once, at boot, and let the
2591
+ // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2592
+ reportVitals();
2593
+ ` : "";
1807
2594
  const hasLang = infos.some((i) => i.pattern.includes(":lang"));
1808
2595
  const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
1809
2596
  // client-side navigation cannot leave stale (screen readers and CSS
1810
2597
  // logical properties both read it). A route with no [lang] segment
1811
2598
  // returns to the default locale, and a bogus segment falls back to it
1812
2599
  // too, exactly like the server's docAttrs.
2600
+ // Only when this container IS the document's app root. A mount
2601
+ // (dist/mount.js) renders into a foreign page, whose language and
2602
+ // direction belong to the host, not to the mounted route.
1813
2603
  const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
1814
2604
  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');
2605
+ if (container === document.getElementById('app')) {
2606
+ const docLang = known && seg ? seg : __defLocale;
2607
+ document.documentElement.lang = docLang;
2608
+ const docDir = localeDir(docLang);
2609
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
2610
+ else document.documentElement.removeAttribute('dir');
2611
+ }
1820
2612
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
1821
2613
  const clientEntry = `
1822
2614
  ${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.
2615
+ 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';
2616
+
2617
+ // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
1833
2618
  setLocales(${clientLocalesJson}, '${defaultLocale}');
1834
2619
  setLocalePacks(${JSON.stringify(packed)});
1835
2620
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
1836
2621
  // follow a route that carries no [lang] segment (a non-i18n page)
1837
2622
  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.
2623
+ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2624
+ // reportVitals alive through minification and tree-shaking; the call is one
2625
+ // statement at boot, before the first render.
2626
+ import { reportVitals } from './runtime.js';` : ""}
2627
+ // 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
2628
  export { ensureLocale, loadLocale } from './runtime.js';
2629
+ ${vitalsBlock}
1843
2630
 
1844
2631
  const routes = [
1845
2632
  ${clientRoutes}
1846
2633
  ];
1847
2634
 
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.
2635
+ // === 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
2636
  const loadChain = async (loaders) => {
1857
2637
  const mods = await Promise.all(loaders.map((load) => load()));
1858
2638
  let expr = (closes, children) => mods[0].render(closes, children);
@@ -1868,36 +2648,62 @@ const getRender = async (route) => {
1868
2648
  return (route.render ??= (await route.load()).render);
1869
2649
  };
1870
2650
 
1871
- // pages/404.rose (with its layouts) or null -> built-in plain 404
1872
- const notFound = ${notFoundRender};
2651
+ // Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
2652
+ const notFoundRoutes = ${notFoundTable};
2653
+ const notFoundFor = (pathname) => {
2654
+ for (const [prefix, render] of notFoundRoutes) {
2655
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2656
+ }
2657
+ return null;
2658
+ };
1873
2659
 
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.
2660
+ // 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
2661
  const errorPage = ${errorRender};
1878
2662
 
1879
2663
  // Paint a fallback page (404/500) into the container, wired like any render.
1880
- async function paintFallback(container, page, builtin) {
1881
- resetEffects();
1882
- clearRequestState();
2664
+ async function paintFallback(container, page, builtin, keepState = false) {
2665
+ if (!keepState) __navReset(container);
1883
2666
  clearMounts(); // a failed render leaves stale mounts behind
1884
2667
  // inline mode passes the render itself; split mode passes a loader
1885
2668
  const render = page ? await getRender(page) : null;
1886
2669
  if (render) {
1887
2670
  const closes = [];
1888
- const html = await render(closes, '');
1889
- container.innerHTML = html;
1890
- wire(container, closes);
1891
- bindEvents(container);
1892
- flushMounts();
2671
+ await __withOwner(container, async () => {
2672
+ const html = await render(closes, '');
2673
+ container.innerHTML = html;
2674
+ wire(container, closes);
2675
+ bindEvents(container);
2676
+ flushMounts();
2677
+ });
1893
2678
  return;
1894
2679
  }
1895
2680
  container.innerHTML = builtin;
1896
2681
  }
1897
2682
 
2683
+
2684
+ export async function startNotFound(container, pathname) {
2685
+ const el = document.getElementById('__rosetack_state');
2686
+ if (el) resumeState(el.textContent);
2687
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
2688
+ }
2689
+
1898
2690
  export function matchRoute(pattern, pathname) {
2691
+ // Q0 (bug report): one canonical URL per route.
2692
+ pathname = pathname.replace(/\\/+$/, '') || '/';
1899
2693
  const patternParts = pattern.split('/');
1900
2694
  const pathParts = pathname.split('/');
2695
+
2696
+ const last = patternParts[patternParts.length - 1];
2697
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2698
+ const fixed = patternParts.slice(0, -1);
2699
+ if (pathParts.length < fixed.length) return false;
2700
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2701
+ for (let i = 0; i < fixed.length; i++) {
2702
+ if (fixed[i].startsWith(':')) continue;
2703
+ if (fixed[i] !== pathParts[i]) return false;
2704
+ }
2705
+ return true;
2706
+ }
1901
2707
  if (patternParts.length !== pathParts.length) return false;
1902
2708
  for (let i = 0; i < patternParts.length; i++) {
1903
2709
  if (patternParts[i].startsWith(':')) continue;
@@ -1906,78 +2712,64 @@ export function matchRoute(pattern, pathname) {
1906
2712
  return true;
1907
2713
  }
1908
2714
 
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).
2715
+ // === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
1930
2716
  let prefetchMode = ${JSON.stringify(prefetchMode)};
1931
2717
  export function setPrefetchMode(mode) { prefetchMode = mode; }
1932
2718
  const PREFETCH_BUDGET = 8;
1933
2719
  const PREFETCH_MAX_CACHED = 4;
1934
- const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
2720
+ const prefetchCache = new Map();
1935
2721
  let prefetchQueue = Promise.resolve();
1936
2722
  let prefetchPending = 0;
1937
2723
 
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.
2724
+
1944
2725
  async function applyParams(route, pathname) {
1945
2726
  const patternParts = route.pattern.split('/');
1946
2727
  const pathParts = pathname.split('/');
1947
2728
  for (let i = 0; i < patternParts.length; i++) {
1948
- if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
2729
+ const seg = patternParts[i];
2730
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2731
+
2732
+
2733
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
1949
2734
  }
1950
2735
  const langIdx = patternParts.indexOf(':lang');
1951
2736
  if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
1952
2737
  }
1953
2738
 
2739
+
2740
+ function __netOk() {
2741
+ const c = navigator.connection;
2742
+ if (!c) return true;
2743
+ if (c.saveData) return false;
2744
+ const t = c.effectiveType;
2745
+ return t !== 'slow-2g' && t !== '2g';
2746
+ }
2747
+
1954
2748
  export function prefetch(pathname, source = 'hover') {
1955
2749
  if (prefetchMode === 'off') return;
1956
2750
  if (prefetchMode === 'hover' && source !== 'hover') return;
1957
2751
  if (prefetchMode === 'viewport' && source !== 'viewport') return;
2752
+ if (!__netOk()) return; // save-data / 2g: no bytes before the click
1958
2753
  if (prefetchCache.has(pathname)) return;
1959
- if (pathname === location.pathname) return; // already here: nothing to prefetch
2754
+ if (pathname === location.pathname) return;
1960
2755
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
1961
2756
  if (!route) return;
1962
- if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
2757
+ if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
2758
+ const qi = pathname.indexOf('?');
2759
+ const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
1963
2760
  const p = prefetchQueue.then(async () => {
1964
2761
  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
2762
+ setPrefetchOverride(qOverride);
2763
+ // The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
1970
2764
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
1971
2765
  await applyParams(route, pathname); // a packed locale's dictionary lands before the render
1972
2766
  const closes = [];
1973
- const render = await getRender(route); // split mode: loads the route's chunk here
2767
+ const render = await getRender(route);
1974
2768
  const html = await render(closes, '');
1975
2769
  return { html, closes };
1976
2770
  });
1977
2771
  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)
2772
+ prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
1981
2773
  while (prefetchCache.size > PREFETCH_MAX_CACHED) {
1982
2774
  const oldest = prefetchCache.keys().next().value;
1983
2775
  if (prefetchCache.get(oldest) instanceof Promise) break;
@@ -1985,9 +2777,10 @@ export function prefetch(pathname, source = 'hover') {
1985
2777
  }
1986
2778
  return entry;
1987
2779
  } catch {
1988
- prefetchCache.delete(pathname); // failed: the next hover retries
2780
+ prefetchCache.delete(pathname);
1989
2781
  return null;
1990
2782
  } finally {
2783
+ setPrefetchOverride(null);
1991
2784
  prefetchPending--;
1992
2785
  }
1993
2786
  });
@@ -1997,13 +2790,10 @@ export function prefetch(pathname, source = 'hover') {
1997
2790
  }
1998
2791
 
1999
2792
  export function prefetchStats() {
2000
- return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
2793
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
2001
2794
  }
2002
2795
 
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.
2796
+ // One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
2007
2797
  const DELEGATED = ['click', 'input', 'change', 'submit'];
2008
2798
  function bindEvents(container) {
2009
2799
  if (container.__rosetack_bound) return;
@@ -2020,41 +2810,64 @@ function bindEvents(container) {
2020
2810
  }
2021
2811
  }
2022
2812
 
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 });
2813
+ // === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
2814
+ async function postForm(body, container, pathname) {
2815
+
2816
+ const box = container || document.getElementById('app');
2817
+ const route = pathname || location.pathname;
2818
+ const res = await fetch(route, { method: 'POST', body });
2031
2819
  const html = await res.text();
2032
2820
  const doc = new DOMParser().parseFromString(html, 'text/html');
2033
2821
  const next = doc.getElementById('app');
2034
2822
  const st = doc.getElementById('__rosetack_state');
2035
2823
  const paint = () => {
2036
- const container = document.getElementById('app');
2037
- adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
2824
+ adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
2038
2825
  };
2039
2826
  if (document.startViewTransition) document.startViewTransition(paint);
2040
2827
  else paint();
2041
2828
  }
2042
2829
 
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.
2830
+ // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
2046
2831
  export async function $action(name, e) {
2047
2832
  if (e && e.preventDefault) e.preventDefault();
2048
2833
  const body = new FormData();
2049
2834
  body.append('__action', name);
2050
- return postForm(body);
2835
+ // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
2836
+ const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
2837
+ return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
2051
2838
  }
2052
2839
 
2053
2840
  export { postForm };
2054
2841
 
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.
2842
+ // The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
2843
+ export { serializeState };
2844
+
2845
+ // Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
2846
+
2847
+
2848
+ function __ownsDoc(container) {
2849
+ return container === document.getElementById('app');
2850
+ }
2851
+ function __navReset(container) {
2852
+ if (__ownsDoc(container)) {
2853
+ resetEffects();
2854
+ clearRequestState();
2855
+ } else {
2856
+ resetContainerFx(container);
2857
+ }
2858
+ }
2859
+ // Attribute everything a render creates (state keys, effects, onCleanups) to
2860
+ // its container. The document path sets no owner and keeps the global sets.
2861
+ async function __withOwner(container, fn) {
2862
+ if (__ownsDoc(container)) return fn();
2863
+ setFxOwner(container);
2864
+ try {
2865
+ return await fn();
2866
+ } finally {
2867
+ setFxOwner(null);
2868
+ }
2869
+ }
2870
+
2058
2871
  export async function start(container, pathname, initial) {
2059
2872
  clearMounts(); // stale mounts from a failed render never fire
2060
2873
  if (initial) {
@@ -2063,104 +2876,110 @@ export async function start(container, pathname, initial) {
2063
2876
  }
2064
2877
  for (const route of routes) {
2065
2878
  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)
2879
+ // 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
2880
  const langIdx = route.pattern.split('/').indexOf(':lang');
2070
2881
  ${langDirBlock}
2071
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2882
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2072
2883
  return;
2073
2884
  }
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.
2885
+ // 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
2886
  let hit = initial ? undefined : prefetchCache.get(pathname);
2078
2887
  if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2079
2888
  if (hit) {
2080
- prefetchCache.delete(pathname); // single-use: the next hover refetches
2081
- resetEffects();
2889
+ prefetchCache.delete(pathname);
2890
+ __navReset(container);
2082
2891
  restoreState(hit.state);
2083
2892
  container.innerHTML = hit.html;
2084
- wire(container, hit.closes);
2893
+ await __withOwner(container, () => {
2894
+ wire(container, hit.closes);
2895
+ bindEvents(container);
2896
+ hit.mounts.forEach((fn) => fn());
2897
+ adoptCleanups(hit.cleanups);
2898
+ });
2899
+ return;
2900
+ }
2901
+ if (!initial) __navReset(container);
2902
+ let broken = false;
2903
+ let signal = null;
2904
+ await __withOwner(container, async () => {
2905
+ await applyParams(route, pathname);
2906
+ const closes = [];
2907
+ let html;
2908
+ try {
2909
+ const render = await getRender(route);
2910
+ html = await render(closes, '');
2911
+ } catch (err) {
2912
+
2913
+ if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
2914
+ if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
2915
+
2916
+
2917
+ broken = true;
2918
+ return;
2919
+ }
2920
+ if (!initial) container.innerHTML = html;
2921
+ wire(container, closes);
2085
2922
  bindEvents(container);
2086
- hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2087
- adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
2923
+ flushMounts();
2924
+ });
2925
+ if (signal === 'notFound') {
2926
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2088
2927
  return;
2089
2928
  }
2090
- if (!initial) {
2091
- resetEffects();
2092
- clearRequestState();
2929
+ if (signal) {
2930
+ location.href = signal;
2931
+ return;
2093
2932
  }
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
2933
+ if (broken) {
2103
2934
  await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2104
- return;
2105
2935
  }
2106
- if (!initial) container.innerHTML = html;
2107
- wire(container, closes);
2108
- bindEvents(container);
2109
- flushMounts();
2110
2936
  return;
2111
2937
  }
2112
2938
  }
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>');
2119
- }
2120
-
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();
2939
+ // Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
2940
+ ${hasLang ? ` // the same app-root gate as above - a mount never touches the
2941
+ // host document's language or direction.
2942
+ if (container === document.getElementById('app')) {
2943
+ document.documentElement.lang = __defLocale;
2944
+ document.documentElement.removeAttribute('dir');
2945
+ }` : ""}
2946
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2947
+ }
2948
+
2949
+ // Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
2950
+ export async function adopt(container, html, stateJson, pathname) {
2951
+
2952
+
2953
+ const route0 = pathname || location.pathname;
2954
+ __navReset(container);
2130
2955
  clearMounts(); // stale mounts from a failed render never fire
2131
2956
  resumeState(stateJson);
2132
2957
  container.innerHTML = html;
2133
- // keep the embedded state in sync so a later SPA-fallback check agrees
2958
+
2134
2959
  const st = document.getElementById('__rosetack_state');
2135
2960
  if (st) st.textContent = stateJson;
2136
2961
  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();
2962
+ if (matchRoute(route.pattern, route0)) {
2963
+ await __withOwner(container, async () => {
2964
+ await applyParams(route, route0);
2965
+ const closes = [];
2966
+ try {
2967
+ const render = await getRender(route);
2968
+ await render(closes, '');
2969
+ } catch {
2970
+
2971
+
2972
+ return;
2973
+ }
2974
+ wire(container, closes);
2975
+ bindEvents(container);
2976
+ flushMounts();
2977
+ });
2151
2978
  return;
2152
2979
  }
2153
2980
  }
2154
2981
  }
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.
2982
+ // === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
2164
2983
  setRefreshHook(async () => {
2165
2984
  prefetchCache.delete(location.pathname);
2166
2985
  await start(document.getElementById('app'), location.pathname, false);
@@ -2194,26 +3013,44 @@ setRefreshHook(async () => {
2194
3013
  ...TS_LOADER
2195
3014
  });
2196
3015
  }
3016
+ await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
2197
3017
  await fs.promises.rm(buildDir, { recursive: true, force: true });
2198
3018
  const publicDir = path.join(root, "public");
2199
3019
  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
- );
3020
+ await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
3021
+ const favicon = path.join(publicDir, "favicon.ico");
3022
+ if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
2206
3023
  }
2207
3024
  console.log("rosetack zero-JS report:");
2208
3025
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
3026
+ const warnGroups = /* @__PURE__ */ new Map();
2209
3027
  for (const { info, i } of pages) {
2210
3028
  if (!routeShipsNoJs(infos, compiled, i)) continue;
2211
3029
  for (const ci of [i, ...layoutsOf(infos, i)]) {
2212
3030
  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}`);
3031
+ let g = warnGroups.get(w);
3032
+ if (!g) {
3033
+ g = { why: w, files: /* @__PURE__ */ new Map() };
3034
+ warnGroups.set(w, g);
3035
+ }
3036
+ const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
3037
+ let routes = g.files.get(file);
3038
+ if (!routes) {
3039
+ routes = /* @__PURE__ */ new Set();
3040
+ g.files.set(file, routes);
3041
+ }
3042
+ routes.add(info.routePath);
2214
3043
  }
2215
3044
  }
2216
3045
  }
3046
+ for (const g of warnGroups.values()) {
3047
+ const allRoutes = /* @__PURE__ */ new Set();
3048
+ for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
3049
+ 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`})`);
3050
+ const shown = parts.slice(0, 4).join(", ");
3051
+ const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
3052
+ console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
3053
+ }
2217
3054
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2218
3055
  }
2219
3056
  async function scanRoseFiles(root) {
@@ -2258,15 +3095,21 @@ function getRouteInfo(filePath, root) {
2258
3095
  const base = path.posix.basename(withoutExt);
2259
3096
  const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2260
3097
  const isLayout = !isComponent && base === "_layout";
2261
- const isNotFound = !isComponent && base === "404";
3098
+ const isNotFound = !isComponent && (base === "404" || base === "_notfound");
2262
3099
  const isError = !isComponent && base === "500";
2263
3100
  const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2264
3101
  const isMiddleware = !isComponent && withoutExt === "_middleware";
2265
- let parts = withoutExt.split("/").filter((p) => p !== "_layout");
3102
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
2266
3103
  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
- );
3104
+ const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
3105
+ const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
3106
+ const routeParts = parts.map((part) => {
3107
+ const optional = OPTIONAL_CATCH_ALL.exec(part);
3108
+ if (optional) return `**${optional[1]}`;
3109
+ const catchAll = CATCH_ALL.exec(part);
3110
+ if (catchAll) return `*${catchAll[1]}`;
3111
+ return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
3112
+ });
2270
3113
  let routePath;
2271
3114
  if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2272
3115
  routePath = "/";
@@ -2277,7 +3120,13 @@ function getRouteInfo(filePath, root) {
2277
3120
  filePath,
2278
3121
  routePath,
2279
3122
  pattern: routePath,
2280
- paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
3123
+ paramNames: parts.flatMap((p) => {
3124
+ const optional = OPTIONAL_CATCH_ALL.exec(p);
3125
+ if (optional) return [optional[1]];
3126
+ const catchAll = CATCH_ALL.exec(p);
3127
+ if (catchAll) return [catchAll[1]];
3128
+ return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
3129
+ }),
2281
3130
  isLayout,
2282
3131
  isNotFound,
2283
3132
  isError,
@@ -2290,13 +3139,18 @@ function capitalize(s) {
2290
3139
  return s.charAt(0).toUpperCase() + s.slice(1);
2291
3140
  }
2292
3141
  export {
3142
+ RoseError,
2293
3143
  buildProject,
2294
3144
  buildReport,
2295
3145
  compileComponent,
3146
+ errorInfo,
2296
3147
  extractExports,
3148
+ lineAt,
3149
+ lineOf,
2297
3150
  loadConfig,
2298
3151
  loadPlugins,
2299
3152
  scanComponentFiles,
2300
3153
  scanRoseFiles,
2301
- scriptOf
3154
+ scriptOf,
3155
+ templateExprSpans
2302
3156
  };