rosetack 0.1.3 → 0.1.4

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,15 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli/index.ts
4
- import * as fs3 from "fs";
5
- import * as path3 from "path";
4
+ import * as fs5 from "fs";
5
+ import * as path4 from "path";
6
6
  import * as zlib from "zlib";
7
+ import { createHash as createHash2 } from "crypto";
7
8
  import { createRequire } from "module";
8
- import { pathToFileURL as pathToFileURL2, fileURLToPath as fileURLToPath2 } from "url";
9
+ import { pathToFileURL as pathToFileURL3, fileURLToPath as fileURLToPath2 } from "url";
9
10
 
10
11
  // src/compiler/index.ts
11
- import * as fs from "fs";
12
- import * as path from "path";
12
+ import * as fs3 from "fs";
13
+ import * as path2 from "path";
13
14
  import { pathToFileURL, fileURLToPath } from "url";
14
15
  import * as esbuild from "esbuild";
15
16
 
@@ -52,16 +53,209 @@ function errorInfo(err) {
52
53
  return { code: "E-UNKNOWN", message: err instanceof Error ? err.message : String(err) };
53
54
  }
54
55
 
56
+ // src/cli/image-size.ts
57
+ import fs from "node:fs";
58
+ function readImageSize(filePath) {
59
+ try {
60
+ const fd = fs.openSync(filePath, "r");
61
+ const buf = Buffer.alloc(64);
62
+ const read = fs.readSync(fd, buf, 0, 64, 0);
63
+ fs.closeSync(fd);
64
+ if (read < 24) return null;
65
+ if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
66
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
67
+ }
68
+ if (buf.slice(0, 3).toString("latin1") === "GIF") {
69
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
70
+ }
71
+ if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP") {
72
+ return parseWebP(buf);
73
+ }
74
+ if (buf[0] === 255 && buf[1] === 216) {
75
+ return parseJpeg(filePath);
76
+ }
77
+ return null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+ function parseWebP(buf) {
83
+ const format = buf.slice(12, 16).toString("latin1");
84
+ if (format === "VP8 ") {
85
+ return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
86
+ }
87
+ if (format === "VP8L") {
88
+ const b = buf.readUInt32LE(21);
89
+ return { width: (b & 16383) + 1, height: (b >> 14 & 16383) + 1 };
90
+ }
91
+ if (format === "VP8X") {
92
+ const w = buf.readUIntLE(24, 3) + 1;
93
+ const h = buf.readUIntLE(27, 3) + 1;
94
+ return { width: w, height: h };
95
+ }
96
+ return null;
97
+ }
98
+ function parseJpeg(filePath) {
99
+ const fd = fs.openSync(filePath, "r");
100
+ try {
101
+ const buf = Buffer.alloc(4);
102
+ let pos = 2;
103
+ for (let guard = 0; guard < 64; guard++) {
104
+ if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
105
+ if (buf[0] !== 255) {
106
+ pos += 1;
107
+ continue;
108
+ }
109
+ const marker = buf[1];
110
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
111
+ pos += 2;
112
+ continue;
113
+ }
114
+ const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
115
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
116
+ const seg = Buffer.alloc(8);
117
+ fs.readSync(fd, seg, 0, 8, pos + 4);
118
+ return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
119
+ }
120
+ pos += 2 + len;
121
+ }
122
+ return null;
123
+ } finally {
124
+ fs.closeSync(fd);
125
+ }
126
+ }
127
+
128
+ // src/cli/content.ts
129
+ import fs2 from "node:fs";
130
+ import path from "node:path";
131
+ function parseFrontmatter(raw) {
132
+ if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
133
+ const end = raw.indexOf("\n---", 3);
134
+ if (end < 0) return { frontmatter: {}, body: raw };
135
+ const head = raw.slice(4, end);
136
+ const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
137
+ const frontmatter = {};
138
+ for (const line of head.split("\n")) {
139
+ const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
140
+ if (!m) continue;
141
+ const [, k, v] = m;
142
+ const arr = /^\[(.+)\]$/.exec(v.trim());
143
+ frontmatter[k] = arr ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")) : v.trim().replace(/^["']|["']$/g, "");
144
+ }
145
+ return { frontmatter, body };
146
+ }
147
+ function interpolate(md, vars) {
148
+ return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
149
+ const v = k.split(".").reduce((o, p) => o == null ? o : o[p], vars);
150
+ return v === void 0 || v === null ? "" : String(v);
151
+ });
152
+ }
153
+ function renderMarkdown(md, vars) {
154
+ if (vars) md = interpolate(md, vars);
155
+ const blocks = [];
156
+ let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
157
+ blocks.push(
158
+ `<pre data-lang="${lang}"><code>${code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</code></pre>`
159
+ );
160
+ return `\0CODE${blocks.length - 1}\0`;
161
+ });
162
+ 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(
163
+ /\[([^\]]+)\]\(([^)]+)\)/g,
164
+ '<a href="$2" rel="noopener">$1</a>'
165
+ );
166
+ const out = [];
167
+ let listOpen = null;
168
+ const closeList = () => {
169
+ if (listOpen) {
170
+ out.push(`</${listOpen}>`);
171
+ listOpen = null;
172
+ }
173
+ };
174
+ for (const line of src.split("\n")) {
175
+ const h = /^(#{1,4})\s+(.*)$/.exec(line);
176
+ const li = /^\s*[-*]\s+(.*)$/.exec(line);
177
+ const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
178
+ if (h) {
179
+ closeList();
180
+ out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
181
+ } else if (li) {
182
+ if (listOpen !== "ul") {
183
+ closeList();
184
+ out.push("<ul>");
185
+ listOpen = "ul";
186
+ }
187
+ out.push(`<li>${inline(li[1])}</li>`);
188
+ } else if (oli) {
189
+ if (listOpen !== "ol") {
190
+ closeList();
191
+ out.push("<ol>");
192
+ listOpen = "ol";
193
+ }
194
+ out.push(`<li>${inline(oli[1])}</li>`);
195
+ } else if (line.trim() === "") {
196
+ closeList();
197
+ } else if (line.startsWith("\0CODE")) {
198
+ closeList();
199
+ out.push(line);
200
+ } else {
201
+ closeList();
202
+ out.push(`<p>${inline(line)}</p>`);
203
+ }
204
+ }
205
+ closeList();
206
+ return out.join("\n").replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
207
+ }
208
+ function scanContentDir(contentDir) {
209
+ const collections = {};
210
+ if (!fs2.existsSync(contentDir)) return collections;
211
+ for (const coll of fs2.readdirSync(contentDir, { withFileTypes: true })) {
212
+ if (!coll.isDirectory()) continue;
213
+ const entries = [];
214
+ const dir = path.join(contentDir, coll.name);
215
+ for (const f of fs2.readdirSync(dir)) {
216
+ if (!f.endsWith(".md")) continue;
217
+ const raw = fs2.readFileSync(path.join(dir, f), "utf-8");
218
+ const { frontmatter, body } = parseFrontmatter(raw);
219
+ if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
220
+ const slug = f.replace(/\.md$/, "");
221
+ const html = renderMarkdown(body);
222
+ const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
223
+ const headings = [];
224
+ const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl, txt) => {
225
+ const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
226
+ headings.push({ level: Number(lvl), text: txt, id });
227
+ return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
228
+ });
229
+ entries.push({
230
+ slug,
231
+ frontmatter,
232
+ body,
233
+ html: tocHtml,
234
+ readingTime: Math.max(1, Math.round(words / 200)),
235
+ wordCount: words,
236
+ toc: headings,
237
+ excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160)
238
+ });
239
+ }
240
+ entries.sort(
241
+ (a, b) => String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? ""))
242
+ );
243
+ collections[coll.name] = entries;
244
+ }
245
+ return collections;
246
+ }
247
+ globalThis.__rosetackContentMk = renderMarkdown;
248
+
55
249
  // src/compiler/index.ts
56
250
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
57
251
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
58
252
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
59
253
  var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
60
- var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
254
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
61
255
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
62
256
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
63
- var SLOT_RE = /<slot\s*\/?>/g;
64
- var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
257
+ var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
258
+ var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
65
259
  function encodeSlotCall(attrs) {
66
260
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
67
261
  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} />' });
@@ -456,8 +650,8 @@ function scriptOf(source) {
456
650
  return source.match(COMPONENT_RE)?.[1] ?? null;
457
651
  }
458
652
  async function loadConfig(root) {
459
- const file = path.join(root, "rosetack.config.js");
460
- if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
653
+ const file = path2.join(root, "rosetack.config.js");
654
+ if (!fs3.existsSync(file)) return { plugins: [], i18n: {} };
461
655
  const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
462
656
  return {
463
657
  plugins: mod.default ?? [],
@@ -470,12 +664,12 @@ async function loadPlugins(root) {
470
664
  function resolveRoseImports(script, fromFile, registry) {
471
665
  const imports = [];
472
666
  const resolve3 = (spec, at) => {
473
- const abs = path.resolve(path.dirname(fromFile), spec);
667
+ const abs = path2.resolve(path2.dirname(fromFile), spec);
474
668
  const hit = registry.get(abs);
475
669
  if (!hit) {
476
670
  throw new RoseError(
477
671
  "E-IMPORT",
478
- `${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.`,
672
+ `${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.`,
479
673
  {
480
674
  file: fromFile,
481
675
  line: lineOf(script, at),
@@ -510,16 +704,45 @@ function nodeOnlyImports(importStmts) {
510
704
  }
511
705
  return out;
512
706
  }
513
- function wireEventBindings(template, actionNames) {
707
+ function wireEventBindings(template, actionNames, filePath = "<template>") {
514
708
  const bindings = [];
515
709
  let out = "";
516
710
  let rest = template;
711
+ const TARGET_MODS = { window: "w", document: "d" };
712
+ const MOD_PRE = {
713
+ preventDefault: () => "e.preventDefault()",
714
+ stopPropagation: () => "e.stopPropagation()",
715
+ self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`
716
+ };
717
+ const MOD_POST = {
718
+ 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);`
719
+ };
720
+ const KNOWN_MODS = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
517
721
  for (; ; ) {
518
- const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
722
+ const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
519
723
  if (!m) {
520
724
  out += rest;
521
725
  break;
522
726
  }
727
+ const mods = m[2] ? m[2].slice(1).split("|") : [];
728
+ const targets = mods.filter((mod) => TARGET_MODS[mod]);
729
+ if (targets.length > 1) {
730
+ throw new RoseError(
731
+ "E-TEMPLATE",
732
+ `${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
733
+ { hint: "a handler binds to one target - the element (default), |window or |document" }
734
+ );
735
+ }
736
+ const prefix = targets.length ? "on" + TARGET_MODS[targets[0]] : "on";
737
+ for (const mod of mods) {
738
+ if (!KNOWN_MODS.includes(mod)) {
739
+ throw new RoseError(
740
+ "E-TEMPLATE",
741
+ `${filePath}: unknown event modifier |${mod}`,
742
+ { 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` }
743
+ );
744
+ }
745
+ }
523
746
  out += rest.slice(0, m.index);
524
747
  let i = m.index + m[0].length;
525
748
  let depth = 1;
@@ -541,7 +764,24 @@ function wireEventBindings(template, actionNames) {
541
764
  i++;
542
765
  }
543
766
  const expr = rest.slice(m.index + m[0].length, i).trim();
544
- if (actionNames.has(expr)) {
767
+ const wrap = (body) => {
768
+ if (!mods.length) return body;
769
+ const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
770
+ const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
771
+ return `(e) => {${pre.length ? " " + pre.join("; ") + ";" : ""} (${body})(e);${post.length ? " " + post.join("; ") + ";" : ""} }`;
772
+ };
773
+ if (mods.length && actionNames.has(expr)) {
774
+ throw new RoseError(
775
+ "E-TEMPLATE",
776
+ `${filePath}: event modifiers are not supported on the server action ${expr}`,
777
+ { hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
778
+ );
779
+ }
780
+ if (mods.length) {
781
+ const name = `__h${bindings.length}`;
782
+ out += `data-${prefix}-${m[1]}="${name}"`;
783
+ bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
784
+ } else if (actionNames.has(expr)) {
545
785
  out += `data-on-${m[1]}="$action:${expr}"`;
546
786
  } else if (/^\w+$/.test(expr)) {
547
787
  out += `data-on-${m[1]}="${expr}"`;
@@ -558,7 +798,7 @@ function wireEventBindings(template, actionNames) {
558
798
  function scanSlotDecls(filePath) {
559
799
  let src;
560
800
  try {
561
- src = fs.readFileSync(filePath, "utf-8");
801
+ src = fs3.readFileSync(filePath, "utf-8");
562
802
  } catch {
563
803
  return [];
564
804
  }
@@ -612,7 +852,7 @@ function hoistImports(script) {
612
852
  return { imports: imports.join("\n"), rest: rest.join("\n") };
613
853
  }
614
854
  async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
615
- let source = await fs.promises.readFile(filePath, "utf-8");
855
+ let source = await fs3.promises.readFile(filePath, "utf-8");
616
856
  for (const p of plugins) {
617
857
  if (!p.transform) continue;
618
858
  try {
@@ -620,7 +860,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
620
860
  } catch (err) {
621
861
  throw new RoseError(
622
862
  "E-PLUGIN",
623
- `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
863
+ `plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
624
864
  { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
625
865
  );
626
866
  }
@@ -663,7 +903,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
663
903
  const rawScript = roseResolved.script;
664
904
  const roseImports = roseResolved.imports;
665
905
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
666
- if (path.basename(filePath) !== "_middleware.rose") {
906
+ if (path2.basename(filePath) !== "_middleware.rose") {
667
907
  for (const spec of nodeOnlyImports(importStmts)) {
668
908
  const at = importStmts.indexOf(spec);
669
909
  throw new RoseError(
@@ -689,6 +929,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
689
929
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
690
930
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
691
931
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
932
+ const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
933
+ const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : void 0;
692
934
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
693
935
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
694
936
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
@@ -793,6 +1035,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
793
1035
  }
794
1036
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
795
1037
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
1038
+ if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
796
1039
  const needsClient = clientReasons.length > 0;
797
1040
  const jsWarnings = [];
798
1041
  if (!needsClient) {
@@ -817,7 +1060,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
817
1060
  const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
818
1061
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
819
1062
  const decls = extractDecls(script);
820
- const stateDecls = decls.filter((d) => d.kind === "state");
1063
+ const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
821
1064
  const setterNames = /* @__PURE__ */ new Map();
822
1065
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
823
1066
  const declCode = (d) => {
@@ -827,6 +1070,17 @@ ${hoisted.rest}`, "ssr").trim()}`,
827
1070
  }
828
1071
  const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
829
1072
  const fn = isFn ? d.expr : `() => (${d.expr})`;
1073
+ if (d.kind === "persist") {
1074
+ return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1075
+ }
1076
+ if (d.kind === "kv") {
1077
+ const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1078
+ const fnExpr = mTtl ? mTtl[1] : d.expr;
1079
+ const ttl = mTtl ? mTtl[2] : "300";
1080
+ return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1081
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1082
+ if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}));`;
1083
+ }
830
1084
  return `const __had_${d.name} = hasState(${JSON.stringify(key)});
831
1085
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
832
1086
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
@@ -851,15 +1105,119 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
851
1105
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
852
1106
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
853
1107
  const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
854
- const wired = wireEventBindings(templateCalled, actionNames);
855
- const eventBindings = wired.bindings;
1108
+ const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
1109
+ const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
856
1110
  const stateKeys = decls.map((d) => d.name);
1111
+ const bindBindings = [];
1112
+ let bindCounter = 0;
1113
+ const bindExpanded = wired.template.replace(
1114
+ /\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1115
+ (whole, kind, name) => {
1116
+ if (!stateKeys.includes(name)) {
1117
+ throw new Error(
1118
+ `${filePath}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1119
+ );
1120
+ }
1121
+ if (kind === "this") return ` data-bind-this="${name}"`;
1122
+ const setter = setterNames.get(name);
1123
+ const evt = kind === "checked" ? "change" : "input";
1124
+ const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1125
+ bindBindings.push({
1126
+ event: evt,
1127
+ fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`
1128
+ });
1129
+ const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
1130
+ return ` ${kind}={${name}()}${evtAttr}`;
1131
+ }
1132
+ );
857
1133
  const comps = new Map(roseImports.map((r) => {
858
- const abs = path.resolve(path.dirname(filePath), r.specifier);
1134
+ const abs = path2.resolve(path2.dirname(filePath), r.specifier);
859
1135
  const hit = registry.get(abs);
860
1136
  return [r.name, { index: hit.index, slots: hit.slots }];
861
1137
  }));
862
- const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
1138
+ const groupBindings = [];
1139
+ let groupCounter = 0;
1140
+ const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1141
+ const groupExpanded = (() => {
1142
+ if (!bindExpanded.includes("bind:group")) return bindExpanded;
1143
+ let out = "";
1144
+ let pos2 = 0;
1145
+ let m;
1146
+ TAG_SCAN_RE.lastIndex = 0;
1147
+ while (m = TAG_SCAN_RE.exec(bindExpanded)) {
1148
+ const [whole, tag, attrs, selfClose] = m;
1149
+ const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
1150
+ if (!gm) continue;
1151
+ const name = gm[1];
1152
+ if (!stateKeys.includes(name)) {
1153
+ throw new RoseError(
1154
+ "E-TEMPLATE",
1155
+ `${filePath}: bind:group={${name}} must name a $state declaration`,
1156
+ { hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
1157
+ );
1158
+ }
1159
+ if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
1160
+ throw new RoseError(
1161
+ "E-TEMPLATE",
1162
+ `${filePath}: bind:group is for radio and checkbox inputs`,
1163
+ { 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([]))' }
1164
+ );
1165
+ }
1166
+ const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
1167
+ const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
1168
+ if (!vm || /\{/.test(vm[0])) {
1169
+ throw new RoseError(
1170
+ "E-TEMPLATE",
1171
+ `${filePath}: a bind:group input needs a static value attribute`,
1172
+ { hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
1173
+ );
1174
+ }
1175
+ if (/\schecked\s*=/.test(attrs)) {
1176
+ throw new RoseError(
1177
+ "E-TEMPLATE",
1178
+ `${filePath}: a bind:group input cannot also carry checked=`,
1179
+ { hint: "the group state alone decides which inputs are checked" }
1180
+ );
1181
+ }
1182
+ const setter = setterNames.get(name);
1183
+ const hname = `__rvbg_${scopeKey.replace(/\W/g, "_")}_${groupCounter++}`;
1184
+ const groupValue = JSON.stringify(vm[1] ?? vm[2]);
1185
+ const checkedExpr = isArrayGroup ? `${name}().includes(${groupValue})` : `${name}() === ${groupValue}`;
1186
+ const handlerBody = isArrayGroup ? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))` : `${setter}(e.target.value)`;
1187
+ groupBindings.push({ event: "change", fn: `${hname}: (e) => { ${handlerBody}; }` });
1188
+ const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
1189
+ out += bindExpanded.slice(pos2, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1190
+ pos2 = m.index + whole.length;
1191
+ }
1192
+ if (pos2 === 0) return bindExpanded;
1193
+ out += bindExpanded.slice(pos2);
1194
+ return out;
1195
+ })();
1196
+ const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
1197
+ const useExpanded = groupExpanded.replace(
1198
+ /\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
1199
+ (_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
1200
+ );
1201
+ const classExpanded = expandClassDirectives(useExpanded, filePath);
1202
+ const styleExpanded = expandStyleDirectives(classExpanded, filePath);
1203
+ const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
1204
+ const elseExpanded = expandIfElse(keyExpanded);
1205
+ const deferExpanded = expandDeferBlocks(elseExpanded);
1206
+ const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
1207
+ const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
1208
+ const call = `{__slot(${encodeSlotCall(attrs)})}`;
1209
+ if (fallback) {
1210
+ if (/\{[^{}]*\}/.test(fallback)) {
1211
+ throw new RoseError(
1212
+ "E-TEMPLATE",
1213
+ `${filePath}: slot fallback content must be static markup`,
1214
+ { 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" }
1215
+ );
1216
+ }
1217
+ return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
1218
+ }
1219
+ return call;
1220
+ }).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
863
1221
  assertKnownDirectives(ssrTemplate, filePath);
864
1222
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
865
1223
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
@@ -868,7 +1226,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
868
1226
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
869
1227
  const ssrGuard = guard ? `
870
1228
  ${guard}` : "";
871
- const isMiddleware = path.basename(filePath) === "_middleware.rose";
1229
+ const isMiddleware = path2.basename(filePath) === "_middleware.rose";
872
1230
  const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
873
1231
 
874
1232
  ${importStmts}
@@ -877,8 +1235,8 @@ ${ssrExports}
877
1235
  ${ssrGuard}
878
1236
 
879
1237
  ${cleanScript}
880
- ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
881
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1238
+ ` : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1239
+ const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
882
1240
  return {
883
1241
  ssr: rewriteRoseImports(ssr, "ssr"),
884
1242
  client: rewriteRoseImports(client, "client"),
@@ -889,6 +1247,7 @@ ${cleanScript}
889
1247
  hasParams,
890
1248
  usesContext,
891
1249
  revalidate,
1250
+ cache: cacheSeconds,
892
1251
  csr,
893
1252
  shell,
894
1253
  buffer,
@@ -1079,6 +1438,20 @@ function extractExports(script) {
1079
1438
  out += script.slice(pos);
1080
1439
  return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
1081
1440
  }
1441
+ var REGEX_PRECEDERS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
1442
+ function isRegexStart(src, i) {
1443
+ let j = i - 1;
1444
+ while (j >= 0 && /\s/.test(src[j])) j--;
1445
+ if (j < 0) return true;
1446
+ const p = src[j];
1447
+ if (REGEX_PRECEDERS.has(p)) return true;
1448
+ if (/[A-Za-z0-9_$]/.test(p)) {
1449
+ const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
1450
+ if (!w) return false;
1451
+ return ["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else"].includes(w[1]);
1452
+ }
1453
+ return false;
1454
+ }
1082
1455
  function extractDecls(script) {
1083
1456
  const decls = [];
1084
1457
  DECL_RE.lastIndex = 0;
@@ -1170,6 +1543,35 @@ function braceDepthAt(src, index) {
1170
1543
  i = close === -1 ? src.length : close + 2;
1171
1544
  continue;
1172
1545
  }
1546
+ if (ch === "/" && isRegexStart(src, i)) {
1547
+ i++;
1548
+ let inClass = false;
1549
+ while (i < index) {
1550
+ const c2 = src[i];
1551
+ if (c2 === "\\") {
1552
+ i += 2;
1553
+ continue;
1554
+ }
1555
+ if (inClass) {
1556
+ if (c2 === "]") inClass = false;
1557
+ i++;
1558
+ continue;
1559
+ }
1560
+ if (c2 === "[") {
1561
+ inClass = true;
1562
+ i++;
1563
+ continue;
1564
+ }
1565
+ if (c2 === "/") {
1566
+ i++;
1567
+ break;
1568
+ }
1569
+ if (c2 === "\n") break;
1570
+ i++;
1571
+ }
1572
+ while (i < index && /[a-z]/.test(src[i])) i++;
1573
+ continue;
1574
+ }
1173
1575
  if (ch === "{") depth++;
1174
1576
  else if (ch === "}") depth--;
1175
1577
  i++;
@@ -1180,8 +1582,410 @@ function autoCall(expr) {
1180
1582
  const e = expr.trim();
1181
1583
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1182
1584
  }
1585
+ var DEFER_ENABLED = true;
1586
+ function expandKeyBlocks(template, filePath) {
1587
+ if (!template.includes("{#key")) return template;
1588
+ for (let pass = 0; pass < 10; pass++) {
1589
+ const OPEN_RE = /\{#key\s+([^}]+)\}/g;
1590
+ OPEN_RE.lastIndex = 0;
1591
+ const openM = OPEN_RE.exec(template);
1592
+ if (!openM) return template;
1593
+ const expr = openM[1].trim();
1594
+ const bodyStart = openM.index + openM[0].length;
1595
+ const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
1596
+ TOK_RE.lastIndex = bodyStart;
1597
+ let depth = 1;
1598
+ let closeAt = -1;
1599
+ let tm;
1600
+ while (tm = TOK_RE.exec(template)) {
1601
+ if (tm[0].startsWith("{#")) {
1602
+ depth++;
1603
+ continue;
1604
+ }
1605
+ depth--;
1606
+ if (depth === 0) {
1607
+ closeAt = tm.index;
1608
+ break;
1609
+ }
1610
+ }
1611
+ if (closeAt < 0) {
1612
+ throw new RoseError(
1613
+ "E-TEMPLATE",
1614
+ `${filePath}: {#key ${expr}} is never closed`,
1615
+ { hint: "every {#key} needs its {/key}" }
1616
+ );
1617
+ }
1618
+ template = template.slice(0, openM.index) + `{#each [${expr}] as __rvkv}` + template.slice(bodyStart, closeAt) + "{/each}" + template.slice(closeAt + "{/key}".length);
1619
+ }
1620
+ return template;
1621
+ }
1622
+ function expandIfElseOnce(template) {
1623
+ const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
1624
+ let out = "";
1625
+ let pos = 0;
1626
+ let changed = false;
1627
+ for (; ; ) {
1628
+ const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
1629
+ if (!openM) {
1630
+ out += template.slice(pos);
1631
+ break;
1632
+ }
1633
+ const kind = openM[1];
1634
+ const head = openM[2];
1635
+ const start = pos + openM.index;
1636
+ const cond = kind === "if" ? head.trim() : "";
1637
+ const bodyStart = start + openM[0].length;
1638
+ out += template.slice(pos, start);
1639
+ TOK_RE.lastIndex = bodyStart;
1640
+ let depth = 1;
1641
+ let closeAt = -1;
1642
+ let closeLen = 0;
1643
+ const elses = [];
1644
+ let tm;
1645
+ while (tm = TOK_RE.exec(template)) {
1646
+ const tok = tm[0];
1647
+ if (tok.startsWith("{:else")) {
1648
+ if (depth === 1) {
1649
+ const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
1650
+ elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
1651
+ }
1652
+ continue;
1653
+ }
1654
+ if (tok.startsWith("{#")) {
1655
+ depth++;
1656
+ continue;
1657
+ }
1658
+ depth--;
1659
+ if (depth === 0) {
1660
+ closeAt = tm.index;
1661
+ closeLen = tok.length;
1662
+ break;
1663
+ }
1664
+ }
1665
+ if (closeAt < 0 || elses.length === 0) {
1666
+ out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
1667
+ if (closeAt < 0) break;
1668
+ pos = closeAt + closeLen;
1669
+ continue;
1670
+ }
1671
+ const body = template.slice(bodyStart, closeAt);
1672
+ if (kind === "each") {
1673
+ const lastBare = [...elses].reverse().find((e) => e.cond === null);
1674
+ if (!lastBare) {
1675
+ out += template.slice(start, closeAt + closeLen);
1676
+ pos = closeAt + closeLen;
1677
+ continue;
1678
+ }
1679
+ const relLast = lastBare.at - bodyStart;
1680
+ const eachBody = body.slice(0, relLast);
1681
+ const elseBody = body.slice(relLast + lastBare.len);
1682
+ const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, "").trim();
1683
+ out += template.slice(start, bodyStart) + eachBody + `{/each}{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
1684
+ pos = closeAt + closeLen;
1685
+ changed = true;
1686
+ continue;
1687
+ }
1688
+ const branches = [];
1689
+ let cursor = 0;
1690
+ for (let i = 0; i < elses.length; i++) {
1691
+ const e = elses[i];
1692
+ const rel = e.at - bodyStart;
1693
+ branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
1694
+ cursor = rel + e.len;
1695
+ }
1696
+ branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
1697
+ const first = branches.shift();
1698
+ const build3 = (bs) => {
1699
+ if (!bs.length) return "";
1700
+ const head2 = bs[0];
1701
+ const rest = bs.slice(1);
1702
+ if (head2.cond == null) return head2.body;
1703
+ let s = `{#if ${head2.cond}}${head2.body}{/if}`;
1704
+ if (rest.length) s += `{#if !(${head2.cond})}` + build3(rest) + `{/if}`;
1705
+ return s;
1706
+ };
1707
+ let emitted = `{#if ${cond}}${first.body}{/if}`;
1708
+ if (branches.length) emitted += `{#if !(${cond})}` + build3(branches) + `{/if}`;
1709
+ out += emitted;
1710
+ pos = closeAt + closeLen;
1711
+ changed = true;
1712
+ }
1713
+ return { template: out, changed };
1714
+ }
1715
+ function expandClassDirectives(template, filePath) {
1716
+ if (!template.includes("class:")) return template;
1717
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1718
+ let out = "";
1719
+ let pos = 0;
1720
+ let m;
1721
+ TAG_RE.lastIndex = 0;
1722
+ while (m = TAG_RE.exec(template)) {
1723
+ const [whole, tag, attrs, selfClose] = m;
1724
+ if (!attrs.includes("class:")) continue;
1725
+ const pairs = [];
1726
+ const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
1727
+ let nm;
1728
+ while (nm = NAME_RE.exec(attrs)) {
1729
+ let i = nm.index + nm[0].length;
1730
+ let depth = 1;
1731
+ while (i < attrs.length && depth > 0) {
1732
+ const ch = attrs[i];
1733
+ if (ch === '"' || ch === "'") {
1734
+ i = skipQuoted(attrs, i);
1735
+ continue;
1736
+ }
1737
+ if (ch === "{") depth++;
1738
+ else if (ch === "}") depth--;
1739
+ i++;
1740
+ }
1741
+ if (depth !== 0) {
1742
+ throw new RoseError("E-TEMPLATE", `${filePath}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
1743
+ }
1744
+ pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1745
+ }
1746
+ const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1747
+ const clsM = clsRe.exec(attrs);
1748
+ if (clsM && clsM[2].startsWith("{")) {
1749
+ throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both class={...} and class: directives`, { file: filePath, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
1750
+ }
1751
+ const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
1752
+ let closure = `(${JSON.stringify(staticCls)}`;
1753
+ for (const p of pairs) {
1754
+ closure += `+((${p.expr})?${JSON.stringify(" " + p.name)}:'')`;
1755
+ }
1756
+ closure += `)`;
1757
+ let newAttrs = attrs;
1758
+ for (let k = pairs.length - 1; k >= 0; k--) {
1759
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1760
+ }
1761
+ if (clsM) {
1762
+ newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
1763
+ } else {
1764
+ newAttrs = ` class={${closure}}` + newAttrs;
1765
+ }
1766
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1767
+ pos = m.index + whole.length;
1768
+ }
1769
+ if (pos === 0) return template;
1770
+ out += template.slice(pos);
1771
+ return out;
1772
+ }
1773
+ function expandStyleDirectives(template, filePath) {
1774
+ if (!template.includes("style:")) return template;
1775
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1776
+ let out = "";
1777
+ let pos = 0;
1778
+ let m;
1779
+ TAG_RE.lastIndex = 0;
1780
+ while (m = TAG_RE.exec(template)) {
1781
+ const [whole, tag, attrs, selfClose] = m;
1782
+ if (!attrs.includes("style:")) continue;
1783
+ const pairs = [];
1784
+ const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
1785
+ let nm;
1786
+ while (nm = NAME_RE.exec(attrs)) {
1787
+ let i = nm.index + nm[0].length;
1788
+ let depth = 1;
1789
+ while (i < attrs.length && depth > 0) {
1790
+ const ch = attrs[i];
1791
+ if (ch === '"' || ch === "'") {
1792
+ i = skipQuoted(attrs, i);
1793
+ continue;
1794
+ }
1795
+ if (ch === "{") depth++;
1796
+ else if (ch === "}") depth--;
1797
+ i++;
1798
+ }
1799
+ if (depth !== 0) {
1800
+ throw new RoseError("E-TEMPLATE", `${filePath}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
1801
+ }
1802
+ pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1803
+ }
1804
+ const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1805
+ const stM = styleRe.exec(attrs);
1806
+ if (stM && stM[2].startsWith("{")) {
1807
+ throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both style={...} and style: directives`, { file: filePath, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
1808
+ }
1809
+ const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
1810
+ let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
1811
+ for (const p of pairs) {
1812
+ closure += `+${JSON.stringify(p.prop + ":")}+(${p.expr})+';'`;
1813
+ }
1814
+ let newAttrs = attrs;
1815
+ for (let k = pairs.length - 1; k >= 0; k--) {
1816
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1817
+ }
1818
+ if (stM) {
1819
+ newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
1820
+ } else {
1821
+ newAttrs = ` style={${closure}}` + newAttrs;
1822
+ }
1823
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1824
+ pos = m.index + whole.length;
1825
+ }
1826
+ if (pos === 0) return template;
1827
+ out += template.slice(pos);
1828
+ return out;
1829
+ }
1830
+ function expandBoundaryFallbacks(template, filePath) {
1831
+ if (!template.includes("{:fallback")) return template;
1832
+ for (let pass = 0; pass < 10; pass++) {
1833
+ const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
1834
+ let out = "";
1835
+ let pos = 0;
1836
+ let changed = false;
1837
+ let tm;
1838
+ while (tm = TOK_RE.exec(template)) {
1839
+ if (tm[0] !== "{#boundary}") continue;
1840
+ const start = tm.index;
1841
+ const bodyStart = start + tm[0].length;
1842
+ let depth = 1;
1843
+ let closeAt = -1;
1844
+ let tm2;
1845
+ while (tm2 = TOK_RE.exec(template)) {
1846
+ if (tm2[0] === "{#boundary}") {
1847
+ depth++;
1848
+ continue;
1849
+ }
1850
+ if (tm2[0] === "{/boundary}") {
1851
+ depth--;
1852
+ if (depth === 0) {
1853
+ closeAt = tm2.index;
1854
+ break;
1855
+ }
1856
+ }
1857
+ }
1858
+ if (closeAt < 0) break;
1859
+ const body = template.slice(bodyStart, closeAt);
1860
+ const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
1861
+ const kindStack = ["boundary"];
1862
+ let d = 1;
1863
+ let fbAt = -1;
1864
+ let fbLen = 0;
1865
+ let tm3;
1866
+ BTOK2.lastIndex = 0;
1867
+ while (tm3 = BTOK2.exec(body)) {
1868
+ const tok = tm3[0];
1869
+ if (tok === "{:fallback}") {
1870
+ const top = kindStack[kindStack.length - 1];
1871
+ if (top !== "boundary") {
1872
+ throw new RoseError(
1873
+ "E-TEMPLATE",
1874
+ `${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
1875
+ { hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
1876
+ );
1877
+ }
1878
+ if (fbAt >= 0) {
1879
+ throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
1880
+ }
1881
+ fbAt = tm3.index;
1882
+ fbLen = tok.length;
1883
+ continue;
1884
+ }
1885
+ if (tok.startsWith("{#")) {
1886
+ d++;
1887
+ kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]);
1888
+ continue;
1889
+ }
1890
+ d--;
1891
+ kindStack.pop();
1892
+ }
1893
+ if (fbAt < 0) continue;
1894
+ const custom = body.slice(0, fbAt);
1895
+ const fbMarkup = body.slice(fbAt + fbLen);
1896
+ const b64 = Buffer.from(fbMarkup, "utf-8").toString("base64");
1897
+ out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + "{/boundary}";
1898
+ pos = closeAt + "{/boundary}".length;
1899
+ changed = true;
1900
+ }
1901
+ if (!changed) break;
1902
+ template = out + template.slice(pos);
1903
+ }
1904
+ return template;
1905
+ }
1906
+ function expandIfElse(template) {
1907
+ for (let pass = 0; pass < 10; pass++) {
1908
+ if (!/\{:else\b/.test(template)) return template;
1909
+ const r = expandIfElseOnce(template);
1910
+ template = r.template;
1911
+ if (!r.changed) return template;
1912
+ }
1913
+ return template;
1914
+ }
1915
+ function expandDeferBlocks(template) {
1916
+ if (!DEFER_ENABLED) {
1917
+ const openRe2 = /\{#defer(?:\s+hold=\\d+)?\}/g;
1918
+ let out2 = "";
1919
+ let dpos = 0;
1920
+ for (; ; ) {
1921
+ openRe2.lastIndex = dpos;
1922
+ const openM = openRe2.exec(template);
1923
+ if (!openM) break;
1924
+ const openAt = openM.index;
1925
+ const openLen = openM[0].length;
1926
+ const closeAt = template.indexOf("{/defer}", openAt + openLen);
1927
+ if (closeAt < 0) break;
1928
+ out2 += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
1929
+ dpos = closeAt + 8;
1930
+ }
1931
+ return { template: dpos === 0 ? template : out2, count: 0, holds: [] };
1932
+ }
1933
+ let count = 0;
1934
+ const holds = [];
1935
+ let out = "";
1936
+ let pos = 0;
1937
+ const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
1938
+ for (; ; ) {
1939
+ openRe.lastIndex = pos;
1940
+ const openM = openRe.exec(template);
1941
+ if (!openM) break;
1942
+ const openAt = openM.index;
1943
+ const openLen = openM[0].length;
1944
+ const hold = openM[1] ? Number(openM[1]) : 0;
1945
+ let depth = 1;
1946
+ let i = openAt + openLen;
1947
+ let closeAt = -1;
1948
+ while (i < template.length) {
1949
+ openRe.lastIndex = i;
1950
+ const nextOpenM = openRe.exec(template);
1951
+ const nextOpen = nextOpenM ? nextOpenM.index : -1;
1952
+ const nextClose = template.indexOf("{/defer}", i);
1953
+ if (nextClose < 0) break;
1954
+ if (nextOpen >= 0 && nextOpen < nextClose) {
1955
+ depth++;
1956
+ i = nextOpen + nextOpenM[0].length;
1957
+ continue;
1958
+ }
1959
+ depth--;
1960
+ if (depth === 0) {
1961
+ closeAt = nextClose;
1962
+ break;
1963
+ }
1964
+ i = nextClose + 8;
1965
+ }
1966
+ if (closeAt < 0) break;
1967
+ const content = template.slice(openAt + openLen, closeAt);
1968
+ holds.push(hold);
1969
+ const n = ++count;
1970
+ out += template.slice(pos, openAt);
1971
+ out += "{#if __rvDefer" + n + "()}" + content + "{/if}\n{#if !__rvDefer" + n + '()}<div class="rv-defer-loading"></div>{/if}';
1972
+ pos = closeAt + 8;
1973
+ }
1974
+ if (count === 0) return { template, count: 0, holds: [] };
1975
+ out += template.slice(pos);
1976
+ return { template: out, count, holds };
1977
+ }
1978
+ function deferBootCode(count, holds = []) {
1979
+ let code = "";
1980
+ for (let n = 1; n <= count; n++) {
1981
+ code += "const [__rvDefer" + n + ", set__rvDefer" + n + '] = state("__rvdefer' + n + '", false);\n';
1982
+ const hold = holds[n - 1] || 0;
1983
+ code += hold > 0 ? "onMount(function () { setTimeout(function () { set__rvDefer" + n + "(true); }, " + hold + "); });\n" : "onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer" + n + "(true); }); }); });\n";
1984
+ }
1985
+ return code;
1986
+ }
1183
1987
  function findBlock(src, kind) {
1184
- const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
1988
+ const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
1185
1989
  const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1186
1990
  let open;
1187
1991
  while (open = head.exec(src)) {
@@ -1203,7 +2007,7 @@ function findBlock(src, kind) {
1203
2007
  i = nextClose.index + nextClose[0].length;
1204
2008
  if (--depth === 0) {
1205
2009
  const content = src.slice(afterOpen, nextClose.index);
1206
- const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
2010
+ const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", content];
1207
2011
  const arr = [src.slice(start, i), ...groups];
1208
2012
  arr.index = start;
1209
2013
  return arr;
@@ -1246,7 +2050,7 @@ function compileHead(head) {
1246
2050
  flush();
1247
2051
  return out;
1248
2052
  }
1249
- var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
2053
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
1250
2054
  function assertKnownDirectives(template, filePath) {
1251
2055
  const rawRanges = [];
1252
2056
  const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
@@ -1280,21 +2084,28 @@ function assertKnownDirectives(template, filePath) {
1280
2084
  if (word === "else") {
1281
2085
  throw new RoseError(
1282
2086
  "E-TEMPLATE",
1283
- `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1284
- { file: filePath, line: lineAt(template, m), hint: "nest a second {#if}: {#if cond}A{/if}{#if !cond}B{/if} - the negation of the first condition IS the else" }
2087
+ `${filePath}: a stray {:else} with no {#if} above it`,
2088
+ { file: filePath, line: lineAt(template, m), hint: "{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}" }
2089
+ );
2090
+ }
2091
+ if (word === "fallback") {
2092
+ throw new RoseError(
2093
+ "E-TEMPLATE",
2094
+ `${filePath}: a stray {:fallback} with no {#boundary} above it`,
2095
+ { file: filePath, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
1285
2096
  );
1286
2097
  }
1287
2098
  throw new RoseError(
1288
2099
  "E-TEMPLATE",
1289
2100
  `${filePath}: {:${word}} is not a rosetack directive`,
1290
- { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary} - and there is no {:else}: nest a second {#if} with the negated condition" }
2101
+ { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
1291
2102
  );
1292
2103
  }
1293
- const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
2104
+ const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
1294
2105
  while (m = OPENER_RE.exec(template)) {
1295
2106
  if (inRaw(m.index)) continue;
1296
2107
  const [, kind, head] = m;
1297
- if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
2108
+ if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
1298
2109
  throw new RoseError(
1299
2110
  "E-TEMPLATE",
1300
2111
  `${filePath}: {#each ${head.trim()}} is missing its item name`,
@@ -1348,10 +2159,12 @@ function rewriteQuotedExprAttrs(template, comps) {
1348
2159
  return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
1349
2160
  });
1350
2161
  }
1351
- function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
2162
+ function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map(), islandDepth = 0) {
1352
2163
  let result = "";
1353
2164
  let remaining = template;
1354
2165
  let blockId = 0;
2166
+ const islandsMode = /\{#island\b/.test(template);
2167
+ const effMarkers = markers && (!islandsMode || islandDepth > 0);
1355
2168
  const nextId = () => `${depth}_${blockId++}`;
1356
2169
  while (remaining.length > 0) {
1357
2170
  const ifMatch = findBlock(remaining, "if");
@@ -1360,10 +2173,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1360
2173
  const firstExpr = templateExprSpans(remaining)[0];
1361
2174
  const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
1362
2175
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2176
+ const islandMatch = findBlock(remaining, "island");
1363
2177
  const candidates = [];
1364
2178
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
1365
2179
  if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
1366
2180
  if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
2181
+ if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
1367
2182
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
1368
2183
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
1369
2184
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
@@ -1397,10 +2212,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1397
2212
  const call = autoCall(cond);
1398
2213
  const id = nextId();
1399
2214
  const innerScope = scope ?? "__s";
1400
- const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, markers, comps);
2215
+ const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, effMarkers, comps, islandDepth);
1401
2216
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
1402
2217
  `;
1403
- if (markers) {
2218
+ if (effMarkers) {
1404
2219
  result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
1405
2220
  `;
1406
2221
  } else {
@@ -1409,43 +2224,62 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1409
2224
  }
1410
2225
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1411
2226
  } else if (earliest.type === "each") {
1412
- const [, items, item, content] = earliest.match;
2227
+ const [, items, item, index, content] = earliest.match;
1413
2228
  const before = remaining.substring(0, earliest.index);
1414
2229
  if (before) result += emitChunk(before, acc, closes, scope);
1415
2230
  const call = autoCall(items);
1416
2231
  const id = nextId();
1417
- const itemRe = new RegExp(`\\b${item}\\b`, "g");
2232
+ const isDestructure = /^[{[]/.test(item);
2233
+ const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, "g");
2234
+ const indexRe = index ? new RegExp(`\\b${index}\\b`, "g") : null;
1418
2235
  let scoped = "";
1419
2236
  let lastSpan = 0;
1420
2237
  for (const s of templateExprSpans(content.trim())) {
1421
- scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
2238
+ let expr = itemRe ? s.expr.replace(itemRe, "__s") : s.expr;
2239
+ if (indexRe) expr = expr.replace(indexRe, "__i");
2240
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + expr + "}";
1422
2241
  lastSpan = s.end + 1;
1423
2242
  }
1424
2243
  scoped += content.trim().slice(lastSpan);
1425
- const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
1426
- result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
2244
+ const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2245
+ const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2246
+ result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
1427
2247
  `;
1428
- if (markers) {
2248
+ if (effMarkers) {
1429
2249
  result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
1430
2250
  `;
1431
2251
  } else {
1432
- result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');
2252
+ const param = isDestructure ? "__s" : item;
2253
+ result += `${acc} += (${call}).map((${param}${index ? ", __i" : ""}) => __b${id}(${param}, []${index ? ", __i" : ""}))).join('');
1433
2254
  `;
1434
2255
  }
1435
2256
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1436
2257
  } else if (earliest.type === "boundary") {
1437
- const [, content] = earliest.match;
2258
+ const [, fbAttr, content] = earliest.match;
2259
+ let fallbackSrc = "";
2260
+ if (fbAttr) {
2261
+ const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
2262
+ if (fbM) fallbackSrc = Buffer.from(fbM[1], "base64").toString("utf-8");
2263
+ }
2264
+ const custom = content;
1438
2265
  const before = remaining.substring(0, earliest.index);
1439
2266
  if (before) result += emitChunk(before, acc, closes, scope);
1440
2267
  const id = nextId();
1441
- const catchesAction = /\$action:|<form[\s>]/.test(content);
1442
- const inner = compileTemplate(content.trim(), "h", closes, scope, depth + 1, markers, comps);
2268
+ const catchesAction = /\$action:|<form[\s>]/.test(custom);
2269
+ const inner = compileTemplate(custom.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
1443
2270
  result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
1444
2271
  `;
2272
+ let fbBlock = "";
2273
+ if (fallbackSrc.trim()) {
2274
+ const fbInner = compileTemplate(fallbackSrc.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
2275
+ fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };
2276
+ `;
2277
+ }
2278
+ result += fbBlock;
1445
2279
  result += `let __bd${id} = '';
1446
2280
  `;
1447
- result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
1448
- ` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
2281
+ result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : "$boundaryFallback(e)"}; }
2282
+ ` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
1449
2283
  `;
1450
2284
  result += `${acc} += __bd${id};
1451
2285
  `;
@@ -1468,7 +2302,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1468
2302
  const { def, named } = splitSlots(childrenSrc);
1469
2303
  const hasChildren = def.trim().length > 0;
1470
2304
  if (hasChildren) {
1471
- result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, markers, comps)} return h; };
2305
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; };
1472
2306
  `;
1473
2307
  }
1474
2308
  const slotFns = named.map(([nm, src]) => {
@@ -1484,9 +2318,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1484
2318
  }
1485
2319
  content = out + content.slice(lastSpan);
1486
2320
  }
1487
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
2321
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
1488
2322
  });
1489
2323
  const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
2324
+ if (a.kind === "spread") return `...(${a.value})`;
1490
2325
  const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
1491
2326
  const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
1492
2327
  return `${JSON.stringify(key)}: ${val}`;
@@ -1495,20 +2330,49 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1495
2330
  result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
1496
2331
  `;
1497
2332
  remaining = rest;
2333
+ } else if (earliest.type === "island") {
2334
+ const [, name, hydrate, content] = earliest.match;
2335
+ const before = remaining.substring(0, earliest.index);
2336
+ if (before) result += emitChunk(before, acc, closes, scope);
2337
+ const hydrateAttr = hydrate === "visible" || hydrate === "idle" ? ` data-rv-island-hydrate="${hydrate}"` : "";
2338
+ result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ""}"${hydrateAttr}>`)};
2339
+ `;
2340
+ const inner = compileTemplate(content.trim(), "h", "__c", scope, depth + 1, markers, comps, islandDepth + 1);
2341
+ result += inner;
2342
+ result += `${acc} += '</div>';
2343
+ `;
2344
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1498
2345
  } else {
1499
2346
  const [, expr] = earliest.match;
1500
2347
  const trimmed = expr.trim();
1501
2348
  const before = remaining.substring(0, earliest.index);
2349
+ const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
2350
+ if (constMatch) {
2351
+ if (before) result += emitChunk(before, acc, closes, scope);
2352
+ result += `const ${constMatch[1]} = (${constMatch[2].trim()});
2353
+ `;
2354
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2355
+ continue;
2356
+ }
1502
2357
  if (trimmed === "__slot__") {
1503
2358
  if (before) result += emitChunk(before, acc, closes, scope);
1504
2359
  result += compileSlot(acc);
1505
2360
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1506
2361
  continue;
1507
2362
  }
1508
- const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
2363
+ const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
2364
+ if (slotDefault) {
2365
+ if (before) result += emitChunk(before, acc, closes, scope);
2366
+ result += `${acc} += __slotDefault(children, ${slotDefault[1]});
2367
+ `;
2368
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2369
+ continue;
2370
+ }
2371
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
1509
2372
  if (slotCall) {
1510
2373
  if (before) result += emitChunk(before, acc, closes, scope);
1511
- result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);
2374
+ const fb = slotCall[4] ? `, ${slotCall[4]}` : "";
2375
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});
1512
2376
  `;
1513
2377
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1514
2378
  continue;
@@ -1517,7 +2381,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1517
2381
  if (rawMatch) {
1518
2382
  if (before) result += emitChunk(before, acc, closes, scope);
1519
2383
  const expr2 = rawMatch[1].trim();
1520
- if (!markers) {
2384
+ if (!effMarkers) {
1521
2385
  result += `${acc} += String(${expr2} ?? '');
1522
2386
  `;
1523
2387
  } else {
@@ -1532,12 +2396,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1532
2396
  if (attrMatch) {
1533
2397
  const lit = before.slice(0, before.length - attrMatch[0].length);
1534
2398
  if (lit) result += emitChunk(lit, acc, closes, scope);
1535
- result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
2399
+ result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
1536
2400
  } else {
1537
2401
  if (before) result += emitChunk(before, acc, closes, scope);
1538
2402
  const after = remaining.substring(earliest.index + earliest.match[0].length);
1539
2403
  const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
1540
- result += emitText(trimmed, acc, closes, scope, markers, pair);
2404
+ result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
1541
2405
  }
1542
2406
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1543
2407
  }
@@ -1597,6 +2461,12 @@ function parseCompAttrs(attrs) {
1597
2461
  const out = [];
1598
2462
  let i = 0;
1599
2463
  while (i < attrs.length) {
2464
+ const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
2465
+ if (spread) {
2466
+ out.push({ name: "...", kind: "spread", value: spread[1].trim() });
2467
+ i += spread[0].length;
2468
+ continue;
2469
+ }
1600
2470
  const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
1601
2471
  if (!nm) break;
1602
2472
  i += nm[0].length;
@@ -1734,22 +2604,55 @@ var IMG_MIME = {
1734
2604
  ".ico": "image/x-icon"
1735
2605
  };
1736
2606
  var INLINE_IMG_MAX = 4096;
2607
+ function listImageVariants(publicDir, url) {
2608
+ const ext = path2.extname(url);
2609
+ const base = path2.basename(url, ext);
2610
+ const dirUrl = url.slice(0, url.length - (base + ext).length);
2611
+ let entries;
2612
+ try {
2613
+ entries = fs3.readdirSync(path2.join(publicDir, path2.dirname(url)));
2614
+ } catch {
2615
+ return [];
2616
+ }
2617
+ const re = new RegExp(
2618
+ "^" + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.w(\\d+)" + ext.replace(".", "\\.") + "$",
2619
+ "i"
2620
+ );
2621
+ const out = [];
2622
+ for (const e of entries) {
2623
+ const m = re.exec(e);
2624
+ const width = m ? Number(m[1]) : 0;
2625
+ if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
2626
+ }
2627
+ return out.sort((a, b) => a.width - b.width);
2628
+ }
1737
2629
  function inlineImages(template, publicDir) {
1738
2630
  return template.replace(IMG_RE, (tag) => {
1739
2631
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
1740
2632
  if (!src) return tag;
1741
- const ext = path.extname(src[1]).toLowerCase();
2633
+ const ext = path2.extname(src[1]).toLowerCase();
1742
2634
  const mime = IMG_MIME[ext];
1743
2635
  if (!mime) return tag;
2636
+ const rel = src[1].replace(/^\/public(?=\/)/, "");
2637
+ const filePath = path2.join(publicDir, rel);
1744
2638
  let file;
1745
2639
  try {
1746
- file = fs.readFileSync(path.join(publicDir, src[1]));
2640
+ file = fs3.readFileSync(filePath);
1747
2641
  } catch {
1748
2642
  return tag;
1749
2643
  }
1750
- if (file.length > INLINE_IMG_MAX) return tag;
2644
+ const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
2645
+ const dims = authorDims ? null : readImageSize(filePath);
2646
+ const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
2647
+ if (file.length > INLINE_IMG_MAX) {
2648
+ const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
2649
+ const variants = hasSS ? [] : listImageVariants(publicDir, rel);
2650
+ if (!variants.length) return withDims(tag);
2651
+ const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(", ");
2652
+ return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
2653
+ }
1751
2654
  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")}`;
1752
- return tag.replace(src[0], `src="${uri}"`);
2655
+ return withDims(tag.replace(src[0], `src="${uri}"`));
1753
2656
  });
1754
2657
  }
1755
2658
  function emitText(expr, acc, closes, scope, markers = true, pair = false) {
@@ -1763,6 +2666,7 @@ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
1763
2666
  return `${acc} += textMark(${closes}, ${fn}${extra});
1764
2667
  `;
1765
2668
  }
2669
+ var BOOLEAN_ATTRS = /* @__PURE__ */ new Set(["checked", "disabled", "readonly", "required", "selected", "multiple", "autofocus", "open"]);
1766
2670
  function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1767
2671
  if (!markers) {
1768
2672
  return `${acc} += '${attr}="' + esc(${expr}) + '"';
@@ -1770,6 +2674,10 @@ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1770
2674
  }
1771
2675
  const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1772
2676
  const arg = scope ? `, ${scope}` : "";
2677
+ if (BOOLEAN_ATTRS.has(attr)) {
2678
+ return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});
2679
+ `;
2680
+ }
1773
2681
  return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
1774
2682
  `;
1775
2683
  }
@@ -1777,7 +2685,7 @@ function compileSlot(acc) {
1777
2685
  return `${acc} += String(children);
1778
2686
  `;
1779
2687
  }
1780
- var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
2688
+ var RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
1781
2689
  var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1782
2690
  function propsCode(props) {
1783
2691
  if (props.length === 0) return "";
@@ -1790,7 +2698,16 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1790
2698
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1791
2699
  return { o, fn };
1792
2700
  };
1793
- const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
2701
+ const __slotBlock = (closes, sl, name, pairs, fallback) => {
2702
+ const hit = __slot(sl, name, pairs);
2703
+ if (hit) return slotBlockMark(closes, hit);
2704
+ return fallback || '';
2705
+ };
2706
+ const __slotDefault = (children, fallback) => {
2707
+ const c = children == null ? '' : String(children);
2708
+ if (c.trim()) return c;
2709
+ return fallback || '';
2710
+ };`;
1794
2711
  function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1795
2712
  const headCode = headFn ? `
1796
2713
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -1866,7 +2783,7 @@ function buildReport(infos, compiled) {
1866
2783
  if (routeShipsNoJs(infos, compiled, i)) {
1867
2784
  return `${info.routePath} zero-JS nothing in the chain needs the client`;
1868
2785
  }
1869
- 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("; ");
2786
+ 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("; ");
1870
2787
  const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
1871
2788
  return `${info.routePath} client JS ${why}${forced}`;
1872
2789
  });
@@ -1914,44 +2831,44 @@ for (const el of document.querySelectorAll('[data-rosetack]')) {
1914
2831
  }
1915
2832
  `;
1916
2833
  async function buildProject(root, outDir) {
1917
- await fs.promises.mkdir(outDir, { recursive: true });
1918
- const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
1919
- await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
2834
+ await fs3.promises.mkdir(outDir, { recursive: true });
2835
+ const stale = (await fs3.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
2836
+ await Promise.all(stale.map((f) => fs3.promises.rm(path2.join(outDir, f), { force: true })));
1920
2837
  const pageFiles = await scanRoseFiles(root);
1921
2838
  const compFiles = await scanComponentFiles(root);
1922
2839
  const files = [...pageFiles, ...compFiles];
1923
2840
  if (pageFiles.length === 0) {
1924
2841
  throw new RoseError(
1925
2842
  "E-ROUTE",
1926
- `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1927
- { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
2843
+ `no .rose pages found under ${path2.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
2844
+ { file: path2.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1928
2845
  );
1929
2846
  }
1930
2847
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1931
2848
  const config = await loadConfig(root);
1932
2849
  const plugins = config.plugins;
1933
2850
  const scopeKeys = files.map((f, i) => {
1934
- const base = infos[i].isComponent ? path.join(root, "src") : path.join(root, "src", "pages");
1935
- return path.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
2851
+ const base = infos[i].isComponent ? path2.join(root, "src") : path2.join(root, "src", "pages");
2852
+ return path2.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
1936
2853
  });
1937
2854
  const registry = new Map(
1938
2855
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1939
2856
  );
1940
2857
  const compiled = await Promise.all(
1941
- files.map((f, i) => compileComponent(f, path.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
2858
+ files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
1942
2859
  );
1943
2860
  const importsOf = /* @__PURE__ */ new Map();
1944
2861
  files.forEach((_, i) => {
1945
2862
  const list = [];
1946
2863
  for (const r of compiled[i].roseImports ?? []) {
1947
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
2864
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1948
2865
  const hit = registry.get(abs);
1949
2866
  if (hit) list.push(hit.index);
1950
2867
  }
1951
2868
  importsOf.set(i, list);
1952
2869
  });
1953
2870
  const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
1954
- if (compiled[i].needsClient) return path.basename(files[i]);
2871
+ if (compiled[i].needsClient) return path2.basename(files[i]);
1955
2872
  if (seen.has(i)) return null;
1956
2873
  seen.add(i);
1957
2874
  for (const dep of importsOf.get(i) ?? []) {
@@ -1973,7 +2890,7 @@ async function buildProject(root, outDir) {
1973
2890
  if (reachable.has(i)) return;
1974
2891
  reachable.add(i);
1975
2892
  for (const r of compiled[i].roseImports ?? []) {
1976
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
2893
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1977
2894
  const hit = registry.get(abs);
1978
2895
  if (hit) visit(hit.index);
1979
2896
  }
@@ -1982,13 +2899,13 @@ async function buildProject(root, outDir) {
1982
2899
  if (!infos[i].isComponent) visit(i);
1983
2900
  });
1984
2901
  const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
1985
- if (styles) await fs.promises.writeFile(path.join(outDir, "styles.css"), styles);
1986
- else await fs.promises.rm(path.join(outDir, "styles.css"), { force: true });
2902
+ if (styles) await fs3.promises.writeFile(path2.join(outDir, "styles.css"), styles);
2903
+ else await fs3.promises.rm(path2.join(outDir, "styles.css"), { force: true });
1987
2904
  let locales = {};
1988
2905
  try {
1989
- for (const f of await fs.promises.readdir(path.join(root, "src", "locales"))) {
2906
+ for (const f of await fs3.promises.readdir(path2.join(root, "src", "locales"))) {
1990
2907
  if (!f.endsWith(".json")) continue;
1991
- locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, "src", "locales", f), "utf-8"));
2908
+ locales[f.slice(0, -5)] = JSON.parse(await fs3.promises.readFile(path2.join(root, "src", "locales", f), "utf-8"));
1992
2909
  }
1993
2910
  } catch {
1994
2911
  locales = {};
@@ -2000,21 +2917,24 @@ async function buildProject(root, outDir) {
2000
2917
  for (const l of preload) {
2001
2918
  if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
2002
2919
  }
2003
- await fs.promises.rm(path.join(outDir, "locales"), { recursive: true, force: true });
2920
+ await fs3.promises.rm(path2.join(outDir, "locales"), { recursive: true, force: true });
2004
2921
  if (packed.length > 0) {
2005
- const packDir = path.join(outDir, "locales");
2006
- await fs.promises.mkdir(packDir, { recursive: true });
2007
- for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
2922
+ const packDir = path2.join(outDir, "locales");
2923
+ await fs3.promises.mkdir(packDir, { recursive: true });
2924
+ for (const l of packed) await fs3.promises.writeFile(path2.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
2008
2925
  }
2009
2926
  const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
2010
2927
  const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
2011
- const buildDir = path.join(outDir, ".build");
2012
- await fs.promises.rm(buildDir, { recursive: true, force: true });
2013
- await fs.promises.mkdir(buildDir, { recursive: true });
2928
+ const buildDir = path2.join(outDir, ".build");
2929
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
2930
+ await fs3.promises.mkdir(buildDir, { recursive: true });
2931
+ 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")];
2932
+ const contentSrc = contentSrcCands.find((c) => fs3.existsSync(c)) ?? contentSrcCands[0];
2933
+ fs3.copyFileSync(contentSrc, path2.join(buildDir, "content-md.ts"));
2014
2934
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
2015
2935
  if (runtimePlugins.length > 0) {
2016
- const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
2017
- await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
2936
+ const configRel = path2.relative(buildDir, path2.join(root, "rosetack.config.js")).replace(/\\/g, "/");
2937
+ await fs3.promises.writeFile(path2.join(buildDir, "plugins.js"), `
2018
2938
  import config from ${JSON.stringify(configRel)};
2019
2939
 
2020
2940
  const list = Array.isArray(config) ? config : [];
@@ -2026,21 +2946,21 @@ export const hasRequestHooks = hooks.some((p) => p.onRequest);
2026
2946
  export const hasResponseHooks = hooks.some((p) => p.onResponse);
2027
2947
  `);
2028
2948
  }
2029
- const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
2949
+ const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs3.existsSync(p));
2030
2950
  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" });
2031
2951
  await esbuild.build({
2032
2952
  entryPoints: [runtimeEntry],
2033
2953
  bundle: true,
2034
- outfile: path.join(buildDir, "runtime.js"),
2954
+ outfile: path2.join(buildDir, "runtime.js"),
2035
2955
  format: "esm",
2036
2956
  platform: "browser",
2037
2957
  write: true
2038
2958
  });
2039
2959
  for (let i = 0; i < compiled.length; i++) {
2040
2960
  const src = compiled[i].api ?? compiled[i].ssr;
2041
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
2961
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.ssr.js`), src);
2042
2962
  if (!infos[i].isApi) {
2043
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
2963
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
2044
2964
  }
2045
2965
  }
2046
2966
  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) => {
@@ -2102,17 +3022,17 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2102
3022
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
2103
3023
  }).join("\n");
2104
3024
  const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
2105
- const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
2106
- const dir = path.posix.dirname(rel);
3025
+ const rel = path2.relative(path2.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
3026
+ const dir = path2.posix.dirname(rel);
2107
3027
  const prefix = dir === "." ? "/" : "/" + dir;
2108
3028
  const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
2109
- return { prefix, render: split ? loaderOf(i) : compose(i), flags };
3029
+ return { prefix, render: compose(i), flags };
2110
3030
  }).sort((a, b) => b.prefix.length - a.prefix.length);
2111
3031
  const notFoundTable = `[
2112
3032
  ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
2113
3033
  ]`;
2114
3034
  const errIdx = infos.findIndex((info) => info.isError);
2115
- const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
3035
+ const errorRender = errIdx >= 0 ? compose(errIdx) : "null";
2116
3036
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
2117
3037
  const serverRoutes = pages.map(({ info, i }) => {
2118
3038
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -2142,7 +3062,9 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
2142
3062
  }).join(",\n ");
2143
3063
  const serverEntry = `
2144
3064
  ${serverImports}
2145
- import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
3065
+ import { renderMarkdown } from './content-md.ts';
3066
+ import crypto from 'node:crypto';
3067
+ import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
2146
3068
  ${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
2147
3069
  // module to import - the runners below stay no-ops and the servers call them
2148
3070
  // unconditionally (one code path, no flags to keep in sync).
@@ -2234,6 +3156,235 @@ export const revalidate = [
2234
3156
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
2235
3157
  ];
2236
3158
 
3159
+ // Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
3160
+ export const routeCaches = [
3161
+ ${pages.filter(({ i }) => compiled[i].cache !== void 0).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(",\n ")}
3162
+ ];
3163
+ const __dynCache = new Map();
3164
+ export function invalidateRenderCache(): void {
3165
+ __dynCache.clear();
3166
+ }
3167
+ // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3168
+ const __kvStore = new Map<string, { v: unknown; exp: number }>();
3169
+ // Content collections: src/content/<coll>/*.md scanned once at build time,
3170
+
3171
+ const contentCollections = ${JSON.stringify(scanContentDir(path2.join(root, "src", "content")))};
3172
+ export const kv = {
3173
+ get(key: string): unknown {
3174
+ const e = __kvStore.get(key);
3175
+ if (!e) return undefined;
3176
+ if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
3177
+ return e.v;
3178
+ },
3179
+ set(key: string, value: unknown, ttlSeconds = 300): void {
3180
+ if (__kvStore.size > 1000) {
3181
+ const cutoff = Date.now();
3182
+ for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
3183
+ if (__kvStore.size > 2000) __kvStore.clear();
3184
+ }
3185
+ __kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
3186
+ },
3187
+ del(key: string): void { __kvStore.delete(key); },
3188
+ has(key: string): boolean {
3189
+ const e = __kvStore.get(key);
3190
+ return !!e && e.exp >= Date.now();
3191
+ },
3192
+ };
3193
+ globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
3194
+ globalThis.__rosetackContent = {
3195
+ list: (coll: string, filter?: { tag: string }) => {
3196
+ let items = contentCollections[coll] ?? [];
3197
+ if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
3198
+ return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
3199
+ },
3200
+ rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
3201
+ return buildRss(contentCollections[coll] ?? [], opts);
3202
+ },
3203
+ get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
3204
+ const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
3205
+ if (!e) return null;
3206
+ return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
3207
+ },
3208
+ };
3209
+
3210
+ const v = {
3211
+ validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
3212
+ const errors: Record<string, string> = {};
3213
+ const values: Record<string, unknown> = {};
3214
+ for (const [field, ruleList] of Object.entries(rules)) {
3215
+ let val = body[field];
3216
+ for (const rule of ruleList) {
3217
+ if (val === undefined || val === null || val === "") {
3218
+ if (rule === "required") errors[field] = field + " is required";
3219
+ else if (rule.startsWith("default:")) val = rule.slice(8);
3220
+ continue;
3221
+ }
3222
+ if (rule === "string") val = String(val);
3223
+ else if (rule === "trim") val = String(val).trim();
3224
+ else if (rule === "number") {
3225
+ const num = Number(val);
3226
+ if (Number.isNaN(num)) errors[field] = field + " must be a number";
3227
+ else val = num;
3228
+ } else if (rule === "email") {
3229
+ if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
3230
+ } else if (rule.startsWith("min:")) {
3231
+ const min = Number(rule.slice(4));
3232
+ if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
3233
+ } else if (rule.startsWith("max:")) {
3234
+ const max = Number(rule.slice(4));
3235
+ if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
3236
+ }
3237
+ }
3238
+ values[field] = val;
3239
+ }
3240
+ return { ok: Object.keys(errors).length === 0, errors, values };
3241
+ },
3242
+ };
3243
+
3244
+ const jobs = {
3245
+ _timers: new Map<string, ReturnType<typeof setInterval>>(),
3246
+ every(name: string, seconds: number, fn: () => void | Promise<void>): void {
3247
+ if (this._timers.has(name)) return;
3248
+ const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
3249
+ this._timers.set(name, t as any);
3250
+ },
3251
+ cancel(name: string): void {
3252
+ const t = this._timers.get(name);
3253
+ if (t) { clearInterval(t); this._timers.delete(name); }
3254
+ },
3255
+ cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
3256
+ };
3257
+
3258
+ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
3259
+ const encoder = new TextEncoder();
3260
+ const stream = new ReadableStream({
3261
+ async start(controller) {
3262
+ let closed = false;
3263
+ const send = (event: string, data: unknown) => {
3264
+ if (closed) return;
3265
+ controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
3266
+ };
3267
+ try {
3268
+ await handler(send);
3269
+ } finally {
3270
+ closed = true;
3271
+ try { controller.close(); } catch { }
3272
+ }
3273
+ },
3274
+ });
3275
+ return new Response(stream, {
3276
+ headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
3277
+ });
3278
+ }
3279
+ globalThis.__rosetackExtras = { v, jobs, sse };
3280
+ const auth = {
3281
+ hashPassword(password: string): string {
3282
+ const salt = crypto.randomBytes(16).toString("hex");
3283
+ const hash = crypto.scryptSync(password, salt, 32).toString("hex");
3284
+ return salt + ":" + hash;
3285
+ },
3286
+ verifyPassword(password: string, stored: string): boolean {
3287
+ const [salt, hash] = stored.split(":");
3288
+ if (!salt || !hash) return false;
3289
+ return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
3290
+ },
3291
+ signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
3292
+ const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
3293
+ const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3294
+ return payload + "." + sig;
3295
+ },
3296
+ verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
3297
+ const dot = token.lastIndexOf(".");
3298
+ if (dot < 0) return null;
3299
+ const payload = token.slice(0, dot);
3300
+ const sig = token.slice(dot + 1);
3301
+ const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3302
+ try {
3303
+ if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
3304
+ } catch { return null; }
3305
+ try {
3306
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString());
3307
+ if (data.exp < Date.now()) return null;
3308
+ return data as T;
3309
+ } catch { return null; }
3310
+ },
3311
+ csrfToken(secret: string, sessionId: string): string {
3312
+ return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
3313
+ },
3314
+ verifyCsrf(token: string, secret: string, sessionId: string): boolean {
3315
+ try {
3316
+ return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
3317
+ } catch { return false; }
3318
+ },
3319
+ };
3320
+ globalThis.__rosetackAuth = auth;
3321
+
3322
+ export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3323
+ const hit = kv.get(key);
3324
+ if (hit !== undefined) return hit;
3325
+ const v = await compute();
3326
+ if (v !== undefined) kv.set(key, v, ttlSeconds);
3327
+ return v;
3328
+ }
3329
+ export function isCachedRoute(pathname: string): boolean {
3330
+ return routeCaches.some((r) => matchRoute(r.pattern, pathname));
3331
+ }
3332
+ export function invalidatePath(pathname: string): number {
3333
+ let n = 0;
3334
+ for (const key of [...__dynCache.keys()]) {
3335
+ if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
3336
+ }
3337
+ return n;
3338
+ }
3339
+ export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
3340
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3341
+ if (!cfg) return null;
3342
+ let h = 0x811c9dc5;
3343
+ const c = cookieHeader || '';
3344
+ for (let i = 0; i < c.length; i++) {
3345
+ h ^= c.charCodeAt(i);
3346
+ h = (h * 0x01000193) >>> 0;
3347
+ }
3348
+ const hit = __dynCache.get(pathname + '|' + h.toString(16));
3349
+ return hit && hit.expires > Date.now() ? hit.page : null;
3350
+ }
3351
+ export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
3352
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3353
+ if (!cfg) return renderPage(pathname);
3354
+ let h = 0x811c9dc5;
3355
+ for (let i = 0; i < cookieHeader.length; i++) {
3356
+ h ^= cookieHeader.charCodeAt(i);
3357
+ h = (h * 0x01000193) >>> 0;
3358
+ }
3359
+ const key = pathname + '|' + h.toString(16);
3360
+ const hit = __dynCache.get(key);
3361
+ if (hit && hit.expires > Date.now()) {
3362
+ __dynCache.delete(key);
3363
+ __dynCache.set(key, hit);
3364
+ return hit.page;
3365
+ }
3366
+ // Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
3367
+ if (hit && !hit.refreshing) {
3368
+ hit.refreshing = true;
3369
+ renderPage(pathname).then((fresh: any) => {
3370
+ if (fresh.status === 200 && !fresh.redirect) {
3371
+ __dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
3372
+ } else {
3373
+ __dynCache.delete(key);
3374
+ }
3375
+ }).catch(() => { __dynCache.delete(key); });
3376
+ return hit.page;
3377
+ }
3378
+ const page = await renderPage(pathname);
3379
+ if (page.status === 200 && !page.redirect) {
3380
+ __dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
3381
+ if (__dynCache.size > 300) {
3382
+ __dynCache.delete(__dynCache.keys().next().value as string);
3383
+ }
3384
+ }
3385
+ return page;
3386
+ }
3387
+
2237
3388
  // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
2238
3389
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
2239
3390
 
@@ -2348,7 +3499,14 @@ export function docAttrs(pathname) {
2348
3499
 
2349
3500
  // Paint a fallback page (404/500) and serialize its state.
2350
3501
  async function renderFallback(pathname, render) {
2351
- const { html, head } = extractHead(await render([], ''));
3502
+ // Split mode: the not-found entry's render is a loader object \u2014 resolve it through getRender (which memoizes the composed function) exactly like.
3503
+ let fn = render;
3504
+ if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
3505
+
3506
+ // { render } once the route's chunk graph is loaded
3507
+ fn = (await fn.load()).render;
3508
+ }
3509
+ const { html, head } = extractHead(await fn([], ''));
2352
3510
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2353
3511
  return { html, state, head, ...docAttrs(pathname) };
2354
3512
  }
@@ -2455,8 +3613,27 @@ export async function renderPage(pathname, form) {
2455
3613
  return await notFoundPage(pathname);
2456
3614
  }
2457
3615
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2458
- if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
2459
- return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
3616
+ // F10: in dev the response body carries the real error \u2014 message, file:line and the fix hint.
3617
+ let devDetail = '';
3618
+ if (process.env.rosetack_DEV === '1' && err) {
3619
+ const msg = esc(err instanceof Error ? err.message : String(err));
3620
+ const file = esc(String(err.file || ''));
3621
+ const line = err.line != null ? esc(String(err.line)) : '';
3622
+ const hint = esc(String(err.hint || ''));
3623
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
3624
+ 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">'
3625
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
3626
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
3627
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
3628
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
3629
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
3630
+ + '</div>';
3631
+ }
3632
+ if (errorPage) {
3633
+ const fb = await renderFallback(pathname, errorPage);
3634
+ return { ...fb, html: fb.html + devDetail, status: 500 };
3635
+ }
3636
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2460
3637
  }
2461
3638
  // __route tells the bootstrap which route this document was rendered for.
2462
3639
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
@@ -2563,7 +3740,24 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2563
3740
  } catch (err) {
2564
3741
 
2565
3742
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2566
- html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
3743
+ // F10: dev carries the real error in the body here too \u2014 the shell
3744
+ // is out, so the detail rides after the error page body.
3745
+ let devDetail = '';
3746
+ if (process.env.rosetack_DEV === '1' && err) {
3747
+ const msg = esc(err instanceof Error ? err.message : String(err));
3748
+ const file = esc(String(err.file || ''));
3749
+ const line = err.line != null ? esc(String(err.line)) : '';
3750
+ const hint = esc(String(err.hint || ''));
3751
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
3752
+ 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">'
3753
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
3754
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
3755
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
3756
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
3757
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
3758
+ + '</div>';
3759
+ }
3760
+ html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
2567
3761
  }
2568
3762
  write(html);
2569
3763
  // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
@@ -2581,16 +3775,68 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2581
3775
  return 404;
2582
3776
  }
2583
3777
  `;
2584
- await fs.promises.writeFile(path.join(buildDir, "server-entry.js"), serverEntry);
3778
+ try {
3779
+ const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
3780
+ const uniq = [...new Set(patterns)].sort();
3781
+ const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
3782
+ const paramsOf = (pattern) => (pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
3783
+ const paramSig = uniq.map((p) => {
3784
+ const ps = paramsOf(p);
3785
+ if (!ps.length) return "";
3786
+ return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
3787
+ }).join("");
3788
+ const outDirTs = path2.join(root, "src", ".rosetack");
3789
+ await fs3.promises.mkdir(outDirTs, { recursive: true });
3790
+ const srcLines = [
3791
+ "// GENERATED by rosetack build - do not edit.",
3792
+ "export type RoutePath = " + lit + ";",
3793
+ "export const routePatterns = " + JSON.stringify(uniq) + " as const;",
3794
+ "export type RouteParams = {",
3795
+ paramSig,
3796
+ "};",
3797
+ "/** Build a URL from a route pattern and its params. */",
3798
+ "export function url(",
3799
+ " path: RoutePath,",
3800
+ " params: RouteParams[keyof RouteParams] = {} as never,",
3801
+ "): string {",
3802
+ " let out = path as string;",
3803
+ " for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
3804
+ " out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
3805
+ " }",
3806
+ " return out;",
3807
+ "}"
3808
+ ].join("\n") + "\n";
3809
+ await fs3.promises.writeFile(path2.join(outDirTs, "routes.ts"), srcLines);
3810
+ } catch {
3811
+ }
3812
+ await fs3.promises.writeFile(path2.join(buildDir, "server-entry.js"), serverEntry);
2585
3813
  await esbuild.build({
2586
- entryPoints: [path.join(buildDir, "server-entry.js")],
3814
+ entryPoints: [path2.join(buildDir, "server-entry.js")],
2587
3815
  bundle: true,
2588
- outfile: path.join(outDir, "server.js"),
3816
+ outfile: path2.join(outDir, "server.js"),
2589
3817
  format: "esm",
2590
3818
  platform: "node",
2591
3819
  write: true,
2592
3820
  ...TS_LOADER
2593
3821
  });
3822
+ await esbuild.build({
3823
+ entryPoints: [(() => {
3824
+ const here = path2.dirname(fileURLToPath(import.meta.url));
3825
+ for (const cand of [path2.join(here, "..", "cli", "prod-server.ts"), path2.join(here, "..", "src", "cli", "prod-server.ts")]) {
3826
+ if (fs3.existsSync(cand)) return cand;
3827
+ }
3828
+ return path2.join(here, "..", "cli", "prod-server.ts");
3829
+ })()],
3830
+ bundle: true,
3831
+ outfile: path2.join(outDir, "prod.mjs"),
3832
+ format: "esm",
3833
+ platform: "node",
3834
+ write: true,
3835
+ banner: {
3836
+ 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);"
3837
+ },
3838
+ ...TS_LOADER
3839
+ });
2594
3840
  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");
2595
3841
  const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
2596
3842
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
@@ -2621,7 +3867,7 @@ reportVitals();
2621
3867
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2622
3868
  const clientEntry = `
2623
3869
  ${clientImports}
2624
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
3870
+ import { 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';
2625
3871
 
2626
3872
  // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
2627
3873
  setLocales(${clientLocalesJson}, '${defaultLocale}');
@@ -2845,6 +4091,8 @@ export async function $action(name, e) {
2845
4091
  const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
2846
4092
  return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
2847
4093
  }
4094
+ // 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.
4095
+ setActionDispatcher($action);
2848
4096
 
2849
4097
  export { postForm };
2850
4098
 
@@ -2876,6 +4124,16 @@ async function __withOwner(container, fn) {
2876
4124
  setFxOwner(null);
2877
4125
  }
2878
4126
  }
4127
+ // View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
4128
+ async function __swap(container, html) {
4129
+ const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
4130
+ if (typeof document.startViewTransition === 'function' && !reduce) {
4131
+ const vt = document.startViewTransition(() => { container.innerHTML = html; });
4132
+ await vt.updateCallbackDone.catch(() => {});
4133
+ } else {
4134
+ container.innerHTML = html;
4135
+ }
4136
+ }
2879
4137
 
2880
4138
  export async function start(container, pathname, initial) {
2881
4139
  clearMounts(); // stale mounts from a failed render never fire
@@ -2898,7 +4156,7 @@ ${langDirBlock}
2898
4156
  prefetchCache.delete(pathname);
2899
4157
  __navReset(container);
2900
4158
  restoreState(hit.state);
2901
- container.innerHTML = hit.html;
4159
+ await __swap(container, hit.html);
2902
4160
  await __withOwner(container, () => {
2903
4161
  wire(container, hit.closes);
2904
4162
  bindEvents(container);
@@ -2923,15 +4181,18 @@ ${langDirBlock}
2923
4181
  if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
2924
4182
 
2925
4183
 
4184
+ console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
2926
4185
  broken = true;
2927
4186
  return;
2928
4187
  }
2929
- if (!initial) container.innerHTML = html;
4188
+ if (!initial) await __swap(container, html);
2930
4189
  wire(container, closes);
2931
4190
  bindEvents(container);
2932
4191
  flushMounts();
2933
4192
  });
2934
4193
  if (signal === 'notFound') {
4194
+ // 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.
4195
+ if (!initial) { try { location.assign(pathname); return; } catch { } }
2935
4196
  await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2936
4197
  return;
2937
4198
  }
@@ -2994,11 +4255,11 @@ setRefreshHook(async () => {
2994
4255
  await start(document.getElementById('app'), location.pathname, false);
2995
4256
  });
2996
4257
  `;
2997
- await fs.promises.writeFile(path.join(buildDir, "client-entry.js"), clientEntry);
4258
+ await fs3.promises.writeFile(path2.join(buildDir, "client-entry.js"), clientEntry);
2998
4259
  if (split) {
2999
- await fs.promises.rm(path.join(outDir, "chunks"), { recursive: true, force: true });
4260
+ await fs3.promises.rm(path2.join(outDir, "chunks"), { recursive: true, force: true });
3000
4261
  await esbuild.build({
3001
- entryPoints: [path.join(buildDir, "client-entry.js")],
4262
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
3002
4263
  bundle: true,
3003
4264
  format: "esm",
3004
4265
  platform: "browser",
@@ -3012,9 +4273,9 @@ setRefreshHook(async () => {
3012
4273
  });
3013
4274
  } else {
3014
4275
  await esbuild.build({
3015
- entryPoints: [path.join(buildDir, "client-entry.js")],
4276
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
3016
4277
  bundle: true,
3017
- outfile: path.join(outDir, "client.js"),
4278
+ outfile: path2.join(outDir, "client.js"),
3018
4279
  format: "esm",
3019
4280
  platform: "browser",
3020
4281
  minify: true,
@@ -3022,13 +4283,13 @@ setRefreshHook(async () => {
3022
4283
  ...TS_LOADER
3023
4284
  });
3024
4285
  }
3025
- await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
3026
- await fs.promises.rm(buildDir, { recursive: true, force: true });
3027
- const publicDir = path.join(root, "public");
3028
- if (fs.existsSync(publicDir)) {
3029
- await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
3030
- const favicon = path.join(publicDir, "favicon.ico");
3031
- if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
4286
+ await fs3.promises.writeFile(path2.join(outDir, "mount.js"), MOUNT_ENTRY);
4287
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
4288
+ const publicDir = path2.join(root, "public");
4289
+ if (fs3.existsSync(publicDir)) {
4290
+ await fs3.promises.cp(publicDir, path2.join(outDir, "public"), { recursive: true });
4291
+ const favicon = path2.join(publicDir, "favicon.ico");
4292
+ if (fs3.existsSync(favicon)) await fs3.promises.copyFile(favicon, path2.join(outDir, "favicon.ico"));
3032
4293
  }
3033
4294
  console.log("rosetack zero-JS report:");
3034
4295
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
@@ -3042,7 +4303,7 @@ setRefreshHook(async () => {
3042
4303
  g = { why: w, files: /* @__PURE__ */ new Map() };
3043
4304
  warnGroups.set(w, g);
3044
4305
  }
3045
- const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
4306
+ const file = path2.relative(root, infos[ci].filePath).replace(/\\/g, "/");
3046
4307
  let routes = g.files.get(file);
3047
4308
  if (!routes) {
3048
4309
  routes = /* @__PURE__ */ new Set();
@@ -3063,13 +4324,13 @@ setRefreshHook(async () => {
3063
4324
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
3064
4325
  }
3065
4326
  async function scanRoseFiles(root) {
3066
- const pagesDir = path.join(root, "src", "pages");
3067
- if (!fs.existsSync(pagesDir)) return [];
4327
+ const pagesDir = path2.join(root, "src", "pages");
4328
+ if (!fs3.existsSync(pagesDir)) return [];
3068
4329
  async function scan(dir) {
3069
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4330
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
3070
4331
  const files = [];
3071
4332
  for (const entry of entries) {
3072
- const full = path.join(dir, entry.name);
4333
+ const full = path2.join(dir, entry.name);
3073
4334
  if (entry.isDirectory()) files.push(...await scan(full));
3074
4335
  else if (entry.name.endsWith(".rose")) files.push(full);
3075
4336
  }
@@ -3078,13 +4339,13 @@ async function scanRoseFiles(root) {
3078
4339
  return scan(pagesDir);
3079
4340
  }
3080
4341
  async function scanComponentFiles(root) {
3081
- const compDir = path.join(root, "src", "components");
3082
- if (!fs.existsSync(compDir)) return [];
4342
+ const compDir = path2.join(root, "src", "components");
4343
+ if (!fs3.existsSync(compDir)) return [];
3083
4344
  async function scan(dir) {
3084
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4345
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
3085
4346
  const files = [];
3086
4347
  for (const entry of entries) {
3087
- const full = path.join(dir, entry.name);
4348
+ const full = path2.join(dir, entry.name);
3088
4349
  if (entry.isDirectory()) files.push(...await scan(full));
3089
4350
  else if (entry.name.endsWith(".rose")) files.push(full);
3090
4351
  }
@@ -3093,15 +4354,15 @@ async function scanComponentFiles(root) {
3093
4354
  return scan(compDir);
3094
4355
  }
3095
4356
  function isAncestorDir(layoutPath, pagePath) {
3096
- const layoutDir = path.dirname(layoutPath);
3097
- const pageDir = path.dirname(pagePath);
3098
- return pageDir === layoutDir || pageDir.startsWith(layoutDir + path.sep);
4357
+ const layoutDir = path2.dirname(layoutPath);
4358
+ const pageDir = path2.dirname(pagePath);
4359
+ return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
3099
4360
  }
3100
4361
  function getRouteInfo(filePath, root) {
3101
- const pagesDir = path.join(root, "src", "pages");
3102
- const relative3 = path.relative(pagesDir, filePath).replace(/\\/g, "/");
4362
+ const pagesDir = path2.join(root, "src", "pages");
4363
+ const relative3 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
3103
4364
  const withoutExt = relative3.replace(/\.rose$/, "");
3104
- const base = path.posix.basename(withoutExt);
4365
+ const base = path2.posix.basename(withoutExt);
3105
4366
  const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
3106
4367
  const isLayout = !isComponent && base === "_layout";
3107
4368
  const isNotFound = !isComponent && (base === "404" || base === "_notfound");
@@ -3149,11 +4410,11 @@ function capitalize(s) {
3149
4410
  }
3150
4411
 
3151
4412
  // src/cli/shell.ts
3152
- import * as fs2 from "fs";
3153
- import * as path2 from "path";
4413
+ import * as fs4 from "fs";
4414
+ import * as path3 from "path";
3154
4415
  import * as esbuild2 from "esbuild";
3155
4416
  import { createHash } from "crypto";
3156
- var OUT_DIR = path2.join(process.cwd(), "dist");
4417
+ var OUT_DIR = path3.join(process.cwd(), "dist");
3157
4418
  var clientCache = null;
3158
4419
  var splitMode = false;
3159
4420
  function setBundleMode(mode) {
@@ -3161,11 +4422,11 @@ function setBundleMode(mode) {
3161
4422
  }
3162
4423
  function getClientSource() {
3163
4424
  if (splitMode) return null;
3164
- const file = path2.join(OUT_DIR, "client.js");
4425
+ const file = path3.join(OUT_DIR, "client.js");
3165
4426
  try {
3166
- const st = fs2.statSync(file);
4427
+ const st = fs4.statSync(file);
3167
4428
  if (!clientCache || clientCache.mtimeMs !== st.mtimeMs) {
3168
- clientCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
4429
+ clientCache = { mtimeMs: st.mtimeMs, source: fs4.readFileSync(file, "utf-8") };
3169
4430
  }
3170
4431
  return clientCache.source;
3171
4432
  } catch {
@@ -3174,18 +4435,18 @@ function getClientSource() {
3174
4435
  }
3175
4436
  var styleCache = null;
3176
4437
  function getStyles() {
3177
- const file = path2.join(OUT_DIR, "styles.css");
4438
+ const file = path3.join(OUT_DIR, "styles.css");
3178
4439
  try {
3179
- const st = fs2.statSync(file);
4440
+ const st = fs4.statSync(file);
3180
4441
  if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
3181
- styleCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
4442
+ styleCache = { mtimeMs: st.mtimeMs, source: fs4.readFileSync(file, "utf-8") };
3182
4443
  }
3183
4444
  return styleCache.source;
3184
4445
  } catch {
3185
4446
  return "";
3186
4447
  }
3187
4448
  }
3188
- var BOOTSTRAP = esbuild2.transformSync(`
4449
+ var BOOTSTRAP_SOURCE = `
3189
4450
  // shell = false: the document's SSR content sits directly in <body> - no
3190
4451
  // #app wrapper, no demo styles, so a real theme's CSS owns the document from
3191
4452
  // the first byte (and a JS-less visitor never sees either). The bundle still
@@ -3308,16 +4569,47 @@ if (__state.__notFound) {
3308
4569
  } else {
3309
4570
  start(__app, window.location.pathname);
3310
4571
  }
3311
- `, { minify: true }).code;
4572
+ `;
4573
+ var BOOTSTRAP_CACHE = null;
4574
+ function bootstrap() {
4575
+ if (BOOTSTRAP_CACHE === null) {
4576
+ if (globalThis.__rosetack_SKIP_MINIFY) {
4577
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
4578
+ } else {
4579
+ try {
4580
+ BOOTSTRAP_CACHE = esbuild2.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
4581
+ } catch {
4582
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
4583
+ }
4584
+ }
4585
+ }
4586
+ return BOOTSTRAP_CACHE;
4587
+ }
3312
4588
  var CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
3313
4589
  var cspCache = null;
3314
- var EXTERNAL_BOOTSTRAP = `
3315
- import { start, prefetch, postForm, prefetchStats } from '/client.js';
3316
- ${BOOTSTRAP}`;
4590
+ var EXTERNAL_BOOTSTRAP_CACHE = null;
4591
+ function externalBootstrap() {
4592
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `
4593
+ import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';
4594
+ ${bootstrap()}`;
4595
+ return EXTERNAL_BOOTSTRAP_CACHE;
4596
+ }
3317
4597
  function inlineScript(client) {
4598
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
4599
+ let body = client;
4600
+ let aliases = "";
4601
+ if (m) {
4602
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
4603
+ aliases = m[1].split(",").map((pair) => {
4604
+ const parts = pair.split(" as ").map((x) => x.trim());
4605
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
4606
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
4607
+ }).join("");
4608
+ }
3318
4609
  return `
3319
- ${client}
3320
- ${BOOTSTRAP}`;
4610
+ ${body}
4611
+ ${aliases}
4612
+ ${bootstrap()}`;
3321
4613
  }
3322
4614
  function mintNonce() {
3323
4615
  const bytes = new Uint8Array(16);
@@ -3329,7 +4621,7 @@ function mintNonce() {
3329
4621
  function securityHeaders(client, nonce = "") {
3330
4622
  if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
3331
4623
  if (!cspCache || cspCache.for !== client) {
3332
- const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(EXTERNAL_BOOTSTRAP, "utf-8").digest("base64")}'`;
4624
+ const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(externalBootstrap(), "utf-8").digest("base64")}'`;
3333
4625
  cspCache = {
3334
4626
  for: client,
3335
4627
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`
@@ -3394,7 +4686,7 @@ function mergeHeadBlocks(blocks) {
3394
4686
  function clientScriptTag(client, nonce = "") {
3395
4687
  const n = nonce ? ` nonce="${nonce}"` : "";
3396
4688
  return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
3397
- <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
4689
+ <script type="module"${n}>${externalBootstrap()}</script>`;
3398
4690
  }
3399
4691
  function shellOpen(styles = getStyles(), lang = "en", dir = "", shell = true) {
3400
4692
  const styleTag = styles ? `
@@ -3501,6 +4793,9 @@ Rules the compiler enforces (breaking one fails the build):
3501
4793
  type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
3502
4794
  - $state / $data declarations are top-level statements. The declared name IS the
3503
4795
  getter: write count() in the template and the script, never bare count.
4796
+ $persist is $state backed by localStorage: let theme = $persist('light') \u2014
4797
+ the value survives reloads (SSR renders the initial; the client re-seeds
4798
+ from storage at boot).
3504
4799
  - A route param (pages/blog/[id].rose) is read as state too: declare it
3505
4800
  (\`let id = $state('1')\`) and read id() - the server overwrites the default
3506
4801
  with the URL's value, and export const params = { id: [...] } bakes those
@@ -3509,9 +4804,36 @@ Rules the compiler enforces (breaking one fails the build):
3509
4804
  synchronously inside its parent. Fetch in the page or the middleware and pass
3510
4805
  the value down as a prop.
3511
4806
  - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
3512
- trusted-HTML escape hatch - use it only for content you control.
3513
- - Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
3514
- {#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
4807
+ trusted-HTML escape hatch - use it only for content you control. {@const name
4808
+ = expr} is a template-level binding: it evaluates once and is visible to every
4809
+ expression that follows in the same scope (use it to name a computed value
4810
+ inside {#each} without re-evaluating, or to shorten a long expression).
4811
+ - Blocks: {#if cond}...{:else if cond2}...{:else}...{/if},
4812
+ {#each items as item, i}...{:else}...{/each} (i is the zero-based index, the
4813
+ {:else} renders when the list is empty, and the item may be a DESTRUCTURING
4814
+ pattern - {#each items as {name, price}} or {#each entries as [k, v]} - the
4815
+ body then reads the properties/elements directly),
4816
+ {#key expr}...{/key} (re-creates the
4817
+ body whenever expr changes), {#boundary}...{:fallback}...{/boundary} (the
4818
+ fallback renders on a throw; {$boundaryError()?.message} reads the caught
4819
+ error), {#island name="x"}...{/island} (partial hydration) and
4820
+ {#defer}...{/defer} (progressive render; hold=N keeps the skeleton up at
4821
+ least N ms). {:else} / {:else if} must sit inside an {#if} block.
4822
+ - Two-way binding: <input bind:value={q}> / <input type="checkbox"
4823
+ bind:checked={on}> / <select bind:value={s}>. Numeric inputs coerce through
4824
+ valueAsNumber. Radio groups: <input type="radio" value="free"
4825
+ bind:group={plan}> - the group state holds the selected value and every
4826
+ radio's checked state follows it. bind:this={ref} captures the ELEMENT into
4827
+ a $state slot (declare it: let ref = $state(null)) - call ref().focus() or
4828
+ measure it after mount. A bind:* name must be a $state declaration.
4829
+ - Conditional attributes: class:NAME={expr} and style:PROP={expr} merge with
4830
+ the tag's static class/style into one reactive attribute.
4831
+ - Boolean attributes (checked/disabled/...) are presence-correct: a false
4832
+ expression omits the attribute entirely.
4833
+ - use:NAME attaches a registered element action: directives.NAME = (el, param)
4834
+ => { ...; return { update: (p) => ..., destroy: () => ... } } (or return a
4835
+ cleanup function). A reactive param: use:tooltip={text} - the action's
4836
+ update half re-runs when text changes; the param arrives JSON-parsed.
3515
4837
  - A <slot> with attributes is a named slot and must declare its name:
3516
4838
  <slot name="row" item={post} />. A named slot must be a DIRECT child of the
3517
4839
  component tag - never inside another element or an {#if}/{#each} block.
@@ -3526,8 +4848,19 @@ Rules the compiler enforces (breaking one fails the build):
3526
4848
 
3527
4849
  ## Events and server actions
3528
4850
 
3529
- - on:click={handler} wires a client event. The handler is a named function from
3530
- the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
4851
+ - on:EVENT={handler} wires a client event - ANY event, not just click. The
4852
+ handler is a named function from the script or an inline arrow:
4853
+ on:click={() => $setState('n', n() + 1)}, on:keydown={noteKey}.
4854
+ click/input/change/submit ride one delegated listener per event type; every
4855
+ other event (keydown, focus, scroll, mouseenter, ...) is bound directly on
4856
+ the element by wire(), so no handler is ever silently dead. |window /
4857
+ |document move the binding onto the global instead (Escape closes the modal,
4858
+ scroll, resize) - one target per handler.
4859
+ Modifiers ride the event: on:submit|preventDefault={save} (supported:
4860
+ |preventDefault, |stopPropagation, |self - only when the event target IS the
4861
+ bound element, |once - unbind after the first run). capture/passive are NOT
4862
+ supported: they are listener options and one delegated listener per event
4863
+ type cannot carry per-element options.
3531
4864
  - A server action is an exported async function. Call it from a native form
3532
4865
  (method="POST", no JS needed - progressive enhancement) or from any event
3533
4866
  (on:click={like} - one POST, in-place adopt). Its return value is an
@@ -3574,6 +4907,130 @@ window., timers) belongs in onMount, and anything the predicate cannot see
3574
4907
  (inline on* attributes, javascript: URLs, eval) is reported by the build.
3575
4908
  `;
3576
4909
 
4910
+ // src/cli/index.ts
4911
+ import { Readable } from "stream";
4912
+
4913
+ // src/cli/edge.ts
4914
+ import { pathToFileURL as pathToFileURL2 } from "url";
4915
+ import { join as join3 } from "path";
4916
+ function crossSiteWrite(request) {
4917
+ const m = request.method;
4918
+ if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
4919
+ const origin = request.headers.get("origin");
4920
+ if (origin) {
4921
+ let host;
4922
+ try {
4923
+ host = new URL(origin).host;
4924
+ } catch {
4925
+ return new Response("Cross-site request blocked (unparsable Origin header)", { status: 403 });
4926
+ }
4927
+ return host === new URL(request.url).host ? null : new Response("Cross-site request blocked (Origin does not match Host)", { status: 403 });
4928
+ }
4929
+ const site = request.headers.get("sec-fetch-site");
4930
+ if (site && site !== "same-origin" && site !== "same-site" && site !== "none") {
4931
+ return new Response(`Cross-site request blocked (sec-fetch-site: ${site})`, { status: 403 });
4932
+ }
4933
+ return null;
4934
+ }
4935
+ async function createEdgeHandler(outDir, preloaded) {
4936
+ const mod = preloaded?.server ?? await import(pathToFileURL2(join3(outDir, "server.js")).href);
4937
+ let client = null;
4938
+ let styles = "";
4939
+ if (preloaded && "client" in preloaded) {
4940
+ client = preloaded.client ?? null;
4941
+ } else {
4942
+ try {
4943
+ client = await (await import("fs/promises")).readFile(join3(outDir, "client.js"), "utf-8");
4944
+ } catch {
4945
+ client = null;
4946
+ }
4947
+ }
4948
+ if (client && client.includes("chunks/")) client = null;
4949
+ if (preloaded && "styles" in preloaded) {
4950
+ styles = preloaded.styles ?? "";
4951
+ } else {
4952
+ try {
4953
+ styles = await (await import("fs/promises")).readFile(join3(outDir, "styles.css"), "utf-8");
4954
+ } catch {
4955
+ styles = "";
4956
+ }
4957
+ }
4958
+ let broken = /* @__PURE__ */ new Set();
4959
+ if (preloaded && "broken" in preloaded) {
4960
+ broken = new Set(preloaded.broken);
4961
+ } else {
4962
+ try {
4963
+ broken = new Set(JSON.parse(await (await import("fs/promises")).readFile(join3(outDir, "broken.json"), "utf-8")));
4964
+ } catch {
4965
+ broken = /* @__PURE__ */ new Set();
4966
+ }
4967
+ }
4968
+ const pageHeaders2 = (pathname, nonce = "") => {
4969
+ const headers = {};
4970
+ if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
4971
+ const own = mod.headersFor?.(pathname);
4972
+ if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
4973
+ return headers;
4974
+ };
4975
+ return async function handle(request) {
4976
+ const refused = crossSiteWrite(request);
4977
+ if (refused) return refused;
4978
+ const { pathname, searchParams } = new URL(request.url);
4979
+ const canonical = pathname.replace(/\/+$/, "") || "/";
4980
+ if (canonical !== pathname) {
4981
+ return new Response(null, { status: 308, headers: { location: canonical + new URL(request.url).search } });
4982
+ }
4983
+ mod.setQuery?.(Object.fromEntries(searchParams));
4984
+ const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks ? { request, url: new URL(request.url), method: request.method, pathname, state: {} } : null;
4985
+ if (hookCtx) {
4986
+ const short = await mod.runRequestHooks(hookCtx);
4987
+ if (short) return mod.runResponseHooks(hookCtx, short);
4988
+ }
4989
+ if (mod.middleware) {
4990
+ const mw = await mod.runMiddleware(request);
4991
+ if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
4992
+ }
4993
+ if (mod.isApi(pathname)) {
4994
+ const apiRes = await mod.handleApi(request.method, pathname, request);
4995
+ return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
4996
+ }
4997
+ const form = request.method === "POST" ? await request.formData() : void 0;
4998
+ if (form) mod.invalidateRenderCache?.();
4999
+ if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
5000
+ const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
5001
+ const streamed = new Response(null, {
5002
+ status: 200,
5003
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders2(pathname, nonce2) }
5004
+ });
5005
+ const head = hookCtx ? await mod.runResponseHooks(hookCtx, streamed) : streamed;
5006
+ const encoder = new TextEncoder();
5007
+ const stream = new ReadableStream({
5008
+ async start(controller) {
5009
+ const doc = mod.docAttrs(pathname);
5010
+ await mod.renderPageStream(
5011
+ pathname,
5012
+ (chunk) => controller.enqueue(encoder.encode(chunk)),
5013
+ shellOpen(styles, doc.lang, doc.dir, !mod.shellOff?.(pathname)),
5014
+ clientScriptTag(client, nonce2)
5015
+ );
5016
+ controller.close();
5017
+ }
5018
+ });
5019
+ return new Response(stream, { status: head.status, headers: head.headers });
5020
+ }
5021
+ const cookieHeader = request.headers.get("cookie") || "";
5022
+ const memoHit = !form && mod.isCachedRoute?.(pathname) ? mod.peekRenderCache?.(pathname, cookieHeader) : null;
5023
+ const page = memoHit ?? (mod.renderPageCached && !form ? await mod.renderPageCached(pathname, cookieHeader) : await mod.renderPage(pathname, form));
5024
+ const nonce = mod.cspNonce?.(pathname) ? mintNonce() : "";
5025
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
5026
+ const buffered = new Response(html, {
5027
+ status: page.status ?? 200,
5028
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders2(pathname, nonce) }
5029
+ });
5030
+ return hookCtx ? mod.runResponseHooks(hookCtx, buffered) : buffered;
5031
+ };
5032
+ }
5033
+
3577
5034
  // src/cli/index.ts
3578
5035
  function pickEncoding(req) {
3579
5036
  const ae = req.headers["accept-encoding"] || "";
@@ -3672,25 +5129,42 @@ if (__portArg) {
3672
5129
  const __v = __portArg.includes("=") ? __portArg.slice("--port=".length) : process.argv[process.argv.indexOf(__portArg) + 1];
3673
5130
  if (__v && Number(__v) > 0) process.env.PORT = __v;
3674
5131
  }
3675
- var SRC_DIR = process.argv[3] && !process.argv[3].startsWith("-") ? path3.resolve(process.argv[3]) : process.cwd();
3676
- var OUT_DIR2 = path3.join(process.cwd(), "dist");
5132
+ var SRC_DIR = process.argv[3] && !process.argv[3].startsWith("-") ? path4.resolve(process.argv[3]) : process.cwd();
5133
+ var OUT_DIR2 = path4.join(process.cwd(), "dist");
3677
5134
  var PORT = Number(process.env.PORT) || 3e3;
3678
5135
  var serverModule = null;
3679
5136
  var serverMtime = -1;
3680
5137
  var serverVersion = 0;
5138
+ function loadDotEnv(dir) {
5139
+ try {
5140
+ const raw = fs5.readFileSync(path4.join(dir, ".env"), "utf-8");
5141
+ for (const line of raw.split(/\r?\n/)) {
5142
+ const t = line.trim();
5143
+ if (!t || t.startsWith("#")) continue;
5144
+ const eq = t.indexOf("=");
5145
+ if (eq <= 0) continue;
5146
+ const k = t.slice(0, eq).trim();
5147
+ let v = t.slice(eq + 1).trim();
5148
+ if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) v = v.slice(1, -1);
5149
+ if (!(k in process.env)) process.env[k] = v;
5150
+ }
5151
+ } catch {
5152
+ }
5153
+ }
5154
+ loadDotEnv(process.cwd());
3681
5155
  async function loadServer() {
3682
- const file = path3.join(OUT_DIR2, "server.js");
3683
- const mtimeMs = fs3.statSync(file).mtimeMs;
5156
+ const file = path4.join(OUT_DIR2, "server.js");
5157
+ const mtimeMs = fs5.statSync(file).mtimeMs;
3684
5158
  if (!serverModule || mtimeMs !== serverMtime) {
3685
5159
  serverMtime = mtimeMs;
3686
5160
  serverVersion++;
3687
5161
  let target = file;
3688
5162
  if (devMode) {
3689
- target = path3.join(OUT_DIR2, ".build", `server-${serverVersion}.mjs`);
3690
- await fs3.promises.mkdir(path3.dirname(target), { recursive: true });
3691
- await fs3.promises.copyFile(file, target);
5163
+ target = path4.join(OUT_DIR2, ".build", `server-${serverVersion}.mjs`);
5164
+ await fs5.promises.mkdir(path4.dirname(target), { recursive: true });
5165
+ await fs5.promises.copyFile(file, target);
3692
5166
  }
3693
- serverModule = await import(pathToFileURL2(target).href);
5167
+ serverModule = await import(pathToFileURL3(target).href);
3694
5168
  }
3695
5169
  return serverModule;
3696
5170
  }
@@ -3699,9 +5173,9 @@ async function build2() {
3699
5173
  await clearPrerendered(OUT_DIR2);
3700
5174
  setBundleMode(bundle);
3701
5175
  const skipped = await prerender(routes);
3702
- await fs3.promises.writeFile(path3.join(OUT_DIR2, "broken.json"), JSON.stringify(skipped));
5176
+ await fs5.promises.writeFile(path4.join(OUT_DIR2, "broken.json"), JSON.stringify(skipped));
3703
5177
  const ssrModule = await loadServer();
3704
- await fs3.promises.writeFile(path3.join(OUT_DIR2, "headers.json"), JSON.stringify({
5178
+ await fs5.promises.writeFile(path4.join(OUT_DIR2, "headers.json"), JSON.stringify({
3705
5179
  default: securityHeaders(getClientSource()),
3706
5180
  routes: ssrModule.routeHeaders ?? []
3707
5181
  }));
@@ -3724,33 +5198,33 @@ async function build2() {
3724
5198
  }
3725
5199
  var BROTLI_EXT = /* @__PURE__ */ new Set([".html", ".js", ".css", ".json", ".svg", ".txt"]);
3726
5200
  async function writeBrotli(dir) {
3727
- for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
3728
- const p = path3.join(dir, e.name);
5201
+ for (const e of await fs5.promises.readdir(dir, { withFileTypes: true })) {
5202
+ const p = path4.join(dir, e.name);
3729
5203
  if (e.isDirectory()) {
3730
5204
  await writeBrotli(p);
3731
5205
  continue;
3732
5206
  }
3733
- if (!BROTLI_EXT.has(path3.extname(e.name).toLowerCase())) continue;
3734
- await fs3.promises.writeFile(p + ".br", zlib.brotliCompressSync(await fs3.promises.readFile(p)));
5207
+ if (!BROTLI_EXT.has(path4.extname(e.name).toLowerCase())) continue;
5208
+ await fs5.promises.writeFile(p + ".br", zlib.brotliCompressSync(await fs5.promises.readFile(p)));
3735
5209
  }
3736
5210
  }
3737
5211
  async function analyze(outDir, dynamic) {
3738
5212
  const rows = [];
3739
5213
  const walk = async (dir, prefix) => {
3740
- for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
5214
+ for (const e of await fs5.promises.readdir(dir, { withFileTypes: true })) {
3741
5215
  if (e.isDirectory()) {
3742
- await walk(path3.join(dir, e.name), `${prefix}/${e.name}`);
5216
+ await walk(path4.join(dir, e.name), `${prefix}/${e.name}`);
3743
5217
  continue;
3744
5218
  }
3745
5219
  if (!e.name.endsWith(".html")) continue;
3746
- const file = path3.join(dir, e.name);
3747
- const raw = await fs3.promises.readFile(file);
5220
+ const file = path4.join(dir, e.name);
5221
+ const raw = await fs5.promises.readFile(file);
3748
5222
  const brFile = `${file}.br`;
3749
5223
  rows.push({
3750
5224
  route: prefix || "/",
3751
5225
  raw: raw.length,
3752
5226
  gzip: zlib.gzipSync(raw, { level: 9 }).length,
3753
- br: fs3.existsSync(brFile) ? (await fs3.promises.stat(brFile)).size : 0,
5227
+ br: fs5.existsSync(brFile) ? (await fs5.promises.stat(brFile)).size : 0,
3754
5228
  js: /<script type="module"/.test(raw.toString("utf8"))
3755
5229
  });
3756
5230
  }
@@ -3761,10 +5235,10 @@ async function analyze(outDir, dynamic) {
3761
5235
  for (const r of rows.sort((a, b) => a.route < b.route ? -1 : 1)) {
3762
5236
  lines.push(` ${r.route.padEnd(16)}${kb(r.raw).padStart(9)} raw ${kb(r.gzip).padStart(8)} gzip ${kb(r.br).padStart(8)} br ${r.js ? "bundle inlined" : "zero-JS"}`);
3763
5237
  }
3764
- const client = path3.join(outDir, "client.js");
3765
- if (fs3.existsSync(client)) {
3766
- const raw = await fs3.promises.readFile(client);
3767
- lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs3.existsSync(`${client}.br`) ? (await fs3.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
5238
+ const client = path4.join(outDir, "client.js");
5239
+ if (fs5.existsSync(client)) {
5240
+ const raw = await fs5.promises.readFile(client);
5241
+ lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs5.existsSync(`${client}.br`) ? (await fs5.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
3768
5242
  }
3769
5243
  if (dynamic.length > 0) {
3770
5244
  lines.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${dynamic.join(" ")}`);
@@ -3772,9 +5246,9 @@ async function analyze(outDir, dynamic) {
3772
5246
  for (const l of lines) console.log(l);
3773
5247
  }
3774
5248
  async function clearPrerendered(dir, depth = 0) {
3775
- for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
5249
+ for (const e of await fs5.promises.readdir(dir, { withFileTypes: true })) {
3776
5250
  if (depth === 0 && e.name === "locales" && e.isDirectory()) continue;
3777
- const p = path3.join(dir, e.name);
5251
+ const p = path4.join(dir, e.name);
3778
5252
  if (e.isDirectory()) {
3779
5253
  await clearPrerendered(p, depth + 1);
3780
5254
  continue;
@@ -3782,7 +5256,7 @@ async function clearPrerendered(dir, depth = 0) {
3782
5256
  if (!/\.(?:html|json)(?:\.br)?$/.test(e.name)) continue;
3783
5257
  for (let attempt = 0; ; attempt++) {
3784
5258
  try {
3785
- await fs3.promises.rm(p, { force: true });
5259
+ await fs5.promises.rm(p, { force: true });
3786
5260
  break;
3787
5261
  } catch (err) {
3788
5262
  if (attempt >= 2 || !/EPERM|EBUSY|EACCES/.test(String(err))) throw err;
@@ -3808,10 +5282,10 @@ async function prerender(routes) {
3808
5282
  skipped.push(routePath);
3809
5283
  return;
3810
5284
  }
3811
- const routeDir = routePath === "/" ? OUT_DIR2 : path3.join(OUT_DIR2, routePath.slice(1));
3812
- await fs3.promises.mkdir(routeDir, { recursive: true });
3813
- await fs3.promises.writeFile(path3.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
3814
- console.log(`prerendered ${routePath} -> ${path3.relative(process.cwd(), path3.join(routeDir, "index.html"))}`);
5285
+ const routeDir = routePath === "/" ? OUT_DIR2 : path4.join(OUT_DIR2, routePath.slice(1));
5286
+ await fs5.promises.mkdir(routeDir, { recursive: true });
5287
+ await fs5.promises.writeFile(path4.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
5288
+ console.log(`prerendered ${routePath} -> ${path4.relative(process.cwd(), path4.join(routeDir, "index.html"))}`);
3815
5289
  };
3816
5290
  for (const info of routes) {
3817
5291
  if (ssrModule.dynamicRoutes.includes(info.routePath)) {
@@ -3848,10 +5322,10 @@ async function prerender(routes) {
3848
5322
  continue;
3849
5323
  }
3850
5324
  const body = await res.text();
3851
- const outFile = path3.join(OUT_DIR2, routePath.slice(1) + ".json");
3852
- await fs3.promises.mkdir(path3.dirname(outFile), { recursive: true });
3853
- await fs3.promises.writeFile(outFile, body);
3854
- console.log(`prerendered api ${routePath} -> ${path3.relative(process.cwd(), outFile)}`);
5325
+ const outFile = path4.join(OUT_DIR2, routePath.slice(1) + ".json");
5326
+ await fs5.promises.mkdir(path4.dirname(outFile), { recursive: true });
5327
+ await fs5.promises.writeFile(outFile, body);
5328
+ console.log(`prerendered api ${routePath} -> ${path4.relative(process.cwd(), outFile)}`);
3855
5329
  } catch (err) {
3856
5330
  console.error(`api prerender skipped for ${routePath}: ${err instanceof Error ? err.message : err}`);
3857
5331
  }
@@ -3894,7 +5368,7 @@ function revalidateInBackground(routePath, filePath) {
3894
5368
  ssrModule.setQuery?.({});
3895
5369
  const page = await ssrModule.renderPage(routePath);
3896
5370
  if (page.status === 200) {
3897
- await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
5371
+ await fs5.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
3898
5372
  fileCache.delete(filePath);
3899
5373
  console.log(`rosetack: revalidated ${routePath} in the background`);
3900
5374
  }
@@ -3928,7 +5402,7 @@ function readBody(req, res, onDone) {
3928
5402
  req.on("error", () => {
3929
5403
  });
3930
5404
  }
3931
- function crossSiteWrite(req) {
5405
+ function crossSiteWrite2(req) {
3932
5406
  const m = req.method;
3933
5407
  if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
3934
5408
  const origin = req.headers.origin;
@@ -4052,6 +5526,7 @@ function settleDevBuild() {
4052
5526
  if (!devMode || !devBuild && !devBuildPending) return null;
4053
5527
  return startDevBuild();
4054
5528
  }
5529
+ var invalidateHook = null;
4055
5530
  function devWrap(inner) {
4056
5531
  devMode = true;
4057
5532
  return (req, res) => {
@@ -4084,13 +5559,44 @@ function devWrap(inner) {
4084
5559
  }
4085
5560
  function serveStatic(dir, isr = false, dev2 = false) {
4086
5561
  return (req, res) => {
4087
- const blocked = crossSiteWrite(req);
5562
+ const blocked = crossSiteWrite2(req);
4088
5563
  if (blocked) {
4089
5564
  res.statusCode = blocked.status;
4090
5565
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
4091
5566
  res.end(blocked.body);
4092
5567
  return;
4093
5568
  }
5569
+ if (req.method === "POST" && (req.url || "").startsWith("/__rosetack/revalidate")) {
5570
+ const token = process.env.rosetack_REVALIDATE_TOKEN || "";
5571
+ if (!token) {
5572
+ res.statusCode = 404;
5573
+ res.end();
5574
+ return;
5575
+ }
5576
+ if (req.headers["x-rosetack-token"] !== token) {
5577
+ res.statusCode = 403;
5578
+ res.setHeader("content-type", "application/json");
5579
+ res.end(JSON.stringify({ error: "invalid token" }));
5580
+ return;
5581
+ }
5582
+ let body = "";
5583
+ req.on("data", (c) => {
5584
+ body += c;
5585
+ if (body.length > 1e6) req.destroy();
5586
+ });
5587
+ req.on("end", () => {
5588
+ try {
5589
+ const payload = JSON.parse(body || "{}");
5590
+ if (invalidateHook) invalidateHook();
5591
+ res.setHeader("content-type", "application/json");
5592
+ res.end(JSON.stringify({ revalidated: true, scope: payload.all ? "all" : "paths" }));
5593
+ } catch (e) {
5594
+ res.statusCode = 400;
5595
+ res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
5596
+ }
5597
+ });
5598
+ return;
5599
+ }
4094
5600
  const want = pathnameOf(req.url || "/");
4095
5601
  const canonical = want.replace(/\/+$/, "") || "/";
4096
5602
  if (canonical !== want) {
@@ -4107,8 +5613,8 @@ function serveStatic(dir, isr = false, dev2 = false) {
4107
5613
  return;
4108
5614
  }
4109
5615
  const settled = settleDevBuild();
4110
- const ready = settled ? settled.then(() => loadServer()) : loadServer();
4111
- ready.then(async (ssrModule) => {
5616
+ const ready2 = settled ? settled.then(() => loadServer()) : loadServer();
5617
+ ready2.then(async (ssrModule) => {
4112
5618
  const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true ? await hookContext(req) : null;
4113
5619
  if (hookCtx) {
4114
5620
  const short = await ssrModule.runRequestHooks(hookCtx);
@@ -4140,6 +5646,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4140
5646
  body: body.length > 0 ? body : void 0
4141
5647
  });
4142
5648
  ssrModule.setQuery?.(queryOf(req.url));
5649
+ if ((req.method || "GET") !== "GET") ssrModule.invalidateRenderCache?.();
4143
5650
  let apiRes = await ssrModule.handleApi(req.method || "GET", apiPath, request);
4144
5651
  if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
4145
5652
  writeWebHeaders(apiRes, res);
@@ -4168,6 +5675,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4168
5675
  }
4169
5676
  }
4170
5677
  ssrModule.setQuery?.(queryOf(req.url));
5678
+ ssrModule.invalidateRenderCache?.();
4171
5679
  const page2 = await ssrModule.renderPage(pathnameOf(req.url || "/"), form);
4172
5680
  await sendPage(req, res, ssrModule, hookCtx, page2, pathnameOf(req.url || "/"));
4173
5681
  } catch (err) {
@@ -4180,31 +5688,31 @@ function serveStatic(dir, isr = false, dev2 = false) {
4180
5688
  });
4181
5689
  return;
4182
5690
  }
4183
- let safe = path3.normalize(pathnameOf(req.url || "/")).replace(/^(\.\.(\/)?)+/, "");
5691
+ let safe = path4.normalize(pathnameOf(req.url || "/")).replace(/^(\.\.(\/)?)+/, "");
4184
5692
  if (safe === "\\" || safe === "/") safe = "/";
4185
- let filePath = path3.join(dir, safe);
4186
- if (!fs3.existsSync(filePath) && ASSET_EXT.has(path3.extname(safe).toLowerCase())) {
4187
- const pubFile = path3.join(dir, "public", safe);
4188
- if (fs3.existsSync(pubFile)) filePath = pubFile;
5693
+ let filePath = path4.join(dir, safe);
5694
+ if (!fs5.existsSync(filePath) && ASSET_EXT.has(path4.extname(safe).toLowerCase())) {
5695
+ const pubFile = path4.join(dir, "public", safe);
5696
+ if (fs5.existsSync(pubFile)) filePath = pubFile;
4189
5697
  }
4190
- if (fs3.existsSync(filePath) && fs3.statSync(filePath).isDirectory()) {
4191
- filePath = path3.join(filePath, "index.html");
5698
+ if (fs5.existsSync(filePath) && fs5.statSync(filePath).isDirectory()) {
5699
+ filePath = path4.join(filePath, "index.html");
4192
5700
  }
4193
5701
  if (/\.(?:br|gz)$/i.test(safe)) {
4194
5702
  const base = filePath.replace(/\.(?:br|gz)$/i, "");
4195
- if (fs3.existsSync(base)) filePath = base;
5703
+ if (fs5.existsSync(base)) filePath = base;
4196
5704
  }
4197
- const isAsset = ASSET_EXT.has(path3.extname(safe).toLowerCase());
5705
+ const isAsset = ASSET_EXT.has(path4.extname(safe).toLowerCase());
4198
5706
  const isDynamic = !isAsset && ssrModule.dynamicRoutes?.includes(pathnameOf(req.url));
4199
- if (!isDynamic && fs3.existsSync(filePath) && fs3.statSync(filePath).isFile()) {
4200
- const st = fs3.statSync(filePath);
5707
+ if (!isDynamic && fs5.existsSync(filePath) && fs5.statSync(filePath).isFile()) {
5708
+ const st = fs5.statSync(filePath);
4201
5709
  const rev = isAsset ? void 0 : (ssrModule.revalidate || []).find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
4202
5710
  if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1e3) {
4203
5711
  revalidateInBackground(pathnameOf(req.url), filePath);
4204
5712
  }
4205
5713
  let entry = fileCache.get(filePath);
4206
5714
  if (!entry || entry.mtimeMs !== st.mtimeMs) {
4207
- const raw = fs3.readFileSync(filePath);
5715
+ const raw = fs5.readFileSync(filePath);
4208
5716
  entry = {
4209
5717
  mtimeMs: st.mtimeMs,
4210
5718
  raw,
@@ -4214,7 +5722,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4214
5722
  };
4215
5723
  fileCache.set(filePath, entry);
4216
5724
  }
4217
- const ext = path3.extname(filePath);
5725
+ const ext = path4.extname(filePath);
4218
5726
  const types = {
4219
5727
  ".html": "text/html",
4220
5728
  ".js": "application/javascript",
@@ -4229,7 +5737,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4229
5737
  };
4230
5738
  const fileHeaders = {
4231
5739
  "Content-Type": types[ext] || "application/octet-stream",
4232
- "Cache-Control": rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : "public, max-age=3600",
5740
+ "Cache-Control": devMode ? "no-cache" : rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : "public, max-age=3600",
4233
5741
  "ETag": entry.etag,
4234
5742
  "Vary": "Accept-Encoding"
4235
5743
  };
@@ -4259,7 +5767,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4259
5767
  }
4260
5768
  let broken = /* @__PURE__ */ new Set();
4261
5769
  try {
4262
- broken = new Set(JSON.parse(fs3.readFileSync(path3.join(dir, "broken.json"), "utf-8")));
5770
+ broken = new Set(JSON.parse(fs5.readFileSync(path4.join(dir, "broken.json"), "utf-8")));
4263
5771
  } catch {
4264
5772
  }
4265
5773
  const safe2 = pathnameOf(req.url || "/");
@@ -4303,7 +5811,8 @@ function serveStatic(dir, isr = false, dev2 = false) {
4303
5811
  done();
4304
5812
  return;
4305
5813
  }
4306
- const page = await ssrModule.renderPage(safe2);
5814
+ const hasQuery = (req.url || "").includes("?");
5815
+ const page = req.method === "GET" && !hasQuery && ssrModule.renderPageCached ? await ssrModule.renderPageCached(safe2, String(req.headers.cookie || "")) : await ssrModule.renderPage(safe2);
4307
5816
  await sendPage(req, res, ssrModule, hookCtx, page, safe2);
4308
5817
  }).catch((err) => {
4309
5818
  console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
@@ -4313,10 +5822,19 @@ function serveStatic(dir, isr = false, dev2 = false) {
4313
5822
  }
4314
5823
  res.statusCode = 500;
4315
5824
  res.setHeader("Content-Type", "text/html; charset=utf-8");
4316
- res.end("<h1>500</h1><p>Something went wrong rendering this page.</p>");
5825
+ const devErr = err;
5826
+ let devDetail = "";
5827
+ if (process.env.rosetack_DEV === "1" && err) {
5828
+ const stack = err instanceof Error ? (err.stack || "").split("\n").slice(1, 7).join("\n") : "";
5829
+ 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"><div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + escapeHtml(req.url || "") + '</div><div style="margin:10px 0 0;color:#ffd479">' + escapeHtml(err instanceof Error ? err.message : err) + "</div>" + (devErr.file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + escapeHtml(devErr.file) + (devErr.line != null ? ":" + devErr.line : "") + "</div>" : "") + (devErr.hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + escapeHtml(devErr.hint) + "</div>" : "") + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + escapeHtml(stack) + "</pre>" : "") + "</div>";
5830
+ }
5831
+ res.end("<h1>500</h1><p>Something went wrong rendering this page.</p>" + devDetail);
4317
5832
  });
4318
5833
  };
4319
5834
  }
5835
+ function escapeHtml(v) {
5836
+ return String(v ?? "").replace(/[<>&"]/g, (ch) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;" })[ch]);
5837
+ }
4320
5838
  function pathnameOf(url) {
4321
5839
  try {
4322
5840
  return new URL(url || "/", "http://localhost").pathname;
@@ -4369,7 +5887,7 @@ async function freePort(from) {
4369
5887
  function version() {
4370
5888
  for (const rel of ["../FRAMEWORK_VERSION", "../../FRAMEWORK_VERSION", "../../package.json", "../package.json"]) {
4371
5889
  try {
4372
- const raw = fs3.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8");
5890
+ const raw = fs5.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8");
4373
5891
  const v = rel.endsWith("FRAMEWORK_VERSION") ? raw.trim() : JSON.parse(raw).version;
4374
5892
  if (v) return v;
4375
5893
  } catch {
@@ -4379,7 +5897,7 @@ function version() {
4379
5897
  }
4380
5898
  function projectTag() {
4381
5899
  try {
4382
- const pkg = JSON.parse(fs3.readFileSync(path3.join(process.cwd(), "package.json"), "utf-8"));
5900
+ const pkg = JSON.parse(fs5.readFileSync(path4.join(process.cwd(), "package.json"), "utf-8"));
4383
5901
  if (!pkg.version || pkg.name === "rosetack") return "";
4384
5902
  return ` - project: ${pkg.name} v${pkg.version}`;
4385
5903
  } catch {
@@ -4387,6 +5905,8 @@ function projectTag() {
4387
5905
  }
4388
5906
  }
4389
5907
  async function dev() {
5908
+ devMode = true;
5909
+ process.env.rosetack_DEV = "1";
4390
5910
  console.log(`\u{1F339} RoseTack v${version()}${projectTag()} dev server starting...`);
4391
5911
  try {
4392
5912
  await build2();
@@ -4394,7 +5914,7 @@ async function dev() {
4394
5914
  console.error("Initial build failed (server still running):", err instanceof Error ? err.message : err);
4395
5915
  }
4396
5916
  let timeout;
4397
- fs3.watch(SRC_DIR, { recursive: true }, () => {
5917
+ fs5.watch(SRC_DIR, { recursive: true }, () => {
4398
5918
  devBuildPending = true;
4399
5919
  clearTimeout(timeout);
4400
5920
  timeout = setTimeout(() => {
@@ -4416,7 +5936,7 @@ async function preview() {
4416
5936
  });
4417
5937
  }
4418
5938
  async function serve() {
4419
- if (!fs3.existsSync(path3.join(OUT_DIR2, "server.js"))) {
5939
+ if (!fs5.existsSync(path4.join(OUT_DIR2, "server.js"))) {
4420
5940
  console.error(`rosetack: ${OUT_DIR2} has no server.js - run rosetack build first`);
4421
5941
  process.exit(1);
4422
5942
  }
@@ -4468,12 +5988,103 @@ async function serve() {
4468
5988
  }
4469
5989
  };
4470
5990
  try {
4471
- await loadServer();
5991
+ const hooksMod = await loadServer();
5992
+ invalidateHook = () => {
5993
+ try {
5994
+ hooksMod.invalidateRenderCache();
5995
+ } catch {
5996
+ }
5997
+ };
4472
5998
  } catch (err) {
4473
5999
  console.error("rosetack: dist/server.js failed to load for the serve hooks:", err instanceof Error ? err.message : String(err));
4474
6000
  }
4475
6001
  const http = await import("node:http");
4476
- const server = http.createServer(withAccessLog(serveStatic(OUT_DIR2, true), `w${process.pid}`));
6002
+ const edgeReady = createEdgeHandler(OUT_DIR2);
6003
+ edgeReady.then(async (handle) => {
6004
+ await ready;
6005
+ for (const r of serverModule?.dynamicRoutes || []) {
6006
+ if (r.includes(":")) continue;
6007
+ try {
6008
+ const res = await handle(new Request("http://localhost" + r));
6009
+ await res.arrayBuffer();
6010
+ } catch {
6011
+ }
6012
+ }
6013
+ }).catch(() => {
6014
+ });
6015
+ const baseHandler = withAccessLog(serveStatic(OUT_DIR2, true), `w${process.pid}`);
6016
+ const earlyHintLinks = (() => {
6017
+ try {
6018
+ const html = fs5.readFileSync(path4.join(OUT_DIR2, "index.html"), "utf8");
6019
+ const links = [];
6020
+ for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
6021
+ const v = `<${m[1]}>; rel=preload; as=script`;
6022
+ if (!links.includes(v)) links.push(v);
6023
+ }
6024
+ for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
6025
+ const href = /href="([^"]+)"/.exec(m[0])?.[1];
6026
+ if (href) {
6027
+ const v = `<${href}>; rel=preload; as=style`;
6028
+ if (!links.includes(v)) links.push(v);
6029
+ }
6030
+ }
6031
+ for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
6032
+ const v = `<${m[1]}>; rel=preload; as=style`;
6033
+ if (!links.includes(v)) links.push(v);
6034
+ }
6035
+ return links;
6036
+ } catch {
6037
+ return [];
6038
+ }
6039
+ })();
6040
+ let dynRouteSet = null;
6041
+ const dynRoutesOf = () => {
6042
+ const list = serverModule?.dynamicRoutes || [];
6043
+ if (!dynRouteSet || dynRouteSet.size !== list.length) dynRouteSet = new Set(list);
6044
+ return dynRouteSet;
6045
+ };
6046
+ const server = http.createServer(async (req, res) => {
6047
+ try {
6048
+ if ((req.method === "GET" || req.method === "HEAD") && dynRoutesOf().has(pathnameOf(req.url || "/"))) {
6049
+ const handle = await edgeReady;
6050
+ if (earlyHintLinks.length && req.method === "GET" && String(req.headers.accept ?? "").includes("text/html")) {
6051
+ try {
6052
+ res.writeEarlyHints({ link: earlyHintLinks });
6053
+ } catch {
6054
+ }
6055
+ }
6056
+ const url = "http://" + (req.headers.host || `localhost:${PORT}`) + (req.url || "/");
6057
+ const response = await handle(new Request(url, { method: req.method, headers: req.headers }));
6058
+ res.statusCode = response.status;
6059
+ response.headers.forEach((v, k) => res.setHeader(k, v));
6060
+ const htmlDoc = (response.headers.get("content-type") ?? "").startsWith("text/html");
6061
+ const enc = htmlDoc && req.method === "GET" ? pickEncoding(req) : null;
6062
+ if (response.body && enc) {
6063
+ const raw = Buffer.from(await response.arrayBuffer());
6064
+ const etag = 'W/"' + createHash2("sha1").update(raw).digest("base64url").slice(0, 24) + '"';
6065
+ if (req.headers["if-none-match"] === etag) {
6066
+ res.statusCode = 304;
6067
+ res.end();
6068
+ return;
6069
+ }
6070
+ const body = compress(enc, raw);
6071
+ res.setHeader("ETag", etag);
6072
+ res.setHeader("Content-Encoding", enc);
6073
+ res.setHeader("Content-Length", String(body.length));
6074
+ res.end(body);
6075
+ return;
6076
+ }
6077
+ if (response.body) {
6078
+ Readable.fromWeb(response.body).pipe(res);
6079
+ } else {
6080
+ res.end();
6081
+ }
6082
+ return;
6083
+ }
6084
+ } catch {
6085
+ }
6086
+ baseHandler(req, res);
6087
+ });
4477
6088
  server.requestTimeout = 3e4;
4478
6089
  server.headersTimeout = 65e3;
4479
6090
  server.keepAliveTimeout = 5e3;
@@ -4508,14 +6119,14 @@ async function serve() {
4508
6119
  function templatesDir() {
4509
6120
  for (const rel of ["../../templates", "../templates"]) {
4510
6121
  const p = fileURLToPath2(new URL(rel, import.meta.url));
4511
- if (fs3.existsSync(p)) return p;
6122
+ if (fs5.existsSync(p)) return p;
4512
6123
  }
4513
6124
  return null;
4514
6125
  }
4515
6126
  function writeTypeScriptReady(dir) {
4516
- fs3.writeFileSync(path3.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
6127
+ fs5.writeFileSync(path4.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
4517
6128
  `);
4518
- fs3.writeFileSync(path3.join(dir, "tsconfig.json"), JSON.stringify({
6129
+ fs5.writeFileSync(path4.join(dir, "tsconfig.json"), JSON.stringify({
4519
6130
  compilerOptions: {
4520
6131
  target: "ES2022",
4521
6132
  module: "ESNext",
@@ -4530,27 +6141,27 @@ function writeTypeScriptReady(dir) {
4530
6141
  }
4531
6142
  function copyTemplate(dir, name, display) {
4532
6143
  const base = templatesDir();
4533
- const shipped = base ? path3.resolve(base, name) : "";
4534
- const src = fs3.existsSync(shipped) ? shipped : path3.resolve(name);
4535
- if (!fs3.existsSync(src) || !fs3.statSync(src).isDirectory()) {
4536
- const available = base ? fs3.readdirSync(base).join(", ") : "(none found)";
6144
+ const shipped = base ? path4.resolve(base, name) : "";
6145
+ const src = fs5.existsSync(shipped) ? shipped : path4.resolve(name);
6146
+ if (!fs5.existsSync(src) || !fs5.statSync(src).isDirectory()) {
6147
+ const available = base ? fs5.readdirSync(base).join(", ") : "(none found)";
4537
6148
  console.error(`rosetack: no template '${name}' - available: ${available} (or pass a path to any project directory)`);
4538
6149
  process.exit(1);
4539
6150
  }
4540
- fs3.cpSync(src, dir, {
6151
+ fs5.cpSync(src, dir, {
4541
6152
  recursive: true,
4542
6153
  filter: (s) => !/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(s)
4543
6154
  });
4544
- const pkgFile = path3.join(dir, "package.json");
4545
- if (fs3.existsSync(pkgFile)) {
4546
- const pkg = JSON.parse(fs3.readFileSync(pkgFile, "utf8"));
4547
- pkg.name = path3.basename(dir);
6155
+ const pkgFile = path4.join(dir, "package.json");
6156
+ if (fs5.existsSync(pkgFile)) {
6157
+ const pkg = JSON.parse(fs5.readFileSync(pkgFile, "utf8"));
6158
+ pkg.name = path4.basename(dir);
4548
6159
  if (pkg.dependencies?.rosetack) pkg.dependencies.rosetack = `^${version()}`;
4549
6160
  pkg.devDependencies = { ...pkg.devDependencies, typescript: "^5.6.0" };
4550
- fs3.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
6161
+ fs5.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
4551
6162
  }
4552
6163
  writeTypeScriptReady(dir);
4553
- console.log(`\u{1F339} RoseTack new: ${display}/ from the '${path3.basename(src)}' template`);
6164
+ console.log(`\u{1F339} RoseTack new: ${display}/ from the '${path4.basename(src)}' template`);
4554
6165
  console.log(`
4555
6166
  cd ${display}`);
4556
6167
  console.log(` npm install && npm run dev`);
@@ -4562,12 +6173,12 @@ async function scaffold() {
4562
6173
  const template = tplIdx >= 0 ? args[tplIdx + 1] : null;
4563
6174
  const name = args.find((a, i) => !a.startsWith("-") && i !== (tplIdx >= 0 ? tplIdx + 1 : -1));
4564
6175
  if (!name || tplIdx >= 0 && !template) {
4565
- const available = templatesDir() ? fs3.readdirSync(templatesDir()).join(", ") : "blog, api, admin, site";
6176
+ const available = templatesDir() ? fs5.readdirSync(templatesDir()).join(", ") : "blog, api, admin, site";
4566
6177
  console.log(`Usage: rosetack new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${available} - or any project directory)`);
4567
6178
  return;
4568
6179
  }
4569
- const dir = path3.resolve(name);
4570
- if (fs3.existsSync(dir)) {
6180
+ const dir = path4.resolve(name);
6181
+ if (fs5.existsSync(dir)) {
4571
6182
  console.error(`rosetack: ${dir} already exists - pick another name`);
4572
6183
  process.exit(1);
4573
6184
  }
@@ -4575,10 +6186,10 @@ async function scaffold() {
4575
6186
  copyTemplate(dir, template, name);
4576
6187
  return;
4577
6188
  }
4578
- const pages = path3.join(dir, "src", "pages");
4579
- fs3.mkdirSync(pages, { recursive: true });
4580
- fs3.writeFileSync(path3.join(dir, "package.json"), JSON.stringify({
4581
- name: path3.basename(dir),
6189
+ const pages = path4.join(dir, "src", "pages");
6190
+ fs5.mkdirSync(pages, { recursive: true });
6191
+ fs5.writeFileSync(path4.join(dir, "package.json"), JSON.stringify({
6192
+ name: path4.basename(dir),
4582
6193
  private: true,
4583
6194
  type: "module",
4584
6195
  scripts: {
@@ -4592,7 +6203,7 @@ async function scaffold() {
4592
6203
  devDependencies: { typescript: "^5.6.0" }
4593
6204
  }, null, 2) + "\n");
4594
6205
  writeTypeScriptReady(dir);
4595
- fs3.writeFileSync(path3.join(pages, "index.rose"), `<script>
6206
+ fs5.writeFileSync(path4.join(pages, "index.rose"), `<script>
4596
6207
 
4597
6208
  interface Item { label: string }
4598
6209
 
@@ -4625,7 +6236,7 @@ async function scaffold() {
4625
6236
  button { padding: 0.5rem 1rem; margin-right: 0.5rem; }
4626
6237
  </style>
4627
6238
  `);
4628
- fs3.writeFileSync(path3.join(dir, "README.md"), `# ${path3.basename(dir)}
6239
+ fs5.writeFileSync(path4.join(dir, "README.md"), `# ${path4.basename(dir)}
4629
6240
 
4630
6241
  A rosetack project. One file per route in \`src/pages/\`.
4631
6242
 
@@ -4641,7 +6252,7 @@ Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
4641
6252
  \`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
4642
6253
  runs before every request, \`src/pages/api/*.rose\` answers JSON.
4643
6254
  `);
4644
- fs3.writeFileSync(path3.join(dir, ".gitignore"), "node_modules/\ndist/\n");
6255
+ fs5.writeFileSync(path4.join(dir, ".gitignore"), "node_modules/\ndist/\n");
4645
6256
  console.log(`\u{1F339} Created ${dir}`);
4646
6257
  console.log(` src/pages/index.rose - a typed page that builds and runs`);
4647
6258
  console.log(` rosetack-env.d.ts + tsconfig.json - the script globals, typed`);
@@ -4653,29 +6264,29 @@ runs before every request, \`src/pages/api/*.rose\` answers JSON.
4653
6264
  async function check() {
4654
6265
  const files = [...await scanRoseFiles(SRC_DIR), ...await scanComponentFiles(SRC_DIR)];
4655
6266
  if (files.length === 0) {
4656
- console.error(`rosetack: no .rose pages found under ${path3.join(SRC_DIR, "src", "pages")} - run rosetack check from a project root, or pass one: rosetack check <dir>`);
6267
+ console.error(`rosetack: no .rose pages found under ${path4.join(SRC_DIR, "src", "pages")} - run rosetack check from a project root, or pass one: rosetack check <dir>`);
4657
6268
  process.exit(1);
4658
6269
  }
4659
6270
  let tsMod;
4660
6271
  try {
4661
- const req = createRequire(pathToFileURL2(path3.join(SRC_DIR, "package.json")));
4662
- tsMod = await import(pathToFileURL2(req.resolve("typescript")).href);
6272
+ const req = createRequire(pathToFileURL3(path4.join(SRC_DIR, "package.json")));
6273
+ tsMod = await import(pathToFileURL3(req.resolve("typescript")).href);
4663
6274
  } catch {
4664
6275
  console.error(`rosetack: type checking needs typescript in this project - npm i -D typescript`);
4665
6276
  process.exit(1);
4666
6277
  }
4667
- const nextTo = (rel) => rel.map((r) => fileURLToPath2(new URL(r, import.meta.url))).find((p) => fs3.existsSync(p));
6278
+ const nextTo = (rel) => rel.map((r) => fileURLToPath2(new URL(r, import.meta.url))).find((p) => fs5.existsSync(p));
4668
6279
  const typesFile = nextTo(["../types/rosetack.d.ts", "../src/types/rosetack.d.ts"]);
4669
6280
  if (!typesFile) {
4670
6281
  console.error("rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler");
4671
6282
  process.exit(1);
4672
6283
  }
4673
6284
  const runtimeSource = nextTo(["../runtime/index.ts", "../src/runtime/index.ts"]);
4674
- const norm = (f) => path3.resolve(f).replace(/\\/g, "/");
6285
+ const norm = (f) => path4.resolve(f).replace(/\\/g, "/");
4675
6286
  const virtual = /* @__PURE__ */ new Map();
4676
6287
  let checked = 0;
4677
6288
  for (const file of files) {
4678
- const source = await fs3.promises.readFile(file, "utf-8");
6289
+ const source = await fs5.promises.readFile(file, "utf-8");
4679
6290
  const m = /<script>/.exec(source);
4680
6291
  const script = scriptOf(source);
4681
6292
  if (!script) continue;
@@ -4698,12 +6309,12 @@ async function check() {
4698
6309
  const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
4699
6310
  const declared = /* @__PURE__ */ new Set();
4700
6311
  for (const file of [...virtual.keys()]) {
4701
- const script = scriptOf(await fs3.promises.readFile(file, "utf-8").catch(() => ""));
6312
+ const script = scriptOf(await fs5.promises.readFile(file, "utf-8").catch(() => ""));
4702
6313
  if (!script) continue;
4703
6314
  for (const spec of script.matchAll(ROSE_IMPORT_RE)) {
4704
- const target = norm(path3.resolve(path3.dirname(file), spec[1]));
6315
+ const target = norm(path4.resolve(path4.dirname(file), spec[1]));
4705
6316
  if (target === file || declared.has(target)) continue;
4706
- const targetSource = await fs3.promises.readFile(target, "utf-8").catch(() => null);
6317
+ const targetSource = await fs5.promises.readFile(target, "utf-8").catch(() => null);
4707
6318
  if (targetSource === null) continue;
4708
6319
  const props = extractExports(scriptOf(targetSource) ?? "").props;
4709
6320
  virtual.set(`${target}.d.ts`, [
@@ -4726,7 +6337,7 @@ async function check() {
4726
6337
  skipLibCheck: true
4727
6338
  };
4728
6339
  const host = tsMod.createCompilerHost(options);
4729
- host.getCurrentDirectory = () => path3.resolve(SRC_DIR);
6340
+ host.getCurrentDirectory = () => path4.resolve(SRC_DIR);
4730
6341
  const realRead = host.readFile.bind(host);
4731
6342
  const realGet = host.getSourceFile.bind(host);
4732
6343
  host.readFile = (f) => virtual.get(norm(f)) ?? realRead(f);
@@ -4743,7 +6354,7 @@ async function check() {
4743
6354
  }
4744
6355
  for (const d of diagnostics) {
4745
6356
  const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
4746
- const where = d.file && at ? `${path3.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})` : "rosetack";
6357
+ const where = d.file && at ? `${path4.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})` : "rosetack";
4747
6358
  const text = tsMod.flattenDiagnosticMessageText(d.messageText, "\n");
4748
6359
  const kind = d.category === 1 ? "error" : "warning";
4749
6360
  console.error(`${where}: ${kind} TS${d.code}: ${text}`);