rosetack 0.1.3 → 0.1.5

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.
package/dist-cli/test.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  // src/cli/test.ts
2
- import * as fs3 from "fs";
3
- import * as os from "os";
4
- import * as path3 from "path";
2
+ import * as fs5 from "fs";
3
+ import * as os2 from "os";
4
+ import * as path4 from "path";
5
5
  import { pathToFileURL as pathToFileURL2 } from "url";
6
6
 
7
7
  // src/compiler/index.ts
8
- import * as fs from "fs";
9
- import * as path from "path";
8
+ import * as fs3 from "fs";
9
+ import * as path2 from "path";
10
+ import * as os from "os";
10
11
  import { pathToFileURL, fileURLToPath } from "url";
11
12
  import * as esbuild from "esbuild";
12
13
 
@@ -45,16 +46,209 @@ function lineAt(src, match) {
45
46
  return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
46
47
  }
47
48
 
49
+ // src/cli/image-size.ts
50
+ import fs from "node:fs";
51
+ function readImageSize(filePath2) {
52
+ try {
53
+ const fd = fs.openSync(filePath2, "r");
54
+ const buf = Buffer.alloc(64);
55
+ const read = fs.readSync(fd, buf, 0, 64, 0);
56
+ fs.closeSync(fd);
57
+ if (read < 24) return null;
58
+ if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
59
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
60
+ }
61
+ if (buf.slice(0, 3).toString("latin1") === "GIF") {
62
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
63
+ }
64
+ if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP") {
65
+ return parseWebP(buf);
66
+ }
67
+ if (buf[0] === 255 && buf[1] === 216) {
68
+ return parseJpeg(filePath2);
69
+ }
70
+ return null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+ function parseWebP(buf) {
76
+ const format = buf.slice(12, 16).toString("latin1");
77
+ if (format === "VP8 ") {
78
+ return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
79
+ }
80
+ if (format === "VP8L") {
81
+ const b = buf.readUInt32LE(21);
82
+ return { width: (b & 16383) + 1, height: (b >> 14 & 16383) + 1 };
83
+ }
84
+ if (format === "VP8X") {
85
+ const w = buf.readUIntLE(24, 3) + 1;
86
+ const h = buf.readUIntLE(27, 3) + 1;
87
+ return { width: w, height: h };
88
+ }
89
+ return null;
90
+ }
91
+ function parseJpeg(filePath2) {
92
+ const fd = fs.openSync(filePath2, "r");
93
+ try {
94
+ const buf = Buffer.alloc(4);
95
+ let pos = 2;
96
+ for (let guard = 0; guard < 64; guard++) {
97
+ if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
98
+ if (buf[0] !== 255) {
99
+ pos += 1;
100
+ continue;
101
+ }
102
+ const marker = buf[1];
103
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
104
+ pos += 2;
105
+ continue;
106
+ }
107
+ const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
108
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
109
+ const seg = Buffer.alloc(8);
110
+ fs.readSync(fd, seg, 0, 8, pos + 4);
111
+ return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
112
+ }
113
+ pos += 2 + len;
114
+ }
115
+ return null;
116
+ } finally {
117
+ fs.closeSync(fd);
118
+ }
119
+ }
120
+
121
+ // src/cli/content.ts
122
+ import fs2 from "node:fs";
123
+ import path from "node:path";
124
+ function parseFrontmatter(raw) {
125
+ if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
126
+ const end = raw.indexOf("\n---", 3);
127
+ if (end < 0) return { frontmatter: {}, body: raw };
128
+ const head = raw.slice(4, end);
129
+ const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
130
+ const frontmatter = {};
131
+ for (const line of head.split("\n")) {
132
+ const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
133
+ if (!m) continue;
134
+ const [, k, v] = m;
135
+ const arr = /^\[(.+)\]$/.exec(v.trim());
136
+ frontmatter[k] = arr ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")) : v.trim().replace(/^["']|["']$/g, "");
137
+ }
138
+ return { frontmatter, body };
139
+ }
140
+ function interpolate(md, vars) {
141
+ return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
142
+ const v = k.split(".").reduce((o, p) => o == null ? o : o[p], vars);
143
+ return v === void 0 || v === null ? "" : String(v);
144
+ });
145
+ }
146
+ function renderMarkdown(md, vars) {
147
+ if (vars) md = interpolate(md, vars);
148
+ const blocks = [];
149
+ let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
150
+ blocks.push(
151
+ `<pre data-lang="${lang}"><code>${code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</code></pre>`
152
+ );
153
+ return `\0CODE${blocks.length - 1}\0`;
154
+ });
155
+ const inline = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
156
+ /\[([^\]]+)\]\(([^)]+)\)/g,
157
+ '<a href="$2" rel="noopener">$1</a>'
158
+ );
159
+ const out = [];
160
+ let listOpen = null;
161
+ const closeList = () => {
162
+ if (listOpen) {
163
+ out.push(`</${listOpen}>`);
164
+ listOpen = null;
165
+ }
166
+ };
167
+ for (const line of src.split("\n")) {
168
+ const h = /^(#{1,4})\s+(.*)$/.exec(line);
169
+ const li = /^\s*[-*]\s+(.*)$/.exec(line);
170
+ const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
171
+ if (h) {
172
+ closeList();
173
+ out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
174
+ } else if (li) {
175
+ if (listOpen !== "ul") {
176
+ closeList();
177
+ out.push("<ul>");
178
+ listOpen = "ul";
179
+ }
180
+ out.push(`<li>${inline(li[1])}</li>`);
181
+ } else if (oli) {
182
+ if (listOpen !== "ol") {
183
+ closeList();
184
+ out.push("<ol>");
185
+ listOpen = "ol";
186
+ }
187
+ out.push(`<li>${inline(oli[1])}</li>`);
188
+ } else if (line.trim() === "") {
189
+ closeList();
190
+ } else if (line.startsWith("\0CODE")) {
191
+ closeList();
192
+ out.push(line);
193
+ } else {
194
+ closeList();
195
+ out.push(`<p>${inline(line)}</p>`);
196
+ }
197
+ }
198
+ closeList();
199
+ return out.join("\n").replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
200
+ }
201
+ function scanContentDir(contentDir) {
202
+ const collections = {};
203
+ if (!fs2.existsSync(contentDir)) return collections;
204
+ for (const coll of fs2.readdirSync(contentDir, { withFileTypes: true })) {
205
+ if (!coll.isDirectory()) continue;
206
+ const entries = [];
207
+ const dir = path.join(contentDir, coll.name);
208
+ for (const f of fs2.readdirSync(dir)) {
209
+ if (!f.endsWith(".md")) continue;
210
+ const raw = fs2.readFileSync(path.join(dir, f), "utf-8");
211
+ const { frontmatter, body } = parseFrontmatter(raw);
212
+ if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
213
+ const slug = f.replace(/\.md$/, "");
214
+ const html = renderMarkdown(body);
215
+ const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
216
+ const headings = [];
217
+ const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl, txt) => {
218
+ const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
219
+ headings.push({ level: Number(lvl), text: txt, id });
220
+ return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
221
+ });
222
+ entries.push({
223
+ slug,
224
+ frontmatter,
225
+ body,
226
+ html: tocHtml,
227
+ readingTime: Math.max(1, Math.round(words / 200)),
228
+ wordCount: words,
229
+ toc: headings,
230
+ excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160)
231
+ });
232
+ }
233
+ entries.sort(
234
+ (a, b) => String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? ""))
235
+ );
236
+ collections[coll.name] = entries;
237
+ }
238
+ return collections;
239
+ }
240
+ globalThis.__rosetackContentMk = renderMarkdown;
241
+
48
242
  // src/compiler/index.ts
49
243
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
50
244
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
51
245
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
52
246
  var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
53
- var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
247
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist|derived)\b/g;
54
248
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
55
249
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
56
- var SLOT_RE = /<slot\s*\/?>/g;
57
- var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
250
+ var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
251
+ var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
58
252
  function encodeSlotCall(attrs) {
59
253
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
60
254
  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} />' });
@@ -446,8 +640,8 @@ function stripGuardedBranches(src) {
446
640
  return out.join("");
447
641
  }
448
642
  async function loadConfig(root) {
449
- const file = path.join(root, "rosetack.config.js");
450
- if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
643
+ const file = path2.join(root, "rosetack.config.js");
644
+ if (!fs3.existsSync(file)) return { plugins: [], i18n: {} };
451
645
  const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
452
646
  return {
453
647
  plugins: mod.default ?? [],
@@ -457,12 +651,12 @@ async function loadConfig(root) {
457
651
  function resolveRoseImports(script, fromFile, registry) {
458
652
  const imports = [];
459
653
  const resolve3 = (spec, at) => {
460
- const abs = path.resolve(path.dirname(fromFile), spec);
654
+ const abs = path2.resolve(path2.dirname(fromFile), spec);
461
655
  const hit = registry.get(abs);
462
656
  if (!hit) {
463
657
  throw new RoseError(
464
658
  "E-IMPORT",
465
- `${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
659
+ `${path2.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
466
660
  {
467
661
  file: fromFile,
468
662
  line: lineOf(script, at),
@@ -497,16 +691,45 @@ function nodeOnlyImports(importStmts) {
497
691
  }
498
692
  return out;
499
693
  }
500
- function wireEventBindings(template, actionNames) {
694
+ function wireEventBindings(template, actionNames, filePath2 = "<template>") {
501
695
  const bindings = [];
502
696
  let out = "";
503
697
  let rest = template;
698
+ const TARGET_MODS = { window: "w", document: "d" };
699
+ const MOD_PRE = {
700
+ preventDefault: () => "e.preventDefault()",
701
+ stopPropagation: () => "e.stopPropagation()",
702
+ self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`
703
+ };
704
+ const MOD_POST = {
705
+ once: (p) => `const __o = e.target && e.target.closest ? e.target.closest('[data-${p}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${p}-' + e.type);`
706
+ };
707
+ const KNOWN_MODS = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
504
708
  for (; ; ) {
505
- const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
709
+ const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
506
710
  if (!m) {
507
711
  out += rest;
508
712
  break;
509
713
  }
714
+ const mods = m[2] ? m[2].slice(1).split("|") : [];
715
+ const targets = mods.filter((mod) => TARGET_MODS[mod]);
716
+ if (targets.length > 1) {
717
+ throw new RoseError(
718
+ "E-TEMPLATE",
719
+ `${filePath2}: on:${m[1]} carries both |${targets.join(" and |")}`,
720
+ { hint: "a handler binds to one target - the element (default), |window or |document" }
721
+ );
722
+ }
723
+ const prefix = targets.length ? "on" + TARGET_MODS[targets[0]] : "on";
724
+ for (const mod of mods) {
725
+ if (!KNOWN_MODS.includes(mod)) {
726
+ throw new RoseError(
727
+ "E-TEMPLATE",
728
+ `${filePath2}: unknown event modifier |${mod}`,
729
+ { hint: `the supported modifiers are ${KNOWN_MODS.map((k) => "|" + k).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` }
730
+ );
731
+ }
732
+ }
510
733
  out += rest.slice(0, m.index);
511
734
  let i = m.index + m[0].length;
512
735
  let depth = 1;
@@ -528,7 +751,24 @@ function wireEventBindings(template, actionNames) {
528
751
  i++;
529
752
  }
530
753
  const expr = rest.slice(m.index + m[0].length, i).trim();
531
- if (actionNames.has(expr)) {
754
+ const wrap = (body) => {
755
+ if (!mods.length) return body;
756
+ const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
757
+ const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
758
+ return `(e) => {${pre.length ? " " + pre.join("; ") + ";" : ""} (${body})(e);${post.length ? " " + post.join("; ") + ";" : ""} }`;
759
+ };
760
+ if (mods.length && actionNames.has(expr)) {
761
+ throw new RoseError(
762
+ "E-TEMPLATE",
763
+ `${filePath2}: event modifiers are not supported on the server action ${expr}`,
764
+ { hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
765
+ );
766
+ }
767
+ if (mods.length) {
768
+ const name = `__h${bindings.length}`;
769
+ out += `data-${prefix}-${m[1]}="${name}"`;
770
+ bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
771
+ } else if (actionNames.has(expr)) {
532
772
  out += `data-on-${m[1]}="$action:${expr}"`;
533
773
  } else if (/^\w+$/.test(expr)) {
534
774
  out += `data-on-${m[1]}="${expr}"`;
@@ -542,10 +782,10 @@ function wireEventBindings(template, actionNames) {
542
782
  }
543
783
  return { template: out, bindings };
544
784
  }
545
- function scanSlotDecls(filePath) {
785
+ function scanSlotDecls(filePath2) {
546
786
  let src;
547
787
  try {
548
- src = fs.readFileSync(filePath, "utf-8");
788
+ src = fs3.readFileSync(filePath2, "utf-8");
549
789
  } catch {
550
790
  return [];
551
791
  }
@@ -598,17 +838,104 @@ function hoistImports(script) {
598
838
  if (buf) imports.push(buf.join("\n"));
599
839
  return { imports: imports.join("\n"), rest: rest.join("\n") };
600
840
  }
601
- async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
602
- let source = await fs.promises.readFile(filePath, "utf-8");
841
+ var __compileMemo = /* @__PURE__ */ new Map();
842
+ function compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry) {
843
+ let st;
844
+ try {
845
+ st = fs3.statSync(filePath2);
846
+ } catch {
847
+ return null;
848
+ }
849
+ const reg = [];
850
+ for (const [p, e] of registry) reg.push(`${p}#${e.index}:${e.scopeKey}:${e.slots.join("|")}`);
851
+ return [filePath2, String(st.mtimeMs), String(st.size), scopeKey, isApi ? "1" : "0", reg.join(";")].join("\0");
852
+ }
853
+ var __compilerStamp = (() => {
854
+ try {
855
+ return String(fs3.statSync(fileURLToPath(import.meta.url)).mtimeMs);
856
+ } catch {
857
+ return "noid";
858
+ }
859
+ })();
860
+ var __diskCacheDir = (() => {
861
+ try {
862
+ const dir = path2.join(os.tmpdir(), "rosetack-compile-cache");
863
+ fs3.mkdirSync(dir, { recursive: true });
864
+ return dir;
865
+ } catch {
866
+ return null;
867
+ }
868
+ })();
869
+ var __diskWrites = 0;
870
+ function __fnv1a(str) {
871
+ let h = 2166136261;
872
+ for (let i = 0; i < str.length; i++) {
873
+ h ^= str.charCodeAt(i);
874
+ h = Math.imul(h, 16777619);
875
+ }
876
+ return (h >>> 0).toString(16).padStart(8, "0");
877
+ }
878
+ function __diskFile(key) {
879
+ return path2.join(__diskCacheDir, __fnv1a(key + "|" + __compilerStamp) + ".json");
880
+ }
881
+ function __diskGet(key) {
882
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return null;
883
+ try {
884
+ const obj = JSON.parse(fs3.readFileSync(__diskFile(key), "utf-8"));
885
+ if (obj && typeof obj === "object" && typeof obj.ssr === "string") return obj;
886
+ } catch {
887
+ }
888
+ return null;
889
+ }
890
+ function __diskSet(key, result) {
891
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return;
892
+ try {
893
+ fs3.writeFileSync(__diskFile(key), JSON.stringify(result));
894
+ if ((__diskWrites++ & 511) === 0) {
895
+ try {
896
+ const entries = fs3.readdirSync(__diskCacheDir);
897
+ if (entries.length > 5e3) {
898
+ for (const e of entries) {
899
+ try {
900
+ fs3.unlinkSync(path2.join(__diskCacheDir, e));
901
+ } catch {
902
+ }
903
+ }
904
+ }
905
+ } catch {
906
+ }
907
+ }
908
+ } catch {
909
+ }
910
+ }
911
+ async function compileComponentMemo(filePath2, publicDir, scopeKey, isApi, plugins, registry) {
912
+ if (plugins.length > 0) return compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
913
+ const key = compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry);
914
+ if (key) {
915
+ const hit = __compileMemo.get(key);
916
+ if (hit) return { ...hit };
917
+ const disk = __diskGet(key);
918
+ if (disk) return disk;
919
+ }
920
+ const result = await compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
921
+ if (key) {
922
+ if (__compileMemo.size > 500) __compileMemo.clear();
923
+ __compileMemo.set(key, result);
924
+ __diskSet(key, result);
925
+ }
926
+ return result;
927
+ }
928
+ async function compileComponent(filePath2, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
929
+ let source = await fs3.promises.readFile(filePath2, "utf-8");
603
930
  for (const p of plugins) {
604
931
  if (!p.transform) continue;
605
932
  try {
606
- source = await p.transform(source, filePath);
933
+ source = await p.transform(source, filePath2);
607
934
  } catch (err) {
608
935
  throw new RoseError(
609
936
  "E-PLUGIN",
610
- `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
611
- { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
937
+ `plugin ${p.name} failed on ${path2.basename(filePath2)}: ${err instanceof Error ? err.message : String(err)}`,
938
+ { file: filePath2, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
612
939
  );
613
940
  }
614
941
  }
@@ -618,7 +945,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
618
945
  const apiMethods = [...rawScript2.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)].map((m) => m[1]).filter((name) => HTTP_METHODS.has(name));
619
946
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
620
947
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
621
- const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
948
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath2, registry).script);
622
949
  const ownRuntimeImports = new Set(
623
950
  [...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
624
951
  );
@@ -646,43 +973,46 @@ ${hoisted.rest}`, "ssr").trim()}`,
646
973
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
647
974
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
648
975
  const scriptMatch = source.match(COMPONENT_RE);
649
- const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
976
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath2, registry);
650
977
  const rawScript = roseResolved.script;
978
+ const usesrosetackAuth = rawScript.includes("__rosetackAuth");
651
979
  const roseImports = roseResolved.imports;
652
980
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
653
- if (path.basename(filePath) !== "_middleware.rose") {
981
+ if (path2.basename(filePath2) !== "_middleware.rose") {
654
982
  for (const spec of nodeOnlyImports(importStmts)) {
655
983
  const at = importStmts.indexOf(spec);
656
984
  throw new RoseError(
657
985
  "E-NODE-ONLY",
658
- `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
986
+ `${filePath2}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
659
987
  {
660
- file: filePath,
988
+ file: filePath2,
661
989
  line: at >= 0 ? lineOf(importStmts, at) : void 0,
662
990
  hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`
663
991
  }
664
992
  );
665
993
  }
666
994
  }
667
- const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
995
+ const isComponent = registry.get(filePath2)?.scopeKey.startsWith("components/") ?? false;
668
996
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
669
997
  throw new RoseError(
670
998
  "E-EXPORT",
671
- `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
672
- { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
999
+ `${filePath2}: $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()}>.`,
1000
+ { file: filePath2, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
673
1001
  );
674
1002
  }
675
1003
  const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
676
1004
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
677
1005
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
678
1006
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
1007
+ const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
1008
+ const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : void 0;
679
1009
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
680
1010
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
681
1011
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
682
1012
  throw new RoseError(
683
1013
  "E-EXPORT",
684
- `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
685
- { file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
1014
+ `${filePath2}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
1015
+ { file: filePath2, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
686
1016
  );
687
1017
  }
688
1018
  const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
@@ -690,8 +1020,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
690
1020
  if (vitalsMatch && !vitals) {
691
1021
  throw new RoseError(
692
1022
  "E-EXPORT",
693
- `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
694
- { file: filePath, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
1023
+ `${filePath2}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
1024
+ { file: filePath2, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
695
1025
  );
696
1026
  }
697
1027
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
@@ -699,8 +1029,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
699
1029
  if (bundle && !["inline", "split"].includes(bundle)) {
700
1030
  throw new RoseError(
701
1031
  "E-EXPORT",
702
- `${filePath}: export const bundle must be 'inline' or 'split'`,
703
- { file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
1032
+ `${filePath2}: export const bundle must be 'inline' or 'split'`,
1033
+ { file: filePath2, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
704
1034
  );
705
1035
  }
706
1036
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
@@ -716,9 +1046,9 @@ ${hoisted.rest}`, "ssr").trim()}`,
716
1046
  const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
717
1047
  throw new RoseError(
718
1048
  "E-EXPORT",
719
- `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
1049
+ `${filePath2}: 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
1050
  {
721
- file: filePath,
1051
+ file: filePath2,
722
1052
  line: lineAt(deadSrc, dead),
723
1053
  hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'
724
1054
  }
@@ -734,15 +1064,15 @@ ${hoisted.rest}`, "ssr").trim()}`,
734
1064
  } catch {
735
1065
  throw new RoseError(
736
1066
  "E-EXPORT",
737
- `${filePath}: export const headers must be an object literal`,
738
- { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
1067
+ `${filePath2}: export const headers must be an object literal`,
1068
+ { file: filePath2, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
739
1069
  );
740
1070
  }
741
1071
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
742
1072
  throw new RoseError(
743
1073
  "E-EXPORT",
744
- `${filePath}: export const headers must be a flat map of string -> string`,
745
- { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
1074
+ `${filePath2}: export const headers must be a flat map of string -> string`,
1075
+ { file: filePath2, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
746
1076
  );
747
1077
  }
748
1078
  headers = value;
@@ -756,16 +1086,16 @@ ${hoisted.rest}`, "ssr").trim()}`,
756
1086
  } catch {
757
1087
  throw new RoseError(
758
1088
  "E-EXPORT",
759
- `${filePath}: export const csp must be an object literal`,
760
- { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
1089
+ `${filePath2}: export const csp must be an object literal`,
1090
+ { file: filePath2, hint: "write it as one literal: export const csp = { nonce: true }" }
761
1091
  );
762
1092
  }
763
1093
  const nonce = value?.nonce;
764
1094
  if (nonce !== void 0 && typeof nonce !== "boolean") {
765
1095
  throw new RoseError(
766
1096
  "E-EXPORT",
767
- `${filePath}: csp.nonce must be a boolean`,
768
- { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1097
+ `${filePath2}: csp.nonce must be a boolean`,
1098
+ { file: filePath2, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
769
1099
  );
770
1100
  }
771
1101
  cspNonce = nonce === true;
@@ -778,8 +1108,10 @@ ${hoisted.rest}`, "ssr").trim()}`,
778
1108
  if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
779
1109
  clientReasons.push("a form bound to a client dispatch ($action)");
780
1110
  }
781
- const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
1111
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);
782
1112
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
1113
+ if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
1114
+ if (source.includes("{#await")) clientReasons.push("{#await} async block");
783
1115
  const needsClient = clientReasons.length > 0;
784
1116
  const jsWarnings = [];
785
1117
  if (!needsClient) {
@@ -804,7 +1136,9 @@ ${hoisted.rest}`, "ssr").trim()}`,
804
1136
  const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
805
1137
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
806
1138
  const decls = extractDecls(script);
807
- const stateDecls = decls.filter((d) => d.kind === "state");
1139
+ const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
1140
+ const derivedNames = decls.filter((d) => d.kind === "derived").map((d) => d.name);
1141
+ const callifyNames = [...stateDecls.map((s) => s.name), ...derivedNames];
808
1142
  const setterNames = /* @__PURE__ */ new Map();
809
1143
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
810
1144
  const declCode = (d) => {
@@ -814,40 +1148,191 @@ ${hoisted.rest}`, "ssr").trim()}`,
814
1148
  }
815
1149
  const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
816
1150
  const fn = isFn ? d.expr : `() => (${d.expr})`;
817
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1151
+ if (d.kind === "persist") {
1152
+ return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1153
+ }
1154
+ if (d.kind === "derived") {
1155
+ return `const ${d.name} = () => (${callifyStateReads(d.expr, callifyNames)});`;
1156
+ }
1157
+ if (d.kind === "kv") {
1158
+ const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1159
+ const fnExpr = mTtl ? mTtl[1] : d.expr;
1160
+ const ttl = mTtl ? mTtl[2] : "300";
1161
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
818
1162
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
819
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1163
+ if (!__seeded_${d.name}) { const __v_${d.name} = await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1164
+ }
1165
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1166
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1167
+ if (!__seeded_${d.name}) { const __v_${d.name} = await $data(${fn}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
820
1168
  };
821
1169
  const nestedDecls = [];
822
1170
  let spliced = "";
823
1171
  let pos = 0;
824
1172
  decls.forEach((d, i) => {
825
1173
  const top = braceDepthAt(script, d.start) === 0;
826
- if (!top) nestedDecls.push(d);
1174
+ if (!top) {
1175
+ if (d.kind === "derived") {
1176
+ throw new Error(
1177
+ `${filePath2}: $derived must be a top-level declaration - inside a function body a plain const arrow already does this natively`
1178
+ );
1179
+ }
1180
+ nestedDecls.push(d);
1181
+ }
827
1182
  spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
828
1183
  pos = d.end;
829
1184
  });
830
1185
  spliced += script.slice(pos);
831
1186
  let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
832
1187
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
1188
+ if (derivedNames.includes(trimmedKey)) {
1189
+ throw new Error(
1190
+ `${filePath2}: $setState('${trimmedKey}', ...) - a $derived value is read-only; make it $state or derive a different expression`
1191
+ );
1192
+ }
833
1193
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
834
1194
  return `${setter}(${val})`;
835
1195
  });
836
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1196
+ cleanScript = callifyStateReads(cleanScript, callifyNames);
837
1197
  cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
838
1198
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
839
1199
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
840
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
841
- const wired = wireEventBindings(templateCalled, actionNames);
842
- const eventBindings = wired.bindings;
843
- const stateKeys = decls.map((d) => d.name);
1200
+ const templateCalled = callifyTemplateExprs(template, callifyNames);
1201
+ const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
1202
+ const wired = wireEventBindings(imgDefaulted, actionNames, filePath2);
1203
+ const stateKeys = decls.filter((d) => d.kind !== "derived").map((d) => d.name);
1204
+ const bindBindings = [];
1205
+ let bindCounter = 0;
1206
+ const bindExpanded = wired.template.replace(
1207
+ /\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1208
+ (whole, kind, name, offset, str) => {
1209
+ if (!stateKeys.includes(name)) {
1210
+ throw new Error(
1211
+ `${filePath2}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1212
+ );
1213
+ }
1214
+ if (kind === "this") return ` data-bind-this="${name}"`;
1215
+ const tagStart = str.lastIndexOf("<", offset);
1216
+ const tagText = tagStart >= 0 ? str.slice(tagStart, offset) : "";
1217
+ if (kind === "value" && /^<select[\s>]/i.test(tagText) && /\smultiple\b/i.test(tagText)) {
1218
+ const setterM = setterNames.get(name);
1219
+ const hnameM = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1220
+ bindBindings.push({
1221
+ event: "change",
1222
+ fn: `${hnameM}: (e) => ${setterM}(Array.from(e.target.selectedOptions, (o) => o.value))`
1223
+ });
1224
+ return ` data-selmulti={${name}().join(',')} data-on-change="${hnameM}"`;
1225
+ }
1226
+ if (kind === "open") {
1227
+ const setterO = setterNames.get(name);
1228
+ const hnameO = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1229
+ bindBindings.push({ event: "toggle", fn: `${hnameO}: (e) => ${setterO}(e.target.open)` });
1230
+ return ` open={${name}()} data-on-toggle="${hnameO}"`;
1231
+ }
1232
+ const setter = setterNames.get(name);
1233
+ const evt = kind === "checked" ? "change" : "input";
1234
+ const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1235
+ bindBindings.push({
1236
+ event: evt,
1237
+ fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; ${setter}(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`
1238
+ });
1239
+ const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
1240
+ return ` ${kind}={${name}()}${evtAttr}`;
1241
+ }
1242
+ );
844
1243
  const comps = new Map(roseImports.map((r) => {
845
- const abs = path.resolve(path.dirname(filePath), r.specifier);
1244
+ const abs = path2.resolve(path2.dirname(filePath2), r.specifier);
846
1245
  const hit = registry.get(abs);
847
1246
  return [r.name, { index: hit.index, slots: hit.slots }];
848
1247
  }));
849
- const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
850
- assertKnownDirectives(ssrTemplate, filePath);
1248
+ const groupBindings = [];
1249
+ let groupCounter = 0;
1250
+ const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1251
+ const groupExpanded = (() => {
1252
+ if (!bindExpanded.includes("bind:group")) return bindExpanded;
1253
+ let out = "";
1254
+ let pos2 = 0;
1255
+ let m;
1256
+ TAG_SCAN_RE.lastIndex = 0;
1257
+ while (m = TAG_SCAN_RE.exec(bindExpanded)) {
1258
+ const [whole, tag, attrs, selfClose] = m;
1259
+ const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
1260
+ if (!gm) continue;
1261
+ const name = gm[1];
1262
+ if (!stateKeys.includes(name)) {
1263
+ throw new RoseError(
1264
+ "E-TEMPLATE",
1265
+ `${filePath2}: bind:group={${name}} must name a $state declaration`,
1266
+ { hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
1267
+ );
1268
+ }
1269
+ if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
1270
+ throw new RoseError(
1271
+ "E-TEMPLATE",
1272
+ `${filePath2}: bind:group is for radio and checkbox inputs`,
1273
+ { hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' }
1274
+ );
1275
+ }
1276
+ const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
1277
+ const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
1278
+ if (!vm || /\{/.test(vm[0])) {
1279
+ throw new RoseError(
1280
+ "E-TEMPLATE",
1281
+ `${filePath2}: a bind:group input needs a static value attribute`,
1282
+ { hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
1283
+ );
1284
+ }
1285
+ if (/\schecked\s*=/.test(attrs)) {
1286
+ throw new RoseError(
1287
+ "E-TEMPLATE",
1288
+ `${filePath2}: a bind:group input cannot also carry checked=`,
1289
+ { hint: "the group state alone decides which inputs are checked" }
1290
+ );
1291
+ }
1292
+ const setter = setterNames.get(name);
1293
+ const hname = `__rvbg_${scopeKey.replace(/\W/g, "_")}_${groupCounter++}`;
1294
+ const groupValue = JSON.stringify(vm[1] ?? vm[2]);
1295
+ const checkedExpr = isArrayGroup ? `${name}().includes(${groupValue})` : `${name}() === ${groupValue}`;
1296
+ const handlerBody = isArrayGroup ? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))` : `${setter}(e.target.value)`;
1297
+ groupBindings.push({ event: "change", fn: `${hname}: (e) => { ${handlerBody}; }` });
1298
+ const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
1299
+ out += bindExpanded.slice(pos2, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1300
+ pos2 = m.index + whole.length;
1301
+ }
1302
+ if (pos2 === 0) return bindExpanded;
1303
+ out += bindExpanded.slice(pos2);
1304
+ return out;
1305
+ })();
1306
+ const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
1307
+ const useExpanded = groupExpanded.replace(
1308
+ /\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
1309
+ (_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
1310
+ );
1311
+ const classExpanded = expandClassDirectives(useExpanded, filePath2);
1312
+ const classMerged = mergeStaticClass(classExpanded);
1313
+ const styleExpanded = expandStyleDirectives(classMerged, filePath2);
1314
+ const transExpanded = expandTransitionDirectives(styleExpanded, filePath2);
1315
+ const animExpanded = expandAnimateDirectives(transExpanded, filePath2);
1316
+ const keyExpanded = expandKeyBlocks(animExpanded, filePath2);
1317
+ const elseExpanded = expandIfElse(keyExpanded);
1318
+ const deferExpanded = expandDeferBlocks(elseExpanded);
1319
+ const awaitExpanded = expandAwaitBlocks(deferExpanded.template, filePath2);
1320
+ const fbExpanded = expandBoundaryFallbacks(awaitExpanded.template, filePath2);
1321
+ const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
1322
+ const call = `{__slot(${encodeSlotCall(attrs)})}`;
1323
+ if (fallback) {
1324
+ if (/\{[^{}]*\}/.test(fallback)) {
1325
+ throw new RoseError(
1326
+ "E-TEMPLATE",
1327
+ `${filePath2}: slot fallback content must be static markup`,
1328
+ { hint: "a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content" }
1329
+ );
1330
+ }
1331
+ return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
1332
+ }
1333
+ return call;
1334
+ }).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
1335
+ assertKnownDirectives(ssrTemplate, filePath2);
851
1336
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
852
1337
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
853
1338
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -855,7 +1340,8 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
855
1340
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
856
1341
  const ssrGuard = guard ? `
857
1342
  ${guard}` : "";
858
- const isMiddleware = path.basename(filePath) === "_middleware.rose";
1343
+ const isMiddleware = path2.basename(filePath2) === "_middleware.rose";
1344
+ const bootCode = deferBootCode(deferExpanded.count, deferExpanded.holds) + (awaitExpanded.blocks.length ? "\n" + awaitBootCode(awaitExpanded.blocks) : "");
859
1345
  const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
860
1346
 
861
1347
  ${importStmts}
@@ -864,8 +1350,8 @@ ${ssrExports}
864
1350
  ${ssrGuard}
865
1351
 
866
1352
  ${cleanScript}
867
- ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
868
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1353
+ ` : generateSSR(cleanScript + bootCode, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1354
+ const client = generateClient(cleanScript + bootCode, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
869
1355
  return {
870
1356
  ssr: rewriteRoseImports(ssr, "ssr"),
871
1357
  client: rewriteRoseImports(client, "client"),
@@ -876,6 +1362,7 @@ ${cleanScript}
876
1362
  hasParams,
877
1363
  usesContext,
878
1364
  revalidate,
1365
+ cache: cacheSeconds,
879
1366
  csr,
880
1367
  shell,
881
1368
  buffer,
@@ -888,6 +1375,7 @@ ${cleanScript}
888
1375
  jsWarnings,
889
1376
  headers,
890
1377
  cspNonce,
1378
+ usesrosetackAuth,
891
1379
  props,
892
1380
  roseImports,
893
1381
  isComponent
@@ -901,6 +1389,13 @@ function minifyDecls(block) {
901
1389
  }
902
1390
  function scopeCss(css, key) {
903
1391
  const attr = `[data-rosetack-c="${key}"]`;
1392
+ const scopeOneSelector = (s) => {
1393
+ const t = s.trim();
1394
+ if (!t.includes(":global")) return `${attr} ${t}`;
1395
+ const stripped = t.replace(/:global\([^()]*\)/g, (m) => m.slice(8, -1)).trim();
1396
+ const outside = t.replace(/:global\([^()]*\)/g, "").trim();
1397
+ return outside ? `${attr} ${stripped}` : stripped;
1398
+ };
904
1399
  const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
905
1400
  let out = "";
906
1401
  let prelude = "";
@@ -920,7 +1415,7 @@ function scopeCss(css, key) {
920
1415
  if (sel.startsWith("@")) {
921
1416
  out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
922
1417
  } else if (sel) {
923
- const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
1418
+ const scoped = sel.split(",").map((s) => scopeOneSelector(s)).join(",");
924
1419
  out += `${scoped}{${minifyDecls(block)}}`;
925
1420
  }
926
1421
  prelude = "";
@@ -1066,6 +1561,20 @@ function extractExports(script) {
1066
1561
  out += script.slice(pos);
1067
1562
  return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
1068
1563
  }
1564
+ var REGEX_PRECEDERS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
1565
+ function isRegexStart(src, i) {
1566
+ let j = i - 1;
1567
+ while (j >= 0 && /\s/.test(src[j])) j--;
1568
+ if (j < 0) return true;
1569
+ const p = src[j];
1570
+ if (REGEX_PRECEDERS.has(p)) return true;
1571
+ if (/[A-Za-z0-9_$]/.test(p)) {
1572
+ const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
1573
+ if (!w) return false;
1574
+ return ["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else"].includes(w[1]);
1575
+ }
1576
+ return false;
1577
+ }
1069
1578
  function extractDecls(script) {
1070
1579
  const decls = [];
1071
1580
  DECL_RE.lastIndex = 0;
@@ -1114,61 +1623,783 @@ function extractDecls(script) {
1114
1623
  end
1115
1624
  });
1116
1625
  }
1117
- return decls;
1626
+ return decls;
1627
+ }
1628
+ function braceDepthAt(src, index) {
1629
+ let depth = 0;
1630
+ let i = 0;
1631
+ while (i < index) {
1632
+ const ch = src[i];
1633
+ if (ch === "'" || ch === '"' || ch === "`") {
1634
+ const quote = ch;
1635
+ i++;
1636
+ while (i < index) {
1637
+ if (src[i] === "\\") {
1638
+ i += 2;
1639
+ continue;
1640
+ }
1641
+ if (src[i] === quote) {
1642
+ i++;
1643
+ break;
1644
+ }
1645
+ if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
1646
+ let d = 1;
1647
+ i += 2;
1648
+ while (i < index && d > 0) {
1649
+ if (src[i] === "{") d++;
1650
+ else if (src[i] === "}") d--;
1651
+ i++;
1652
+ }
1653
+ continue;
1654
+ }
1655
+ i++;
1656
+ }
1657
+ continue;
1658
+ }
1659
+ if (ch === "/" && src[i + 1] === "/") {
1660
+ const nl = src.indexOf("\n", i);
1661
+ i = nl === -1 ? src.length : nl;
1662
+ continue;
1663
+ }
1664
+ if (ch === "/" && src[i + 1] === "*") {
1665
+ const close = src.indexOf("*/", i + 2);
1666
+ i = close === -1 ? src.length : close + 2;
1667
+ continue;
1668
+ }
1669
+ if (ch === "/" && isRegexStart(src, i)) {
1670
+ i++;
1671
+ let inClass = false;
1672
+ while (i < index) {
1673
+ const c2 = src[i];
1674
+ if (c2 === "\\") {
1675
+ i += 2;
1676
+ continue;
1677
+ }
1678
+ if (inClass) {
1679
+ if (c2 === "]") inClass = false;
1680
+ i++;
1681
+ continue;
1682
+ }
1683
+ if (c2 === "[") {
1684
+ inClass = true;
1685
+ i++;
1686
+ continue;
1687
+ }
1688
+ if (c2 === "/") {
1689
+ i++;
1690
+ break;
1691
+ }
1692
+ if (c2 === "\n") break;
1693
+ i++;
1694
+ }
1695
+ while (i < index && /[a-z]/.test(src[i])) i++;
1696
+ continue;
1697
+ }
1698
+ if (ch === "{") depth++;
1699
+ else if (ch === "}") depth--;
1700
+ i++;
1701
+ }
1702
+ return depth;
1703
+ }
1704
+ function autoCall(expr) {
1705
+ const e = expr.trim();
1706
+ return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1707
+ }
1708
+ var DEFER_ENABLED = true;
1709
+ function expandKeyBlocks(template, filePath2) {
1710
+ if (!template.includes("{#key")) return template;
1711
+ for (let pass = 0; pass < 10; pass++) {
1712
+ const OPEN_RE = /\{#key\s+([^}]+)\}/g;
1713
+ OPEN_RE.lastIndex = 0;
1714
+ const openM = OPEN_RE.exec(template);
1715
+ if (!openM) return template;
1716
+ const expr = openM[1].trim();
1717
+ const bodyStart = openM.index + openM[0].length;
1718
+ const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
1719
+ TOK_RE.lastIndex = bodyStart;
1720
+ let depth = 1;
1721
+ let closeAt = -1;
1722
+ let tm;
1723
+ while (tm = TOK_RE.exec(template)) {
1724
+ if (tm[0].startsWith("{#")) {
1725
+ depth++;
1726
+ continue;
1727
+ }
1728
+ depth--;
1729
+ if (depth === 0) {
1730
+ closeAt = tm.index;
1731
+ break;
1732
+ }
1733
+ }
1734
+ if (closeAt < 0) {
1735
+ throw new RoseError(
1736
+ "E-TEMPLATE",
1737
+ `${filePath2}: {#key ${expr}} is never closed`,
1738
+ { hint: "every {#key} needs its {/key}" }
1739
+ );
1740
+ }
1741
+ template = template.slice(0, openM.index) + `{#each [${expr}] as __rvkv}` + template.slice(bodyStart, closeAt) + "{/each}" + template.slice(closeAt + "{/key}".length);
1742
+ }
1743
+ return template;
1744
+ }
1745
+ function expandIfElseOnce(template) {
1746
+ const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
1747
+ let out = "";
1748
+ let pos = 0;
1749
+ let changed = false;
1750
+ for (; ; ) {
1751
+ const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
1752
+ if (!openM) {
1753
+ out += template.slice(pos);
1754
+ break;
1755
+ }
1756
+ const kind = openM[1];
1757
+ const head = openM[2];
1758
+ const start = pos + openM.index;
1759
+ const cond = kind === "if" ? head.trim() : "";
1760
+ const bodyStart = start + openM[0].length;
1761
+ out += template.slice(pos, start);
1762
+ TOK_RE.lastIndex = bodyStart;
1763
+ let depth = 1;
1764
+ let closeAt = -1;
1765
+ let closeLen = 0;
1766
+ const elses = [];
1767
+ let tm;
1768
+ while (tm = TOK_RE.exec(template)) {
1769
+ const tok = tm[0];
1770
+ if (tok.startsWith("{:else")) {
1771
+ if (depth === 1) {
1772
+ const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
1773
+ elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
1774
+ }
1775
+ continue;
1776
+ }
1777
+ if (tok.startsWith("{#")) {
1778
+ depth++;
1779
+ continue;
1780
+ }
1781
+ depth--;
1782
+ if (depth === 0) {
1783
+ closeAt = tm.index;
1784
+ closeLen = tok.length;
1785
+ break;
1786
+ }
1787
+ }
1788
+ if (closeAt < 0 || elses.length === 0) {
1789
+ out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
1790
+ if (closeAt < 0) break;
1791
+ pos = closeAt + closeLen;
1792
+ continue;
1793
+ }
1794
+ const body = template.slice(bodyStart, closeAt);
1795
+ if (kind === "each") {
1796
+ const lastBare = [...elses].reverse().find((e) => e.cond === null);
1797
+ if (!lastBare) {
1798
+ out += template.slice(start, closeAt + closeLen);
1799
+ pos = closeAt + closeLen;
1800
+ continue;
1801
+ }
1802
+ const relLast = lastBare.at - bodyStart;
1803
+ const eachBody = body.slice(0, relLast);
1804
+ const elseBody = body.slice(relLast + lastBare.len);
1805
+ const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, "").trim();
1806
+ out += template.slice(start, bodyStart) + eachBody + `{/each}{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
1807
+ pos = closeAt + closeLen;
1808
+ changed = true;
1809
+ continue;
1810
+ }
1811
+ const branches = [];
1812
+ let cursor = 0;
1813
+ for (let i = 0; i < elses.length; i++) {
1814
+ const e = elses[i];
1815
+ const rel = e.at - bodyStart;
1816
+ branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
1817
+ cursor = rel + e.len;
1818
+ }
1819
+ branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
1820
+ const first = branches.shift();
1821
+ const build2 = (bs) => {
1822
+ if (!bs.length) return "";
1823
+ const head2 = bs[0];
1824
+ const rest = bs.slice(1);
1825
+ if (head2.cond == null) return head2.body;
1826
+ let s = `{#if ${head2.cond}}${head2.body}{/if}`;
1827
+ if (rest.length) s += `{#if !(${head2.cond})}` + build2(rest) + `{/if}`;
1828
+ return s;
1829
+ };
1830
+ let emitted = `{#if ${cond}}${first.body}{/if}`;
1831
+ if (branches.length) emitted += `{#if !(${cond})}` + build2(branches) + `{/if}`;
1832
+ out += emitted;
1833
+ pos = closeAt + closeLen;
1834
+ changed = true;
1835
+ }
1836
+ return { template: out, changed };
1837
+ }
1838
+ function mergeStaticClass(template) {
1839
+ if (!/\sclass\s*=\s*"/.test(template) || !/\sclass\s*=\s*\{/.test(template)) return template;
1840
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1841
+ let out = "";
1842
+ let pos = 0;
1843
+ let m;
1844
+ TAG_RE.lastIndex = 0;
1845
+ while (m = TAG_RE.exec(template)) {
1846
+ const [whole, tag, attrs, selfClose] = m;
1847
+ const sm = /\sclass\s*=\s*"([^"]*)"/.exec(attrs);
1848
+ if (!sm) continue;
1849
+ const rm = /\sclass\s*=\s*\{/.exec(attrs);
1850
+ if (!rm || rm.index === sm.index) continue;
1851
+ const open = attrs.indexOf("{", rm.index);
1852
+ let depth = 1;
1853
+ let j = open + 1;
1854
+ while (j < attrs.length && depth > 0) {
1855
+ const ch = attrs[j];
1856
+ if (ch === '"' || ch === "'") {
1857
+ j = skipQuoted(attrs, j);
1858
+ continue;
1859
+ }
1860
+ if (ch === "{") depth++;
1861
+ else if (ch === "}") depth--;
1862
+ j++;
1863
+ }
1864
+ if (depth !== 0) continue;
1865
+ const expr = attrs.slice(open + 1, j - 1);
1866
+ const base = JSON.stringify(sm[1]);
1867
+ const merged = ` class={((v) => v == null ? ${base} : typeof v === 'object' ? ({ ${base}: true, ...v }) : (${base} + ' ' + v))(${expr})}`;
1868
+ const lo = Math.min(sm.index, rm.index);
1869
+ const hiEnd = Math.max(sm.index + sm[0].length, j);
1870
+ const newAttrs = attrs.slice(0, lo) + merged + attrs.slice(hiEnd);
1871
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1872
+ pos = m.index + whole.length;
1873
+ }
1874
+ out += template.slice(pos);
1875
+ return out;
1876
+ }
1877
+ function expandClassDirectives(template, filePath2) {
1878
+ if (!template.includes("class:")) return template;
1879
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1880
+ let out = "";
1881
+ let pos = 0;
1882
+ let m;
1883
+ TAG_RE.lastIndex = 0;
1884
+ while (m = TAG_RE.exec(template)) {
1885
+ const [whole, tag, attrs, selfClose] = m;
1886
+ if (!attrs.includes("class:")) continue;
1887
+ const pairs = [];
1888
+ const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
1889
+ let nm;
1890
+ while (nm = NAME_RE.exec(attrs)) {
1891
+ let i = nm.index + nm[0].length;
1892
+ let depth = 1;
1893
+ while (i < attrs.length && depth > 0) {
1894
+ const ch = attrs[i];
1895
+ if (ch === '"' || ch === "'") {
1896
+ i = skipQuoted(attrs, i);
1897
+ continue;
1898
+ }
1899
+ if (ch === "{") depth++;
1900
+ else if (ch === "}") depth--;
1901
+ i++;
1902
+ }
1903
+ if (depth !== 0) {
1904
+ throw new RoseError("E-TEMPLATE", `${filePath2}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
1905
+ }
1906
+ pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1907
+ }
1908
+ const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1909
+ const clsM = clsRe.exec(attrs);
1910
+ if (clsM && clsM[2].startsWith("{")) {
1911
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both class={...} and class: directives`, { file: filePath2, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
1912
+ }
1913
+ const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
1914
+ let closure = `(${JSON.stringify(staticCls)}`;
1915
+ for (const p of pairs) {
1916
+ closure += `+((${p.expr})?${JSON.stringify(" " + p.name)}:'')`;
1917
+ }
1918
+ closure += `)`;
1919
+ let newAttrs = attrs;
1920
+ for (let k = pairs.length - 1; k >= 0; k--) {
1921
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1922
+ }
1923
+ if (clsM) {
1924
+ newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
1925
+ } else {
1926
+ newAttrs = ` class={${closure}}` + newAttrs;
1927
+ }
1928
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1929
+ pos = m.index + whole.length;
1930
+ }
1931
+ if (pos === 0) return template;
1932
+ out += template.slice(pos);
1933
+ return out;
1934
+ }
1935
+ function expandTransitionDirectives(template, filePath2) {
1936
+ if (!/\s(?:transition|in|out):/.test(template)) return template;
1937
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1938
+ let out = "";
1939
+ let pos = 0;
1940
+ let m;
1941
+ TAG_RE.lastIndex = 0;
1942
+ while (m = TAG_RE.exec(template)) {
1943
+ const [whole, tag, attrs, selfClose] = m;
1944
+ if (!attrs.includes("transition:") && !/\s(?:in|out):/.test(attrs)) continue;
1945
+ const pairs = [];
1946
+ const NAME_RE = /\s(transition|in|out):([\w-]+)(?:\s*=\s*\{)?/g;
1947
+ let nm;
1948
+ while (nm = NAME_RE.exec(attrs)) {
1949
+ let start = nm.index;
1950
+ let end = nm.index + nm[0].length;
1951
+ let params = "";
1952
+ if (nm[0].endsWith("{")) {
1953
+ let depth = 1;
1954
+ let i = end;
1955
+ while (i < attrs.length && depth > 0) {
1956
+ const ch = attrs[i];
1957
+ if (ch === '"' || ch === "'") {
1958
+ i = skipQuoted(attrs, i);
1959
+ continue;
1960
+ }
1961
+ if (ch === "{") depth++;
1962
+ else if (ch === "}") depth--;
1963
+ i++;
1964
+ }
1965
+ if (depth !== 0) {
1966
+ throw new RoseError("E-TEMPLATE", `${filePath2}: transition:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the transition params expression needs a matching } before the tag ends" });
1967
+ }
1968
+ params = attrs.slice(end, i - 1);
1969
+ end = i;
1970
+ }
1971
+ pairs.push({ dir: nm[1] === "transition" ? "" : nm[1], name: nm[2], params, start, end });
1972
+ }
1973
+ if (pairs.length === 0) continue;
1974
+ let transitionValue = "";
1975
+ for (const p of pairs) {
1976
+ if (transitionValue) transitionValue += "|";
1977
+ transitionValue += (p.dir ? p.dir + ":" : "") + p.name + (p.params ? ":" + p.params : "");
1978
+ }
1979
+ let newAttrs = attrs;
1980
+ for (let k = pairs.length - 1; k >= 0; k--) {
1981
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1982
+ }
1983
+ const transRe = /\sdata-transition\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1984
+ const tm = transRe.exec(newAttrs);
1985
+ if (tm) {
1986
+ const existing = tm[2] ?? tm[3] ?? "";
1987
+ newAttrs = newAttrs.replace(transRe, ` data-transition="${existing}${transitionValue ? (existing ? "|" : "") + transitionValue : ""}"`);
1988
+ } else {
1989
+ newAttrs = ` data-transition="${transitionValue}"` + newAttrs;
1990
+ }
1991
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1992
+ pos = m.index + whole.length;
1993
+ }
1994
+ out += template.slice(pos);
1995
+ return out;
1996
+ }
1997
+ function expandAnimateDirectives(template, filePath2) {
1998
+ if (!template.includes("animate:")) return template;
1999
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2000
+ let out = "";
2001
+ let pos = 0;
2002
+ let m;
2003
+ TAG_RE.lastIndex = 0;
2004
+ while (m = TAG_RE.exec(template)) {
2005
+ const [whole, tag, attrs, selfClose] = m;
2006
+ if (!attrs.includes("animate:")) continue;
2007
+ const pairs = [];
2008
+ const NAME_RE = /\sanimate:([\w-]+)(?:\s*=\s*\{)?/g;
2009
+ let nm;
2010
+ while (nm = NAME_RE.exec(attrs)) {
2011
+ let start = nm.index;
2012
+ let end = nm.index + nm[0].length;
2013
+ let params = "";
2014
+ if (nm[0].endsWith("{")) {
2015
+ let depth = 1;
2016
+ let i = end;
2017
+ while (i < attrs.length && depth > 0) {
2018
+ const ch = attrs[i];
2019
+ if (ch === '"' || ch === "'") {
2020
+ i = skipQuoted(attrs, i);
2021
+ continue;
2022
+ }
2023
+ if (ch === "{") depth++;
2024
+ else if (ch === "}") depth--;
2025
+ i++;
2026
+ }
2027
+ if (depth !== 0) {
2028
+ throw new RoseError("E-TEMPLATE", `${filePath2}: animate:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the animate params expression needs a matching } before the tag ends" });
2029
+ }
2030
+ params = attrs.slice(end, i - 1);
2031
+ end = i;
2032
+ }
2033
+ pairs.push({ name: nm[1], params, start, end });
2034
+ }
2035
+ let animateValue = "";
2036
+ for (const p of pairs) {
2037
+ if (animateValue) animateValue += "|";
2038
+ animateValue += p.name + (p.params ? ":" + p.params : "");
2039
+ }
2040
+ let newAttrs = attrs;
2041
+ for (let k = pairs.length - 1; k >= 0; k--) {
2042
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2043
+ }
2044
+ const animRe = /\sdata-animate\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2045
+ const am = animRe.exec(newAttrs);
2046
+ if (am) {
2047
+ const existing = am[2] ?? am[3] ?? "";
2048
+ newAttrs = newAttrs.replace(animRe, ` data-animate="${existing}${animateValue ? (existing ? "|" : "") + animateValue : ""}"`);
2049
+ } else {
2050
+ newAttrs = ` data-animate="${animateValue}"` + newAttrs;
2051
+ }
2052
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2053
+ pos = m.index + whole.length;
2054
+ }
2055
+ out += template.slice(pos);
2056
+ return out;
2057
+ }
2058
+ function expandStyleDirectives(template, filePath2) {
2059
+ if (!template.includes("style:")) return template;
2060
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2061
+ let out = "";
2062
+ let pos = 0;
2063
+ let m;
2064
+ TAG_RE.lastIndex = 0;
2065
+ while (m = TAG_RE.exec(template)) {
2066
+ const [whole, tag, attrs, selfClose] = m;
2067
+ if (!attrs.includes("style:")) continue;
2068
+ const pairs = [];
2069
+ const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
2070
+ let nm;
2071
+ while (nm = NAME_RE.exec(attrs)) {
2072
+ let i = nm.index + nm[0].length;
2073
+ let depth = 1;
2074
+ while (i < attrs.length && depth > 0) {
2075
+ const ch = attrs[i];
2076
+ if (ch === '"' || ch === "'") {
2077
+ i = skipQuoted(attrs, i);
2078
+ continue;
2079
+ }
2080
+ if (ch === "{") depth++;
2081
+ else if (ch === "}") depth--;
2082
+ i++;
2083
+ }
2084
+ if (depth !== 0) {
2085
+ throw new RoseError("E-TEMPLATE", `${filePath2}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
2086
+ }
2087
+ pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
2088
+ }
2089
+ const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2090
+ const stM = styleRe.exec(attrs);
2091
+ if (stM && stM[2].startsWith("{")) {
2092
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both style={...} and style: directives`, { file: filePath2, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
2093
+ }
2094
+ const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
2095
+ let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
2096
+ for (const p of pairs) {
2097
+ closure += `+${JSON.stringify(p.prop + ":")}+(${p.expr})+';'`;
2098
+ }
2099
+ let newAttrs = attrs;
2100
+ for (let k = pairs.length - 1; k >= 0; k--) {
2101
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2102
+ }
2103
+ if (stM) {
2104
+ newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
2105
+ } else {
2106
+ newAttrs = ` style={${closure}}` + newAttrs;
2107
+ }
2108
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2109
+ pos = m.index + whole.length;
2110
+ }
2111
+ if (pos === 0) return template;
2112
+ out += template.slice(pos);
2113
+ return out;
2114
+ }
2115
+ function expandBoundaryFallbacks(template, filePath2) {
2116
+ if (!template.includes("{:fallback")) return template;
2117
+ for (let pass = 0; pass < 10; pass++) {
2118
+ const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
2119
+ let out = "";
2120
+ let pos = 0;
2121
+ let changed = false;
2122
+ let tm;
2123
+ while (tm = TOK_RE.exec(template)) {
2124
+ if (tm[0] !== "{#boundary}") continue;
2125
+ const start = tm.index;
2126
+ const bodyStart = start + tm[0].length;
2127
+ let depth = 1;
2128
+ let closeAt = -1;
2129
+ let tm2;
2130
+ while (tm2 = TOK_RE.exec(template)) {
2131
+ if (tm2[0] === "{#boundary}") {
2132
+ depth++;
2133
+ continue;
2134
+ }
2135
+ if (tm2[0] === "{/boundary}") {
2136
+ depth--;
2137
+ if (depth === 0) {
2138
+ closeAt = tm2.index;
2139
+ break;
2140
+ }
2141
+ }
2142
+ }
2143
+ if (closeAt < 0) break;
2144
+ const body = template.slice(bodyStart, closeAt);
2145
+ const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
2146
+ const kindStack = ["boundary"];
2147
+ let d = 1;
2148
+ let fbAt = -1;
2149
+ let fbLen = 0;
2150
+ let tm3;
2151
+ BTOK2.lastIndex = 0;
2152
+ while (tm3 = BTOK2.exec(body)) {
2153
+ const tok = tm3[0];
2154
+ if (tok === "{:fallback}") {
2155
+ const top = kindStack[kindStack.length - 1];
2156
+ if (top !== "boundary") {
2157
+ throw new RoseError(
2158
+ "E-TEMPLATE",
2159
+ `${filePath2}: {:fallback} must sit directly inside a {#boundary} block`,
2160
+ { hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
2161
+ );
2162
+ }
2163
+ if (fbAt >= 0) {
2164
+ throw new RoseError("E-TEMPLATE", `${filePath2}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
2165
+ }
2166
+ fbAt = tm3.index;
2167
+ fbLen = tok.length;
2168
+ continue;
2169
+ }
2170
+ if (tok.startsWith("{#")) {
2171
+ d++;
2172
+ kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]);
2173
+ continue;
2174
+ }
2175
+ d--;
2176
+ kindStack.pop();
2177
+ }
2178
+ if (fbAt < 0) continue;
2179
+ const custom = body.slice(0, fbAt);
2180
+ const fbMarkup = body.slice(fbAt + fbLen);
2181
+ const b64 = Buffer.from(fbMarkup, "utf-8").toString("base64");
2182
+ out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + "{/boundary}";
2183
+ pos = closeAt + "{/boundary}".length;
2184
+ changed = true;
2185
+ }
2186
+ if (!changed) break;
2187
+ template = out + template.slice(pos);
2188
+ }
2189
+ return template;
2190
+ }
2191
+ function expandIfElse(template) {
2192
+ for (let pass = 0; pass < 10; pass++) {
2193
+ if (!/\{:else\b/.test(template)) return template;
2194
+ const r = expandIfElseOnce(template);
2195
+ template = r.template;
2196
+ if (!r.changed) return template;
2197
+ }
2198
+ return template;
2199
+ }
2200
+ function expandDeferBlocks(template) {
2201
+ if (!DEFER_ENABLED) {
2202
+ const openRe2 = /\{#defer(?:\s+hold=\\d+)?\}/g;
2203
+ let out2 = "";
2204
+ let dpos = 0;
2205
+ for (; ; ) {
2206
+ openRe2.lastIndex = dpos;
2207
+ const openM = openRe2.exec(template);
2208
+ if (!openM) break;
2209
+ const openAt = openM.index;
2210
+ const openLen = openM[0].length;
2211
+ const closeAt = template.indexOf("{/defer}", openAt + openLen);
2212
+ if (closeAt < 0) break;
2213
+ out2 += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
2214
+ dpos = closeAt + 8;
2215
+ }
2216
+ return { template: dpos === 0 ? template : out2, count: 0, holds: [] };
2217
+ }
2218
+ let count = 0;
2219
+ const holds = [];
2220
+ let out = "";
2221
+ let pos = 0;
2222
+ const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
2223
+ for (; ; ) {
2224
+ openRe.lastIndex = pos;
2225
+ const openM = openRe.exec(template);
2226
+ if (!openM) break;
2227
+ const openAt = openM.index;
2228
+ const openLen = openM[0].length;
2229
+ const hold = openM[1] ? Number(openM[1]) : 0;
2230
+ let depth = 1;
2231
+ let i = openAt + openLen;
2232
+ let closeAt = -1;
2233
+ while (i < template.length) {
2234
+ openRe.lastIndex = i;
2235
+ const nextOpenM = openRe.exec(template);
2236
+ const nextOpen = nextOpenM ? nextOpenM.index : -1;
2237
+ const nextClose = template.indexOf("{/defer}", i);
2238
+ if (nextClose < 0) break;
2239
+ if (nextOpen >= 0 && nextOpen < nextClose) {
2240
+ depth++;
2241
+ i = nextOpen + nextOpenM[0].length;
2242
+ continue;
2243
+ }
2244
+ depth--;
2245
+ if (depth === 0) {
2246
+ closeAt = nextClose;
2247
+ break;
2248
+ }
2249
+ i = nextClose + 8;
2250
+ }
2251
+ if (closeAt < 0) break;
2252
+ const content = template.slice(openAt + openLen, closeAt);
2253
+ holds.push(hold);
2254
+ const n = ++count;
2255
+ out += template.slice(pos, openAt);
2256
+ out += "{#if __rvDefer" + n + "()}" + content + "{/if}\n{#if !__rvDefer" + n + '()}<div class="rv-defer-loading"></div>{/if}';
2257
+ pos = closeAt + 8;
2258
+ }
2259
+ if (count === 0) return { template, count: 0, holds: [] };
2260
+ out += template.slice(pos);
2261
+ return { template: out, count, holds };
1118
2262
  }
1119
- function braceDepthAt(src, index) {
1120
- let depth = 0;
1121
- let i = 0;
1122
- while (i < index) {
1123
- const ch = src[i];
1124
- if (ch === "'" || ch === '"' || ch === "`") {
1125
- const quote = ch;
2263
+ function deferBootCode(count, holds = []) {
2264
+ let code = "";
2265
+ for (let n = 1; n <= count; n++) {
2266
+ code += "const [__rvDefer" + n + ", set__rvDefer" + n + '] = state("__rvdefer' + n + '", false);\n';
2267
+ const hold = holds[n - 1] || 0;
2268
+ code += hold > 0 ? "onMount(function () { setTimeout(function () { set__rvDefer" + n + "(true); }, " + hold + "); });\n" : "onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer" + n + "(true); }); }); });\n";
2269
+ }
2270
+ return code;
2271
+ }
2272
+ function expandAwaitBlocks(template, filePath2) {
2273
+ let out = "";
2274
+ let pos = 0;
2275
+ let n = 0;
2276
+ const blocks = [];
2277
+ for (; ; ) {
2278
+ const openAt = template.indexOf("{#await", pos);
2279
+ if (openAt < 0) break;
2280
+ let i = openAt + 7;
2281
+ let brace = 1;
2282
+ while (i < template.length && brace > 0) {
2283
+ const c = template[i];
2284
+ if (c === "{") brace++;
2285
+ else if (c === "}") brace--;
1126
2286
  i++;
1127
- while (i < index) {
1128
- if (src[i] === "\\") {
1129
- i += 2;
1130
- continue;
2287
+ }
2288
+ if (brace !== 0) break;
2289
+ const openLen = i - openAt;
2290
+ const expr = template.slice(openAt + 7, i - 1).trim();
2291
+ if (!expr) {
2292
+ throw new RoseError("E-TEMPLATE", `${filePath2}: {#await} needs a promise expression`, {
2293
+ file: filePath2,
2294
+ hint: "write {#await fetchUsers()}...{:then users}...{/await}"
2295
+ });
2296
+ }
2297
+ const blockOpenRe = /\{\#(if|each|boundary|island|await)\b/g;
2298
+ const blockCloseRe = /\{\/(if|each|boundary|island|await)\}/g;
2299
+ const thenRe = /\{:then\b([^}]*)\}/g;
2300
+ const catchRe = /\{:catch\b([^}]*)\}/g;
2301
+ let d = 1;
2302
+ let j = i;
2303
+ let thenAt = -1, catchAt = -1, closeAt = -1;
2304
+ let thenRaw = "", catchRaw = "";
2305
+ for (; ; ) {
2306
+ blockOpenRe.lastIndex = j;
2307
+ blockCloseRe.lastIndex = j;
2308
+ thenRe.lastIndex = j;
2309
+ catchRe.lastIndex = j;
2310
+ const nextOpen = blockOpenRe.exec(template);
2311
+ const nextClose = blockCloseRe.exec(template);
2312
+ const nextThen = thenRe.exec(template);
2313
+ const nextCatch = catchRe.exec(template);
2314
+ let nearestPos = Infinity, kind = "", m = null;
2315
+ const consider = (mm, k) => {
2316
+ if (mm && mm.index < nearestPos) {
2317
+ nearestPos = mm.index;
2318
+ kind = k;
2319
+ m = mm;
1131
2320
  }
1132
- if (src[i] === quote) {
1133
- i++;
2321
+ };
2322
+ consider(nextOpen, "open");
2323
+ consider(nextClose, "close");
2324
+ consider(nextThen, "then");
2325
+ consider(nextCatch, "catch");
2326
+ if (!m) break;
2327
+ if (kind === "open") {
2328
+ d++;
2329
+ j = m.index + m[0].length;
2330
+ continue;
2331
+ }
2332
+ if (kind === "close") {
2333
+ if (d === 1 && m[1] === "await") {
2334
+ closeAt = m.index;
1134
2335
  break;
1135
2336
  }
1136
- if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
1137
- let d = 1;
1138
- i += 2;
1139
- while (i < index && d > 0) {
1140
- if (src[i] === "{") d++;
1141
- else if (src[i] === "}") d--;
1142
- i++;
1143
- }
1144
- continue;
2337
+ d--;
2338
+ j = m.index + m[0].length;
2339
+ continue;
2340
+ }
2341
+ if (d === 1) {
2342
+ if (kind === "then" && thenAt < 0) {
2343
+ thenAt = m.index;
2344
+ thenRaw = m[1];
2345
+ } else if (kind === "catch" && catchAt < 0) {
2346
+ catchAt = m.index;
2347
+ catchRaw = m[1];
1145
2348
  }
1146
- i++;
1147
2349
  }
1148
- continue;
1149
- }
1150
- if (ch === "/" && src[i + 1] === "/") {
1151
- const nl = src.indexOf("\n", i);
1152
- i = nl === -1 ? src.length : nl;
1153
- continue;
2350
+ j = m.index + m[0].length;
1154
2351
  }
1155
- if (ch === "/" && src[i + 1] === "*") {
1156
- const close = src.indexOf("*/", i + 2);
1157
- i = close === -1 ? src.length : close + 2;
1158
- continue;
2352
+ if (closeAt < 0 || thenAt < 0) break;
2353
+ const thenTokenEnd = thenAt + 7 + thenRaw.length;
2354
+ const catchTokenEnd = catchAt >= 0 ? catchAt + 7 + catchRaw.length : -1;
2355
+ const pending = template.slice(i, thenAt);
2356
+ const thenBody = template.slice(thenTokenEnd, catchAt >= 0 ? catchAt : closeAt);
2357
+ const catchBody = catchAt >= 0 ? template.slice(catchTokenEnd, closeAt) : "";
2358
+ const thenVarRaw = thenRaw.trim();
2359
+ const catchVarRaw = catchRaw.trim();
2360
+ const thenVar = /^\w+$/.test(thenVarRaw) ? thenVarRaw : `__rvAwaitThen${n + 1}`;
2361
+ const catchVar = catchAt >= 0 ? /^\w+$/.test(catchVarRaw) ? catchVarRaw : `__rvAwaitCatch${n + 1}` : "";
2362
+ n++;
2363
+ const nn = n;
2364
+ const stateName = `__rvAwait${nn}`;
2365
+ blocks.push({ n: nn, expr, thenVar, catchVar });
2366
+ out += template.slice(pos, openAt);
2367
+ out += `{#if ${stateName}().status === 'pending'}` + pending + "{/if}\n";
2368
+ out += `{#each (${stateName}().status === 'resolved' ? [${stateName}().value] : []) as ${thenVar}}` + thenBody + "{/each}\n";
2369
+ if (catchAt >= 0) {
2370
+ out += `{#each (${stateName}().status === 'rejected' ? [${stateName}().error] : []) as ${catchVar}}` + catchBody + "{/each}\n";
1159
2371
  }
1160
- if (ch === "{") depth++;
1161
- else if (ch === "}") depth--;
1162
- i++;
2372
+ pos = closeAt + 8;
1163
2373
  }
1164
- return depth;
2374
+ if (n === 0) return { template, blocks };
2375
+ out += template.slice(pos);
2376
+ return { template: out, blocks };
1165
2377
  }
1166
- function autoCall(expr) {
1167
- const e = expr.trim();
1168
- return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
2378
+ function awaitBootCode(blocks) {
2379
+ let code = "";
2380
+ for (const b of blocks) {
2381
+ const stateName = `__rvAwait${b.n}`;
2382
+ code += `const [${stateName}, set${stateName}] = state("__rvawait${b.n}", { status: 'pending', value: null, error: null });
2383
+ `;
2384
+ code += `onMount(function () {
2385
+ `;
2386
+ code += ` Promise.resolve(${b.expr}).then(function (__rvAwaitVal) {
2387
+ `;
2388
+ code += ` set${stateName}({ status: 'resolved', value: __rvAwaitVal });
2389
+ `;
2390
+ code += ` }).catch(function (__rvAwaitErr) {
2391
+ `;
2392
+ code += ` set${stateName}({ status: 'rejected', error: __rvAwaitErr });
2393
+ `;
2394
+ code += ` });
2395
+ `;
2396
+ code += `});
2397
+ `;
2398
+ }
2399
+ return code;
1169
2400
  }
1170
2401
  function findBlock(src, kind) {
1171
- const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
2402
+ const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : kind === "snippet" ? /\{#snippet\s+(\w+)(?:\s*\(([^)]+)\))?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([^)]+)\))?\}/g;
1172
2403
  const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1173
2404
  let open;
1174
2405
  while (open = head.exec(src)) {
@@ -1190,7 +2421,7 @@ function findBlock(src, kind) {
1190
2421
  i = nextClose.index + nextClose[0].length;
1191
2422
  if (--depth === 0) {
1192
2423
  const content = src.slice(afterOpen, nextClose.index);
1193
- const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
2424
+ const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "snippet" ? [open[1], open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", open[4] ?? "", content];
1194
2425
  const arr = [src.slice(start, i), ...groups];
1195
2426
  arr.index = start;
1196
2427
  return arr;
@@ -1233,8 +2464,20 @@ function compileHead(head) {
1233
2464
  flush();
1234
2465
  return out;
1235
2466
  }
1236
- var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
1237
- function assertKnownDirectives(template, filePath) {
2467
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island", "await", "snippet"]);
2468
+ var __blockResCache = /* @__PURE__ */ new Map();
2469
+ function blockCloseRes(kind) {
2470
+ let hit = __blockResCache.get(kind);
2471
+ if (!hit) {
2472
+ hit = {
2473
+ open: new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g"),
2474
+ close: new RegExp(`\\{/${kind}\\}`, "g")
2475
+ };
2476
+ __blockResCache.set(kind, hit);
2477
+ }
2478
+ return hit;
2479
+ }
2480
+ function assertKnownDirectives(template, filePath2) {
1238
2481
  const rawRanges = [];
1239
2482
  const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
1240
2483
  let raw;
@@ -1260,36 +2503,83 @@ function assertKnownDirectives(template, filePath) {
1260
2503
  if (sigil === "/") {
1261
2504
  throw new RoseError(
1262
2505
  "E-TEMPLATE",
1263
- `${filePath}: {/${word}} does not close anything`,
1264
- { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2506
+ `${filePath2}: {/${word}} does not close anything`,
2507
+ { file: filePath2, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
1265
2508
  );
1266
2509
  }
1267
2510
  if (word === "else") {
2511
+ const netOpens = (re, closer, at) => {
2512
+ let n = 0, mm;
2513
+ re.lastIndex = 0;
2514
+ while (mm = re.exec(template)) {
2515
+ if (mm.index >= at) break;
2516
+ if (!inRaw(mm.index)) n++;
2517
+ }
2518
+ const cr = new RegExp(closer, "g");
2519
+ let c = 0;
2520
+ while (mm = cr.exec(template)) {
2521
+ if (mm.index >= at) break;
2522
+ if (!inRaw(mm.index)) c++;
2523
+ }
2524
+ return n - c;
2525
+ };
2526
+ const ifNet = netOpens(/\{#if\b/g, "\\{/if\\b", m.index);
2527
+ const eachNet = netOpens(/\{#each\b/g, "\\{/each\\b", m.index);
2528
+ if (ifNet <= 0 && eachNet <= 0) {
2529
+ throw new RoseError(
2530
+ "E-TEMPLATE",
2531
+ `${filePath2}: a stray {:else} with no {#if} or {#each} above it`,
2532
+ { file: filePath2, line: lineAt(template, m), hint: "{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block" }
2533
+ );
2534
+ }
2535
+ continue;
2536
+ }
2537
+ if (word === "fallback") {
1268
2538
  throw new RoseError(
1269
2539
  "E-TEMPLATE",
1270
- `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1271
- { file: filePath, line: lineAt(template, m), hint: "nest a second {#if}: {#if cond}A{/if}{#if !cond}B{/if} - the negation of the first condition IS the else" }
2540
+ `${filePath2}: a stray {:fallback} with no {#boundary} above it`,
2541
+ { file: filePath2, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
1272
2542
  );
1273
2543
  }
2544
+ if (word === "then" || word === "catch") {
2545
+ const opensBefore = (re, at) => {
2546
+ re.lastIndex = 0;
2547
+ let n = 0, mm;
2548
+ while (mm = re.exec(template)) {
2549
+ if (mm.index >= at) break;
2550
+ if (!inRaw(mm.index)) n++;
2551
+ }
2552
+ return n;
2553
+ };
2554
+ const open = opensBefore(/\{#await\b/g, m.index);
2555
+ const close = opensBefore(/\{\/await\b/g, m.index);
2556
+ if (open <= close) {
2557
+ throw new RoseError(
2558
+ "E-TEMPLATE",
2559
+ `${filePath2}: a stray {:${word}} with no {#await} above it`,
2560
+ { file: filePath2, line: lineAt(template, m), hint: "{:then} / {:catch} belong inside an {#await} ... {/await} block" }
2561
+ );
2562
+ }
2563
+ continue;
2564
+ }
1274
2565
  throw new RoseError(
1275
2566
  "E-TEMPLATE",
1276
- `${filePath}: {:${word}} is not a rosetack directive`,
1277
- { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary} - and there is no {:else}: nest a second {#if} with the negated condition" }
2567
+ `${filePath2}: {:${word}} is not a rosetack directive`,
2568
+ { file: filePath2, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
1278
2569
  );
1279
2570
  }
1280
- const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
2571
+ const OPENER_RE = /\{#(if|each|boundary|island|await)\b([^}]*)\}/g;
1281
2572
  while (m = OPENER_RE.exec(template)) {
1282
2573
  if (inRaw(m.index)) continue;
1283
2574
  const [, kind, head] = m;
1284
- if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
2575
+ if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?(?:\s*\([^)]*\))?\s*$/.test(head)) {
1285
2576
  throw new RoseError(
1286
2577
  "E-TEMPLATE",
1287
- `${filePath}: {#each ${head.trim()}} is missing its item name`,
1288
- { file: filePath, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
2578
+ `${filePath2}: {#each ${head.trim()}} is missing its item name`,
2579
+ { file: filePath2, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
1289
2580
  );
1290
2581
  }
1291
- const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
1292
- const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
2582
+ const { open: OPEN_RE, close: CLOSE_RE } = blockCloseRes(kind);
1293
2583
  let depth = 1;
1294
2584
  let i = m.index + m[0].length;
1295
2585
  for (; ; ) {
@@ -1308,8 +2598,8 @@ function assertKnownDirectives(template, filePath) {
1308
2598
  if (depth !== 0) {
1309
2599
  throw new RoseError(
1310
2600
  "E-TEMPLATE",
1311
- `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
1312
- { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2601
+ `${filePath2}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2602
+ { file: filePath2, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
1313
2603
  );
1314
2604
  }
1315
2605
  }
@@ -1335,11 +2625,14 @@ function rewriteQuotedExprAttrs(template, comps) {
1335
2625
  return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
1336
2626
  });
1337
2627
  }
1338
- function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
2628
+ function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map(), islandDepth = 0) {
1339
2629
  let result = "";
1340
2630
  let remaining = template;
1341
2631
  let blockId = 0;
2632
+ const islandsMode = /\{#island\b/.test(template);
2633
+ const effMarkers = markers && (!islandsMode || islandDepth > 0);
1342
2634
  const nextId = () => `${depth}_${blockId++}`;
2635
+ if (depth === 0) result += "const __snip = {};\n";
1343
2636
  while (remaining.length > 0) {
1344
2637
  const ifMatch = findBlock(remaining, "if");
1345
2638
  const eachMatch = findBlock(remaining, "each");
@@ -1347,10 +2640,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1347
2640
  const firstExpr = templateExprSpans(remaining)[0];
1348
2641
  const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
1349
2642
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2643
+ const islandMatch = findBlock(remaining, "island");
2644
+ const snippetMatch = findBlock(remaining, "snippet");
1350
2645
  const candidates = [];
1351
2646
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
1352
2647
  if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
1353
2648
  if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
2649
+ if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
2650
+ if (snippetMatch?.index !== void 0) candidates.push({ type: "snippet", match: snippetMatch, index: snippetMatch.index });
1354
2651
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
1355
2652
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
1356
2653
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
@@ -1384,10 +2681,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1384
2681
  const call = autoCall(cond);
1385
2682
  const id = nextId();
1386
2683
  const innerScope = scope ?? "__s";
1387
- const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, markers, comps);
2684
+ const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, effMarkers, comps, islandDepth);
1388
2685
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
1389
2686
  `;
1390
- if (markers) {
2687
+ if (effMarkers) {
1391
2688
  result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
1392
2689
  `;
1393
2690
  } else {
@@ -1396,45 +2693,88 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1396
2693
  }
1397
2694
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1398
2695
  } else if (earliest.type === "each") {
1399
- const [, items, item, content] = earliest.match;
2696
+ const [, items, item, index, key, content] = earliest.match;
1400
2697
  const before = remaining.substring(0, earliest.index);
1401
2698
  if (before) result += emitChunk(before, acc, closes, scope);
1402
2699
  const call = autoCall(items);
1403
2700
  const id = nextId();
1404
- const itemRe = new RegExp(`\\b${item}\\b`, "g");
2701
+ const isDestructure = /^[{[]/.test(item);
2702
+ const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, "g");
2703
+ const indexRe = index ? new RegExp(`\\b${index}\\b`, "g") : null;
1405
2704
  let scoped = "";
1406
2705
  let lastSpan = 0;
1407
2706
  for (const s of templateExprSpans(content.trim())) {
1408
- scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
2707
+ let expr = itemRe ? s.expr.replace(itemRe, "__s") : s.expr;
2708
+ if (indexRe) expr = expr.replace(indexRe, "__i");
2709
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + expr + "}";
1409
2710
  lastSpan = s.end + 1;
1410
2711
  }
1411
2712
  scoped += content.trim().slice(lastSpan);
1412
- const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
1413
- result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
2713
+ const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2714
+ const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2715
+ let keyFn = "";
2716
+ if (key) {
2717
+ if (isDestructure) {
2718
+ throw new RoseError(
2719
+ "E-TEMPLATE",
2720
+ `${filePath}: a keyed {#each} keys on a named item's property - write {#each xs as x (x.id)}, not a destructuring pattern`,
2721
+ { file: filePath, hint: "name the item first, then key on one of its properties" }
2722
+ );
2723
+ }
2724
+ let k = key.trim();
2725
+ if (itemRe) k = k.replace(itemRe, "__s");
2726
+ if (indexRe) k = k.replace(indexRe, "__i");
2727
+ keyFn = `, (__s, __i) => (${k})`;
2728
+ }
2729
+ result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
1414
2730
  `;
1415
- if (markers) {
1416
- result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
2731
+ if (effMarkers) {
2732
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id}${keyFn});
1417
2733
  `;
1418
2734
  } else {
1419
- result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');
2735
+ const param = isDestructure ? "__s" : item;
2736
+ result += `${acc} += (${call}).map((${param}${index ? ", __i" : ""}) => __b${id}(${param}, []${index ? ", __i" : ""}))).join('');
1420
2737
  `;
1421
2738
  }
1422
2739
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1423
2740
  } else if (earliest.type === "boundary") {
1424
- const [, content] = earliest.match;
2741
+ const [, fbAttr, content] = earliest.match;
2742
+ let fallbackSrc = "";
2743
+ if (fbAttr) {
2744
+ const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
2745
+ if (fbM) fallbackSrc = Buffer.from(fbM[1], "base64").toString("utf-8");
2746
+ }
2747
+ const custom = content;
1425
2748
  const before = remaining.substring(0, earliest.index);
1426
2749
  if (before) result += emitChunk(before, acc, closes, scope);
1427
2750
  const id = nextId();
1428
- const catchesAction = /\$action:|<form[\s>]/.test(content);
1429
- const inner = compileTemplate(content.trim(), "h", closes, scope, depth + 1, markers, comps);
2751
+ const catchesAction = /\$action:|<form[\s>]/.test(custom);
2752
+ const inner = compileTemplate(custom.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
1430
2753
  result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
1431
2754
  `;
2755
+ let fbBlock = "";
2756
+ if (fallbackSrc.trim()) {
2757
+ const fbInner = compileTemplate(fallbackSrc.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
2758
+ fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };
2759
+ `;
2760
+ }
2761
+ result += fbBlock;
1432
2762
  result += `let __bd${id} = '';
1433
2763
  `;
1434
- result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
1435
- ` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
2764
+ result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : "$boundaryFallback(e)"}; }
2765
+ ` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
1436
2766
  `;
1437
2767
  result += `${acc} += __bd${id};
2768
+ `;
2769
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2770
+ } else if (earliest.type === "snippet") {
2771
+ const [, name, params, content] = earliest.match;
2772
+ const before = remaining.substring(0, earliest.index);
2773
+ if (before) result += emitChunk(before, acc, closes, scope);
2774
+ const id = nextId();
2775
+ const paramList = params ? params.split(",").map((p) => p.trim()).filter(Boolean).join(",") : "";
2776
+ const inner = compileTemplate(content.trim(), "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2777
+ result += `__snip.${name} = (__s, __c${paramList ? "," + paramList : ""}) => { let h = ''; ${inner} return h; };
1438
2778
  `;
1439
2779
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1440
2780
  } else if (earliest.type === "comp") {
@@ -1455,7 +2795,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1455
2795
  const { def, named } = splitSlots(childrenSrc);
1456
2796
  const hasChildren = def.trim().length > 0;
1457
2797
  if (hasChildren) {
1458
- result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, markers, comps)} return h; };
2798
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; };
1459
2799
  `;
1460
2800
  }
1461
2801
  const slotFns = named.map(([nm, src]) => {
@@ -1471,9 +2811,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1471
2811
  }
1472
2812
  content = out + content.slice(lastSpan);
1473
2813
  }
1474
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
2814
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; }`;
1475
2815
  });
1476
2816
  const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
2817
+ if (a.kind === "spread") return `...(${a.value})`;
1477
2818
  const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
1478
2819
  const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
1479
2820
  return `${JSON.stringify(key)}: ${val}`;
@@ -1482,20 +2823,49 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1482
2823
  result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
1483
2824
  `;
1484
2825
  remaining = rest;
2826
+ } else if (earliest.type === "island") {
2827
+ const [, name, hydrate, content] = earliest.match;
2828
+ const before = remaining.substring(0, earliest.index);
2829
+ if (before) result += emitChunk(before, acc, closes, scope);
2830
+ const hydrateAttr = hydrate === "visible" || hydrate === "idle" ? ` data-rv-island-hydrate="${hydrate}"` : "";
2831
+ result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ""}"${hydrateAttr}>`)};
2832
+ `;
2833
+ const inner = compileTemplate(content.trim(), "h", "__c", scope, depth + 1, markers, comps, islandDepth + 1);
2834
+ result += inner;
2835
+ result += `${acc} += '</div>';
2836
+ `;
2837
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1485
2838
  } else {
1486
2839
  const [, expr] = earliest.match;
1487
2840
  const trimmed = expr.trim();
1488
2841
  const before = remaining.substring(0, earliest.index);
2842
+ const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
2843
+ if (constMatch) {
2844
+ if (before) result += emitChunk(before, acc, closes, scope);
2845
+ result += `const ${constMatch[1]} = (${constMatch[2].trim()});
2846
+ `;
2847
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2848
+ continue;
2849
+ }
1489
2850
  if (trimmed === "__slot__") {
1490
2851
  if (before) result += emitChunk(before, acc, closes, scope);
1491
2852
  result += compileSlot(acc);
1492
2853
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1493
2854
  continue;
1494
2855
  }
1495
- const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
2856
+ const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
2857
+ if (slotDefault) {
2858
+ if (before) result += emitChunk(before, acc, closes, scope);
2859
+ result += `${acc} += __slotDefault(children, ${slotDefault[1]});
2860
+ `;
2861
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2862
+ continue;
2863
+ }
2864
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
1496
2865
  if (slotCall) {
1497
2866
  if (before) result += emitChunk(before, acc, closes, scope);
1498
- result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);
2867
+ const fb = slotCall[4] ? `, ${slotCall[4]}` : "";
2868
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});
1499
2869
  `;
1500
2870
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1501
2871
  continue;
@@ -1504,7 +2874,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1504
2874
  if (rawMatch) {
1505
2875
  if (before) result += emitChunk(before, acc, closes, scope);
1506
2876
  const expr2 = rawMatch[1].trim();
1507
- if (!markers) {
2877
+ if (!effMarkers) {
1508
2878
  result += `${acc} += String(${expr2} ?? '');
1509
2879
  `;
1510
2880
  } else {
@@ -1515,16 +2885,43 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1515
2885
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1516
2886
  continue;
1517
2887
  }
2888
+ const dbgMatch = /^@debug\b([\s\S]*)$/.exec(trimmed);
2889
+ if (dbgMatch) {
2890
+ if (before) result += emitChunk(before, acc, closes, scope);
2891
+ const names = dbgMatch[1].trim().replace(/,$/, "");
2892
+ result += names ? `console.log('[rosetack:debug]', { ${names} });
2893
+ ` : `console.log('[rosetack:debug]'); debugger;
2894
+ `;
2895
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2896
+ continue;
2897
+ }
2898
+ const renderMatch = /^@render\s+([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(trimmed);
2899
+ if (renderMatch) {
2900
+ const ahead = new RegExp(`\\{#snippet\\s+${renderMatch[1]}\\b`).test(remaining.substring(earliest.index + earliest.match[0].length));
2901
+ if (ahead) {
2902
+ throw new RoseError(
2903
+ "E-TEMPLATE",
2904
+ `${filePath}: {@render ${renderMatch[1]}} runs before its {#snippet ${renderMatch[1]}} is defined`,
2905
+ { file: filePath, hint: "move the {#snippet} definition above the {@render} call - definitions register as the statement stream reaches them" }
2906
+ );
2907
+ }
2908
+ if (before) result += emitChunk(before, acc, closes, scope);
2909
+ const renderArgs = renderMatch[2].trim();
2910
+ result += `${acc} += ((__snip && __snip.${renderMatch[1]}) ? __snip.${renderMatch[1]}(${scope ?? "null"}, ${closes}${renderArgs ? ", " + renderArgs : ""}) : '');
2911
+ `;
2912
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2913
+ continue;
2914
+ }
1518
2915
  const attrMatch = before.match(/([\w-]+)=\s*$/);
1519
2916
  if (attrMatch) {
1520
2917
  const lit = before.slice(0, before.length - attrMatch[0].length);
1521
2918
  if (lit) result += emitChunk(lit, acc, closes, scope);
1522
- result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
2919
+ result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
1523
2920
  } else {
1524
2921
  if (before) result += emitChunk(before, acc, closes, scope);
1525
2922
  const after = remaining.substring(earliest.index + earliest.match[0].length);
1526
2923
  const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
1527
- result += emitText(trimmed, acc, closes, scope, markers, pair);
2924
+ result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
1528
2925
  }
1529
2926
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1530
2927
  }
@@ -1584,6 +2981,12 @@ function parseCompAttrs(attrs) {
1584
2981
  const out = [];
1585
2982
  let i = 0;
1586
2983
  while (i < attrs.length) {
2984
+ const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
2985
+ if (spread) {
2986
+ out.push({ name: "...", kind: "spread", value: spread[1].trim() });
2987
+ i += spread[0].length;
2988
+ continue;
2989
+ }
1587
2990
  const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
1588
2991
  if (!nm) break;
1589
2992
  i += nm[0].length;
@@ -1637,6 +3040,7 @@ function splitSlots(src) {
1637
3040
  let i = 0;
1638
3041
  let elemDepth = 0;
1639
3042
  let blockDepth = 0;
3043
+ const blockStack = [];
1640
3044
  while (i < src.length) {
1641
3045
  const lt = src.indexOf("<", i);
1642
3046
  const ob = src.indexOf("{#", i);
@@ -1651,8 +3055,14 @@ function splitSlots(src) {
1651
3055
  if (next === ob || next === cb) {
1652
3056
  const close = src.indexOf("}", next);
1653
3057
  const token = src.slice(next, close < 0 ? src.length : close + 1);
1654
- if (next === ob) blockDepth++;
1655
- else blockDepth = Math.max(0, blockDepth - 1);
3058
+ if (next === ob) {
3059
+ const m = /^\{#(\w+)/.exec(token);
3060
+ blockStack.push({ header: token, type: m ? m[1] : "" });
3061
+ blockDepth++;
3062
+ } else {
3063
+ blockDepth = Math.max(0, blockDepth - 1);
3064
+ if (blockStack.length) blockStack.pop();
3065
+ }
1656
3066
  def += token;
1657
3067
  i = next + token.length;
1658
3068
  continue;
@@ -1679,20 +3089,16 @@ function splitSlots(src) {
1679
3089
  }
1680
3090
  if (!selfClosing && !isVoid) elemDepth++;
1681
3091
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
1682
- if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
1683
- throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
1684
- }
1685
- if (slotName) {
1686
- const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3092
+ if (slotName && elemDepth === 1 && blockDepth === 0) {
1687
3093
  if (selfClosing || isVoid) {
1688
- named.set(slotName, (named.get(slotName) ?? "") + stripped);
3094
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, ""));
1689
3095
  } else {
1690
3096
  const closeIdx = findClose(src, end, nm[2]);
1691
- if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
3097
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
1692
3098
  const tail = `</${nm[2]}>`;
1693
3099
  const inner = src.slice(end, closeIdx);
1694
3100
  rejectNestedSlot(inner, slotName);
1695
- named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
3101
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "") + inner + tail);
1696
3102
  elemDepth = Math.max(0, elemDepth - 1);
1697
3103
  i = closeIdx + tail.length;
1698
3104
  continue;
@@ -1700,6 +3106,32 @@ function splitSlots(src) {
1700
3106
  i = end;
1701
3107
  continue;
1702
3108
  }
3109
+ if (slotName && blockDepth > 0) {
3110
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3111
+ let lifted = "";
3112
+ for (const b of blockStack) lifted += b.header;
3113
+ lifted += stripped;
3114
+ if (selfClosing || isVoid) {
3115
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3116
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3117
+ i = end;
3118
+ continue;
3119
+ }
3120
+ const closeIdx = findClose(src, end, nm[2]);
3121
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
3122
+ const tail = `</${nm[2]}>`;
3123
+ lifted += src.slice(end, closeIdx) + tail;
3124
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3125
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3126
+ elemDepth = Math.max(0, elemDepth - 1);
3127
+ i = closeIdx + tail.length;
3128
+ continue;
3129
+ }
3130
+ if (slotName) {
3131
+ throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component, or wrapped only by an {#if}/{#each}/{#boundary} block - it is nested inside another element`, {
3132
+ hint: 'place the element with slot="..." directly inside the component tag, or inside a single {#if}/{#each} block - wrapping it in another element is not yet supported'
3133
+ });
3134
+ }
1703
3135
  def += tagText;
1704
3136
  i = end;
1705
3137
  }
@@ -1720,23 +3152,76 @@ var IMG_MIME = {
1720
3152
  ".svg": "image/svg+xml",
1721
3153
  ".ico": "image/x-icon"
1722
3154
  };
1723
- var INLINE_IMG_MAX = 4096;
3155
+ var INLINE_IMG_MAX = 8192;
3156
+ var INLINE_SVG_MAX = 16384;
3157
+ function listImageVariants(publicDir, url) {
3158
+ const ext = path2.extname(url);
3159
+ const base = path2.basename(url, ext);
3160
+ const dirUrl = url.slice(0, url.length - (base + ext).length);
3161
+ let entries;
3162
+ try {
3163
+ entries = fs3.readdirSync(path2.join(publicDir, path2.dirname(url)));
3164
+ } catch {
3165
+ return [];
3166
+ }
3167
+ const re = new RegExp(
3168
+ "^" + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.w(\\d+)" + ext.replace(".", "\\.") + "$",
3169
+ "i"
3170
+ );
3171
+ const out = [];
3172
+ for (const e of entries) {
3173
+ const m = re.exec(e);
3174
+ const width = m ? Number(m[1]) : 0;
3175
+ if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
3176
+ }
3177
+ return out.sort((a, b) => a.width - b.width);
3178
+ }
3179
+ var __imgReadCache = /* @__PURE__ */ new Map();
3180
+ function cachedImageRead(filePath2) {
3181
+ let st;
3182
+ try {
3183
+ st = fs3.statSync(filePath2);
3184
+ } catch {
3185
+ return null;
3186
+ }
3187
+ const hit = __imgReadCache.get(filePath2);
3188
+ if (hit && hit.mtime === st.mtimeMs) return { buffer: hit.buffer, dims: hit.dims };
3189
+ let buffer;
3190
+ try {
3191
+ buffer = fs3.readFileSync(filePath2);
3192
+ } catch {
3193
+ return null;
3194
+ }
3195
+ const dims = readImageSize(filePath2);
3196
+ const entry = { mtime: st.mtimeMs, buffer, dims };
3197
+ __imgReadCache.set(filePath2, entry);
3198
+ return { buffer, dims: entry.dims };
3199
+ }
1724
3200
  function inlineImages(template, publicDir) {
1725
3201
  return template.replace(IMG_RE, (tag) => {
1726
3202
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
1727
3203
  if (!src) return tag;
1728
- const ext = path.extname(src[1]).toLowerCase();
3204
+ const ext = path2.extname(src[1]).toLowerCase();
1729
3205
  const mime = IMG_MIME[ext];
1730
3206
  if (!mime) return tag;
1731
- let file;
1732
- try {
1733
- file = fs.readFileSync(path.join(publicDir, src[1]));
1734
- } catch {
1735
- return tag;
3207
+ const rel = src[1].replace(/^\/public(?=\/)/, "");
3208
+ const filePath2 = path2.join(publicDir, rel);
3209
+ const read = cachedImageRead(filePath2);
3210
+ if (!read) return tag;
3211
+ const file = read.buffer;
3212
+ const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
3213
+ const dims = authorDims ? null : read.dims;
3214
+ const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
3215
+ const inlineMax = ext === ".svg" ? INLINE_SVG_MAX : INLINE_IMG_MAX;
3216
+ if (file.length > inlineMax) {
3217
+ const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
3218
+ const variants = hasSS ? [] : listImageVariants(publicDir, rel);
3219
+ if (!variants.length) return withDims(tag);
3220
+ const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(", ");
3221
+ return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
1736
3222
  }
1737
- if (file.length > INLINE_IMG_MAX) return tag;
1738
3223
  const uri = ext === ".svg" ? `data:image/svg+xml,${file.toString("utf-8").replace(/%/g, "%25").replace(/#/g, "%23").replace(/\{/g, "%7B").replace(/\}/g, "%7D").replace(/"/g, "%22")}` : `data:${mime};base64,${file.toString("base64")}`;
1739
- return tag.replace(src[0], `src="${uri}"`);
3224
+ return withDims(tag.replace(src[0], `src="${uri}"`));
1740
3225
  });
1741
3226
  }
1742
3227
  function emitText(expr, acc, closes, scope, markers = true, pair = false) {
@@ -1750,6 +3235,7 @@ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
1750
3235
  return `${acc} += textMark(${closes}, ${fn}${extra});
1751
3236
  `;
1752
3237
  }
3238
+ var BOOLEAN_ATTRS = /* @__PURE__ */ new Set(["checked", "disabled", "readonly", "required", "selected", "multiple", "autofocus", "open"]);
1753
3239
  function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1754
3240
  if (!markers) {
1755
3241
  return `${acc} += '${attr}="' + esc(${expr}) + '"';
@@ -1757,6 +3243,10 @@ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1757
3243
  }
1758
3244
  const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1759
3245
  const arg = scope ? `, ${scope}` : "";
3246
+ if (BOOLEAN_ATTRS.has(attr)) {
3247
+ return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});
3248
+ `;
3249
+ }
1760
3250
  return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
1761
3251
  `;
1762
3252
  }
@@ -1764,7 +3254,7 @@ function compileSlot(acc) {
1764
3254
  return `${acc} += String(children);
1765
3255
  `;
1766
3256
  }
1767
- var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
3257
+ var RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, isSeeded, markSeeded, esc, refresh, onMount, onCleanup, $effect, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $actionPending, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
1768
3258
  var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1769
3259
  function propsCode(props) {
1770
3260
  if (props.length === 0) return "";
@@ -1777,7 +3267,16 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1777
3267
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1778
3268
  return { o, fn };
1779
3269
  };
1780
- const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
3270
+ const __slotBlock = (closes, sl, name, pairs, fallback) => {
3271
+ const hit = __slot(sl, name, pairs);
3272
+ if (hit) return slotBlockMark(closes, hit);
3273
+ return fallback || '';
3274
+ };
3275
+ const __slotDefault = (children, fallback) => {
3276
+ const c = children == null ? '' : String(children);
3277
+ if (c.trim()) return c;
3278
+ return fallback || '';
3279
+ };`;
1781
3280
  function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1782
3281
  const headCode = headFn ? `
1783
3282
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -1853,7 +3352,7 @@ function buildReport(infos, compiled) {
1853
3352
  if (routeShipsNoJs(infos, compiled, i)) {
1854
3353
  return `${info.routePath} zero-JS nothing in the chain needs the client`;
1855
3354
  }
1856
- const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path.basename(infos[ci].filePath)}`).join("; ");
3355
+ const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path2.basename(infos[ci].filePath)}`).join("; ");
1857
3356
  const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
1858
3357
  return `${info.routePath} client JS ${why}${forced}`;
1859
3358
  });
@@ -1901,44 +3400,44 @@ for (const el of document.querySelectorAll('[data-rosetack]')) {
1901
3400
  }
1902
3401
  `;
1903
3402
  async function buildProject(root, outDir) {
1904
- await fs.promises.mkdir(outDir, { recursive: true });
1905
- const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
1906
- await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
3403
+ await fs3.promises.mkdir(outDir, { recursive: true });
3404
+ const stale = (await fs3.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
3405
+ await Promise.all(stale.map((f) => fs3.promises.rm(path2.join(outDir, f), { force: true })));
1907
3406
  const pageFiles = await scanRoseFiles(root);
1908
3407
  const compFiles = await scanComponentFiles(root);
1909
3408
  const files = [...pageFiles, ...compFiles];
1910
3409
  if (pageFiles.length === 0) {
1911
3410
  throw new RoseError(
1912
3411
  "E-ROUTE",
1913
- `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1914
- { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
3412
+ `no .rose pages found under ${path2.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
3413
+ { file: path2.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1915
3414
  );
1916
3415
  }
1917
3416
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1918
3417
  const config = await loadConfig(root);
1919
3418
  const plugins = config.plugins;
1920
3419
  const scopeKeys = files.map((f, i) => {
1921
- const base = infos[i].isComponent ? path.join(root, "src") : path.join(root, "src", "pages");
1922
- return path.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
3420
+ const base = infos[i].isComponent ? path2.join(root, "src") : path2.join(root, "src", "pages");
3421
+ return path2.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
1923
3422
  });
1924
3423
  const registry = new Map(
1925
3424
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1926
3425
  );
1927
3426
  const compiled = await Promise.all(
1928
- files.map((f, i) => compileComponent(f, path.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
3427
+ files.map((f, i) => compileComponentMemo(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
1929
3428
  );
1930
3429
  const importsOf = /* @__PURE__ */ new Map();
1931
3430
  files.forEach((_, i) => {
1932
3431
  const list = [];
1933
3432
  for (const r of compiled[i].roseImports ?? []) {
1934
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
3433
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1935
3434
  const hit = registry.get(abs);
1936
3435
  if (hit) list.push(hit.index);
1937
3436
  }
1938
3437
  importsOf.set(i, list);
1939
3438
  });
1940
3439
  const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
1941
- if (compiled[i].needsClient) return path.basename(files[i]);
3440
+ if (compiled[i].needsClient) return path2.basename(files[i]);
1942
3441
  if (seen.has(i)) return null;
1943
3442
  seen.add(i);
1944
3443
  for (const dep of importsOf.get(i) ?? []) {
@@ -1960,7 +3459,7 @@ async function buildProject(root, outDir) {
1960
3459
  if (reachable.has(i)) return;
1961
3460
  reachable.add(i);
1962
3461
  for (const r of compiled[i].roseImports ?? []) {
1963
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
3462
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1964
3463
  const hit = registry.get(abs);
1965
3464
  if (hit) visit(hit.index);
1966
3465
  }
@@ -1969,13 +3468,13 @@ async function buildProject(root, outDir) {
1969
3468
  if (!infos[i].isComponent) visit(i);
1970
3469
  });
1971
3470
  const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
1972
- if (styles) await fs.promises.writeFile(path.join(outDir, "styles.css"), styles);
1973
- else await fs.promises.rm(path.join(outDir, "styles.css"), { force: true });
3471
+ if (styles) await fs3.promises.writeFile(path2.join(outDir, "styles.css"), styles);
3472
+ else await fs3.promises.rm(path2.join(outDir, "styles.css"), { force: true });
1974
3473
  let locales = {};
1975
3474
  try {
1976
- for (const f of await fs.promises.readdir(path.join(root, "src", "locales"))) {
3475
+ for (const f of await fs3.promises.readdir(path2.join(root, "src", "locales"))) {
1977
3476
  if (!f.endsWith(".json")) continue;
1978
- locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, "src", "locales", f), "utf-8"));
3477
+ locales[f.slice(0, -5)] = JSON.parse(await fs3.promises.readFile(path2.join(root, "src", "locales", f), "utf-8"));
1979
3478
  }
1980
3479
  } catch {
1981
3480
  locales = {};
@@ -1987,21 +3486,24 @@ async function buildProject(root, outDir) {
1987
3486
  for (const l of preload) {
1988
3487
  if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
1989
3488
  }
1990
- await fs.promises.rm(path.join(outDir, "locales"), { recursive: true, force: true });
3489
+ await fs3.promises.rm(path2.join(outDir, "locales"), { recursive: true, force: true });
1991
3490
  if (packed.length > 0) {
1992
- const packDir = path.join(outDir, "locales");
1993
- await fs.promises.mkdir(packDir, { recursive: true });
1994
- for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
3491
+ const packDir = path2.join(outDir, "locales");
3492
+ await fs3.promises.mkdir(packDir, { recursive: true });
3493
+ for (const l of packed) await fs3.promises.writeFile(path2.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
1995
3494
  }
1996
3495
  const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
1997
3496
  const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
1998
- const buildDir = path.join(outDir, ".build");
1999
- await fs.promises.rm(buildDir, { recursive: true, force: true });
2000
- await fs.promises.mkdir(buildDir, { recursive: true });
3497
+ const buildDir = path2.join(outDir, ".build");
3498
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
3499
+ await fs3.promises.mkdir(buildDir, { recursive: true });
3500
+ const contentSrcCands = [path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "cli", "content.ts"), path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "src", "cli", "content.ts")];
3501
+ const contentSrc = contentSrcCands.find((c) => fs3.existsSync(c)) ?? contentSrcCands[0];
3502
+ fs3.copyFileSync(contentSrc, path2.join(buildDir, "content-md.ts"));
2001
3503
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
2002
3504
  if (runtimePlugins.length > 0) {
2003
- const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
2004
- await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
3505
+ const configRel = path2.relative(buildDir, path2.join(root, "rosetack.config.js")).replace(/\\/g, "/");
3506
+ await fs3.promises.writeFile(path2.join(buildDir, "plugins.js"), `
2005
3507
  import config from ${JSON.stringify(configRel)};
2006
3508
 
2007
3509
  const list = Array.isArray(config) ? config : [];
@@ -2013,21 +3515,21 @@ export const hasRequestHooks = hooks.some((p) => p.onRequest);
2013
3515
  export const hasResponseHooks = hooks.some((p) => p.onResponse);
2014
3516
  `);
2015
3517
  }
2016
- const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
3518
+ const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs3.existsSync(p));
2017
3519
  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" });
2018
3520
  await esbuild.build({
2019
3521
  entryPoints: [runtimeEntry],
2020
3522
  bundle: true,
2021
- outfile: path.join(buildDir, "runtime.js"),
3523
+ outfile: path2.join(buildDir, "runtime.js"),
2022
3524
  format: "esm",
2023
3525
  platform: "browser",
2024
3526
  write: true
2025
3527
  });
2026
3528
  for (let i = 0; i < compiled.length; i++) {
2027
3529
  const src = compiled[i].api ?? compiled[i].ssr;
2028
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
3530
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.ssr.js`), src);
2029
3531
  if (!infos[i].isApi) {
2030
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
3532
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
2031
3533
  }
2032
3534
  }
2033
3535
  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) => {
@@ -2089,17 +3591,17 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2089
3591
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
2090
3592
  }).join("\n");
2091
3593
  const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
2092
- const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
2093
- const dir = path.posix.dirname(rel);
3594
+ const rel = path2.relative(path2.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
3595
+ const dir = path2.posix.dirname(rel);
2094
3596
  const prefix = dir === "." ? "/" : "/" + dir;
2095
3597
  const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
2096
- return { prefix, render: split ? loaderOf(i) : compose(i), flags };
3598
+ return { prefix, render: compose(i), flags };
2097
3599
  }).sort((a, b) => b.prefix.length - a.prefix.length);
2098
3600
  const notFoundTable = `[
2099
3601
  ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
2100
3602
  ]`;
2101
3603
  const errIdx = infos.findIndex((info) => info.isError);
2102
- const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
3604
+ const errorRender = errIdx >= 0 ? compose(errIdx) : "null";
2103
3605
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
2104
3606
  const serverRoutes = pages.map(({ info, i }) => {
2105
3607
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -2127,9 +3629,12 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
2127
3629
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
2128
3630
  return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
2129
3631
  }).join(",\n ");
3632
+ const appUsesAuth = compiled.some((c) => c.usesrosetackAuth);
2130
3633
  const serverEntry = `
2131
3634
  ${serverImports}
2132
- import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
3635
+ import { renderMarkdown } from './content-md.ts';
3636
+ ${appUsesAuth ? "import crypto from 'node:crypto';" : "// no route references __rosetackAuth: the node:crypto auth helpers are omitted, keeping the bundle edge-loadable"}
3637
+ import { setState, persistState, clearRequestState, isolateRender, serializeState, resetRequestContext, installContextStore, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
2133
3638
  ${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
2134
3639
  // module to import - the runners below stay no-ops and the servers call them
2135
3640
  // unconditionally (one code path, no flags to keep in sync).
@@ -2186,6 +3691,7 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
2186
3691
  });
2187
3692
  }
2188
3693
 
3694
+
2189
3695
  // (the cross-machine seam): the cluster relay above covers ONE machine.
2190
3696
  export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
2191
3697
  setStoreTransport(send);
@@ -2206,6 +3712,11 @@ export const routeParams = {
2206
3712
 
2207
3713
  // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
2208
3714
  export const dynamicRoutes = [
3715
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal || compiled[i].needsClient).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3716
+ ];
3717
+
3718
+ // Routes that the prerender function should skip (not bake into static files).
3719
+ export const prerenderSkipRoutes = [
2209
3720
  ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
2210
3721
  ];
2211
3722
 
@@ -2221,6 +3732,239 @@ export const revalidate = [
2221
3732
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
2222
3733
  ];
2223
3734
 
3735
+ // Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
3736
+ export const routeCaches = [
3737
+ ${pages.filter(({ i }) => compiled[i].cache !== void 0).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(",\n ")}
3738
+ ];
3739
+ const __dynCache = new Map();
3740
+ export function invalidateRenderCache(): void {
3741
+ __dynCache.clear();
3742
+ }
3743
+
3744
+
3745
+ // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3746
+ const __kvStore = new Map<string, { v: unknown; exp: number }>();
3747
+ // Content collections: src/content/<coll>/*.md scanned once at build time,
3748
+
3749
+ const contentCollections = ${JSON.stringify(scanContentDir(path2.join(root, "src", "content")))};
3750
+ export const kv = {
3751
+ get(key: string): unknown {
3752
+ const e = __kvStore.get(key);
3753
+ if (!e) return undefined;
3754
+ if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
3755
+ return e.v;
3756
+ },
3757
+ set(key: string, value: unknown, ttlSeconds = 300): void {
3758
+ if (__kvStore.size > 1000) {
3759
+ const cutoff = Date.now();
3760
+ for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
3761
+ if (__kvStore.size > 2000) __kvStore.clear();
3762
+ }
3763
+ __kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
3764
+ },
3765
+ del(key: string): void { __kvStore.delete(key); },
3766
+ has(key: string): boolean {
3767
+ const e = __kvStore.get(key);
3768
+ return !!e && e.exp >= Date.now();
3769
+ },
3770
+ };
3771
+ globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
3772
+ globalThis.__rosetackContent = {
3773
+ list: (coll: string, filter?: { tag: string }) => {
3774
+ let items = contentCollections[coll] ?? [];
3775
+ if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
3776
+ return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
3777
+ },
3778
+ rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
3779
+ return buildRss(contentCollections[coll] ?? [], opts);
3780
+ },
3781
+ get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
3782
+ const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
3783
+ if (!e) return null;
3784
+ return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
3785
+ },
3786
+ };
3787
+
3788
+ const v = {
3789
+ validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
3790
+ const errors: Record<string, string> = {};
3791
+ const values: Record<string, unknown> = {};
3792
+ for (const [field, ruleList] of Object.entries(rules)) {
3793
+ let val = body[field];
3794
+ for (const rule of ruleList) {
3795
+ if (val === undefined || val === null || val === "") {
3796
+ if (rule === "required") errors[field] = field + " is required";
3797
+ else if (rule.startsWith("default:")) val = rule.slice(8);
3798
+ continue;
3799
+ }
3800
+ if (rule === "string") val = String(val);
3801
+ else if (rule === "trim") val = String(val).trim();
3802
+ else if (rule === "number") {
3803
+ const num = Number(val);
3804
+ if (Number.isNaN(num)) errors[field] = field + " must be a number";
3805
+ else val = num;
3806
+ } else if (rule === "email") {
3807
+ if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
3808
+ } else if (rule.startsWith("min:")) {
3809
+ const min = Number(rule.slice(4));
3810
+ if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
3811
+ } else if (rule.startsWith("max:")) {
3812
+ const max = Number(rule.slice(4));
3813
+ if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
3814
+ }
3815
+ }
3816
+ values[field] = val;
3817
+ }
3818
+ return { ok: Object.keys(errors).length === 0, errors, values };
3819
+ },
3820
+ };
3821
+
3822
+ const jobs = {
3823
+ _timers: new Map<string, ReturnType<typeof setInterval>>(),
3824
+ every(name: string, seconds: number, fn: () => void | Promise<void>): void {
3825
+ if (this._timers.has(name)) return;
3826
+ const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
3827
+ this._timers.set(name, t as any);
3828
+ },
3829
+ cancel(name: string): void {
3830
+ const t = this._timers.get(name);
3831
+ if (t) { clearInterval(t); this._timers.delete(name); }
3832
+ },
3833
+ cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
3834
+ };
3835
+
3836
+ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
3837
+ const encoder = new TextEncoder();
3838
+ const stream = new ReadableStream({
3839
+ async start(controller) {
3840
+ let closed = false;
3841
+ const send = (event: string, data: unknown) => {
3842
+ if (closed) return;
3843
+ controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
3844
+ };
3845
+ try {
3846
+ await handler(send);
3847
+ } finally {
3848
+ closed = true;
3849
+ try { controller.close(); } catch { }
3850
+ }
3851
+ },
3852
+ });
3853
+ return new Response(stream, {
3854
+ headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
3855
+ });
3856
+ }
3857
+ globalThis.__rosetackExtras = { v, jobs, sse };
3858
+ ${appUsesAuth ? `
3859
+ const auth = {
3860
+ hashPassword(password: string): string {
3861
+ const salt = crypto.randomBytes(16).toString("hex");
3862
+ const hash = crypto.scryptSync(password, salt, 32).toString("hex");
3863
+ return salt + ":" + hash;
3864
+ },
3865
+ verifyPassword(password: string, stored: string): boolean {
3866
+ const [salt, hash] = stored.split(":");
3867
+ if (!salt || !hash) return false;
3868
+ return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
3869
+ },
3870
+ signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
3871
+ const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
3872
+ const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3873
+ return payload + "." + sig;
3874
+ },
3875
+ verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
3876
+ const dot = token.lastIndexOf(".");
3877
+ if (dot < 0) return null;
3878
+ const payload = token.slice(0, dot);
3879
+ const sig = token.slice(dot + 1);
3880
+ const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3881
+ try {
3882
+ if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
3883
+ } catch { return null; }
3884
+ try {
3885
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString());
3886
+ if (data.exp < Date.now()) return null;
3887
+ return data as T;
3888
+ } catch { return null; }
3889
+ },
3890
+ csrfToken(secret: string, sessionId: string): string {
3891
+ return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
3892
+ },
3893
+ verifyCsrf(token: string, secret: string, sessionId: string): boolean {
3894
+ try {
3895
+ return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
3896
+ } catch { return false; }
3897
+ },
3898
+ };
3899
+ globalThis.__rosetackAuth = auth;
3900
+ ` : "// __rosetackAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
3901
+
3902
+ export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3903
+ const hit = kv.get(key);
3904
+ if (hit !== undefined) return hit;
3905
+ const v = await compute();
3906
+ if (v !== undefined) kv.set(key, v, ttlSeconds);
3907
+ return v;
3908
+ }
3909
+ export function isCachedRoute(pathname: string): boolean {
3910
+ return routeCaches.some((r) => matchRoute(r.pattern, pathname));
3911
+ }
3912
+ export function invalidatePath(pathname: string): number {
3913
+ let n = 0;
3914
+ for (const key of [...__dynCache.keys()]) {
3915
+ if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
3916
+ }
3917
+ return n;
3918
+ }
3919
+ export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
3920
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3921
+ if (!cfg) return null;
3922
+ let h = 0x811c9dc5;
3923
+ const c = cookieHeader || '';
3924
+ for (let i = 0; i < c.length; i++) {
3925
+ h ^= c.charCodeAt(i);
3926
+ h = (h * 0x01000193) >>> 0;
3927
+ }
3928
+ const hit = __dynCache.get(pathname + '|' + h.toString(16));
3929
+ return hit && hit.expires > Date.now() ? hit.page : null;
3930
+ }
3931
+ export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
3932
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3933
+ if (!cfg) return renderPage(pathname);
3934
+ let h = 0x811c9dc5;
3935
+ for (let i = 0; i < cookieHeader.length; i++) {
3936
+ h ^= cookieHeader.charCodeAt(i);
3937
+ h = (h * 0x01000193) >>> 0;
3938
+ }
3939
+ const key = pathname + '|' + h.toString(16);
3940
+ const hit = __dynCache.get(key);
3941
+ if (hit && hit.expires > Date.now()) {
3942
+ __dynCache.delete(key);
3943
+ __dynCache.set(key, hit);
3944
+ return hit.page;
3945
+ }
3946
+ // Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
3947
+ if (hit && !hit.refreshing) {
3948
+ hit.refreshing = true;
3949
+ renderPage(pathname).then((fresh: any) => {
3950
+ if (fresh.status === 200 && !fresh.redirect) {
3951
+ __dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
3952
+ } else {
3953
+ __dynCache.delete(key);
3954
+ }
3955
+ }).catch(() => { __dynCache.delete(key); });
3956
+ return hit.page;
3957
+ }
3958
+ const page = await renderPage(pathname);
3959
+ if (page.status === 200 && !page.redirect) {
3960
+ __dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
3961
+ if (__dynCache.size > 300) {
3962
+ __dynCache.delete(__dynCache.keys().next().value as string);
3963
+ }
3964
+ }
3965
+ return page;
3966
+ }
3967
+
2224
3968
  // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
2225
3969
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
2226
3970
 
@@ -2335,7 +4079,14 @@ export function docAttrs(pathname) {
2335
4079
 
2336
4080
  // Paint a fallback page (404/500) and serialize its state.
2337
4081
  async function renderFallback(pathname, render) {
2338
- const { html, head } = extractHead(await render([], ''));
4082
+ // Split mode: the not-found entry's render is a loader object \u2014 resolve it through getRender (which memoizes the composed function) exactly like.
4083
+ let fn = render;
4084
+ if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
4085
+
4086
+ // { render } once the route's chunk graph is loaded
4087
+ fn = (await fn.load()).render;
4088
+ }
4089
+ const { html, head } = extractHead(await fn([], ''));
2339
4090
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2340
4091
  return { html, state, head, ...docAttrs(pathname) };
2341
4092
  }
@@ -2377,7 +4128,15 @@ function extractHead(rendered) {
2377
4128
 
2378
4129
  // Form: the submitted FormData of a progressive-enhancement POST.
2379
4130
  export async function renderPage(pathname, form) {
4131
+ // Renders DO overlap in one process: prod-server warms every route in the background at startup.
4132
+ return isolateRender(() => renderPageIsolated(pathname, form));
4133
+ }
4134
+
4135
+ async function renderPageIsolated(pathname, form) {
2380
4136
  clearRequestState();
4137
+ // Cold-start readiness gate (oboext #8): await the app's published DB-ready promise before any $data() read.
4138
+ const appReady = globalThis.__rosetackAppReady;
4139
+ if (appReady) await appReady;
2381
4140
  for (const route of routes) {
2382
4141
  if (matchRoute(route.pattern, pathname)) {
2383
4142
  const patternParts = route.pattern.split('/');
@@ -2442,8 +4201,27 @@ export async function renderPage(pathname, form) {
2442
4201
  return await notFoundPage(pathname);
2443
4202
  }
2444
4203
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2445
- if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
2446
- return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
4204
+ // F10: in dev the response body carries the real error \u2014 message, file:line and the fix hint.
4205
+ let devDetail = '';
4206
+ if (process.env.rosetack_DEV === '1' && err) {
4207
+ const msg = esc(err instanceof Error ? err.message : String(err));
4208
+ const file = esc(String(err.file || ''));
4209
+ const line = err.line != null ? esc(String(err.line)) : '';
4210
+ const hint = esc(String(err.hint || ''));
4211
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
4212
+ devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
4213
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
4214
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
4215
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
4216
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
4217
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
4218
+ + '</div>';
4219
+ }
4220
+ if (errorPage) {
4221
+ const fb = await renderFallback(pathname, errorPage);
4222
+ return { ...fb, html: fb.html + devDetail, status: 500 };
4223
+ }
4224
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2447
4225
  }
2448
4226
  // __route tells the bootstrap which route this document was rendered for.
2449
4227
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
@@ -2527,7 +4305,15 @@ export async function handleApi(method, pathname, request) {
2527
4305
 
2528
4306
  // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
2529
4307
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4308
+ // Isolated for the same reason as renderPage: a streaming render awaits inside route.render()
4309
+ return isolateRender(() => renderPageStreamIsolated(pathname, write, shellOpen, clientTag));
4310
+ }
4311
+
4312
+ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
2530
4313
  clearRequestState();
4314
+ // Cold-start readiness gate (oboext #8): same contract as renderPage \u2014 await the app's published DB-ready promise before streaming the shell.
4315
+ const appReady = globalThis.__rosetackAppReady;
4316
+ if (appReady) await appReady;
2531
4317
  for (const route of routes) {
2532
4318
  if (matchRoute(route.pattern, pathname)) {
2533
4319
  const patternParts = route.pattern.split('/');
@@ -2550,7 +4336,24 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2550
4336
  } catch (err) {
2551
4337
 
2552
4338
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2553
- html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
4339
+ // F10: dev carries the real error in the body here too \u2014 the shell
4340
+ // is out, so the detail rides after the error page body.
4341
+ let devDetail = '';
4342
+ if (process.env.rosetack_DEV === '1' && err) {
4343
+ const msg = esc(err instanceof Error ? err.message : String(err));
4344
+ const file = esc(String(err.file || ''));
4345
+ const line = err.line != null ? esc(String(err.line)) : '';
4346
+ const hint = esc(String(err.hint || ''));
4347
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
4348
+ devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
4349
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
4350
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
4351
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
4352
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
4353
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
4354
+ + '</div>';
4355
+ }
4356
+ html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
2554
4357
  }
2555
4358
  write(html);
2556
4359
  // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
@@ -2567,17 +4370,74 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2567
4370
  }
2568
4371
  return 404;
2569
4372
  }
4373
+ // Prevent tree-shaking of invalidateRenderCache (called from prod-server.ts / edge.ts on non-GET writes).
4374
+ void invalidateRenderCache;
4375
+
4376
+ // Same reason, for the per-request context store: prod-server.ts installs an AsyncLocalStorage adapter.
4377
+ export { installContextStore };
2570
4378
  `;
2571
- await fs.promises.writeFile(path.join(buildDir, "server-entry.js"), serverEntry);
4379
+ try {
4380
+ const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
4381
+ const uniq = [...new Set(patterns)].sort();
4382
+ const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
4383
+ const paramsOf = (pattern) => (pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
4384
+ const paramSig = uniq.map((p) => {
4385
+ const ps = paramsOf(p);
4386
+ if (!ps.length) return "";
4387
+ return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
4388
+ }).join("");
4389
+ const outDirTs = path2.join(root, "src", ".rosetack");
4390
+ await fs3.promises.mkdir(outDirTs, { recursive: true });
4391
+ const srcLines = [
4392
+ "// GENERATED by rosetack build - do not edit.",
4393
+ "export type RoutePath = " + lit + ";",
4394
+ "export const routePatterns = " + JSON.stringify(uniq) + " as const;",
4395
+ "export type RouteParams = {",
4396
+ paramSig,
4397
+ "};",
4398
+ "/** Build a URL from a route pattern and its params. */",
4399
+ "export function url(",
4400
+ " path: RoutePath,",
4401
+ " params: RouteParams[keyof RouteParams] = {} as never,",
4402
+ "): string {",
4403
+ " let out = path as string;",
4404
+ " for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
4405
+ " out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
4406
+ " }",
4407
+ " return out;",
4408
+ "}"
4409
+ ].join("\n") + "\n";
4410
+ await fs3.promises.writeFile(path2.join(outDirTs, "routes.ts"), srcLines);
4411
+ } catch {
4412
+ }
4413
+ await fs3.promises.writeFile(path2.join(buildDir, "server-entry.js"), serverEntry);
2572
4414
  await esbuild.build({
2573
- entryPoints: [path.join(buildDir, "server-entry.js")],
4415
+ entryPoints: [path2.join(buildDir, "server-entry.js")],
2574
4416
  bundle: true,
2575
- outfile: path.join(outDir, "server.js"),
4417
+ outfile: path2.join(outDir, "server.js"),
2576
4418
  format: "esm",
2577
4419
  platform: "node",
2578
4420
  write: true,
2579
4421
  ...TS_LOADER
2580
4422
  });
4423
+ await esbuild.build({
4424
+ entryPoints: [(() => {
4425
+ const here = path2.dirname(fileURLToPath(import.meta.url));
4426
+ for (const cand of [path2.join(here, "..", "cli", "prod-server.ts"), path2.join(here, "..", "src", "cli", "prod-server.ts")]) {
4427
+ if (fs3.existsSync(cand)) return cand;
4428
+ }
4429
+ return path2.join(here, "..", "cli", "prod-server.ts");
4430
+ })()],
4431
+ bundle: true,
4432
+ outfile: path2.join(outDir, "prod.mjs"),
4433
+ format: "esm",
4434
+ platform: "node",
4435
+ write: true,
4436
+ banner: {
4437
+ js: "import { createRequire } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = createRequire(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);"
4438
+ },
4439
+ ...TS_LOADER
4440
+ });
2581
4441
  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");
2582
4442
  const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
2583
4443
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
@@ -2608,7 +4468,7 @@ reportVitals();
2608
4468
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2609
4469
  const clientEntry = `
2610
4470
  ${clientImports}
2611
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
4471
+ import { state, setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
2612
4472
 
2613
4473
  // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
2614
4474
  setLocales(${clientLocalesJson}, '${defaultLocale}');
@@ -2826,12 +4686,22 @@ async function postForm(body, container, pathname) {
2826
4686
  // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
2827
4687
  export async function $action(name, e) {
2828
4688
  if (e && e.preventDefault) e.preventDefault();
4689
+ // F34: the pending flag is ordinary signal state - {#if $actionPending()}
4690
+ // disables a submit button while the action is in flight, reactively.
4691
+ const [__rvPending, __rvSetPending] = state('actionPending', false);
4692
+ __rvSetPending(true);
2829
4693
  const body = new FormData();
2830
4694
  body.append('__action', name);
2831
4695
  // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
2832
4696
  const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
2833
- return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4697
+ try {
4698
+ return await postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4699
+ } finally {
4700
+ __rvSetPending(false);
4701
+ }
2834
4702
  }
4703
+ // F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
4704
+ setActionDispatcher($action);
2835
4705
 
2836
4706
  export { postForm };
2837
4707
 
@@ -2863,6 +4733,16 @@ async function __withOwner(container, fn) {
2863
4733
  setFxOwner(null);
2864
4734
  }
2865
4735
  }
4736
+ // View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
4737
+ async function __swap(container, html) {
4738
+ const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
4739
+ if (typeof document.startViewTransition === 'function' && !reduce) {
4740
+ const vt = document.startViewTransition(() => { container.innerHTML = html; });
4741
+ await vt.updateCallbackDone.catch(() => {});
4742
+ } else {
4743
+ container.innerHTML = html;
4744
+ }
4745
+ }
2866
4746
 
2867
4747
  export async function start(container, pathname, initial) {
2868
4748
  clearMounts(); // stale mounts from a failed render never fire
@@ -2885,7 +4765,7 @@ ${langDirBlock}
2885
4765
  prefetchCache.delete(pathname);
2886
4766
  __navReset(container);
2887
4767
  restoreState(hit.state);
2888
- container.innerHTML = hit.html;
4768
+ await __swap(container, hit.html);
2889
4769
  await __withOwner(container, () => {
2890
4770
  wire(container, hit.closes);
2891
4771
  bindEvents(container);
@@ -2910,15 +4790,18 @@ ${langDirBlock}
2910
4790
  if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
2911
4791
 
2912
4792
 
4793
+ console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
2913
4794
  broken = true;
2914
4795
  return;
2915
4796
  }
2916
- if (!initial) container.innerHTML = html;
4797
+ if (!initial) await __swap(container, html);
2917
4798
  wire(container, closes);
2918
4799
  bindEvents(container);
2919
4800
  flushMounts();
2920
4801
  });
2921
4802
  if (signal === 'notFound') {
4803
+ // T17: a client-side render of a $data route without a prefetch entry has no data source (the server fills the context bag) - the correct.
4804
+ if (!initial) { try { location.assign(pathname); return; } catch { } }
2922
4805
  await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2923
4806
  return;
2924
4807
  }
@@ -2981,11 +4864,11 @@ setRefreshHook(async () => {
2981
4864
  await start(document.getElementById('app'), location.pathname, false);
2982
4865
  });
2983
4866
  `;
2984
- await fs.promises.writeFile(path.join(buildDir, "client-entry.js"), clientEntry);
4867
+ await fs3.promises.writeFile(path2.join(buildDir, "client-entry.js"), clientEntry);
2985
4868
  if (split) {
2986
- await fs.promises.rm(path.join(outDir, "chunks"), { recursive: true, force: true });
4869
+ await fs3.promises.rm(path2.join(outDir, "chunks"), { recursive: true, force: true });
2987
4870
  await esbuild.build({
2988
- entryPoints: [path.join(buildDir, "client-entry.js")],
4871
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
2989
4872
  bundle: true,
2990
4873
  format: "esm",
2991
4874
  platform: "browser",
@@ -2999,9 +4882,9 @@ setRefreshHook(async () => {
2999
4882
  });
3000
4883
  } else {
3001
4884
  await esbuild.build({
3002
- entryPoints: [path.join(buildDir, "client-entry.js")],
4885
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
3003
4886
  bundle: true,
3004
- outfile: path.join(outDir, "client.js"),
4887
+ outfile: path2.join(outDir, "client.js"),
3005
4888
  format: "esm",
3006
4889
  platform: "browser",
3007
4890
  minify: true,
@@ -3009,13 +4892,13 @@ setRefreshHook(async () => {
3009
4892
  ...TS_LOADER
3010
4893
  });
3011
4894
  }
3012
- await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
3013
- await fs.promises.rm(buildDir, { recursive: true, force: true });
3014
- const publicDir = path.join(root, "public");
3015
- if (fs.existsSync(publicDir)) {
3016
- await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
3017
- const favicon = path.join(publicDir, "favicon.ico");
3018
- if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
4895
+ await fs3.promises.writeFile(path2.join(outDir, "mount.js"), MOUNT_ENTRY);
4896
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
4897
+ const publicDir = path2.join(root, "public");
4898
+ if (fs3.existsSync(publicDir)) {
4899
+ await fs3.promises.cp(publicDir, path2.join(outDir, "public"), { recursive: true });
4900
+ const favicon = path2.join(publicDir, "favicon.ico");
4901
+ if (fs3.existsSync(favicon)) await fs3.promises.copyFile(favicon, path2.join(outDir, "favicon.ico"));
3019
4902
  }
3020
4903
  console.log("rosetack zero-JS report:");
3021
4904
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
@@ -3029,7 +4912,7 @@ setRefreshHook(async () => {
3029
4912
  g = { why: w, files: /* @__PURE__ */ new Map() };
3030
4913
  warnGroups.set(w, g);
3031
4914
  }
3032
- const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
4915
+ const file = path2.relative(root, infos[ci].filePath).replace(/\\/g, "/");
3033
4916
  let routes = g.files.get(file);
3034
4917
  if (!routes) {
3035
4918
  routes = /* @__PURE__ */ new Set();
@@ -3050,13 +4933,13 @@ setRefreshHook(async () => {
3050
4933
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
3051
4934
  }
3052
4935
  async function scanRoseFiles(root) {
3053
- const pagesDir = path.join(root, "src", "pages");
3054
- if (!fs.existsSync(pagesDir)) return [];
4936
+ const pagesDir = path2.join(root, "src", "pages");
4937
+ if (!fs3.existsSync(pagesDir)) return [];
3055
4938
  async function scan(dir) {
3056
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4939
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
3057
4940
  const files = [];
3058
4941
  for (const entry of entries) {
3059
- const full = path.join(dir, entry.name);
4942
+ const full = path2.join(dir, entry.name);
3060
4943
  if (entry.isDirectory()) files.push(...await scan(full));
3061
4944
  else if (entry.name.endsWith(".rose")) files.push(full);
3062
4945
  }
@@ -3065,13 +4948,13 @@ async function scanRoseFiles(root) {
3065
4948
  return scan(pagesDir);
3066
4949
  }
3067
4950
  async function scanComponentFiles(root) {
3068
- const compDir = path.join(root, "src", "components");
3069
- if (!fs.existsSync(compDir)) return [];
4951
+ const compDir = path2.join(root, "src", "components");
4952
+ if (!fs3.existsSync(compDir)) return [];
3070
4953
  async function scan(dir) {
3071
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4954
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
3072
4955
  const files = [];
3073
4956
  for (const entry of entries) {
3074
- const full = path.join(dir, entry.name);
4957
+ const full = path2.join(dir, entry.name);
3075
4958
  if (entry.isDirectory()) files.push(...await scan(full));
3076
4959
  else if (entry.name.endsWith(".rose")) files.push(full);
3077
4960
  }
@@ -3080,16 +4963,16 @@ async function scanComponentFiles(root) {
3080
4963
  return scan(compDir);
3081
4964
  }
3082
4965
  function isAncestorDir(layoutPath, pagePath) {
3083
- const layoutDir = path.dirname(layoutPath);
3084
- const pageDir = path.dirname(pagePath);
3085
- return pageDir === layoutDir || pageDir.startsWith(layoutDir + path.sep);
4966
+ const layoutDir = path2.dirname(layoutPath);
4967
+ const pageDir = path2.dirname(pagePath);
4968
+ return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
3086
4969
  }
3087
- function getRouteInfo(filePath, root) {
3088
- const pagesDir = path.join(root, "src", "pages");
3089
- const relative3 = path.relative(pagesDir, filePath).replace(/\\/g, "/");
4970
+ function getRouteInfo(filePath2, root) {
4971
+ const pagesDir = path2.join(root, "src", "pages");
4972
+ const relative3 = path2.relative(pagesDir, filePath2).replace(/\\/g, "/");
3090
4973
  const withoutExt = relative3.replace(/\.rose$/, "");
3091
- const base = path.posix.basename(withoutExt);
3092
- const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
4974
+ const base = path2.posix.basename(withoutExt);
4975
+ const isComponent = filePath2.replace(/\\/g, "/").includes("/src/components/");
3093
4976
  const isLayout = !isComponent && base === "_layout";
3094
4977
  const isNotFound = !isComponent && (base === "404" || base === "_notfound");
3095
4978
  const isError = !isComponent && base === "500";
@@ -3113,7 +4996,7 @@ function getRouteInfo(filePath, root) {
3113
4996
  routePath = "/" + routeParts.join("/");
3114
4997
  }
3115
4998
  return {
3116
- filePath,
4999
+ filePath: filePath2,
3117
5000
  routePath,
3118
5001
  pattern: routePath,
3119
5002
  paramNames: parts.flatMap((p) => {
@@ -3136,24 +5019,24 @@ function capitalize(s) {
3136
5019
  }
3137
5020
 
3138
5021
  // src/cli/shell.ts
3139
- import * as fs2 from "fs";
3140
- import * as path2 from "path";
5022
+ import * as fs4 from "fs";
5023
+ import * as path3 from "path";
3141
5024
  import * as esbuild2 from "esbuild";
3142
- var OUT_DIR = path2.join(process.cwd(), "dist");
5025
+ var OUT_DIR = path3.join(process.cwd(), "dist");
3143
5026
  var styleCache = null;
3144
5027
  function getStyles() {
3145
- const file = path2.join(OUT_DIR, "styles.css");
5028
+ const file = path3.join(OUT_DIR, "styles.css");
3146
5029
  try {
3147
- const st = fs2.statSync(file);
5030
+ const st = fs4.statSync(file);
3148
5031
  if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
3149
- styleCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
5032
+ styleCache = { mtimeMs: st.mtimeMs, source: fs4.readFileSync(file, "utf-8") };
3150
5033
  }
3151
5034
  return styleCache.source;
3152
5035
  } catch {
3153
5036
  return "";
3154
5037
  }
3155
5038
  }
3156
- var BOOTSTRAP = esbuild2.transformSync(`
5039
+ var BOOTSTRAP_SOURCE = `
3157
5040
  // shell = false: the document's SSR content sits directly in <body> - no
3158
5041
  // #app wrapper, no demo styles, so a real theme's CSS owns the document from
3159
5042
  // the first byte (and a JS-less visitor never sees either). The bundle still
@@ -3175,18 +5058,39 @@ if (!__app) {
3175
5058
  }
3176
5059
  // Native View Transitions around client-side navigation (progressive:
3177
5060
  // browsers without the API navigate normally, no polyfill, no CSS required).
3178
- function __navigate(pathname) {
3179
- const paint = () => start(__app, pathname);
5061
+ // F35: stash the CURRENT entry's scroll position into its history state
5062
+ // before a new push - the browser only restores scroll on full page loads; a
5063
+ // pjax swap would land wherever the swap left it.
5064
+ function __saveScroll() {
5065
+ try {
5066
+ const s = history.state || {};
5067
+ history.replaceState(Object.assign({}, s, { __rosetackScroll: window.scrollY }), '');
5068
+ } catch (e) { /* history state unavailable (file:// edge): best effort */ }
5069
+ }
5070
+ function __navigate(pathname, restore) {
5071
+ const paint = () => {
5072
+ const p = start(__app, pathname);
5073
+ if (restore) {
5074
+ // back/forward: restore the entry's scroll (top when it has none)
5075
+ const s = history.state || {};
5076
+ const y = typeof s.__rosetackScroll === 'number' ? s.__rosetackScroll : 0;
5077
+ return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
5078
+ }
5079
+ // a fresh navigation starts at the top, like a full page load
5080
+ window.scrollTo(0, 0);
5081
+ return p;
5082
+ };
3180
5083
  if (document.startViewTransition) {
3181
5084
  return document.startViewTransition(paint).updateCallbackDone;
3182
5085
  }
3183
5086
  return paint();
3184
5087
  }
3185
- window.addEventListener('popstate', () => __navigate(window.location.pathname));
5088
+ window.addEventListener('popstate', () => __navigate(window.location.pathname, true));
3186
5089
  document.addEventListener('click', (e) => {
3187
5090
  const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
3188
5091
  if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
3189
5092
  e.preventDefault();
5093
+ __saveScroll();
3190
5094
  history.pushState(null, '', a.getAttribute('href'));
3191
5095
  __navigate(window.location.pathname);
3192
5096
  }
@@ -3276,14 +5180,45 @@ if (__state.__notFound) {
3276
5180
  } else {
3277
5181
  start(__app, window.location.pathname);
3278
5182
  }
3279
- `, { minify: true }).code;
3280
- var EXTERNAL_BOOTSTRAP = `
3281
- import { start, prefetch, postForm, prefetchStats } from '/client.js';
3282
- ${BOOTSTRAP}`;
5183
+ `;
5184
+ var BOOTSTRAP_CACHE = null;
5185
+ function bootstrap() {
5186
+ if (BOOTSTRAP_CACHE === null) {
5187
+ if (globalThis.__rosetack_SKIP_MINIFY) {
5188
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
5189
+ } else {
5190
+ try {
5191
+ BOOTSTRAP_CACHE = esbuild2.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
5192
+ } catch {
5193
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
5194
+ }
5195
+ }
5196
+ }
5197
+ return BOOTSTRAP_CACHE;
5198
+ }
5199
+ var EXTERNAL_BOOTSTRAP_CACHE = null;
5200
+ function externalBootstrap() {
5201
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `
5202
+ import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';
5203
+ ${bootstrap()}`;
5204
+ return EXTERNAL_BOOTSTRAP_CACHE;
5205
+ }
3283
5206
  function inlineScript(client) {
5207
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
5208
+ let body = client;
5209
+ let aliases = "";
5210
+ if (m) {
5211
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
5212
+ aliases = m[1].split(",").map((pair) => {
5213
+ const parts = pair.split(" as ").map((x) => x.trim());
5214
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
5215
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
5216
+ }).join("");
5217
+ }
3284
5218
  return `
3285
- ${client}
3286
- ${BOOTSTRAP}`;
5219
+ ${body}
5220
+ ${aliases}
5221
+ ${bootstrap()}`;
3287
5222
  }
3288
5223
  var FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
3289
5224
  var STYLES = `
@@ -3342,7 +5277,7 @@ function mergeHeadBlocks(blocks) {
3342
5277
  function clientScriptTag(client, nonce = "") {
3343
5278
  const n = nonce ? ` nonce="${nonce}"` : "";
3344
5279
  return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
3345
- <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
5280
+ <script type="module"${n}>${externalBootstrap()}</script>`;
3346
5281
  }
3347
5282
  function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
3348
5283
  const clientTag = clientScriptTag(client, nonce);
@@ -3387,50 +5322,50 @@ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(),
3387
5322
  // src/cli/test.ts
3388
5323
  var GRAFTED = ["document", "Node", "NodeFilter", "FormData", "DOMParser", "location", "fetch", "Event", "CustomEvent", "MutationObserver", "requestAnimationFrame"];
3389
5324
  function projectRootOf(file) {
3390
- let dir = path3.dirname(path3.resolve(file));
5325
+ let dir = path4.dirname(path4.resolve(file));
3391
5326
  for (; ; ) {
3392
- if (fs3.existsSync(path3.join(dir, "src", "pages"))) return dir;
3393
- const parent = path3.dirname(dir);
5327
+ if (fs5.existsSync(path4.join(dir, "src", "pages"))) return dir;
5328
+ const parent = path4.dirname(dir);
3394
5329
  if (parent === dir) throw new Error(`rosetack/test: ${file} is not inside a project (no src/pages found above it)`);
3395
5330
  dir = parent;
3396
5331
  }
3397
5332
  }
3398
5333
  function routeOf(file, root) {
3399
- const rel = path3.relative(path3.join(root, "src", "pages"), path3.resolve(file)).replace(/\\/g, "/").replace(/\.rose$/, "");
5334
+ const rel = path4.relative(path4.join(root, "src", "pages"), path4.resolve(file)).replace(/\\/g, "/").replace(/\.rose$/, "");
3400
5335
  if (rel === "index") return "/";
3401
5336
  const segs = rel.split("/").map((s) => s.startsWith("[") && s.endsWith("]") ? `:${s.slice(1, -1)}` : s);
3402
5337
  return "/" + segs.join("/");
3403
5338
  }
3404
5339
  function copyTree(from, to) {
3405
- fs3.mkdirSync(to, { recursive: true });
3406
- for (const e of fs3.readdirSync(from, { withFileTypes: true })) {
3407
- const src = path3.join(from, e.name);
3408
- const dst = path3.join(to, e.name);
5340
+ fs5.mkdirSync(to, { recursive: true });
5341
+ for (const e of fs5.readdirSync(from, { withFileTypes: true })) {
5342
+ const src = path4.join(from, e.name);
5343
+ const dst = path4.join(to, e.name);
3409
5344
  if (e.isDirectory()) copyTree(src, dst);
3410
- else fs3.copyFileSync(src, dst);
5345
+ else fs5.copyFileSync(src, dst);
3411
5346
  }
3412
5347
  }
3413
5348
  function propAttrs(props) {
3414
5349
  return Object.entries(props).map(([k, v]) => `${k}={${JSON.stringify(v) ?? "undefined"}}`).join(" ");
3415
5350
  }
3416
5351
  async function test(file, opts = {}) {
3417
- const target = path3.resolve(file);
3418
- if (!fs3.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
5352
+ const target = path4.resolve(file);
5353
+ if (!fs5.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
3419
5354
  const root = projectRootOf(target);
3420
- const rel = path3.relative(root, target).replace(/\\/g, "/");
5355
+ const rel = path4.relative(root, target).replace(/\\/g, "/");
3421
5356
  const isComponent = rel.startsWith("src/components/");
3422
- const dir = opts.dir ?? fs3.mkdtempSync(path3.join(os.tmpdir(), "rosetack-test-"));
5357
+ const dir = opts.dir ?? fs5.mkdtempSync(path4.join(os2.tmpdir(), "rosetack-test-"));
3423
5358
  for (const item of ["src", "public"]) {
3424
- const from = path3.join(root, item);
3425
- if (fs3.existsSync(from)) copyTree(from, path3.join(dir, item));
5359
+ const from = path4.join(root, item);
5360
+ if (fs5.existsSync(from)) copyTree(from, path4.join(dir, item));
3426
5361
  }
3427
5362
  for (const item of ["rosetack.config.js"]) {
3428
- const from = path3.join(root, item);
3429
- if (fs3.existsSync(from)) fs3.copyFileSync(from, path3.join(dir, item));
5363
+ const from = path4.join(root, item);
5364
+ if (fs5.existsSync(from)) fs5.copyFileSync(from, path4.join(dir, item));
3430
5365
  }
3431
5366
  let route;
3432
5367
  if (isComponent) {
3433
- const specifier = path3.relative(path3.join(dir, "src", "pages"), path3.join(dir, rel)).replace(/\\/g, "/");
5368
+ const specifier = path4.relative(path4.join(dir, "src", "pages"), path4.join(dir, rel)).replace(/\\/g, "/");
3434
5369
  const attrs = propAttrs(opts.props ?? {});
3435
5370
  const page = `<script>
3436
5371
  import Target from '${specifier}';
@@ -3440,27 +5375,27 @@ async function test(file, opts = {}) {
3440
5375
  <Target ${attrs} />
3441
5376
  </template>
3442
5377
  `;
3443
- fs3.writeFileSync(path3.join(dir, "src", "pages", "__rosetack_test.rose"), page);
5378
+ fs5.writeFileSync(path4.join(dir, "src", "pages", "__rosetack_test.rose"), page);
3444
5379
  route = "/__rosetack_test";
3445
5380
  } else {
3446
5381
  route = opts.route ?? routeOf(target, root);
3447
5382
  }
3448
- const outDir = path3.join(dir, "dist");
5383
+ const outDir = path4.join(dir, "dist");
3449
5384
  await buildProject(dir, outDir);
3450
- const serverUrl = pathToFileURL2(path3.join(outDir, "server.js")).href;
3451
- const clientUrl = pathToFileURL2(path3.join(outDir, "client.js")).href;
5385
+ const serverUrl = pathToFileURL2(path4.join(outDir, "server.js")).href;
5386
+ const clientUrl = pathToFileURL2(path4.join(outDir, "client.js")).href;
3452
5387
  const mod = await import(serverUrl);
3453
- const clientSource = fs3.readFileSync(path3.join(outDir, "client.js"), "utf-8");
5388
+ const clientSource = fs5.readFileSync(path4.join(outDir, "client.js"), "utf-8");
3454
5389
  let styles = "";
3455
5390
  try {
3456
- styles = fs3.readFileSync(path3.join(outDir, "styles.css"), "utf-8");
5391
+ styles = fs5.readFileSync(path4.join(outDir, "styles.css"), "utf-8");
3457
5392
  } catch {
3458
5393
  }
3459
5394
  if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
3460
5395
  if (!opts.dir && !opts.keep) {
3461
5396
  process.once("exit", () => {
3462
5397
  try {
3463
- fs3.rmSync(dir, { recursive: true, force: true });
5398
+ fs5.rmSync(dir, { recursive: true, force: true });
3464
5399
  } catch {
3465
5400
  }
3466
5401
  });
@@ -3517,9 +5452,9 @@ async function test(file, opts = {}) {
3517
5452
  globalThis.fetch = async (url, init) => {
3518
5453
  const pathname = String(url).startsWith("http") ? new URL(String(url)).pathname : String(url);
3519
5454
  if (pathname.startsWith("/locales/") && pathname.endsWith(".json")) {
3520
- const file2 = path3.join(outDir, pathname.slice(1));
3521
- if (!fs3.existsSync(file2)) return { ok: false, json: async () => ({}) };
3522
- return { ok: true, json: async () => JSON.parse(fs3.readFileSync(file2, "utf-8")) };
5455
+ const file2 = path4.join(outDir, pathname.slice(1));
5456
+ if (!fs5.existsSync(file2)) return { ok: false, json: async () => ({}) };
5457
+ return { ok: true, json: async () => JSON.parse(fs5.readFileSync(file2, "utf-8")) };
3523
5458
  }
3524
5459
  requests++;
3525
5460
  const next = await request(pathname, req, init?.body);