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