rosetack 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist-cli/test.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  // src/cli/test.ts
2
2
  import * as fs5 from "fs";
3
- import * as os from "os";
3
+ import * as os2 from "os";
4
4
  import * as path4 from "path";
5
5
  import { pathToFileURL as pathToFileURL2 } from "url";
6
6
 
7
7
  // src/compiler/index.ts
8
8
  import * as fs3 from "fs";
9
9
  import * as path2 from "path";
10
+ import * as os from "os";
10
11
  import { pathToFileURL, fileURLToPath } from "url";
11
12
  import * as esbuild from "esbuild";
12
13
 
@@ -47,9 +48,9 @@ function lineAt(src, match) {
47
48
 
48
49
  // src/cli/image-size.ts
49
50
  import fs from "node:fs";
50
- function readImageSize(filePath) {
51
+ function readImageSize(filePath2) {
51
52
  try {
52
- const fd = fs.openSync(filePath, "r");
53
+ const fd = fs.openSync(filePath2, "r");
53
54
  const buf = Buffer.alloc(64);
54
55
  const read = fs.readSync(fd, buf, 0, 64, 0);
55
56
  fs.closeSync(fd);
@@ -64,7 +65,7 @@ function readImageSize(filePath) {
64
65
  return parseWebP(buf);
65
66
  }
66
67
  if (buf[0] === 255 && buf[1] === 216) {
67
- return parseJpeg(filePath);
68
+ return parseJpeg(filePath2);
68
69
  }
69
70
  return null;
70
71
  } catch {
@@ -87,8 +88,8 @@ function parseWebP(buf) {
87
88
  }
88
89
  return null;
89
90
  }
90
- function parseJpeg(filePath) {
91
- const fd = fs.openSync(filePath, "r");
91
+ function parseJpeg(filePath2) {
92
+ const fd = fs.openSync(filePath2, "r");
92
93
  try {
93
94
  const buf = Buffer.alloc(4);
94
95
  let pos = 2;
@@ -243,7 +244,7 @@ var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
243
244
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
244
245
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
245
246
  var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
246
- var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
247
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist|derived)\b/g;
247
248
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
248
249
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
249
250
  var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
@@ -690,7 +691,7 @@ function nodeOnlyImports(importStmts) {
690
691
  }
691
692
  return out;
692
693
  }
693
- function wireEventBindings(template, actionNames, filePath = "<template>") {
694
+ function wireEventBindings(template, actionNames, filePath2 = "<template>") {
694
695
  const bindings = [];
695
696
  let out = "";
696
697
  let rest = template;
@@ -715,7 +716,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
715
716
  if (targets.length > 1) {
716
717
  throw new RoseError(
717
718
  "E-TEMPLATE",
718
- `${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
719
+ `${filePath2}: on:${m[1]} carries both |${targets.join(" and |")}`,
719
720
  { hint: "a handler binds to one target - the element (default), |window or |document" }
720
721
  );
721
722
  }
@@ -724,7 +725,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
724
725
  if (!KNOWN_MODS.includes(mod)) {
725
726
  throw new RoseError(
726
727
  "E-TEMPLATE",
727
- `${filePath}: unknown event modifier |${mod}`,
728
+ `${filePath2}: unknown event modifier |${mod}`,
728
729
  { hint: `the supported modifiers are ${KNOWN_MODS.map((k) => "|" + k).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` }
729
730
  );
730
731
  }
@@ -759,7 +760,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
759
760
  if (mods.length && actionNames.has(expr)) {
760
761
  throw new RoseError(
761
762
  "E-TEMPLATE",
762
- `${filePath}: event modifiers are not supported on the server action ${expr}`,
763
+ `${filePath2}: event modifiers are not supported on the server action ${expr}`,
763
764
  { hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
764
765
  );
765
766
  }
@@ -781,10 +782,10 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
781
782
  }
782
783
  return { template: out, bindings };
783
784
  }
784
- function scanSlotDecls(filePath) {
785
+ function scanSlotDecls(filePath2) {
785
786
  let src;
786
787
  try {
787
- src = fs3.readFileSync(filePath, "utf-8");
788
+ src = fs3.readFileSync(filePath2, "utf-8");
788
789
  } catch {
789
790
  return [];
790
791
  }
@@ -837,17 +838,104 @@ function hoistImports(script) {
837
838
  if (buf) imports.push(buf.join("\n"));
838
839
  return { imports: imports.join("\n"), rest: rest.join("\n") };
839
840
  }
840
- async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
841
- let source = await fs3.promises.readFile(filePath, "utf-8");
841
+ var __compileMemo = /* @__PURE__ */ new Map();
842
+ function compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry) {
843
+ let st;
844
+ try {
845
+ st = fs3.statSync(filePath2);
846
+ } catch {
847
+ return null;
848
+ }
849
+ const reg = [];
850
+ for (const [p, e] of registry) reg.push(`${p}#${e.index}:${e.scopeKey}:${e.slots.join("|")}`);
851
+ return [filePath2, String(st.mtimeMs), String(st.size), scopeKey, isApi ? "1" : "0", reg.join(";")].join("\0");
852
+ }
853
+ var __compilerStamp = (() => {
854
+ try {
855
+ return String(fs3.statSync(fileURLToPath(import.meta.url)).mtimeMs);
856
+ } catch {
857
+ return "noid";
858
+ }
859
+ })();
860
+ var __diskCacheDir = (() => {
861
+ try {
862
+ const dir = path2.join(os.tmpdir(), "rosetack-compile-cache");
863
+ fs3.mkdirSync(dir, { recursive: true });
864
+ return dir;
865
+ } catch {
866
+ return null;
867
+ }
868
+ })();
869
+ var __diskWrites = 0;
870
+ function __fnv1a(str) {
871
+ let h = 2166136261;
872
+ for (let i = 0; i < str.length; i++) {
873
+ h ^= str.charCodeAt(i);
874
+ h = Math.imul(h, 16777619);
875
+ }
876
+ return (h >>> 0).toString(16).padStart(8, "0");
877
+ }
878
+ function __diskFile(key) {
879
+ return path2.join(__diskCacheDir, __fnv1a(key + "|" + __compilerStamp) + ".json");
880
+ }
881
+ function __diskGet(key) {
882
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return null;
883
+ try {
884
+ const obj = JSON.parse(fs3.readFileSync(__diskFile(key), "utf-8"));
885
+ if (obj && typeof obj === "object" && typeof obj.ssr === "string") return obj;
886
+ } catch {
887
+ }
888
+ return null;
889
+ }
890
+ function __diskSet(key, result) {
891
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return;
892
+ try {
893
+ fs3.writeFileSync(__diskFile(key), JSON.stringify(result));
894
+ if ((__diskWrites++ & 511) === 0) {
895
+ try {
896
+ const entries = fs3.readdirSync(__diskCacheDir);
897
+ if (entries.length > 5e3) {
898
+ for (const e of entries) {
899
+ try {
900
+ fs3.unlinkSync(path2.join(__diskCacheDir, e));
901
+ } catch {
902
+ }
903
+ }
904
+ }
905
+ } catch {
906
+ }
907
+ }
908
+ } catch {
909
+ }
910
+ }
911
+ async function compileComponentMemo(filePath2, publicDir, scopeKey, isApi, plugins, registry) {
912
+ if (plugins.length > 0) return compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
913
+ const key = compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry);
914
+ if (key) {
915
+ const hit = __compileMemo.get(key);
916
+ if (hit) return { ...hit };
917
+ const disk = __diskGet(key);
918
+ if (disk) return disk;
919
+ }
920
+ const result = await compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
921
+ if (key) {
922
+ if (__compileMemo.size > 500) __compileMemo.clear();
923
+ __compileMemo.set(key, result);
924
+ __diskSet(key, result);
925
+ }
926
+ return result;
927
+ }
928
+ async function compileComponent(filePath2, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
929
+ let source = await fs3.promises.readFile(filePath2, "utf-8");
842
930
  for (const p of plugins) {
843
931
  if (!p.transform) continue;
844
932
  try {
845
- source = await p.transform(source, filePath);
933
+ source = await p.transform(source, filePath2);
846
934
  } catch (err) {
847
935
  throw new RoseError(
848
936
  "E-PLUGIN",
849
- `plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
850
- { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
937
+ `plugin ${p.name} failed on ${path2.basename(filePath2)}: ${err instanceof Error ? err.message : String(err)}`,
938
+ { file: filePath2, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
851
939
  );
852
940
  }
853
941
  }
@@ -857,7 +945,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
857
945
  const apiMethods = [...rawScript2.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)].map((m) => m[1]).filter((name) => HTTP_METHODS.has(name));
858
946
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
859
947
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
860
- const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
948
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath2, registry).script);
861
949
  const ownRuntimeImports = new Set(
862
950
  [...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
863
951
  );
@@ -885,30 +973,31 @@ ${hoisted.rest}`, "ssr").trim()}`,
885
973
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
886
974
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
887
975
  const scriptMatch = source.match(COMPONENT_RE);
888
- const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
976
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath2, registry);
889
977
  const rawScript = roseResolved.script;
978
+ const usesrosetackAuth = rawScript.includes("__rosetackAuth");
890
979
  const roseImports = roseResolved.imports;
891
980
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
892
- if (path2.basename(filePath) !== "_middleware.rose") {
981
+ if (path2.basename(filePath2) !== "_middleware.rose") {
893
982
  for (const spec of nodeOnlyImports(importStmts)) {
894
983
  const at = importStmts.indexOf(spec);
895
984
  throw new RoseError(
896
985
  "E-NODE-ONLY",
897
- `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
986
+ `${filePath2}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
898
987
  {
899
- file: filePath,
988
+ file: filePath2,
900
989
  line: at >= 0 ? lineOf(importStmts, at) : void 0,
901
990
  hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`
902
991
  }
903
992
  );
904
993
  }
905
994
  }
906
- const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
995
+ const isComponent = registry.get(filePath2)?.scopeKey.startsWith("components/") ?? false;
907
996
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
908
997
  throw new RoseError(
909
998
  "E-EXPORT",
910
- `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
911
- { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
999
+ `${filePath2}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
1000
+ { file: filePath2, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
912
1001
  );
913
1002
  }
914
1003
  const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
@@ -922,8 +1011,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
922
1011
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
923
1012
  throw new RoseError(
924
1013
  "E-EXPORT",
925
- `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
926
- { file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
1014
+ `${filePath2}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
1015
+ { file: filePath2, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
927
1016
  );
928
1017
  }
929
1018
  const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
@@ -931,8 +1020,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
931
1020
  if (vitalsMatch && !vitals) {
932
1021
  throw new RoseError(
933
1022
  "E-EXPORT",
934
- `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
935
- { file: filePath, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
1023
+ `${filePath2}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
1024
+ { file: filePath2, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
936
1025
  );
937
1026
  }
938
1027
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
@@ -940,8 +1029,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
940
1029
  if (bundle && !["inline", "split"].includes(bundle)) {
941
1030
  throw new RoseError(
942
1031
  "E-EXPORT",
943
- `${filePath}: export const bundle must be 'inline' or 'split'`,
944
- { file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
1032
+ `${filePath2}: export const bundle must be 'inline' or 'split'`,
1033
+ { file: filePath2, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
945
1034
  );
946
1035
  }
947
1036
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
@@ -957,9 +1046,9 @@ ${hoisted.rest}`, "ssr").trim()}`,
957
1046
  const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
958
1047
  throw new RoseError(
959
1048
  "E-EXPORT",
960
- `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
1049
+ `${filePath2}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
961
1050
  {
962
- file: filePath,
1051
+ file: filePath2,
963
1052
  line: lineAt(deadSrc, dead),
964
1053
  hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'
965
1054
  }
@@ -975,15 +1064,15 @@ ${hoisted.rest}`, "ssr").trim()}`,
975
1064
  } catch {
976
1065
  throw new RoseError(
977
1066
  "E-EXPORT",
978
- `${filePath}: export const headers must be an object literal`,
979
- { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
1067
+ `${filePath2}: export const headers must be an object literal`,
1068
+ { file: filePath2, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
980
1069
  );
981
1070
  }
982
1071
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
983
1072
  throw new RoseError(
984
1073
  "E-EXPORT",
985
- `${filePath}: export const headers must be a flat map of string -> string`,
986
- { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
1074
+ `${filePath2}: export const headers must be a flat map of string -> string`,
1075
+ { file: filePath2, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
987
1076
  );
988
1077
  }
989
1078
  headers = value;
@@ -997,16 +1086,16 @@ ${hoisted.rest}`, "ssr").trim()}`,
997
1086
  } catch {
998
1087
  throw new RoseError(
999
1088
  "E-EXPORT",
1000
- `${filePath}: export const csp must be an object literal`,
1001
- { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
1089
+ `${filePath2}: export const csp must be an object literal`,
1090
+ { file: filePath2, hint: "write it as one literal: export const csp = { nonce: true }" }
1002
1091
  );
1003
1092
  }
1004
1093
  const nonce = value?.nonce;
1005
1094
  if (nonce !== void 0 && typeof nonce !== "boolean") {
1006
1095
  throw new RoseError(
1007
1096
  "E-EXPORT",
1008
- `${filePath}: csp.nonce must be a boolean`,
1009
- { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1097
+ `${filePath2}: csp.nonce must be a boolean`,
1098
+ { file: filePath2, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1010
1099
  );
1011
1100
  }
1012
1101
  cspNonce = nonce === true;
@@ -1019,9 +1108,10 @@ ${hoisted.rest}`, "ssr").trim()}`,
1019
1108
  if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
1020
1109
  clientReasons.push("a form bound to a client dispatch ($action)");
1021
1110
  }
1022
- const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
1111
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);
1023
1112
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
1024
1113
  if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
1114
+ if (source.includes("{#await")) clientReasons.push("{#await} async block");
1025
1115
  const needsClient = clientReasons.length > 0;
1026
1116
  const jsWarnings = [];
1027
1117
  if (!needsClient) {
@@ -1047,6 +1137,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
1047
1137
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
1048
1138
  const decls = extractDecls(script);
1049
1139
  const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
1140
+ const derivedNames = decls.filter((d) => d.kind === "derived").map((d) => d.name);
1141
+ const callifyNames = [...stateDecls.map((s) => s.name), ...derivedNames];
1050
1142
  const setterNames = /* @__PURE__ */ new Map();
1051
1143
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
1052
1144
  const declCode = (d) => {
@@ -1059,65 +1151,97 @@ ${hoisted.rest}`, "ssr").trim()}`,
1059
1151
  if (d.kind === "persist") {
1060
1152
  return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1061
1153
  }
1154
+ if (d.kind === "derived") {
1155
+ return `const ${d.name} = () => (${callifyStateReads(d.expr, callifyNames)});`;
1156
+ }
1062
1157
  if (d.kind === "kv") {
1063
1158
  const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1064
1159
  const fnExpr = mTtl ? mTtl[1] : d.expr;
1065
1160
  const ttl = mTtl ? mTtl[2] : "300";
1066
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1161
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1067
1162
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1068
- if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}));`;
1163
+ if (!__seeded_${d.name}) { const __v_${d.name} = await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1069
1164
  }
1070
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1165
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1071
1166
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1072
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1167
+ if (!__seeded_${d.name}) { const __v_${d.name} = await $data(${fn}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1073
1168
  };
1074
1169
  const nestedDecls = [];
1075
1170
  let spliced = "";
1076
1171
  let pos = 0;
1077
1172
  decls.forEach((d, i) => {
1078
1173
  const top = braceDepthAt(script, d.start) === 0;
1079
- if (!top) nestedDecls.push(d);
1174
+ if (!top) {
1175
+ if (d.kind === "derived") {
1176
+ throw new Error(
1177
+ `${filePath2}: $derived must be a top-level declaration - inside a function body a plain const arrow already does this natively`
1178
+ );
1179
+ }
1180
+ nestedDecls.push(d);
1181
+ }
1080
1182
  spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
1081
1183
  pos = d.end;
1082
1184
  });
1083
1185
  spliced += script.slice(pos);
1084
1186
  let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
1085
1187
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
1188
+ if (derivedNames.includes(trimmedKey)) {
1189
+ throw new Error(
1190
+ `${filePath2}: $setState('${trimmedKey}', ...) - a $derived value is read-only; make it $state or derive a different expression`
1191
+ );
1192
+ }
1086
1193
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
1087
1194
  return `${setter}(${val})`;
1088
1195
  });
1089
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1196
+ cleanScript = callifyStateReads(cleanScript, callifyNames);
1090
1197
  cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
1091
1198
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
1092
1199
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
1093
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
1200
+ const templateCalled = callifyTemplateExprs(template, callifyNames);
1094
1201
  const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
1095
- const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
1096
- const stateKeys = decls.map((d) => d.name);
1202
+ const wired = wireEventBindings(imgDefaulted, actionNames, filePath2);
1203
+ const stateKeys = decls.filter((d) => d.kind !== "derived").map((d) => d.name);
1097
1204
  const bindBindings = [];
1098
1205
  let bindCounter = 0;
1099
1206
  const bindExpanded = wired.template.replace(
1100
- /\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1101
- (whole, kind, name) => {
1207
+ /\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1208
+ (whole, kind, name, offset, str) => {
1102
1209
  if (!stateKeys.includes(name)) {
1103
1210
  throw new Error(
1104
- `${filePath}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1211
+ `${filePath2}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1105
1212
  );
1106
1213
  }
1107
1214
  if (kind === "this") return ` data-bind-this="${name}"`;
1215
+ const tagStart = str.lastIndexOf("<", offset);
1216
+ const tagText = tagStart >= 0 ? str.slice(tagStart, offset) : "";
1217
+ if (kind === "value" && /^<select[\s>]/i.test(tagText) && /\smultiple\b/i.test(tagText)) {
1218
+ const setterM = setterNames.get(name);
1219
+ const hnameM = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1220
+ bindBindings.push({
1221
+ event: "change",
1222
+ fn: `${hnameM}: (e) => ${setterM}(Array.from(e.target.selectedOptions, (o) => o.value))`
1223
+ });
1224
+ return ` data-selmulti={${name}().join(',')} data-on-change="${hnameM}"`;
1225
+ }
1226
+ if (kind === "open") {
1227
+ const setterO = setterNames.get(name);
1228
+ const hnameO = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1229
+ bindBindings.push({ event: "toggle", fn: `${hnameO}: (e) => ${setterO}(e.target.open)` });
1230
+ return ` open={${name}()} data-on-toggle="${hnameO}"`;
1231
+ }
1108
1232
  const setter = setterNames.get(name);
1109
1233
  const evt = kind === "checked" ? "change" : "input";
1110
1234
  const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1111
1235
  bindBindings.push({
1112
1236
  event: evt,
1113
- 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); }`
1237
+ fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; ${setter}(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`
1114
1238
  });
1115
1239
  const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
1116
1240
  return ` ${kind}={${name}()}${evtAttr}`;
1117
1241
  }
1118
1242
  );
1119
1243
  const comps = new Map(roseImports.map((r) => {
1120
- const abs = path2.resolve(path2.dirname(filePath), r.specifier);
1244
+ const abs = path2.resolve(path2.dirname(filePath2), r.specifier);
1121
1245
  const hit = registry.get(abs);
1122
1246
  return [r.name, { index: hit.index, slots: hit.slots }];
1123
1247
  }));
@@ -1138,14 +1262,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1138
1262
  if (!stateKeys.includes(name)) {
1139
1263
  throw new RoseError(
1140
1264
  "E-TEMPLATE",
1141
- `${filePath}: bind:group={${name}} must name a $state declaration`,
1265
+ `${filePath2}: bind:group={${name}} must name a $state declaration`,
1142
1266
  { hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
1143
1267
  );
1144
1268
  }
1145
1269
  if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
1146
1270
  throw new RoseError(
1147
1271
  "E-TEMPLATE",
1148
- `${filePath}: bind:group is for radio and checkbox inputs`,
1272
+ `${filePath2}: bind:group is for radio and checkbox inputs`,
1149
1273
  { hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' }
1150
1274
  );
1151
1275
  }
@@ -1154,14 +1278,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1154
1278
  if (!vm || /\{/.test(vm[0])) {
1155
1279
  throw new RoseError(
1156
1280
  "E-TEMPLATE",
1157
- `${filePath}: a bind:group input needs a static value attribute`,
1281
+ `${filePath2}: a bind:group input needs a static value attribute`,
1158
1282
  { hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
1159
1283
  );
1160
1284
  }
1161
1285
  if (/\schecked\s*=/.test(attrs)) {
1162
1286
  throw new RoseError(
1163
1287
  "E-TEMPLATE",
1164
- `${filePath}: a bind:group input cannot also carry checked=`,
1288
+ `${filePath2}: a bind:group input cannot also carry checked=`,
1165
1289
  { hint: "the group state alone decides which inputs are checked" }
1166
1290
  );
1167
1291
  }
@@ -1184,19 +1308,23 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1184
1308
  /\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
1185
1309
  (_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
1186
1310
  );
1187
- const classExpanded = expandClassDirectives(useExpanded, filePath);
1188
- const styleExpanded = expandStyleDirectives(classExpanded, filePath);
1189
- const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
1311
+ const classExpanded = expandClassDirectives(useExpanded, filePath2);
1312
+ const classMerged = mergeStaticClass(classExpanded);
1313
+ const styleExpanded = expandStyleDirectives(classMerged, filePath2);
1314
+ const transExpanded = expandTransitionDirectives(styleExpanded, filePath2);
1315
+ const animExpanded = expandAnimateDirectives(transExpanded, filePath2);
1316
+ const keyExpanded = expandKeyBlocks(animExpanded, filePath2);
1190
1317
  const elseExpanded = expandIfElse(keyExpanded);
1191
1318
  const deferExpanded = expandDeferBlocks(elseExpanded);
1192
- const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
1319
+ const awaitExpanded = expandAwaitBlocks(deferExpanded.template, filePath2);
1320
+ const fbExpanded = expandBoundaryFallbacks(awaitExpanded.template, filePath2);
1193
1321
  const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
1194
1322
  const call = `{__slot(${encodeSlotCall(attrs)})}`;
1195
1323
  if (fallback) {
1196
1324
  if (/\{[^{}]*\}/.test(fallback)) {
1197
1325
  throw new RoseError(
1198
1326
  "E-TEMPLATE",
1199
- `${filePath}: slot fallback content must be static markup`,
1327
+ `${filePath2}: slot fallback content must be static markup`,
1200
1328
  { hint: "a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content" }
1201
1329
  );
1202
1330
  }
@@ -1204,7 +1332,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1204
1332
  }
1205
1333
  return call;
1206
1334
  }).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
1207
- assertKnownDirectives(ssrTemplate, filePath);
1335
+ assertKnownDirectives(ssrTemplate, filePath2);
1208
1336
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
1209
1337
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
1210
1338
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -1212,7 +1340,8 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1212
1340
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
1213
1341
  const ssrGuard = guard ? `
1214
1342
  ${guard}` : "";
1215
- const isMiddleware = path2.basename(filePath) === "_middleware.rose";
1343
+ const isMiddleware = path2.basename(filePath2) === "_middleware.rose";
1344
+ const bootCode = deferBootCode(deferExpanded.count, deferExpanded.holds) + (awaitExpanded.blocks.length ? "\n" + awaitBootCode(awaitExpanded.blocks) : "");
1216
1345
  const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
1217
1346
 
1218
1347
  ${importStmts}
@@ -1221,8 +1350,8 @@ ${ssrExports}
1221
1350
  ${ssrGuard}
1222
1351
 
1223
1352
  ${cleanScript}
1224
- ` : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1225
- const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1353
+ ` : generateSSR(cleanScript + bootCode, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1354
+ const client = generateClient(cleanScript + bootCode, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1226
1355
  return {
1227
1356
  ssr: rewriteRoseImports(ssr, "ssr"),
1228
1357
  client: rewriteRoseImports(client, "client"),
@@ -1246,6 +1375,7 @@ ${cleanScript}
1246
1375
  jsWarnings,
1247
1376
  headers,
1248
1377
  cspNonce,
1378
+ usesrosetackAuth,
1249
1379
  props,
1250
1380
  roseImports,
1251
1381
  isComponent
@@ -1259,6 +1389,13 @@ function minifyDecls(block) {
1259
1389
  }
1260
1390
  function scopeCss(css, key) {
1261
1391
  const attr = `[data-rosetack-c="${key}"]`;
1392
+ const scopeOneSelector = (s) => {
1393
+ const t = s.trim();
1394
+ if (!t.includes(":global")) return `${attr} ${t}`;
1395
+ const stripped = t.replace(/:global\([^()]*\)/g, (m) => m.slice(8, -1)).trim();
1396
+ const outside = t.replace(/:global\([^()]*\)/g, "").trim();
1397
+ return outside ? `${attr} ${stripped}` : stripped;
1398
+ };
1262
1399
  const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
1263
1400
  let out = "";
1264
1401
  let prelude = "";
@@ -1278,7 +1415,7 @@ function scopeCss(css, key) {
1278
1415
  if (sel.startsWith("@")) {
1279
1416
  out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
1280
1417
  } else if (sel) {
1281
- const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
1418
+ const scoped = sel.split(",").map((s) => scopeOneSelector(s)).join(",");
1282
1419
  out += `${scoped}{${minifyDecls(block)}}`;
1283
1420
  }
1284
1421
  prelude = "";
@@ -1569,7 +1706,7 @@ function autoCall(expr) {
1569
1706
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1570
1707
  }
1571
1708
  var DEFER_ENABLED = true;
1572
- function expandKeyBlocks(template, filePath) {
1709
+ function expandKeyBlocks(template, filePath2) {
1573
1710
  if (!template.includes("{#key")) return template;
1574
1711
  for (let pass = 0; pass < 10; pass++) {
1575
1712
  const OPEN_RE = /\{#key\s+([^}]+)\}/g;
@@ -1597,7 +1734,7 @@ function expandKeyBlocks(template, filePath) {
1597
1734
  if (closeAt < 0) {
1598
1735
  throw new RoseError(
1599
1736
  "E-TEMPLATE",
1600
- `${filePath}: {#key ${expr}} is never closed`,
1737
+ `${filePath2}: {#key ${expr}} is never closed`,
1601
1738
  { hint: "every {#key} needs its {/key}" }
1602
1739
  );
1603
1740
  }
@@ -1698,7 +1835,46 @@ function expandIfElseOnce(template) {
1698
1835
  }
1699
1836
  return { template: out, changed };
1700
1837
  }
1701
- function expandClassDirectives(template, filePath) {
1838
+ function mergeStaticClass(template) {
1839
+ if (!/\sclass\s*=\s*"/.test(template) || !/\sclass\s*=\s*\{/.test(template)) return template;
1840
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1841
+ let out = "";
1842
+ let pos = 0;
1843
+ let m;
1844
+ TAG_RE.lastIndex = 0;
1845
+ while (m = TAG_RE.exec(template)) {
1846
+ const [whole, tag, attrs, selfClose] = m;
1847
+ const sm = /\sclass\s*=\s*"([^"]*)"/.exec(attrs);
1848
+ if (!sm) continue;
1849
+ const rm = /\sclass\s*=\s*\{/.exec(attrs);
1850
+ if (!rm || rm.index === sm.index) continue;
1851
+ const open = attrs.indexOf("{", rm.index);
1852
+ let depth = 1;
1853
+ let j = open + 1;
1854
+ while (j < attrs.length && depth > 0) {
1855
+ const ch = attrs[j];
1856
+ if (ch === '"' || ch === "'") {
1857
+ j = skipQuoted(attrs, j);
1858
+ continue;
1859
+ }
1860
+ if (ch === "{") depth++;
1861
+ else if (ch === "}") depth--;
1862
+ j++;
1863
+ }
1864
+ if (depth !== 0) continue;
1865
+ const expr = attrs.slice(open + 1, j - 1);
1866
+ const base = JSON.stringify(sm[1]);
1867
+ const merged = ` class={((v) => v == null ? ${base} : typeof v === 'object' ? ({ ${base}: true, ...v }) : (${base} + ' ' + v))(${expr})}`;
1868
+ const lo = Math.min(sm.index, rm.index);
1869
+ const hiEnd = Math.max(sm.index + sm[0].length, j);
1870
+ const newAttrs = attrs.slice(0, lo) + merged + attrs.slice(hiEnd);
1871
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1872
+ pos = m.index + whole.length;
1873
+ }
1874
+ out += template.slice(pos);
1875
+ return out;
1876
+ }
1877
+ function expandClassDirectives(template, filePath2) {
1702
1878
  if (!template.includes("class:")) return template;
1703
1879
  const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1704
1880
  let out = "";
@@ -1725,14 +1901,14 @@ function expandClassDirectives(template, filePath) {
1725
1901
  i++;
1726
1902
  }
1727
1903
  if (depth !== 0) {
1728
- 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" });
1904
+ throw new RoseError("E-TEMPLATE", `${filePath2}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
1729
1905
  }
1730
1906
  pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1731
1907
  }
1732
1908
  const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1733
1909
  const clsM = clsRe.exec(attrs);
1734
1910
  if (clsM && clsM[2].startsWith("{")) {
1735
- 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="..."' });
1911
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both class={...} and class: directives`, { file: filePath2, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
1736
1912
  }
1737
1913
  const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
1738
1914
  let closure = `(${JSON.stringify(staticCls)}`;
@@ -1756,7 +1932,130 @@ function expandClassDirectives(template, filePath) {
1756
1932
  out += template.slice(pos);
1757
1933
  return out;
1758
1934
  }
1759
- function expandStyleDirectives(template, filePath) {
1935
+ function expandTransitionDirectives(template, filePath2) {
1936
+ if (!/\s(?:transition|in|out):/.test(template)) return template;
1937
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1938
+ let out = "";
1939
+ let pos = 0;
1940
+ let m;
1941
+ TAG_RE.lastIndex = 0;
1942
+ while (m = TAG_RE.exec(template)) {
1943
+ const [whole, tag, attrs, selfClose] = m;
1944
+ if (!attrs.includes("transition:") && !/\s(?:in|out):/.test(attrs)) continue;
1945
+ const pairs = [];
1946
+ const NAME_RE = /\s(transition|in|out):([\w-]+)(?:\s*=\s*\{)?/g;
1947
+ let nm;
1948
+ while (nm = NAME_RE.exec(attrs)) {
1949
+ let start = nm.index;
1950
+ let end = nm.index + nm[0].length;
1951
+ let params = "";
1952
+ if (nm[0].endsWith("{")) {
1953
+ let depth = 1;
1954
+ let i = end;
1955
+ while (i < attrs.length && depth > 0) {
1956
+ const ch = attrs[i];
1957
+ if (ch === '"' || ch === "'") {
1958
+ i = skipQuoted(attrs, i);
1959
+ continue;
1960
+ }
1961
+ if (ch === "{") depth++;
1962
+ else if (ch === "}") depth--;
1963
+ i++;
1964
+ }
1965
+ if (depth !== 0) {
1966
+ throw new RoseError("E-TEMPLATE", `${filePath2}: transition:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the transition params expression needs a matching } before the tag ends" });
1967
+ }
1968
+ params = attrs.slice(end, i - 1);
1969
+ end = i;
1970
+ }
1971
+ pairs.push({ dir: nm[1] === "transition" ? "" : nm[1], name: nm[2], params, start, end });
1972
+ }
1973
+ if (pairs.length === 0) continue;
1974
+ let transitionValue = "";
1975
+ for (const p of pairs) {
1976
+ if (transitionValue) transitionValue += "|";
1977
+ transitionValue += (p.dir ? p.dir + ":" : "") + p.name + (p.params ? ":" + p.params : "");
1978
+ }
1979
+ let newAttrs = attrs;
1980
+ for (let k = pairs.length - 1; k >= 0; k--) {
1981
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1982
+ }
1983
+ const transRe = /\sdata-transition\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1984
+ const tm = transRe.exec(newAttrs);
1985
+ if (tm) {
1986
+ const existing = tm[2] ?? tm[3] ?? "";
1987
+ newAttrs = newAttrs.replace(transRe, ` data-transition="${existing}${transitionValue ? (existing ? "|" : "") + transitionValue : ""}"`);
1988
+ } else {
1989
+ newAttrs = ` data-transition="${transitionValue}"` + newAttrs;
1990
+ }
1991
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1992
+ pos = m.index + whole.length;
1993
+ }
1994
+ out += template.slice(pos);
1995
+ return out;
1996
+ }
1997
+ function expandAnimateDirectives(template, filePath2) {
1998
+ if (!template.includes("animate:")) return template;
1999
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2000
+ let out = "";
2001
+ let pos = 0;
2002
+ let m;
2003
+ TAG_RE.lastIndex = 0;
2004
+ while (m = TAG_RE.exec(template)) {
2005
+ const [whole, tag, attrs, selfClose] = m;
2006
+ if (!attrs.includes("animate:")) continue;
2007
+ const pairs = [];
2008
+ const NAME_RE = /\sanimate:([\w-]+)(?:\s*=\s*\{)?/g;
2009
+ let nm;
2010
+ while (nm = NAME_RE.exec(attrs)) {
2011
+ let start = nm.index;
2012
+ let end = nm.index + nm[0].length;
2013
+ let params = "";
2014
+ if (nm[0].endsWith("{")) {
2015
+ let depth = 1;
2016
+ let i = end;
2017
+ while (i < attrs.length && depth > 0) {
2018
+ const ch = attrs[i];
2019
+ if (ch === '"' || ch === "'") {
2020
+ i = skipQuoted(attrs, i);
2021
+ continue;
2022
+ }
2023
+ if (ch === "{") depth++;
2024
+ else if (ch === "}") depth--;
2025
+ i++;
2026
+ }
2027
+ if (depth !== 0) {
2028
+ throw new RoseError("E-TEMPLATE", `${filePath2}: animate:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the animate params expression needs a matching } before the tag ends" });
2029
+ }
2030
+ params = attrs.slice(end, i - 1);
2031
+ end = i;
2032
+ }
2033
+ pairs.push({ name: nm[1], params, start, end });
2034
+ }
2035
+ let animateValue = "";
2036
+ for (const p of pairs) {
2037
+ if (animateValue) animateValue += "|";
2038
+ animateValue += p.name + (p.params ? ":" + p.params : "");
2039
+ }
2040
+ let newAttrs = attrs;
2041
+ for (let k = pairs.length - 1; k >= 0; k--) {
2042
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2043
+ }
2044
+ const animRe = /\sdata-animate\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2045
+ const am = animRe.exec(newAttrs);
2046
+ if (am) {
2047
+ const existing = am[2] ?? am[3] ?? "";
2048
+ newAttrs = newAttrs.replace(animRe, ` data-animate="${existing}${animateValue ? (existing ? "|" : "") + animateValue : ""}"`);
2049
+ } else {
2050
+ newAttrs = ` data-animate="${animateValue}"` + newAttrs;
2051
+ }
2052
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2053
+ pos = m.index + whole.length;
2054
+ }
2055
+ out += template.slice(pos);
2056
+ return out;
2057
+ }
2058
+ function expandStyleDirectives(template, filePath2) {
1760
2059
  if (!template.includes("style:")) return template;
1761
2060
  const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1762
2061
  let out = "";
@@ -1783,14 +2082,14 @@ function expandStyleDirectives(template, filePath) {
1783
2082
  i++;
1784
2083
  }
1785
2084
  if (depth !== 0) {
1786
- 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" });
2085
+ throw new RoseError("E-TEMPLATE", `${filePath2}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
1787
2086
  }
1788
2087
  pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1789
2088
  }
1790
2089
  const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1791
2090
  const stM = styleRe.exec(attrs);
1792
2091
  if (stM && stM[2].startsWith("{")) {
1793
- 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}' });
2092
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both style={...} and style: directives`, { file: filePath2, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
1794
2093
  }
1795
2094
  const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
1796
2095
  let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
@@ -1813,7 +2112,7 @@ function expandStyleDirectives(template, filePath) {
1813
2112
  out += template.slice(pos);
1814
2113
  return out;
1815
2114
  }
1816
- function expandBoundaryFallbacks(template, filePath) {
2115
+ function expandBoundaryFallbacks(template, filePath2) {
1817
2116
  if (!template.includes("{:fallback")) return template;
1818
2117
  for (let pass = 0; pass < 10; pass++) {
1819
2118
  const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
@@ -1857,12 +2156,12 @@ function expandBoundaryFallbacks(template, filePath) {
1857
2156
  if (top !== "boundary") {
1858
2157
  throw new RoseError(
1859
2158
  "E-TEMPLATE",
1860
- `${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
2159
+ `${filePath2}: {:fallback} must sit directly inside a {#boundary} block`,
1861
2160
  { hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
1862
2161
  );
1863
2162
  }
1864
2163
  if (fbAt >= 0) {
1865
- throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
2164
+ throw new RoseError("E-TEMPLATE", `${filePath2}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
1866
2165
  }
1867
2166
  fbAt = tm3.index;
1868
2167
  fbLen = tok.length;
@@ -1970,8 +2269,137 @@ function deferBootCode(count, holds = []) {
1970
2269
  }
1971
2270
  return code;
1972
2271
  }
2272
+ function expandAwaitBlocks(template, filePath2) {
2273
+ let out = "";
2274
+ let pos = 0;
2275
+ let n = 0;
2276
+ const blocks = [];
2277
+ for (; ; ) {
2278
+ const openAt = template.indexOf("{#await", pos);
2279
+ if (openAt < 0) break;
2280
+ let i = openAt + 7;
2281
+ let brace = 1;
2282
+ while (i < template.length && brace > 0) {
2283
+ const c = template[i];
2284
+ if (c === "{") brace++;
2285
+ else if (c === "}") brace--;
2286
+ i++;
2287
+ }
2288
+ if (brace !== 0) break;
2289
+ const openLen = i - openAt;
2290
+ const expr = template.slice(openAt + 7, i - 1).trim();
2291
+ if (!expr) {
2292
+ throw new RoseError("E-TEMPLATE", `${filePath2}: {#await} needs a promise expression`, {
2293
+ file: filePath2,
2294
+ hint: "write {#await fetchUsers()}...{:then users}...{/await}"
2295
+ });
2296
+ }
2297
+ const blockOpenRe = /\{\#(if|each|boundary|island|await)\b/g;
2298
+ const blockCloseRe = /\{\/(if|each|boundary|island|await)\}/g;
2299
+ const thenRe = /\{:then\b([^}]*)\}/g;
2300
+ const catchRe = /\{:catch\b([^}]*)\}/g;
2301
+ let d = 1;
2302
+ let j = i;
2303
+ let thenAt = -1, catchAt = -1, closeAt = -1;
2304
+ let thenRaw = "", catchRaw = "";
2305
+ for (; ; ) {
2306
+ blockOpenRe.lastIndex = j;
2307
+ blockCloseRe.lastIndex = j;
2308
+ thenRe.lastIndex = j;
2309
+ catchRe.lastIndex = j;
2310
+ const nextOpen = blockOpenRe.exec(template);
2311
+ const nextClose = blockCloseRe.exec(template);
2312
+ const nextThen = thenRe.exec(template);
2313
+ const nextCatch = catchRe.exec(template);
2314
+ let nearestPos = Infinity, kind = "", m = null;
2315
+ const consider = (mm, k) => {
2316
+ if (mm && mm.index < nearestPos) {
2317
+ nearestPos = mm.index;
2318
+ kind = k;
2319
+ m = mm;
2320
+ }
2321
+ };
2322
+ consider(nextOpen, "open");
2323
+ consider(nextClose, "close");
2324
+ consider(nextThen, "then");
2325
+ consider(nextCatch, "catch");
2326
+ if (!m) break;
2327
+ if (kind === "open") {
2328
+ d++;
2329
+ j = m.index + m[0].length;
2330
+ continue;
2331
+ }
2332
+ if (kind === "close") {
2333
+ if (d === 1 && m[1] === "await") {
2334
+ closeAt = m.index;
2335
+ break;
2336
+ }
2337
+ d--;
2338
+ j = m.index + m[0].length;
2339
+ continue;
2340
+ }
2341
+ if (d === 1) {
2342
+ if (kind === "then" && thenAt < 0) {
2343
+ thenAt = m.index;
2344
+ thenRaw = m[1];
2345
+ } else if (kind === "catch" && catchAt < 0) {
2346
+ catchAt = m.index;
2347
+ catchRaw = m[1];
2348
+ }
2349
+ }
2350
+ j = m.index + m[0].length;
2351
+ }
2352
+ if (closeAt < 0 || thenAt < 0) break;
2353
+ const thenTokenEnd = thenAt + 7 + thenRaw.length;
2354
+ const catchTokenEnd = catchAt >= 0 ? catchAt + 7 + catchRaw.length : -1;
2355
+ const pending = template.slice(i, thenAt);
2356
+ const thenBody = template.slice(thenTokenEnd, catchAt >= 0 ? catchAt : closeAt);
2357
+ const catchBody = catchAt >= 0 ? template.slice(catchTokenEnd, closeAt) : "";
2358
+ const thenVarRaw = thenRaw.trim();
2359
+ const catchVarRaw = catchRaw.trim();
2360
+ const thenVar = /^\w+$/.test(thenVarRaw) ? thenVarRaw : `__rvAwaitThen${n + 1}`;
2361
+ const catchVar = catchAt >= 0 ? /^\w+$/.test(catchVarRaw) ? catchVarRaw : `__rvAwaitCatch${n + 1}` : "";
2362
+ n++;
2363
+ const nn = n;
2364
+ const stateName = `__rvAwait${nn}`;
2365
+ blocks.push({ n: nn, expr, thenVar, catchVar });
2366
+ out += template.slice(pos, openAt);
2367
+ out += `{#if ${stateName}().status === 'pending'}` + pending + "{/if}\n";
2368
+ out += `{#each (${stateName}().status === 'resolved' ? [${stateName}().value] : []) as ${thenVar}}` + thenBody + "{/each}\n";
2369
+ if (catchAt >= 0) {
2370
+ out += `{#each (${stateName}().status === 'rejected' ? [${stateName}().error] : []) as ${catchVar}}` + catchBody + "{/each}\n";
2371
+ }
2372
+ pos = closeAt + 8;
2373
+ }
2374
+ if (n === 0) return { template, blocks };
2375
+ out += template.slice(pos);
2376
+ return { template: out, blocks };
2377
+ }
2378
+ function awaitBootCode(blocks) {
2379
+ let code = "";
2380
+ for (const b of blocks) {
2381
+ const stateName = `__rvAwait${b.n}`;
2382
+ code += `const [${stateName}, set${stateName}] = state("__rvawait${b.n}", { status: 'pending', value: null, error: null });
2383
+ `;
2384
+ code += `onMount(function () {
2385
+ `;
2386
+ code += ` Promise.resolve(${b.expr}).then(function (__rvAwaitVal) {
2387
+ `;
2388
+ code += ` set${stateName}({ status: 'resolved', value: __rvAwaitVal });
2389
+ `;
2390
+ code += ` }).catch(function (__rvAwaitErr) {
2391
+ `;
2392
+ code += ` set${stateName}({ status: 'rejected', error: __rvAwaitErr });
2393
+ `;
2394
+ code += ` });
2395
+ `;
2396
+ code += `});
2397
+ `;
2398
+ }
2399
+ return code;
2400
+ }
1973
2401
  function findBlock(src, kind) {
1974
- 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;
2402
+ const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : kind === "snippet" ? /\{#snippet\s+(\w+)(?:\s*\(([^)]+)\))?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([^)]+)\))?\}/g;
1975
2403
  const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1976
2404
  let open;
1977
2405
  while (open = head.exec(src)) {
@@ -1993,7 +2421,7 @@ function findBlock(src, kind) {
1993
2421
  i = nextClose.index + nextClose[0].length;
1994
2422
  if (--depth === 0) {
1995
2423
  const content = src.slice(afterOpen, nextClose.index);
1996
- 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];
2424
+ const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "snippet" ? [open[1], open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", open[4] ?? "", content];
1997
2425
  const arr = [src.slice(start, i), ...groups];
1998
2426
  arr.index = start;
1999
2427
  return arr;
@@ -2036,8 +2464,20 @@ function compileHead(head) {
2036
2464
  flush();
2037
2465
  return out;
2038
2466
  }
2039
- var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
2040
- function assertKnownDirectives(template, filePath) {
2467
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island", "await", "snippet"]);
2468
+ var __blockResCache = /* @__PURE__ */ new Map();
2469
+ function blockCloseRes(kind) {
2470
+ let hit = __blockResCache.get(kind);
2471
+ if (!hit) {
2472
+ hit = {
2473
+ open: new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g"),
2474
+ close: new RegExp(`\\{/${kind}\\}`, "g")
2475
+ };
2476
+ __blockResCache.set(kind, hit);
2477
+ }
2478
+ return hit;
2479
+ }
2480
+ function assertKnownDirectives(template, filePath2) {
2041
2481
  const rawRanges = [];
2042
2482
  const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
2043
2483
  let raw;
@@ -2063,43 +2503,83 @@ function assertKnownDirectives(template, filePath) {
2063
2503
  if (sigil === "/") {
2064
2504
  throw new RoseError(
2065
2505
  "E-TEMPLATE",
2066
- `${filePath}: {/${word}} does not close anything`,
2067
- { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2506
+ `${filePath2}: {/${word}} does not close anything`,
2507
+ { file: filePath2, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2068
2508
  );
2069
2509
  }
2070
2510
  if (word === "else") {
2071
- throw new RoseError(
2072
- "E-TEMPLATE",
2073
- `${filePath}: a stray {:else} with no {#if} above it`,
2074
- { file: filePath, line: lineAt(template, m), hint: "{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}" }
2075
- );
2511
+ const netOpens = (re, closer, at) => {
2512
+ let n = 0, mm;
2513
+ re.lastIndex = 0;
2514
+ while (mm = re.exec(template)) {
2515
+ if (mm.index >= at) break;
2516
+ if (!inRaw(mm.index)) n++;
2517
+ }
2518
+ const cr = new RegExp(closer, "g");
2519
+ let c = 0;
2520
+ while (mm = cr.exec(template)) {
2521
+ if (mm.index >= at) break;
2522
+ if (!inRaw(mm.index)) c++;
2523
+ }
2524
+ return n - c;
2525
+ };
2526
+ const ifNet = netOpens(/\{#if\b/g, "\\{/if\\b", m.index);
2527
+ const eachNet = netOpens(/\{#each\b/g, "\\{/each\\b", m.index);
2528
+ if (ifNet <= 0 && eachNet <= 0) {
2529
+ throw new RoseError(
2530
+ "E-TEMPLATE",
2531
+ `${filePath2}: a stray {:else} with no {#if} or {#each} above it`,
2532
+ { file: filePath2, line: lineAt(template, m), hint: "{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block" }
2533
+ );
2534
+ }
2535
+ continue;
2076
2536
  }
2077
2537
  if (word === "fallback") {
2078
2538
  throw new RoseError(
2079
2539
  "E-TEMPLATE",
2080
- `${filePath}: a stray {:fallback} with no {#boundary} above it`,
2081
- { file: filePath, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
2540
+ `${filePath2}: a stray {:fallback} with no {#boundary} above it`,
2541
+ { file: filePath2, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
2082
2542
  );
2083
2543
  }
2544
+ if (word === "then" || word === "catch") {
2545
+ const opensBefore = (re, at) => {
2546
+ re.lastIndex = 0;
2547
+ let n = 0, mm;
2548
+ while (mm = re.exec(template)) {
2549
+ if (mm.index >= at) break;
2550
+ if (!inRaw(mm.index)) n++;
2551
+ }
2552
+ return n;
2553
+ };
2554
+ const open = opensBefore(/\{#await\b/g, m.index);
2555
+ const close = opensBefore(/\{\/await\b/g, m.index);
2556
+ if (open <= close) {
2557
+ throw new RoseError(
2558
+ "E-TEMPLATE",
2559
+ `${filePath2}: a stray {:${word}} with no {#await} above it`,
2560
+ { file: filePath2, line: lineAt(template, m), hint: "{:then} / {:catch} belong inside an {#await} ... {/await} block" }
2561
+ );
2562
+ }
2563
+ continue;
2564
+ }
2084
2565
  throw new RoseError(
2085
2566
  "E-TEMPLATE",
2086
- `${filePath}: {:${word}} is not a rosetack directive`,
2087
- { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
2567
+ `${filePath2}: {:${word}} is not a rosetack directive`,
2568
+ { file: filePath2, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
2088
2569
  );
2089
2570
  }
2090
- const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
2571
+ const OPENER_RE = /\{#(if|each|boundary|island|await)\b([^}]*)\}/g;
2091
2572
  while (m = OPENER_RE.exec(template)) {
2092
2573
  if (inRaw(m.index)) continue;
2093
2574
  const [, kind, head] = m;
2094
- if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
2575
+ if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?(?:\s*\([^)]*\))?\s*$/.test(head)) {
2095
2576
  throw new RoseError(
2096
2577
  "E-TEMPLATE",
2097
- `${filePath}: {#each ${head.trim()}} is missing its item name`,
2098
- { file: filePath, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
2578
+ `${filePath2}: {#each ${head.trim()}} is missing its item name`,
2579
+ { file: filePath2, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
2099
2580
  );
2100
2581
  }
2101
- const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
2102
- const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
2582
+ const { open: OPEN_RE, close: CLOSE_RE } = blockCloseRes(kind);
2103
2583
  let depth = 1;
2104
2584
  let i = m.index + m[0].length;
2105
2585
  for (; ; ) {
@@ -2118,8 +2598,8 @@ function assertKnownDirectives(template, filePath) {
2118
2598
  if (depth !== 0) {
2119
2599
  throw new RoseError(
2120
2600
  "E-TEMPLATE",
2121
- `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2122
- { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2601
+ `${filePath2}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2602
+ { file: filePath2, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2123
2603
  );
2124
2604
  }
2125
2605
  }
@@ -2152,6 +2632,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2152
2632
  const islandsMode = /\{#island\b/.test(template);
2153
2633
  const effMarkers = markers && (!islandsMode || islandDepth > 0);
2154
2634
  const nextId = () => `${depth}_${blockId++}`;
2635
+ if (depth === 0) result += "const __snip = {};\n";
2155
2636
  while (remaining.length > 0) {
2156
2637
  const ifMatch = findBlock(remaining, "if");
2157
2638
  const eachMatch = findBlock(remaining, "each");
@@ -2160,11 +2641,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2160
2641
  const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
2161
2642
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2162
2643
  const islandMatch = findBlock(remaining, "island");
2644
+ const snippetMatch = findBlock(remaining, "snippet");
2163
2645
  const candidates = [];
2164
2646
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
2165
2647
  if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
2166
2648
  if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
2167
2649
  if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
2650
+ if (snippetMatch?.index !== void 0) candidates.push({ type: "snippet", match: snippetMatch, index: snippetMatch.index });
2168
2651
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
2169
2652
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
2170
2653
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
@@ -2210,7 +2693,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2210
2693
  }
2211
2694
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2212
2695
  } else if (earliest.type === "each") {
2213
- const [, items, item, index, content] = earliest.match;
2696
+ const [, items, item, index, key, content] = earliest.match;
2214
2697
  const before = remaining.substring(0, earliest.index);
2215
2698
  if (before) result += emitChunk(before, acc, closes, scope);
2216
2699
  const call = autoCall(items);
@@ -2229,10 +2712,24 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2229
2712
  scoped += content.trim().slice(lastSpan);
2230
2713
  const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2231
2714
  const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2715
+ let keyFn = "";
2716
+ if (key) {
2717
+ if (isDestructure) {
2718
+ throw new RoseError(
2719
+ "E-TEMPLATE",
2720
+ `${filePath}: a keyed {#each} keys on a named item's property - write {#each xs as x (x.id)}, not a destructuring pattern`,
2721
+ { file: filePath, hint: "name the item first, then key on one of its properties" }
2722
+ );
2723
+ }
2724
+ let k = key.trim();
2725
+ if (itemRe) k = k.replace(itemRe, "__s");
2726
+ if (indexRe) k = k.replace(indexRe, "__i");
2727
+ keyFn = `, (__s, __i) => (${k})`;
2728
+ }
2232
2729
  result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
2233
2730
  `;
2234
2731
  if (effMarkers) {
2235
- result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
2732
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id}${keyFn});
2236
2733
  `;
2237
2734
  } else {
2238
2735
  const param = isDestructure ? "__s" : item;
@@ -2268,6 +2765,16 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2268
2765
  ` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
2269
2766
  `;
2270
2767
  result += `${acc} += __bd${id};
2768
+ `;
2769
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2770
+ } else if (earliest.type === "snippet") {
2771
+ const [, name, params, content] = earliest.match;
2772
+ const before = remaining.substring(0, earliest.index);
2773
+ if (before) result += emitChunk(before, acc, closes, scope);
2774
+ const id = nextId();
2775
+ const paramList = params ? params.split(",").map((p) => p.trim()).filter(Boolean).join(",") : "";
2776
+ const inner = compileTemplate(content.trim(), "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2777
+ result += `__snip.${name} = (__s, __c${paramList ? "," + paramList : ""}) => { let h = ''; ${inner} return h; };
2271
2778
  `;
2272
2779
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2273
2780
  } else if (earliest.type === "comp") {
@@ -2304,7 +2811,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2304
2811
  }
2305
2812
  content = out + content.slice(lastSpan);
2306
2813
  }
2307
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
2814
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; }`;
2308
2815
  });
2309
2816
  const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
2310
2817
  if (a.kind === "spread") return `...(${a.value})`;
@@ -2378,6 +2885,33 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2378
2885
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2379
2886
  continue;
2380
2887
  }
2888
+ const dbgMatch = /^@debug\b([\s\S]*)$/.exec(trimmed);
2889
+ if (dbgMatch) {
2890
+ if (before) result += emitChunk(before, acc, closes, scope);
2891
+ const names = dbgMatch[1].trim().replace(/,$/, "");
2892
+ result += names ? `console.log('[rosetack:debug]', { ${names} });
2893
+ ` : `console.log('[rosetack:debug]'); debugger;
2894
+ `;
2895
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2896
+ continue;
2897
+ }
2898
+ const renderMatch = /^@render\s+([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(trimmed);
2899
+ if (renderMatch) {
2900
+ const ahead = new RegExp(`\\{#snippet\\s+${renderMatch[1]}\\b`).test(remaining.substring(earliest.index + earliest.match[0].length));
2901
+ if (ahead) {
2902
+ throw new RoseError(
2903
+ "E-TEMPLATE",
2904
+ `${filePath}: {@render ${renderMatch[1]}} runs before its {#snippet ${renderMatch[1]}} is defined`,
2905
+ { file: filePath, hint: "move the {#snippet} definition above the {@render} call - definitions register as the statement stream reaches them" }
2906
+ );
2907
+ }
2908
+ if (before) result += emitChunk(before, acc, closes, scope);
2909
+ const renderArgs = renderMatch[2].trim();
2910
+ result += `${acc} += ((__snip && __snip.${renderMatch[1]}) ? __snip.${renderMatch[1]}(${scope ?? "null"}, ${closes}${renderArgs ? ", " + renderArgs : ""}) : '');
2911
+ `;
2912
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2913
+ continue;
2914
+ }
2381
2915
  const attrMatch = before.match(/([\w-]+)=\s*$/);
2382
2916
  if (attrMatch) {
2383
2917
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -2506,6 +3040,7 @@ function splitSlots(src) {
2506
3040
  let i = 0;
2507
3041
  let elemDepth = 0;
2508
3042
  let blockDepth = 0;
3043
+ const blockStack = [];
2509
3044
  while (i < src.length) {
2510
3045
  const lt = src.indexOf("<", i);
2511
3046
  const ob = src.indexOf("{#", i);
@@ -2520,8 +3055,14 @@ function splitSlots(src) {
2520
3055
  if (next === ob || next === cb) {
2521
3056
  const close = src.indexOf("}", next);
2522
3057
  const token = src.slice(next, close < 0 ? src.length : close + 1);
2523
- if (next === ob) blockDepth++;
2524
- else blockDepth = Math.max(0, blockDepth - 1);
3058
+ if (next === ob) {
3059
+ const m = /^\{#(\w+)/.exec(token);
3060
+ blockStack.push({ header: token, type: m ? m[1] : "" });
3061
+ blockDepth++;
3062
+ } else {
3063
+ blockDepth = Math.max(0, blockDepth - 1);
3064
+ if (blockStack.length) blockStack.pop();
3065
+ }
2525
3066
  def += token;
2526
3067
  i = next + token.length;
2527
3068
  continue;
@@ -2548,20 +3089,16 @@ function splitSlots(src) {
2548
3089
  }
2549
3090
  if (!selfClosing && !isVoid) elemDepth++;
2550
3091
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
2551
- if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
2552
- throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
2553
- }
2554
- if (slotName) {
2555
- const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3092
+ if (slotName && elemDepth === 1 && blockDepth === 0) {
2556
3093
  if (selfClosing || isVoid) {
2557
- named.set(slotName, (named.get(slotName) ?? "") + stripped);
3094
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, ""));
2558
3095
  } else {
2559
3096
  const closeIdx = findClose(src, end, nm[2]);
2560
- if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
3097
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
2561
3098
  const tail = `</${nm[2]}>`;
2562
3099
  const inner = src.slice(end, closeIdx);
2563
3100
  rejectNestedSlot(inner, slotName);
2564
- named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
3101
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "") + inner + tail);
2565
3102
  elemDepth = Math.max(0, elemDepth - 1);
2566
3103
  i = closeIdx + tail.length;
2567
3104
  continue;
@@ -2569,6 +3106,32 @@ function splitSlots(src) {
2569
3106
  i = end;
2570
3107
  continue;
2571
3108
  }
3109
+ if (slotName && blockDepth > 0) {
3110
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3111
+ let lifted = "";
3112
+ for (const b of blockStack) lifted += b.header;
3113
+ lifted += stripped;
3114
+ if (selfClosing || isVoid) {
3115
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3116
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3117
+ i = end;
3118
+ continue;
3119
+ }
3120
+ const closeIdx = findClose(src, end, nm[2]);
3121
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
3122
+ const tail = `</${nm[2]}>`;
3123
+ lifted += src.slice(end, closeIdx) + tail;
3124
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3125
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3126
+ elemDepth = Math.max(0, elemDepth - 1);
3127
+ i = closeIdx + tail.length;
3128
+ continue;
3129
+ }
3130
+ if (slotName) {
3131
+ throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component, or wrapped only by an {#if}/{#each}/{#boundary} block - it is nested inside another element`, {
3132
+ hint: 'place the element with slot="..." directly inside the component tag, or inside a single {#if}/{#each} block - wrapping it in another element is not yet supported'
3133
+ });
3134
+ }
2572
3135
  def += tagText;
2573
3136
  i = end;
2574
3137
  }
@@ -2589,7 +3152,8 @@ var IMG_MIME = {
2589
3152
  ".svg": "image/svg+xml",
2590
3153
  ".ico": "image/x-icon"
2591
3154
  };
2592
- var INLINE_IMG_MAX = 4096;
3155
+ var INLINE_IMG_MAX = 8192;
3156
+ var INLINE_SVG_MAX = 16384;
2593
3157
  function listImageVariants(publicDir, url) {
2594
3158
  const ext = path2.extname(url);
2595
3159
  const base = path2.basename(url, ext);
@@ -2612,6 +3176,27 @@ function listImageVariants(publicDir, url) {
2612
3176
  }
2613
3177
  return out.sort((a, b) => a.width - b.width);
2614
3178
  }
3179
+ var __imgReadCache = /* @__PURE__ */ new Map();
3180
+ function cachedImageRead(filePath2) {
3181
+ let st;
3182
+ try {
3183
+ st = fs3.statSync(filePath2);
3184
+ } catch {
3185
+ return null;
3186
+ }
3187
+ const hit = __imgReadCache.get(filePath2);
3188
+ if (hit && hit.mtime === st.mtimeMs) return { buffer: hit.buffer, dims: hit.dims };
3189
+ let buffer;
3190
+ try {
3191
+ buffer = fs3.readFileSync(filePath2);
3192
+ } catch {
3193
+ return null;
3194
+ }
3195
+ const dims = readImageSize(filePath2);
3196
+ const entry = { mtime: st.mtimeMs, buffer, dims };
3197
+ __imgReadCache.set(filePath2, entry);
3198
+ return { buffer, dims: entry.dims };
3199
+ }
2615
3200
  function inlineImages(template, publicDir) {
2616
3201
  return template.replace(IMG_RE, (tag) => {
2617
3202
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
@@ -2620,17 +3205,15 @@ function inlineImages(template, publicDir) {
2620
3205
  const mime = IMG_MIME[ext];
2621
3206
  if (!mime) return tag;
2622
3207
  const rel = src[1].replace(/^\/public(?=\/)/, "");
2623
- const filePath = path2.join(publicDir, rel);
2624
- let file;
2625
- try {
2626
- file = fs3.readFileSync(filePath);
2627
- } catch {
2628
- return tag;
2629
- }
3208
+ const filePath2 = path2.join(publicDir, rel);
3209
+ const read = cachedImageRead(filePath2);
3210
+ if (!read) return tag;
3211
+ const file = read.buffer;
2630
3212
  const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
2631
- const dims = authorDims ? null : readImageSize(filePath);
3213
+ const dims = authorDims ? null : read.dims;
2632
3214
  const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
2633
- if (file.length > INLINE_IMG_MAX) {
3215
+ const inlineMax = ext === ".svg" ? INLINE_SVG_MAX : INLINE_IMG_MAX;
3216
+ if (file.length > inlineMax) {
2634
3217
  const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
2635
3218
  const variants = hasSS ? [] : listImageVariants(publicDir, rel);
2636
3219
  if (!variants.length) return withDims(tag);
@@ -2671,7 +3254,7 @@ function compileSlot(acc) {
2671
3254
  return `${acc} += String(children);
2672
3255
  `;
2673
3256
  }
2674
- 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';`;
3257
+ var RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, isSeeded, markSeeded, esc, refresh, onMount, onCleanup, $effect, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $actionPending, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
2675
3258
  var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
2676
3259
  function propsCode(props) {
2677
3260
  if (props.length === 0) return "";
@@ -2841,7 +3424,7 @@ async function buildProject(root, outDir) {
2841
3424
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
2842
3425
  );
2843
3426
  const compiled = await Promise.all(
2844
- files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
3427
+ files.map((f, i) => compileComponentMemo(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
2845
3428
  );
2846
3429
  const importsOf = /* @__PURE__ */ new Map();
2847
3430
  files.forEach((_, i) => {
@@ -3046,11 +3629,12 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
3046
3629
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
3047
3630
  return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
3048
3631
  }).join(",\n ");
3632
+ const appUsesAuth = compiled.some((c) => c.usesrosetackAuth);
3049
3633
  const serverEntry = `
3050
3634
  ${serverImports}
3051
3635
  import { renderMarkdown } from './content-md.ts';
3052
- import crypto from 'node:crypto';
3053
- import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
3636
+ ${appUsesAuth ? "import crypto from 'node:crypto';" : "// no route references __rosetackAuth: the node:crypto auth helpers are omitted, keeping the bundle edge-loadable"}
3637
+ import { setState, persistState, clearRequestState, isolateRender, serializeState, resetRequestContext, installContextStore, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
3054
3638
  ${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
3055
3639
  // module to import - the runners below stay no-ops and the servers call them
3056
3640
  // unconditionally (one code path, no flags to keep in sync).
@@ -3107,6 +3691,7 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
3107
3691
  });
3108
3692
  }
3109
3693
 
3694
+
3110
3695
  // (the cross-machine seam): the cluster relay above covers ONE machine.
3111
3696
  export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
3112
3697
  setStoreTransport(send);
@@ -3127,6 +3712,11 @@ export const routeParams = {
3127
3712
 
3128
3713
  // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
3129
3714
  export const dynamicRoutes = [
3715
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal || compiled[i].needsClient).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3716
+ ];
3717
+
3718
+ // Routes that the prerender function should skip (not bake into static files).
3719
+ export const prerenderSkipRoutes = [
3130
3720
  ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3131
3721
  ];
3132
3722
 
@@ -3150,6 +3740,8 @@ const __dynCache = new Map();
3150
3740
  export function invalidateRenderCache(): void {
3151
3741
  __dynCache.clear();
3152
3742
  }
3743
+
3744
+
3153
3745
  // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3154
3746
  const __kvStore = new Map<string, { v: unknown; exp: number }>();
3155
3747
  // Content collections: src/content/<coll>/*.md scanned once at build time,
@@ -3263,6 +3855,7 @@ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<
3263
3855
  });
3264
3856
  }
3265
3857
  globalThis.__rosetackExtras = { v, jobs, sse };
3858
+ ${appUsesAuth ? `
3266
3859
  const auth = {
3267
3860
  hashPassword(password: string): string {
3268
3861
  const salt = crypto.randomBytes(16).toString("hex");
@@ -3304,6 +3897,7 @@ const auth = {
3304
3897
  },
3305
3898
  };
3306
3899
  globalThis.__rosetackAuth = auth;
3900
+ ` : "// __rosetackAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
3307
3901
 
3308
3902
  export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3309
3903
  const hit = kv.get(key);
@@ -3534,7 +4128,15 @@ function extractHead(rendered) {
3534
4128
 
3535
4129
  // Form: the submitted FormData of a progressive-enhancement POST.
3536
4130
  export async function renderPage(pathname, form) {
4131
+ // Renders DO overlap in one process: prod-server warms every route in the background at startup.
4132
+ return isolateRender(() => renderPageIsolated(pathname, form));
4133
+ }
4134
+
4135
+ async function renderPageIsolated(pathname, form) {
3537
4136
  clearRequestState();
4137
+ // Cold-start readiness gate (oboext #8): await the app's published DB-ready promise before any $data() read.
4138
+ const appReady = globalThis.__rosetackAppReady;
4139
+ if (appReady) await appReady;
3538
4140
  for (const route of routes) {
3539
4141
  if (matchRoute(route.pattern, pathname)) {
3540
4142
  const patternParts = route.pattern.split('/');
@@ -3703,7 +4305,15 @@ export async function handleApi(method, pathname, request) {
3703
4305
 
3704
4306
  // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
3705
4307
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4308
+ // Isolated for the same reason as renderPage: a streaming render awaits inside route.render()
4309
+ return isolateRender(() => renderPageStreamIsolated(pathname, write, shellOpen, clientTag));
4310
+ }
4311
+
4312
+ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
3706
4313
  clearRequestState();
4314
+ // Cold-start readiness gate (oboext #8): same contract as renderPage \u2014 await the app's published DB-ready promise before streaming the shell.
4315
+ const appReady = globalThis.__rosetackAppReady;
4316
+ if (appReady) await appReady;
3707
4317
  for (const route of routes) {
3708
4318
  if (matchRoute(route.pattern, pathname)) {
3709
4319
  const patternParts = route.pattern.split('/');
@@ -3760,6 +4370,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3760
4370
  }
3761
4371
  return 404;
3762
4372
  }
4373
+ // Prevent tree-shaking of invalidateRenderCache (called from prod-server.ts / edge.ts on non-GET writes).
4374
+ void invalidateRenderCache;
4375
+
4376
+ // Same reason, for the per-request context store: prod-server.ts installs an AsyncLocalStorage adapter.
4377
+ export { installContextStore };
3763
4378
  `;
3764
4379
  try {
3765
4380
  const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
@@ -3853,7 +4468,7 @@ reportVitals();
3853
4468
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
3854
4469
  const clientEntry = `
3855
4470
  ${clientImports}
3856
- 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';
4471
+ import { state, setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
3857
4472
 
3858
4473
  // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
3859
4474
  setLocales(${clientLocalesJson}, '${defaultLocale}');
@@ -4071,11 +4686,19 @@ async function postForm(body, container, pathname) {
4071
4686
  // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
4072
4687
  export async function $action(name, e) {
4073
4688
  if (e && e.preventDefault) e.preventDefault();
4689
+ // F34: the pending flag is ordinary signal state - {#if $actionPending()}
4690
+ // disables a submit button while the action is in flight, reactively.
4691
+ const [__rvPending, __rvSetPending] = state('actionPending', false);
4692
+ __rvSetPending(true);
4074
4693
  const body = new FormData();
4075
4694
  body.append('__action', name);
4076
4695
  // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
4077
4696
  const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
4078
- return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4697
+ try {
4698
+ return await postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4699
+ } finally {
4700
+ __rvSetPending(false);
4701
+ }
4079
4702
  }
4080
4703
  // F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
4081
4704
  setActionDispatcher($action);
@@ -4344,12 +4967,12 @@ function isAncestorDir(layoutPath, pagePath) {
4344
4967
  const pageDir = path2.dirname(pagePath);
4345
4968
  return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
4346
4969
  }
4347
- function getRouteInfo(filePath, root) {
4970
+ function getRouteInfo(filePath2, root) {
4348
4971
  const pagesDir = path2.join(root, "src", "pages");
4349
- const relative3 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
4972
+ const relative3 = path2.relative(pagesDir, filePath2).replace(/\\/g, "/");
4350
4973
  const withoutExt = relative3.replace(/\.rose$/, "");
4351
4974
  const base = path2.posix.basename(withoutExt);
4352
- const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
4975
+ const isComponent = filePath2.replace(/\\/g, "/").includes("/src/components/");
4353
4976
  const isLayout = !isComponent && base === "_layout";
4354
4977
  const isNotFound = !isComponent && (base === "404" || base === "_notfound");
4355
4978
  const isError = !isComponent && base === "500";
@@ -4373,7 +4996,7 @@ function getRouteInfo(filePath, root) {
4373
4996
  routePath = "/" + routeParts.join("/");
4374
4997
  }
4375
4998
  return {
4376
- filePath,
4999
+ filePath: filePath2,
4377
5000
  routePath,
4378
5001
  pattern: routePath,
4379
5002
  paramNames: parts.flatMap((p) => {
@@ -4435,18 +5058,39 @@ if (!__app) {
4435
5058
  }
4436
5059
  // Native View Transitions around client-side navigation (progressive:
4437
5060
  // browsers without the API navigate normally, no polyfill, no CSS required).
4438
- function __navigate(pathname) {
4439
- const paint = () => start(__app, pathname);
5061
+ // F35: stash the CURRENT entry's scroll position into its history state
5062
+ // before a new push - the browser only restores scroll on full page loads; a
5063
+ // pjax swap would land wherever the swap left it.
5064
+ function __saveScroll() {
5065
+ try {
5066
+ const s = history.state || {};
5067
+ history.replaceState(Object.assign({}, s, { __rosetackScroll: window.scrollY }), '');
5068
+ } catch (e) { /* history state unavailable (file:// edge): best effort */ }
5069
+ }
5070
+ function __navigate(pathname, restore) {
5071
+ const paint = () => {
5072
+ const p = start(__app, pathname);
5073
+ if (restore) {
5074
+ // back/forward: restore the entry's scroll (top when it has none)
5075
+ const s = history.state || {};
5076
+ const y = typeof s.__rosetackScroll === 'number' ? s.__rosetackScroll : 0;
5077
+ return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
5078
+ }
5079
+ // a fresh navigation starts at the top, like a full page load
5080
+ window.scrollTo(0, 0);
5081
+ return p;
5082
+ };
4440
5083
  if (document.startViewTransition) {
4441
5084
  return document.startViewTransition(paint).updateCallbackDone;
4442
5085
  }
4443
5086
  return paint();
4444
5087
  }
4445
- window.addEventListener('popstate', () => __navigate(window.location.pathname));
5088
+ window.addEventListener('popstate', () => __navigate(window.location.pathname, true));
4446
5089
  document.addEventListener('click', (e) => {
4447
5090
  const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
4448
5091
  if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
4449
5092
  e.preventDefault();
5093
+ __saveScroll();
4450
5094
  history.pushState(null, '', a.getAttribute('href'));
4451
5095
  __navigate(window.location.pathname);
4452
5096
  }
@@ -4710,7 +5354,7 @@ async function test(file, opts = {}) {
4710
5354
  const root = projectRootOf(target);
4711
5355
  const rel = path4.relative(root, target).replace(/\\/g, "/");
4712
5356
  const isComponent = rel.startsWith("src/components/");
4713
- const dir = opts.dir ?? fs5.mkdtempSync(path4.join(os.tmpdir(), "rosetack-test-"));
5357
+ const dir = opts.dir ?? fs5.mkdtempSync(path4.join(os2.tmpdir(), "rosetack-test-"));
4714
5358
  for (const item of ["src", "public"]) {
4715
5359
  const from = path4.join(root, item);
4716
5360
  if (fs5.existsSync(from)) copyTree(from, path4.join(dir, item));