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.
@@ -11,6 +11,7 @@ import { pathToFileURL as pathToFileURL3, fileURLToPath as fileURLToPath2 } from
11
11
  // src/compiler/index.ts
12
12
  import * as fs3 from "fs";
13
13
  import * as path2 from "path";
14
+ import * as os from "os";
14
15
  import { pathToFileURL, fileURLToPath } from "url";
15
16
  import * as esbuild from "esbuild";
16
17
 
@@ -55,9 +56,9 @@ function errorInfo(err) {
55
56
 
56
57
  // src/cli/image-size.ts
57
58
  import fs from "node:fs";
58
- function readImageSize(filePath) {
59
+ function readImageSize(filePath2) {
59
60
  try {
60
- const fd = fs.openSync(filePath, "r");
61
+ const fd = fs.openSync(filePath2, "r");
61
62
  const buf = Buffer.alloc(64);
62
63
  const read = fs.readSync(fd, buf, 0, 64, 0);
63
64
  fs.closeSync(fd);
@@ -72,7 +73,7 @@ function readImageSize(filePath) {
72
73
  return parseWebP(buf);
73
74
  }
74
75
  if (buf[0] === 255 && buf[1] === 216) {
75
- return parseJpeg(filePath);
76
+ return parseJpeg(filePath2);
76
77
  }
77
78
  return null;
78
79
  } catch {
@@ -95,8 +96,8 @@ function parseWebP(buf) {
95
96
  }
96
97
  return null;
97
98
  }
98
- function parseJpeg(filePath) {
99
- const fd = fs.openSync(filePath, "r");
99
+ function parseJpeg(filePath2) {
100
+ const fd = fs.openSync(filePath2, "r");
100
101
  try {
101
102
  const buf = Buffer.alloc(4);
102
103
  let pos = 2;
@@ -251,7 +252,7 @@ var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
251
252
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
252
253
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
253
254
  var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
254
- var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
255
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist|derived)\b/g;
255
256
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
256
257
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
257
258
  var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
@@ -704,7 +705,7 @@ function nodeOnlyImports(importStmts) {
704
705
  }
705
706
  return out;
706
707
  }
707
- function wireEventBindings(template, actionNames, filePath = "<template>") {
708
+ function wireEventBindings(template, actionNames, filePath2 = "<template>") {
708
709
  const bindings = [];
709
710
  let out = "";
710
711
  let rest = template;
@@ -729,7 +730,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
729
730
  if (targets.length > 1) {
730
731
  throw new RoseError(
731
732
  "E-TEMPLATE",
732
- `${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
733
+ `${filePath2}: on:${m[1]} carries both |${targets.join(" and |")}`,
733
734
  { hint: "a handler binds to one target - the element (default), |window or |document" }
734
735
  );
735
736
  }
@@ -738,7 +739,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
738
739
  if (!KNOWN_MODS.includes(mod)) {
739
740
  throw new RoseError(
740
741
  "E-TEMPLATE",
741
- `${filePath}: unknown event modifier |${mod}`,
742
+ `${filePath2}: unknown event modifier |${mod}`,
742
743
  { 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
  );
744
745
  }
@@ -773,7 +774,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
773
774
  if (mods.length && actionNames.has(expr)) {
774
775
  throw new RoseError(
775
776
  "E-TEMPLATE",
776
- `${filePath}: event modifiers are not supported on the server action ${expr}`,
777
+ `${filePath2}: event modifiers are not supported on the server action ${expr}`,
777
778
  { hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
778
779
  );
779
780
  }
@@ -795,10 +796,10 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
795
796
  }
796
797
  return { template: out, bindings };
797
798
  }
798
- function scanSlotDecls(filePath) {
799
+ function scanSlotDecls(filePath2) {
799
800
  let src;
800
801
  try {
801
- src = fs3.readFileSync(filePath, "utf-8");
802
+ src = fs3.readFileSync(filePath2, "utf-8");
802
803
  } catch {
803
804
  return [];
804
805
  }
@@ -851,17 +852,104 @@ function hoistImports(script) {
851
852
  if (buf) imports.push(buf.join("\n"));
852
853
  return { imports: imports.join("\n"), rest: rest.join("\n") };
853
854
  }
854
- async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
855
- let source = await fs3.promises.readFile(filePath, "utf-8");
855
+ var __compileMemo = /* @__PURE__ */ new Map();
856
+ function compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry) {
857
+ let st;
858
+ try {
859
+ st = fs3.statSync(filePath2);
860
+ } catch {
861
+ return null;
862
+ }
863
+ const reg = [];
864
+ for (const [p, e] of registry) reg.push(`${p}#${e.index}:${e.scopeKey}:${e.slots.join("|")}`);
865
+ return [filePath2, String(st.mtimeMs), String(st.size), scopeKey, isApi ? "1" : "0", reg.join(";")].join("\0");
866
+ }
867
+ var __compilerStamp = (() => {
868
+ try {
869
+ return String(fs3.statSync(fileURLToPath(import.meta.url)).mtimeMs);
870
+ } catch {
871
+ return "noid";
872
+ }
873
+ })();
874
+ var __diskCacheDir = (() => {
875
+ try {
876
+ const dir = path2.join(os.tmpdir(), "rosetack-compile-cache");
877
+ fs3.mkdirSync(dir, { recursive: true });
878
+ return dir;
879
+ } catch {
880
+ return null;
881
+ }
882
+ })();
883
+ var __diskWrites = 0;
884
+ function __fnv1a(str) {
885
+ let h = 2166136261;
886
+ for (let i = 0; i < str.length; i++) {
887
+ h ^= str.charCodeAt(i);
888
+ h = Math.imul(h, 16777619);
889
+ }
890
+ return (h >>> 0).toString(16).padStart(8, "0");
891
+ }
892
+ function __diskFile(key) {
893
+ return path2.join(__diskCacheDir, __fnv1a(key + "|" + __compilerStamp) + ".json");
894
+ }
895
+ function __diskGet(key) {
896
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return null;
897
+ try {
898
+ const obj = JSON.parse(fs3.readFileSync(__diskFile(key), "utf-8"));
899
+ if (obj && typeof obj === "object" && typeof obj.ssr === "string") return obj;
900
+ } catch {
901
+ }
902
+ return null;
903
+ }
904
+ function __diskSet(key, result) {
905
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return;
906
+ try {
907
+ fs3.writeFileSync(__diskFile(key), JSON.stringify(result));
908
+ if ((__diskWrites++ & 511) === 0) {
909
+ try {
910
+ const entries = fs3.readdirSync(__diskCacheDir);
911
+ if (entries.length > 5e3) {
912
+ for (const e of entries) {
913
+ try {
914
+ fs3.unlinkSync(path2.join(__diskCacheDir, e));
915
+ } catch {
916
+ }
917
+ }
918
+ }
919
+ } catch {
920
+ }
921
+ }
922
+ } catch {
923
+ }
924
+ }
925
+ async function compileComponentMemo(filePath2, publicDir, scopeKey, isApi, plugins, registry) {
926
+ if (plugins.length > 0) return compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
927
+ const key = compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry);
928
+ if (key) {
929
+ const hit = __compileMemo.get(key);
930
+ if (hit) return { ...hit };
931
+ const disk = __diskGet(key);
932
+ if (disk) return disk;
933
+ }
934
+ const result = await compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
935
+ if (key) {
936
+ if (__compileMemo.size > 500) __compileMemo.clear();
937
+ __compileMemo.set(key, result);
938
+ __diskSet(key, result);
939
+ }
940
+ return result;
941
+ }
942
+ async function compileComponent(filePath2, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
943
+ let source = await fs3.promises.readFile(filePath2, "utf-8");
856
944
  for (const p of plugins) {
857
945
  if (!p.transform) continue;
858
946
  try {
859
- source = await p.transform(source, filePath);
947
+ source = await p.transform(source, filePath2);
860
948
  } catch (err) {
861
949
  throw new RoseError(
862
950
  "E-PLUGIN",
863
- `plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
864
- { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
951
+ `plugin ${p.name} failed on ${path2.basename(filePath2)}: ${err instanceof Error ? err.message : String(err)}`,
952
+ { file: filePath2, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
865
953
  );
866
954
  }
867
955
  }
@@ -871,7 +959,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
871
959
  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));
872
960
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
873
961
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
874
- const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
962
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath2, registry).script);
875
963
  const ownRuntimeImports = new Set(
876
964
  [...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))
877
965
  );
@@ -899,30 +987,31 @@ ${hoisted.rest}`, "ssr").trim()}`,
899
987
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
900
988
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
901
989
  const scriptMatch = source.match(COMPONENT_RE);
902
- const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
990
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath2, registry);
903
991
  const rawScript = roseResolved.script;
992
+ const usesrosetackAuth = rawScript.includes("__rosetackAuth");
904
993
  const roseImports = roseResolved.imports;
905
994
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
906
- if (path2.basename(filePath) !== "_middleware.rose") {
995
+ if (path2.basename(filePath2) !== "_middleware.rose") {
907
996
  for (const spec of nodeOnlyImports(importStmts)) {
908
997
  const at = importStmts.indexOf(spec);
909
998
  throw new RoseError(
910
999
  "E-NODE-ONLY",
911
- `${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.`,
1000
+ `${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.`,
912
1001
  {
913
- file: filePath,
1002
+ file: filePath2,
914
1003
  line: at >= 0 ? lineOf(importStmts, at) : void 0,
915
1004
  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`
916
1005
  }
917
1006
  );
918
1007
  }
919
1008
  }
920
- const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
1009
+ const isComponent = registry.get(filePath2)?.scopeKey.startsWith("components/") ?? false;
921
1010
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
922
1011
  throw new RoseError(
923
1012
  "E-EXPORT",
924
- `${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()}>.`,
925
- { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
1013
+ `${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()}>.`,
1014
+ { file: filePath2, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
926
1015
  );
927
1016
  }
928
1017
  const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
@@ -936,8 +1025,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
936
1025
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
937
1026
  throw new RoseError(
938
1027
  "E-EXPORT",
939
- `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
940
- { 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'" }
1028
+ `${filePath2}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
1029
+ { 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'" }
941
1030
  );
942
1031
  }
943
1032
  const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
@@ -945,8 +1034,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
945
1034
  if (vitalsMatch && !vitals) {
946
1035
  throw new RoseError(
947
1036
  "E-EXPORT",
948
- `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
949
- { 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" }
1037
+ `${filePath2}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
1038
+ { 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" }
950
1039
  );
951
1040
  }
952
1041
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
@@ -954,8 +1043,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
954
1043
  if (bundle && !["inline", "split"].includes(bundle)) {
955
1044
  throw new RoseError(
956
1045
  "E-EXPORT",
957
- `${filePath}: export const bundle must be 'inline' or 'split'`,
958
- { 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" }
1046
+ `${filePath2}: export const bundle must be 'inline' or 'split'`,
1047
+ { 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" }
959
1048
  );
960
1049
  }
961
1050
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
@@ -971,9 +1060,9 @@ ${hoisted.rest}`, "ssr").trim()}`,
971
1060
  const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
972
1061
  throw new RoseError(
973
1062
  "E-EXPORT",
974
- `${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.)`,
1063
+ `${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.)`,
975
1064
  {
976
- file: filePath,
1065
+ file: filePath2,
977
1066
  line: lineAt(deadSrc, dead),
978
1067
  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'
979
1068
  }
@@ -989,15 +1078,15 @@ ${hoisted.rest}`, "ssr").trim()}`,
989
1078
  } catch {
990
1079
  throw new RoseError(
991
1080
  "E-EXPORT",
992
- `${filePath}: export const headers must be an object literal`,
993
- { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
1081
+ `${filePath2}: export const headers must be an object literal`,
1082
+ { file: filePath2, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
994
1083
  );
995
1084
  }
996
1085
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
997
1086
  throw new RoseError(
998
1087
  "E-EXPORT",
999
- `${filePath}: export const headers must be a flat map of string -> string`,
1000
- { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
1088
+ `${filePath2}: export const headers must be a flat map of string -> string`,
1089
+ { file: filePath2, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
1001
1090
  );
1002
1091
  }
1003
1092
  headers = value;
@@ -1011,16 +1100,16 @@ ${hoisted.rest}`, "ssr").trim()}`,
1011
1100
  } catch {
1012
1101
  throw new RoseError(
1013
1102
  "E-EXPORT",
1014
- `${filePath}: export const csp must be an object literal`,
1015
- { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
1103
+ `${filePath2}: export const csp must be an object literal`,
1104
+ { file: filePath2, hint: "write it as one literal: export const csp = { nonce: true }" }
1016
1105
  );
1017
1106
  }
1018
1107
  const nonce = value?.nonce;
1019
1108
  if (nonce !== void 0 && typeof nonce !== "boolean") {
1020
1109
  throw new RoseError(
1021
1110
  "E-EXPORT",
1022
- `${filePath}: csp.nonce must be a boolean`,
1023
- { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1111
+ `${filePath2}: csp.nonce must be a boolean`,
1112
+ { file: filePath2, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1024
1113
  );
1025
1114
  }
1026
1115
  cspNonce = nonce === true;
@@ -1033,9 +1122,10 @@ ${hoisted.rest}`, "ssr").trim()}`,
1033
1122
  if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
1034
1123
  clientReasons.push("a form bound to a client dispatch ($action)");
1035
1124
  }
1036
- const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
1125
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);
1037
1126
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
1038
1127
  if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
1128
+ if (source.includes("{#await")) clientReasons.push("{#await} async block");
1039
1129
  const needsClient = clientReasons.length > 0;
1040
1130
  const jsWarnings = [];
1041
1131
  if (!needsClient) {
@@ -1061,6 +1151,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
1061
1151
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
1062
1152
  const decls = extractDecls(script);
1063
1153
  const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
1154
+ const derivedNames = decls.filter((d) => d.kind === "derived").map((d) => d.name);
1155
+ const callifyNames = [...stateDecls.map((s) => s.name), ...derivedNames];
1064
1156
  const setterNames = /* @__PURE__ */ new Map();
1065
1157
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
1066
1158
  const declCode = (d) => {
@@ -1073,65 +1165,97 @@ ${hoisted.rest}`, "ssr").trim()}`,
1073
1165
  if (d.kind === "persist") {
1074
1166
  return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1075
1167
  }
1168
+ if (d.kind === "derived") {
1169
+ return `const ${d.name} = () => (${callifyStateReads(d.expr, callifyNames)});`;
1170
+ }
1076
1171
  if (d.kind === "kv") {
1077
1172
  const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1078
1173
  const fnExpr = mTtl ? mTtl[1] : d.expr;
1079
1174
  const ttl = mTtl ? mTtl[2] : "300";
1080
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1175
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1081
1176
  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}));`;
1177
+ 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)}); }`;
1083
1178
  }
1084
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1179
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1085
1180
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1086
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1181
+ if (!__seeded_${d.name}) { const __v_${d.name} = await $data(${fn}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1087
1182
  };
1088
1183
  const nestedDecls = [];
1089
1184
  let spliced = "";
1090
1185
  let pos = 0;
1091
1186
  decls.forEach((d, i) => {
1092
1187
  const top = braceDepthAt(script, d.start) === 0;
1093
- if (!top) nestedDecls.push(d);
1188
+ if (!top) {
1189
+ if (d.kind === "derived") {
1190
+ throw new Error(
1191
+ `${filePath2}: $derived must be a top-level declaration - inside a function body a plain const arrow already does this natively`
1192
+ );
1193
+ }
1194
+ nestedDecls.push(d);
1195
+ }
1094
1196
  spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
1095
1197
  pos = d.end;
1096
1198
  });
1097
1199
  spliced += script.slice(pos);
1098
1200
  let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
1099
1201
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
1202
+ if (derivedNames.includes(trimmedKey)) {
1203
+ throw new Error(
1204
+ `${filePath2}: $setState('${trimmedKey}', ...) - a $derived value is read-only; make it $state or derive a different expression`
1205
+ );
1206
+ }
1100
1207
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
1101
1208
  return `${setter}(${val})`;
1102
1209
  });
1103
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1210
+ cleanScript = callifyStateReads(cleanScript, callifyNames);
1104
1211
  cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
1105
1212
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
1106
1213
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
1107
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
1214
+ const templateCalled = callifyTemplateExprs(template, callifyNames);
1108
1215
  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);
1110
- const stateKeys = decls.map((d) => d.name);
1216
+ const wired = wireEventBindings(imgDefaulted, actionNames, filePath2);
1217
+ const stateKeys = decls.filter((d) => d.kind !== "derived").map((d) => d.name);
1111
1218
  const bindBindings = [];
1112
1219
  let bindCounter = 0;
1113
1220
  const bindExpanded = wired.template.replace(
1114
- /\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1115
- (whole, kind, name) => {
1221
+ /\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1222
+ (whole, kind, name, offset, str) => {
1116
1223
  if (!stateKeys.includes(name)) {
1117
1224
  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)")
1225
+ `${filePath2}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1119
1226
  );
1120
1227
  }
1121
1228
  if (kind === "this") return ` data-bind-this="${name}"`;
1229
+ const tagStart = str.lastIndexOf("<", offset);
1230
+ const tagText = tagStart >= 0 ? str.slice(tagStart, offset) : "";
1231
+ if (kind === "value" && /^<select[\s>]/i.test(tagText) && /\smultiple\b/i.test(tagText)) {
1232
+ const setterM = setterNames.get(name);
1233
+ const hnameM = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1234
+ bindBindings.push({
1235
+ event: "change",
1236
+ fn: `${hnameM}: (e) => ${setterM}(Array.from(e.target.selectedOptions, (o) => o.value))`
1237
+ });
1238
+ return ` data-selmulti={${name}().join(',')} data-on-change="${hnameM}"`;
1239
+ }
1240
+ if (kind === "open") {
1241
+ const setterO = setterNames.get(name);
1242
+ const hnameO = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1243
+ bindBindings.push({ event: "toggle", fn: `${hnameO}: (e) => ${setterO}(e.target.open)` });
1244
+ return ` open={${name}()} data-on-toggle="${hnameO}"`;
1245
+ }
1122
1246
  const setter = setterNames.get(name);
1123
1247
  const evt = kind === "checked" ? "change" : "input";
1124
1248
  const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1125
1249
  bindBindings.push({
1126
1250
  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); }`
1251
+ 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); }`
1128
1252
  });
1129
1253
  const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
1130
1254
  return ` ${kind}={${name}()}${evtAttr}`;
1131
1255
  }
1132
1256
  );
1133
1257
  const comps = new Map(roseImports.map((r) => {
1134
- const abs = path2.resolve(path2.dirname(filePath), r.specifier);
1258
+ const abs = path2.resolve(path2.dirname(filePath2), r.specifier);
1135
1259
  const hit = registry.get(abs);
1136
1260
  return [r.name, { index: hit.index, slots: hit.slots }];
1137
1261
  }));
@@ -1152,14 +1276,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1152
1276
  if (!stateKeys.includes(name)) {
1153
1277
  throw new RoseError(
1154
1278
  "E-TEMPLATE",
1155
- `${filePath}: bind:group={${name}} must name a $state declaration`,
1279
+ `${filePath2}: bind:group={${name}} must name a $state declaration`,
1156
1280
  { hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
1157
1281
  );
1158
1282
  }
1159
1283
  if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
1160
1284
  throw new RoseError(
1161
1285
  "E-TEMPLATE",
1162
- `${filePath}: bind:group is for radio and checkbox inputs`,
1286
+ `${filePath2}: bind:group is for radio and checkbox inputs`,
1163
1287
  { 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
1288
  );
1165
1289
  }
@@ -1168,14 +1292,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1168
1292
  if (!vm || /\{/.test(vm[0])) {
1169
1293
  throw new RoseError(
1170
1294
  "E-TEMPLATE",
1171
- `${filePath}: a bind:group input needs a static value attribute`,
1295
+ `${filePath2}: a bind:group input needs a static value attribute`,
1172
1296
  { hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
1173
1297
  );
1174
1298
  }
1175
1299
  if (/\schecked\s*=/.test(attrs)) {
1176
1300
  throw new RoseError(
1177
1301
  "E-TEMPLATE",
1178
- `${filePath}: a bind:group input cannot also carry checked=`,
1302
+ `${filePath2}: a bind:group input cannot also carry checked=`,
1179
1303
  { hint: "the group state alone decides which inputs are checked" }
1180
1304
  );
1181
1305
  }
@@ -1198,19 +1322,23 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1198
1322
  /\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
1199
1323
  (_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
1200
1324
  );
1201
- const classExpanded = expandClassDirectives(useExpanded, filePath);
1202
- const styleExpanded = expandStyleDirectives(classExpanded, filePath);
1203
- const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
1325
+ const classExpanded = expandClassDirectives(useExpanded, filePath2);
1326
+ const classMerged = mergeStaticClass(classExpanded);
1327
+ const styleExpanded = expandStyleDirectives(classMerged, filePath2);
1328
+ const transExpanded = expandTransitionDirectives(styleExpanded, filePath2);
1329
+ const animExpanded = expandAnimateDirectives(transExpanded, filePath2);
1330
+ const keyExpanded = expandKeyBlocks(animExpanded, filePath2);
1204
1331
  const elseExpanded = expandIfElse(keyExpanded);
1205
1332
  const deferExpanded = expandDeferBlocks(elseExpanded);
1206
- const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
1333
+ const awaitExpanded = expandAwaitBlocks(deferExpanded.template, filePath2);
1334
+ const fbExpanded = expandBoundaryFallbacks(awaitExpanded.template, filePath2);
1207
1335
  const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
1208
1336
  const call = `{__slot(${encodeSlotCall(attrs)})}`;
1209
1337
  if (fallback) {
1210
1338
  if (/\{[^{}]*\}/.test(fallback)) {
1211
1339
  throw new RoseError(
1212
1340
  "E-TEMPLATE",
1213
- `${filePath}: slot fallback content must be static markup`,
1341
+ `${filePath2}: slot fallback content must be static markup`,
1214
1342
  { 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
1343
  );
1216
1344
  }
@@ -1218,7 +1346,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1218
1346
  }
1219
1347
  return call;
1220
1348
  }).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
1221
- assertKnownDirectives(ssrTemplate, filePath);
1349
+ assertKnownDirectives(ssrTemplate, filePath2);
1222
1350
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
1223
1351
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
1224
1352
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -1226,7 +1354,8 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1226
1354
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
1227
1355
  const ssrGuard = guard ? `
1228
1356
  ${guard}` : "";
1229
- const isMiddleware = path2.basename(filePath) === "_middleware.rose";
1357
+ const isMiddleware = path2.basename(filePath2) === "_middleware.rose";
1358
+ const bootCode = deferBootCode(deferExpanded.count, deferExpanded.holds) + (awaitExpanded.blocks.length ? "\n" + awaitBootCode(awaitExpanded.blocks) : "");
1230
1359
  const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
1231
1360
 
1232
1361
  ${importStmts}
@@ -1235,8 +1364,8 @@ ${ssrExports}
1235
1364
  ${ssrGuard}
1236
1365
 
1237
1366
  ${cleanScript}
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);
1367
+ ` : generateSSR(cleanScript + bootCode, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1368
+ const client = generateClient(cleanScript + bootCode, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1240
1369
  return {
1241
1370
  ssr: rewriteRoseImports(ssr, "ssr"),
1242
1371
  client: rewriteRoseImports(client, "client"),
@@ -1260,6 +1389,7 @@ ${cleanScript}
1260
1389
  jsWarnings,
1261
1390
  headers,
1262
1391
  cspNonce,
1392
+ usesrosetackAuth,
1263
1393
  props,
1264
1394
  roseImports,
1265
1395
  isComponent
@@ -1273,6 +1403,13 @@ function minifyDecls(block) {
1273
1403
  }
1274
1404
  function scopeCss(css, key) {
1275
1405
  const attr = `[data-rosetack-c="${key}"]`;
1406
+ const scopeOneSelector = (s) => {
1407
+ const t = s.trim();
1408
+ if (!t.includes(":global")) return `${attr} ${t}`;
1409
+ const stripped = t.replace(/:global\([^()]*\)/g, (m) => m.slice(8, -1)).trim();
1410
+ const outside = t.replace(/:global\([^()]*\)/g, "").trim();
1411
+ return outside ? `${attr} ${stripped}` : stripped;
1412
+ };
1276
1413
  const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
1277
1414
  let out = "";
1278
1415
  let prelude = "";
@@ -1292,7 +1429,7 @@ function scopeCss(css, key) {
1292
1429
  if (sel.startsWith("@")) {
1293
1430
  out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
1294
1431
  } else if (sel) {
1295
- const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
1432
+ const scoped = sel.split(",").map((s) => scopeOneSelector(s)).join(",");
1296
1433
  out += `${scoped}{${minifyDecls(block)}}`;
1297
1434
  }
1298
1435
  prelude = "";
@@ -1583,7 +1720,7 @@ function autoCall(expr) {
1583
1720
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1584
1721
  }
1585
1722
  var DEFER_ENABLED = true;
1586
- function expandKeyBlocks(template, filePath) {
1723
+ function expandKeyBlocks(template, filePath2) {
1587
1724
  if (!template.includes("{#key")) return template;
1588
1725
  for (let pass = 0; pass < 10; pass++) {
1589
1726
  const OPEN_RE = /\{#key\s+([^}]+)\}/g;
@@ -1611,7 +1748,7 @@ function expandKeyBlocks(template, filePath) {
1611
1748
  if (closeAt < 0) {
1612
1749
  throw new RoseError(
1613
1750
  "E-TEMPLATE",
1614
- `${filePath}: {#key ${expr}} is never closed`,
1751
+ `${filePath2}: {#key ${expr}} is never closed`,
1615
1752
  { hint: "every {#key} needs its {/key}" }
1616
1753
  );
1617
1754
  }
@@ -1712,7 +1849,46 @@ function expandIfElseOnce(template) {
1712
1849
  }
1713
1850
  return { template: out, changed };
1714
1851
  }
1715
- function expandClassDirectives(template, filePath) {
1852
+ function mergeStaticClass(template) {
1853
+ if (!/\sclass\s*=\s*"/.test(template) || !/\sclass\s*=\s*\{/.test(template)) return template;
1854
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1855
+ let out = "";
1856
+ let pos = 0;
1857
+ let m;
1858
+ TAG_RE.lastIndex = 0;
1859
+ while (m = TAG_RE.exec(template)) {
1860
+ const [whole, tag, attrs, selfClose] = m;
1861
+ const sm = /\sclass\s*=\s*"([^"]*)"/.exec(attrs);
1862
+ if (!sm) continue;
1863
+ const rm = /\sclass\s*=\s*\{/.exec(attrs);
1864
+ if (!rm || rm.index === sm.index) continue;
1865
+ const open = attrs.indexOf("{", rm.index);
1866
+ let depth = 1;
1867
+ let j = open + 1;
1868
+ while (j < attrs.length && depth > 0) {
1869
+ const ch = attrs[j];
1870
+ if (ch === '"' || ch === "'") {
1871
+ j = skipQuoted(attrs, j);
1872
+ continue;
1873
+ }
1874
+ if (ch === "{") depth++;
1875
+ else if (ch === "}") depth--;
1876
+ j++;
1877
+ }
1878
+ if (depth !== 0) continue;
1879
+ const expr = attrs.slice(open + 1, j - 1);
1880
+ const base = JSON.stringify(sm[1]);
1881
+ const merged = ` class={((v) => v == null ? ${base} : typeof v === 'object' ? ({ ${base}: true, ...v }) : (${base} + ' ' + v))(${expr})}`;
1882
+ const lo = Math.min(sm.index, rm.index);
1883
+ const hiEnd = Math.max(sm.index + sm[0].length, j);
1884
+ const newAttrs = attrs.slice(0, lo) + merged + attrs.slice(hiEnd);
1885
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1886
+ pos = m.index + whole.length;
1887
+ }
1888
+ out += template.slice(pos);
1889
+ return out;
1890
+ }
1891
+ function expandClassDirectives(template, filePath2) {
1716
1892
  if (!template.includes("class:")) return template;
1717
1893
  const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1718
1894
  let out = "";
@@ -1739,14 +1915,14 @@ function expandClassDirectives(template, filePath) {
1739
1915
  i++;
1740
1916
  }
1741
1917
  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" });
1918
+ 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" });
1743
1919
  }
1744
1920
  pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1745
1921
  }
1746
1922
  const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1747
1923
  const clsM = clsRe.exec(attrs);
1748
1924
  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="..."' });
1925
+ 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="..."' });
1750
1926
  }
1751
1927
  const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
1752
1928
  let closure = `(${JSON.stringify(staticCls)}`;
@@ -1770,7 +1946,130 @@ function expandClassDirectives(template, filePath) {
1770
1946
  out += template.slice(pos);
1771
1947
  return out;
1772
1948
  }
1773
- function expandStyleDirectives(template, filePath) {
1949
+ function expandTransitionDirectives(template, filePath2) {
1950
+ if (!/\s(?:transition|in|out):/.test(template)) return template;
1951
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1952
+ let out = "";
1953
+ let pos = 0;
1954
+ let m;
1955
+ TAG_RE.lastIndex = 0;
1956
+ while (m = TAG_RE.exec(template)) {
1957
+ const [whole, tag, attrs, selfClose] = m;
1958
+ if (!attrs.includes("transition:") && !/\s(?:in|out):/.test(attrs)) continue;
1959
+ const pairs = [];
1960
+ const NAME_RE = /\s(transition|in|out):([\w-]+)(?:\s*=\s*\{)?/g;
1961
+ let nm;
1962
+ while (nm = NAME_RE.exec(attrs)) {
1963
+ let start = nm.index;
1964
+ let end = nm.index + nm[0].length;
1965
+ let params = "";
1966
+ if (nm[0].endsWith("{")) {
1967
+ let depth = 1;
1968
+ let i = end;
1969
+ while (i < attrs.length && depth > 0) {
1970
+ const ch = attrs[i];
1971
+ if (ch === '"' || ch === "'") {
1972
+ i = skipQuoted(attrs, i);
1973
+ continue;
1974
+ }
1975
+ if (ch === "{") depth++;
1976
+ else if (ch === "}") depth--;
1977
+ i++;
1978
+ }
1979
+ if (depth !== 0) {
1980
+ 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" });
1981
+ }
1982
+ params = attrs.slice(end, i - 1);
1983
+ end = i;
1984
+ }
1985
+ pairs.push({ dir: nm[1] === "transition" ? "" : nm[1], name: nm[2], params, start, end });
1986
+ }
1987
+ if (pairs.length === 0) continue;
1988
+ let transitionValue = "";
1989
+ for (const p of pairs) {
1990
+ if (transitionValue) transitionValue += "|";
1991
+ transitionValue += (p.dir ? p.dir + ":" : "") + p.name + (p.params ? ":" + p.params : "");
1992
+ }
1993
+ let newAttrs = attrs;
1994
+ for (let k = pairs.length - 1; k >= 0; k--) {
1995
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1996
+ }
1997
+ const transRe = /\sdata-transition\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1998
+ const tm = transRe.exec(newAttrs);
1999
+ if (tm) {
2000
+ const existing = tm[2] ?? tm[3] ?? "";
2001
+ newAttrs = newAttrs.replace(transRe, ` data-transition="${existing}${transitionValue ? (existing ? "|" : "") + transitionValue : ""}"`);
2002
+ } else {
2003
+ newAttrs = ` data-transition="${transitionValue}"` + newAttrs;
2004
+ }
2005
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2006
+ pos = m.index + whole.length;
2007
+ }
2008
+ out += template.slice(pos);
2009
+ return out;
2010
+ }
2011
+ function expandAnimateDirectives(template, filePath2) {
2012
+ if (!template.includes("animate:")) return template;
2013
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2014
+ let out = "";
2015
+ let pos = 0;
2016
+ let m;
2017
+ TAG_RE.lastIndex = 0;
2018
+ while (m = TAG_RE.exec(template)) {
2019
+ const [whole, tag, attrs, selfClose] = m;
2020
+ if (!attrs.includes("animate:")) continue;
2021
+ const pairs = [];
2022
+ const NAME_RE = /\sanimate:([\w-]+)(?:\s*=\s*\{)?/g;
2023
+ let nm;
2024
+ while (nm = NAME_RE.exec(attrs)) {
2025
+ let start = nm.index;
2026
+ let end = nm.index + nm[0].length;
2027
+ let params = "";
2028
+ if (nm[0].endsWith("{")) {
2029
+ let depth = 1;
2030
+ let i = end;
2031
+ while (i < attrs.length && depth > 0) {
2032
+ const ch = attrs[i];
2033
+ if (ch === '"' || ch === "'") {
2034
+ i = skipQuoted(attrs, i);
2035
+ continue;
2036
+ }
2037
+ if (ch === "{") depth++;
2038
+ else if (ch === "}") depth--;
2039
+ i++;
2040
+ }
2041
+ if (depth !== 0) {
2042
+ 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" });
2043
+ }
2044
+ params = attrs.slice(end, i - 1);
2045
+ end = i;
2046
+ }
2047
+ pairs.push({ name: nm[1], params, start, end });
2048
+ }
2049
+ let animateValue = "";
2050
+ for (const p of pairs) {
2051
+ if (animateValue) animateValue += "|";
2052
+ animateValue += p.name + (p.params ? ":" + p.params : "");
2053
+ }
2054
+ let newAttrs = attrs;
2055
+ for (let k = pairs.length - 1; k >= 0; k--) {
2056
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2057
+ }
2058
+ const animRe = /\sdata-animate\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2059
+ const am = animRe.exec(newAttrs);
2060
+ if (am) {
2061
+ const existing = am[2] ?? am[3] ?? "";
2062
+ newAttrs = newAttrs.replace(animRe, ` data-animate="${existing}${animateValue ? (existing ? "|" : "") + animateValue : ""}"`);
2063
+ } else {
2064
+ newAttrs = ` data-animate="${animateValue}"` + newAttrs;
2065
+ }
2066
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2067
+ pos = m.index + whole.length;
2068
+ }
2069
+ out += template.slice(pos);
2070
+ return out;
2071
+ }
2072
+ function expandStyleDirectives(template, filePath2) {
1774
2073
  if (!template.includes("style:")) return template;
1775
2074
  const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1776
2075
  let out = "";
@@ -1797,14 +2096,14 @@ function expandStyleDirectives(template, filePath) {
1797
2096
  i++;
1798
2097
  }
1799
2098
  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" });
2099
+ 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" });
1801
2100
  }
1802
2101
  pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1803
2102
  }
1804
2103
  const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1805
2104
  const stM = styleRe.exec(attrs);
1806
2105
  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}' });
2106
+ 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}' });
1808
2107
  }
1809
2108
  const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
1810
2109
  let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
@@ -1827,7 +2126,7 @@ function expandStyleDirectives(template, filePath) {
1827
2126
  out += template.slice(pos);
1828
2127
  return out;
1829
2128
  }
1830
- function expandBoundaryFallbacks(template, filePath) {
2129
+ function expandBoundaryFallbacks(template, filePath2) {
1831
2130
  if (!template.includes("{:fallback")) return template;
1832
2131
  for (let pass = 0; pass < 10; pass++) {
1833
2132
  const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
@@ -1871,12 +2170,12 @@ function expandBoundaryFallbacks(template, filePath) {
1871
2170
  if (top !== "boundary") {
1872
2171
  throw new RoseError(
1873
2172
  "E-TEMPLATE",
1874
- `${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
2173
+ `${filePath2}: {:fallback} must sit directly inside a {#boundary} block`,
1875
2174
  { hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
1876
2175
  );
1877
2176
  }
1878
2177
  if (fbAt >= 0) {
1879
- throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
2178
+ throw new RoseError("E-TEMPLATE", `${filePath2}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
1880
2179
  }
1881
2180
  fbAt = tm3.index;
1882
2181
  fbLen = tok.length;
@@ -1984,8 +2283,137 @@ function deferBootCode(count, holds = []) {
1984
2283
  }
1985
2284
  return code;
1986
2285
  }
2286
+ function expandAwaitBlocks(template, filePath2) {
2287
+ let out = "";
2288
+ let pos = 0;
2289
+ let n = 0;
2290
+ const blocks = [];
2291
+ for (; ; ) {
2292
+ const openAt = template.indexOf("{#await", pos);
2293
+ if (openAt < 0) break;
2294
+ let i = openAt + 7;
2295
+ let brace = 1;
2296
+ while (i < template.length && brace > 0) {
2297
+ const c = template[i];
2298
+ if (c === "{") brace++;
2299
+ else if (c === "}") brace--;
2300
+ i++;
2301
+ }
2302
+ if (brace !== 0) break;
2303
+ const openLen = i - openAt;
2304
+ const expr = template.slice(openAt + 7, i - 1).trim();
2305
+ if (!expr) {
2306
+ throw new RoseError("E-TEMPLATE", `${filePath2}: {#await} needs a promise expression`, {
2307
+ file: filePath2,
2308
+ hint: "write {#await fetchUsers()}...{:then users}...{/await}"
2309
+ });
2310
+ }
2311
+ const blockOpenRe = /\{\#(if|each|boundary|island|await)\b/g;
2312
+ const blockCloseRe = /\{\/(if|each|boundary|island|await)\}/g;
2313
+ const thenRe = /\{:then\b([^}]*)\}/g;
2314
+ const catchRe = /\{:catch\b([^}]*)\}/g;
2315
+ let d = 1;
2316
+ let j = i;
2317
+ let thenAt = -1, catchAt = -1, closeAt = -1;
2318
+ let thenRaw = "", catchRaw = "";
2319
+ for (; ; ) {
2320
+ blockOpenRe.lastIndex = j;
2321
+ blockCloseRe.lastIndex = j;
2322
+ thenRe.lastIndex = j;
2323
+ catchRe.lastIndex = j;
2324
+ const nextOpen = blockOpenRe.exec(template);
2325
+ const nextClose = blockCloseRe.exec(template);
2326
+ const nextThen = thenRe.exec(template);
2327
+ const nextCatch = catchRe.exec(template);
2328
+ let nearestPos = Infinity, kind = "", m = null;
2329
+ const consider = (mm, k) => {
2330
+ if (mm && mm.index < nearestPos) {
2331
+ nearestPos = mm.index;
2332
+ kind = k;
2333
+ m = mm;
2334
+ }
2335
+ };
2336
+ consider(nextOpen, "open");
2337
+ consider(nextClose, "close");
2338
+ consider(nextThen, "then");
2339
+ consider(nextCatch, "catch");
2340
+ if (!m) break;
2341
+ if (kind === "open") {
2342
+ d++;
2343
+ j = m.index + m[0].length;
2344
+ continue;
2345
+ }
2346
+ if (kind === "close") {
2347
+ if (d === 1 && m[1] === "await") {
2348
+ closeAt = m.index;
2349
+ break;
2350
+ }
2351
+ d--;
2352
+ j = m.index + m[0].length;
2353
+ continue;
2354
+ }
2355
+ if (d === 1) {
2356
+ if (kind === "then" && thenAt < 0) {
2357
+ thenAt = m.index;
2358
+ thenRaw = m[1];
2359
+ } else if (kind === "catch" && catchAt < 0) {
2360
+ catchAt = m.index;
2361
+ catchRaw = m[1];
2362
+ }
2363
+ }
2364
+ j = m.index + m[0].length;
2365
+ }
2366
+ if (closeAt < 0 || thenAt < 0) break;
2367
+ const thenTokenEnd = thenAt + 7 + thenRaw.length;
2368
+ const catchTokenEnd = catchAt >= 0 ? catchAt + 7 + catchRaw.length : -1;
2369
+ const pending = template.slice(i, thenAt);
2370
+ const thenBody = template.slice(thenTokenEnd, catchAt >= 0 ? catchAt : closeAt);
2371
+ const catchBody = catchAt >= 0 ? template.slice(catchTokenEnd, closeAt) : "";
2372
+ const thenVarRaw = thenRaw.trim();
2373
+ const catchVarRaw = catchRaw.trim();
2374
+ const thenVar = /^\w+$/.test(thenVarRaw) ? thenVarRaw : `__rvAwaitThen${n + 1}`;
2375
+ const catchVar = catchAt >= 0 ? /^\w+$/.test(catchVarRaw) ? catchVarRaw : `__rvAwaitCatch${n + 1}` : "";
2376
+ n++;
2377
+ const nn = n;
2378
+ const stateName = `__rvAwait${nn}`;
2379
+ blocks.push({ n: nn, expr, thenVar, catchVar });
2380
+ out += template.slice(pos, openAt);
2381
+ out += `{#if ${stateName}().status === 'pending'}` + pending + "{/if}\n";
2382
+ out += `{#each (${stateName}().status === 'resolved' ? [${stateName}().value] : []) as ${thenVar}}` + thenBody + "{/each}\n";
2383
+ if (catchAt >= 0) {
2384
+ out += `{#each (${stateName}().status === 'rejected' ? [${stateName}().error] : []) as ${catchVar}}` + catchBody + "{/each}\n";
2385
+ }
2386
+ pos = closeAt + 8;
2387
+ }
2388
+ if (n === 0) return { template, blocks };
2389
+ out += template.slice(pos);
2390
+ return { template: out, blocks };
2391
+ }
2392
+ function awaitBootCode(blocks) {
2393
+ let code = "";
2394
+ for (const b of blocks) {
2395
+ const stateName = `__rvAwait${b.n}`;
2396
+ code += `const [${stateName}, set${stateName}] = state("__rvawait${b.n}", { status: 'pending', value: null, error: null });
2397
+ `;
2398
+ code += `onMount(function () {
2399
+ `;
2400
+ code += ` Promise.resolve(${b.expr}).then(function (__rvAwaitVal) {
2401
+ `;
2402
+ code += ` set${stateName}({ status: 'resolved', value: __rvAwaitVal });
2403
+ `;
2404
+ code += ` }).catch(function (__rvAwaitErr) {
2405
+ `;
2406
+ code += ` set${stateName}({ status: 'rejected', error: __rvAwaitErr });
2407
+ `;
2408
+ code += ` });
2409
+ `;
2410
+ code += `});
2411
+ `;
2412
+ }
2413
+ return code;
2414
+ }
1987
2415
  function findBlock(src, kind) {
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;
2416
+ 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;
1989
2417
  const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1990
2418
  let open;
1991
2419
  while (open = head.exec(src)) {
@@ -2007,7 +2435,7 @@ function findBlock(src, kind) {
2007
2435
  i = nextClose.index + nextClose[0].length;
2008
2436
  if (--depth === 0) {
2009
2437
  const content = src.slice(afterOpen, nextClose.index);
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];
2438
+ 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];
2011
2439
  const arr = [src.slice(start, i), ...groups];
2012
2440
  arr.index = start;
2013
2441
  return arr;
@@ -2050,8 +2478,20 @@ function compileHead(head) {
2050
2478
  flush();
2051
2479
  return out;
2052
2480
  }
2053
- var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
2054
- function assertKnownDirectives(template, filePath) {
2481
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island", "await", "snippet"]);
2482
+ var __blockResCache = /* @__PURE__ */ new Map();
2483
+ function blockCloseRes(kind) {
2484
+ let hit = __blockResCache.get(kind);
2485
+ if (!hit) {
2486
+ hit = {
2487
+ open: new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g"),
2488
+ close: new RegExp(`\\{/${kind}\\}`, "g")
2489
+ };
2490
+ __blockResCache.set(kind, hit);
2491
+ }
2492
+ return hit;
2493
+ }
2494
+ function assertKnownDirectives(template, filePath2) {
2055
2495
  const rawRanges = [];
2056
2496
  const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
2057
2497
  let raw;
@@ -2077,43 +2517,83 @@ function assertKnownDirectives(template, filePath) {
2077
2517
  if (sigil === "/") {
2078
2518
  throw new RoseError(
2079
2519
  "E-TEMPLATE",
2080
- `${filePath}: {/${word}} does not close anything`,
2081
- { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2520
+ `${filePath2}: {/${word}} does not close anything`,
2521
+ { file: filePath2, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2082
2522
  );
2083
2523
  }
2084
2524
  if (word === "else") {
2085
- throw new RoseError(
2086
- "E-TEMPLATE",
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
- );
2525
+ const netOpens = (re, closer, at) => {
2526
+ let n = 0, mm;
2527
+ re.lastIndex = 0;
2528
+ while (mm = re.exec(template)) {
2529
+ if (mm.index >= at) break;
2530
+ if (!inRaw(mm.index)) n++;
2531
+ }
2532
+ const cr = new RegExp(closer, "g");
2533
+ let c = 0;
2534
+ while (mm = cr.exec(template)) {
2535
+ if (mm.index >= at) break;
2536
+ if (!inRaw(mm.index)) c++;
2537
+ }
2538
+ return n - c;
2539
+ };
2540
+ const ifNet = netOpens(/\{#if\b/g, "\\{/if\\b", m.index);
2541
+ const eachNet = netOpens(/\{#each\b/g, "\\{/each\\b", m.index);
2542
+ if (ifNet <= 0 && eachNet <= 0) {
2543
+ throw new RoseError(
2544
+ "E-TEMPLATE",
2545
+ `${filePath2}: a stray {:else} with no {#if} or {#each} above it`,
2546
+ { file: filePath2, line: lineAt(template, m), hint: "{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block" }
2547
+ );
2548
+ }
2549
+ continue;
2090
2550
  }
2091
2551
  if (word === "fallback") {
2092
2552
  throw new RoseError(
2093
2553
  "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" }
2554
+ `${filePath2}: a stray {:fallback} with no {#boundary} above it`,
2555
+ { file: filePath2, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
2096
2556
  );
2097
2557
  }
2558
+ if (word === "then" || word === "catch") {
2559
+ const opensBefore = (re, at) => {
2560
+ re.lastIndex = 0;
2561
+ let n = 0, mm;
2562
+ while (mm = re.exec(template)) {
2563
+ if (mm.index >= at) break;
2564
+ if (!inRaw(mm.index)) n++;
2565
+ }
2566
+ return n;
2567
+ };
2568
+ const open = opensBefore(/\{#await\b/g, m.index);
2569
+ const close = opensBefore(/\{\/await\b/g, m.index);
2570
+ if (open <= close) {
2571
+ throw new RoseError(
2572
+ "E-TEMPLATE",
2573
+ `${filePath2}: a stray {:${word}} with no {#await} above it`,
2574
+ { file: filePath2, line: lineAt(template, m), hint: "{:then} / {:catch} belong inside an {#await} ... {/await} block" }
2575
+ );
2576
+ }
2577
+ continue;
2578
+ }
2098
2579
  throw new RoseError(
2099
2580
  "E-TEMPLATE",
2100
- `${filePath}: {:${word}} is not a rosetack directive`,
2101
- { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
2581
+ `${filePath2}: {:${word}} is not a rosetack directive`,
2582
+ { file: filePath2, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
2102
2583
  );
2103
2584
  }
2104
- const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
2585
+ const OPENER_RE = /\{#(if|each|boundary|island|await)\b([^}]*)\}/g;
2105
2586
  while (m = OPENER_RE.exec(template)) {
2106
2587
  if (inRaw(m.index)) continue;
2107
2588
  const [, kind, head] = m;
2108
- if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
2589
+ if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?(?:\s*\([^)]*\))?\s*$/.test(head)) {
2109
2590
  throw new RoseError(
2110
2591
  "E-TEMPLATE",
2111
- `${filePath}: {#each ${head.trim()}} is missing its item name`,
2112
- { 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)" }
2592
+ `${filePath2}: {#each ${head.trim()}} is missing its item name`,
2593
+ { 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)" }
2113
2594
  );
2114
2595
  }
2115
- const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
2116
- const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
2596
+ const { open: OPEN_RE, close: CLOSE_RE } = blockCloseRes(kind);
2117
2597
  let depth = 1;
2118
2598
  let i = m.index + m[0].length;
2119
2599
  for (; ; ) {
@@ -2132,8 +2612,8 @@ function assertKnownDirectives(template, filePath) {
2132
2612
  if (depth !== 0) {
2133
2613
  throw new RoseError(
2134
2614
  "E-TEMPLATE",
2135
- `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2136
- { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2615
+ `${filePath2}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2616
+ { file: filePath2, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2137
2617
  );
2138
2618
  }
2139
2619
  }
@@ -2166,6 +2646,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2166
2646
  const islandsMode = /\{#island\b/.test(template);
2167
2647
  const effMarkers = markers && (!islandsMode || islandDepth > 0);
2168
2648
  const nextId = () => `${depth}_${blockId++}`;
2649
+ if (depth === 0) result += "const __snip = {};\n";
2169
2650
  while (remaining.length > 0) {
2170
2651
  const ifMatch = findBlock(remaining, "if");
2171
2652
  const eachMatch = findBlock(remaining, "each");
@@ -2174,11 +2655,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2174
2655
  const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
2175
2656
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2176
2657
  const islandMatch = findBlock(remaining, "island");
2658
+ const snippetMatch = findBlock(remaining, "snippet");
2177
2659
  const candidates = [];
2178
2660
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
2179
2661
  if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
2180
2662
  if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
2181
2663
  if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
2664
+ if (snippetMatch?.index !== void 0) candidates.push({ type: "snippet", match: snippetMatch, index: snippetMatch.index });
2182
2665
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
2183
2666
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
2184
2667
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
@@ -2224,7 +2707,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2224
2707
  }
2225
2708
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2226
2709
  } else if (earliest.type === "each") {
2227
- const [, items, item, index, content] = earliest.match;
2710
+ const [, items, item, index, key, content] = earliest.match;
2228
2711
  const before = remaining.substring(0, earliest.index);
2229
2712
  if (before) result += emitChunk(before, acc, closes, scope);
2230
2713
  const call = autoCall(items);
@@ -2243,10 +2726,24 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2243
2726
  scoped += content.trim().slice(lastSpan);
2244
2727
  const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2245
2728
  const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2729
+ let keyFn = "";
2730
+ if (key) {
2731
+ if (isDestructure) {
2732
+ throw new RoseError(
2733
+ "E-TEMPLATE",
2734
+ `${filePath}: a keyed {#each} keys on a named item's property - write {#each xs as x (x.id)}, not a destructuring pattern`,
2735
+ { file: filePath, hint: "name the item first, then key on one of its properties" }
2736
+ );
2737
+ }
2738
+ let k = key.trim();
2739
+ if (itemRe) k = k.replace(itemRe, "__s");
2740
+ if (indexRe) k = k.replace(indexRe, "__i");
2741
+ keyFn = `, (__s, __i) => (${k})`;
2742
+ }
2246
2743
  result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
2247
2744
  `;
2248
2745
  if (effMarkers) {
2249
- result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
2746
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id}${keyFn});
2250
2747
  `;
2251
2748
  } else {
2252
2749
  const param = isDestructure ? "__s" : item;
@@ -2282,6 +2779,16 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2282
2779
  ` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
2283
2780
  `;
2284
2781
  result += `${acc} += __bd${id};
2782
+ `;
2783
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2784
+ } else if (earliest.type === "snippet") {
2785
+ const [, name, params, content] = earliest.match;
2786
+ const before = remaining.substring(0, earliest.index);
2787
+ if (before) result += emitChunk(before, acc, closes, scope);
2788
+ const id = nextId();
2789
+ const paramList = params ? params.split(",").map((p) => p.trim()).filter(Boolean).join(",") : "";
2790
+ const inner = compileTemplate(content.trim(), "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2791
+ result += `__snip.${name} = (__s, __c${paramList ? "," + paramList : ""}) => { let h = ''; ${inner} return h; };
2285
2792
  `;
2286
2793
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2287
2794
  } else if (earliest.type === "comp") {
@@ -2318,7 +2825,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2318
2825
  }
2319
2826
  content = out + content.slice(lastSpan);
2320
2827
  }
2321
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
2828
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; }`;
2322
2829
  });
2323
2830
  const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
2324
2831
  if (a.kind === "spread") return `...(${a.value})`;
@@ -2392,6 +2899,33 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2392
2899
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2393
2900
  continue;
2394
2901
  }
2902
+ const dbgMatch = /^@debug\b([\s\S]*)$/.exec(trimmed);
2903
+ if (dbgMatch) {
2904
+ if (before) result += emitChunk(before, acc, closes, scope);
2905
+ const names = dbgMatch[1].trim().replace(/,$/, "");
2906
+ result += names ? `console.log('[rosetack:debug]', { ${names} });
2907
+ ` : `console.log('[rosetack:debug]'); debugger;
2908
+ `;
2909
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2910
+ continue;
2911
+ }
2912
+ const renderMatch = /^@render\s+([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(trimmed);
2913
+ if (renderMatch) {
2914
+ const ahead = new RegExp(`\\{#snippet\\s+${renderMatch[1]}\\b`).test(remaining.substring(earliest.index + earliest.match[0].length));
2915
+ if (ahead) {
2916
+ throw new RoseError(
2917
+ "E-TEMPLATE",
2918
+ `${filePath}: {@render ${renderMatch[1]}} runs before its {#snippet ${renderMatch[1]}} is defined`,
2919
+ { file: filePath, hint: "move the {#snippet} definition above the {@render} call - definitions register as the statement stream reaches them" }
2920
+ );
2921
+ }
2922
+ if (before) result += emitChunk(before, acc, closes, scope);
2923
+ const renderArgs = renderMatch[2].trim();
2924
+ result += `${acc} += ((__snip && __snip.${renderMatch[1]}) ? __snip.${renderMatch[1]}(${scope ?? "null"}, ${closes}${renderArgs ? ", " + renderArgs : ""}) : '');
2925
+ `;
2926
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2927
+ continue;
2928
+ }
2395
2929
  const attrMatch = before.match(/([\w-]+)=\s*$/);
2396
2930
  if (attrMatch) {
2397
2931
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -2520,6 +3054,7 @@ function splitSlots(src) {
2520
3054
  let i = 0;
2521
3055
  let elemDepth = 0;
2522
3056
  let blockDepth = 0;
3057
+ const blockStack = [];
2523
3058
  while (i < src.length) {
2524
3059
  const lt = src.indexOf("<", i);
2525
3060
  const ob = src.indexOf("{#", i);
@@ -2534,8 +3069,14 @@ function splitSlots(src) {
2534
3069
  if (next === ob || next === cb) {
2535
3070
  const close = src.indexOf("}", next);
2536
3071
  const token = src.slice(next, close < 0 ? src.length : close + 1);
2537
- if (next === ob) blockDepth++;
2538
- else blockDepth = Math.max(0, blockDepth - 1);
3072
+ if (next === ob) {
3073
+ const m = /^\{#(\w+)/.exec(token);
3074
+ blockStack.push({ header: token, type: m ? m[1] : "" });
3075
+ blockDepth++;
3076
+ } else {
3077
+ blockDepth = Math.max(0, blockDepth - 1);
3078
+ if (blockStack.length) blockStack.pop();
3079
+ }
2539
3080
  def += token;
2540
3081
  i = next + token.length;
2541
3082
  continue;
@@ -2562,20 +3103,16 @@ function splitSlots(src) {
2562
3103
  }
2563
3104
  if (!selfClosing && !isVoid) elemDepth++;
2564
3105
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
2565
- if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
2566
- 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' });
2567
- }
2568
- if (slotName) {
2569
- const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3106
+ if (slotName && elemDepth === 1 && blockDepth === 0) {
2570
3107
  if (selfClosing || isVoid) {
2571
- named.set(slotName, (named.get(slotName) ?? "") + stripped);
3108
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, ""));
2572
3109
  } else {
2573
3110
  const closeIdx = findClose(src, end, nm[2]);
2574
- if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
3111
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
2575
3112
  const tail = `</${nm[2]}>`;
2576
3113
  const inner = src.slice(end, closeIdx);
2577
3114
  rejectNestedSlot(inner, slotName);
2578
- named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
3115
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "") + inner + tail);
2579
3116
  elemDepth = Math.max(0, elemDepth - 1);
2580
3117
  i = closeIdx + tail.length;
2581
3118
  continue;
@@ -2583,6 +3120,32 @@ function splitSlots(src) {
2583
3120
  i = end;
2584
3121
  continue;
2585
3122
  }
3123
+ if (slotName && blockDepth > 0) {
3124
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3125
+ let lifted = "";
3126
+ for (const b of blockStack) lifted += b.header;
3127
+ lifted += stripped;
3128
+ if (selfClosing || isVoid) {
3129
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3130
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3131
+ i = end;
3132
+ continue;
3133
+ }
3134
+ const closeIdx = findClose(src, end, nm[2]);
3135
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
3136
+ const tail = `</${nm[2]}>`;
3137
+ lifted += src.slice(end, closeIdx) + tail;
3138
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3139
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3140
+ elemDepth = Math.max(0, elemDepth - 1);
3141
+ i = closeIdx + tail.length;
3142
+ continue;
3143
+ }
3144
+ if (slotName) {
3145
+ 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`, {
3146
+ 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'
3147
+ });
3148
+ }
2586
3149
  def += tagText;
2587
3150
  i = end;
2588
3151
  }
@@ -2603,7 +3166,8 @@ var IMG_MIME = {
2603
3166
  ".svg": "image/svg+xml",
2604
3167
  ".ico": "image/x-icon"
2605
3168
  };
2606
- var INLINE_IMG_MAX = 4096;
3169
+ var INLINE_IMG_MAX = 8192;
3170
+ var INLINE_SVG_MAX = 16384;
2607
3171
  function listImageVariants(publicDir, url) {
2608
3172
  const ext = path2.extname(url);
2609
3173
  const base = path2.basename(url, ext);
@@ -2626,6 +3190,27 @@ function listImageVariants(publicDir, url) {
2626
3190
  }
2627
3191
  return out.sort((a, b) => a.width - b.width);
2628
3192
  }
3193
+ var __imgReadCache = /* @__PURE__ */ new Map();
3194
+ function cachedImageRead(filePath2) {
3195
+ let st;
3196
+ try {
3197
+ st = fs3.statSync(filePath2);
3198
+ } catch {
3199
+ return null;
3200
+ }
3201
+ const hit = __imgReadCache.get(filePath2);
3202
+ if (hit && hit.mtime === st.mtimeMs) return { buffer: hit.buffer, dims: hit.dims };
3203
+ let buffer;
3204
+ try {
3205
+ buffer = fs3.readFileSync(filePath2);
3206
+ } catch {
3207
+ return null;
3208
+ }
3209
+ const dims = readImageSize(filePath2);
3210
+ const entry = { mtime: st.mtimeMs, buffer, dims };
3211
+ __imgReadCache.set(filePath2, entry);
3212
+ return { buffer, dims: entry.dims };
3213
+ }
2629
3214
  function inlineImages(template, publicDir) {
2630
3215
  return template.replace(IMG_RE, (tag) => {
2631
3216
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
@@ -2634,17 +3219,15 @@ function inlineImages(template, publicDir) {
2634
3219
  const mime = IMG_MIME[ext];
2635
3220
  if (!mime) return tag;
2636
3221
  const rel = src[1].replace(/^\/public(?=\/)/, "");
2637
- const filePath = path2.join(publicDir, rel);
2638
- let file;
2639
- try {
2640
- file = fs3.readFileSync(filePath);
2641
- } catch {
2642
- return tag;
2643
- }
3222
+ const filePath2 = path2.join(publicDir, rel);
3223
+ const read = cachedImageRead(filePath2);
3224
+ if (!read) return tag;
3225
+ const file = read.buffer;
2644
3226
  const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
2645
- const dims = authorDims ? null : readImageSize(filePath);
3227
+ const dims = authorDims ? null : read.dims;
2646
3228
  const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
2647
- if (file.length > INLINE_IMG_MAX) {
3229
+ const inlineMax = ext === ".svg" ? INLINE_SVG_MAX : INLINE_IMG_MAX;
3230
+ if (file.length > inlineMax) {
2648
3231
  const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
2649
3232
  const variants = hasSS ? [] : listImageVariants(publicDir, rel);
2650
3233
  if (!variants.length) return withDims(tag);
@@ -2685,7 +3268,7 @@ function compileSlot(acc) {
2685
3268
  return `${acc} += String(children);
2686
3269
  `;
2687
3270
  }
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';`;
3271
+ 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';`;
2689
3272
  var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
2690
3273
  function propsCode(props) {
2691
3274
  if (props.length === 0) return "";
@@ -2855,7 +3438,7 @@ async function buildProject(root, outDir) {
2855
3438
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
2856
3439
  );
2857
3440
  const compiled = await Promise.all(
2858
- files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
3441
+ files.map((f, i) => compileComponentMemo(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
2859
3442
  );
2860
3443
  const importsOf = /* @__PURE__ */ new Map();
2861
3444
  files.forEach((_, i) => {
@@ -3060,11 +3643,12 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
3060
3643
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
3061
3644
  return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
3062
3645
  }).join(",\n ");
3646
+ const appUsesAuth = compiled.some((c) => c.usesrosetackAuth);
3063
3647
  const serverEntry = `
3064
3648
  ${serverImports}
3065
3649
  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';
3650
+ ${appUsesAuth ? "import crypto from 'node:crypto';" : "// no route references __rosetackAuth: the node:crypto auth helpers are omitted, keeping the bundle edge-loadable"}
3651
+ import { setState, persistState, clearRequestState, isolateRender, serializeState, resetRequestContext, installContextStore, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
3068
3652
  ${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
3069
3653
  // module to import - the runners below stay no-ops and the servers call them
3070
3654
  // unconditionally (one code path, no flags to keep in sync).
@@ -3121,6 +3705,7 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
3121
3705
  });
3122
3706
  }
3123
3707
 
3708
+
3124
3709
  // (the cross-machine seam): the cluster relay above covers ONE machine.
3125
3710
  export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
3126
3711
  setStoreTransport(send);
@@ -3141,6 +3726,11 @@ export const routeParams = {
3141
3726
 
3142
3727
  // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
3143
3728
  export const dynamicRoutes = [
3729
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal || compiled[i].needsClient).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3730
+ ];
3731
+
3732
+ // Routes that the prerender function should skip (not bake into static files).
3733
+ export const prerenderSkipRoutes = [
3144
3734
  ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3145
3735
  ];
3146
3736
 
@@ -3164,6 +3754,8 @@ const __dynCache = new Map();
3164
3754
  export function invalidateRenderCache(): void {
3165
3755
  __dynCache.clear();
3166
3756
  }
3757
+
3758
+
3167
3759
  // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3168
3760
  const __kvStore = new Map<string, { v: unknown; exp: number }>();
3169
3761
  // Content collections: src/content/<coll>/*.md scanned once at build time,
@@ -3277,6 +3869,7 @@ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<
3277
3869
  });
3278
3870
  }
3279
3871
  globalThis.__rosetackExtras = { v, jobs, sse };
3872
+ ${appUsesAuth ? `
3280
3873
  const auth = {
3281
3874
  hashPassword(password: string): string {
3282
3875
  const salt = crypto.randomBytes(16).toString("hex");
@@ -3318,6 +3911,7 @@ const auth = {
3318
3911
  },
3319
3912
  };
3320
3913
  globalThis.__rosetackAuth = auth;
3914
+ ` : "// __rosetackAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
3321
3915
 
3322
3916
  export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3323
3917
  const hit = kv.get(key);
@@ -3548,7 +4142,15 @@ function extractHead(rendered) {
3548
4142
 
3549
4143
  // Form: the submitted FormData of a progressive-enhancement POST.
3550
4144
  export async function renderPage(pathname, form) {
4145
+ // Renders DO overlap in one process: prod-server warms every route in the background at startup.
4146
+ return isolateRender(() => renderPageIsolated(pathname, form));
4147
+ }
4148
+
4149
+ async function renderPageIsolated(pathname, form) {
3551
4150
  clearRequestState();
4151
+ // Cold-start readiness gate (oboext #8): await the app's published DB-ready promise before any $data() read.
4152
+ const appReady = globalThis.__rosetackAppReady;
4153
+ if (appReady) await appReady;
3552
4154
  for (const route of routes) {
3553
4155
  if (matchRoute(route.pattern, pathname)) {
3554
4156
  const patternParts = route.pattern.split('/');
@@ -3717,7 +4319,15 @@ export async function handleApi(method, pathname, request) {
3717
4319
 
3718
4320
  // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
3719
4321
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4322
+ // Isolated for the same reason as renderPage: a streaming render awaits inside route.render()
4323
+ return isolateRender(() => renderPageStreamIsolated(pathname, write, shellOpen, clientTag));
4324
+ }
4325
+
4326
+ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
3720
4327
  clearRequestState();
4328
+ // Cold-start readiness gate (oboext #8): same contract as renderPage \u2014 await the app's published DB-ready promise before streaming the shell.
4329
+ const appReady = globalThis.__rosetackAppReady;
4330
+ if (appReady) await appReady;
3721
4331
  for (const route of routes) {
3722
4332
  if (matchRoute(route.pattern, pathname)) {
3723
4333
  const patternParts = route.pattern.split('/');
@@ -3774,6 +4384,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3774
4384
  }
3775
4385
  return 404;
3776
4386
  }
4387
+ // Prevent tree-shaking of invalidateRenderCache (called from prod-server.ts / edge.ts on non-GET writes).
4388
+ void invalidateRenderCache;
4389
+
4390
+ // Same reason, for the per-request context store: prod-server.ts installs an AsyncLocalStorage adapter.
4391
+ export { installContextStore };
3777
4392
  `;
3778
4393
  try {
3779
4394
  const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
@@ -3867,7 +4482,7 @@ reportVitals();
3867
4482
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
3868
4483
  const clientEntry = `
3869
4484
  ${clientImports}
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';
4485
+ 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';
3871
4486
 
3872
4487
  // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
3873
4488
  setLocales(${clientLocalesJson}, '${defaultLocale}');
@@ -4085,11 +4700,19 @@ async function postForm(body, container, pathname) {
4085
4700
  // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
4086
4701
  export async function $action(name, e) {
4087
4702
  if (e && e.preventDefault) e.preventDefault();
4703
+ // F34: the pending flag is ordinary signal state - {#if $actionPending()}
4704
+ // disables a submit button while the action is in flight, reactively.
4705
+ const [__rvPending, __rvSetPending] = state('actionPending', false);
4706
+ __rvSetPending(true);
4088
4707
  const body = new FormData();
4089
4708
  body.append('__action', name);
4090
4709
  // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
4091
4710
  const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
4092
- return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4711
+ try {
4712
+ return await postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4713
+ } finally {
4714
+ __rvSetPending(false);
4715
+ }
4093
4716
  }
4094
4717
  // 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
4718
  setActionDispatcher($action);
@@ -4358,12 +4981,12 @@ function isAncestorDir(layoutPath, pagePath) {
4358
4981
  const pageDir = path2.dirname(pagePath);
4359
4982
  return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
4360
4983
  }
4361
- function getRouteInfo(filePath, root) {
4984
+ function getRouteInfo(filePath2, root) {
4362
4985
  const pagesDir = path2.join(root, "src", "pages");
4363
- const relative3 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
4986
+ const relative3 = path2.relative(pagesDir, filePath2).replace(/\\/g, "/");
4364
4987
  const withoutExt = relative3.replace(/\.rose$/, "");
4365
4988
  const base = path2.posix.basename(withoutExt);
4366
- const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
4989
+ const isComponent = filePath2.replace(/\\/g, "/").includes("/src/components/");
4367
4990
  const isLayout = !isComponent && base === "_layout";
4368
4991
  const isNotFound = !isComponent && (base === "404" || base === "_notfound");
4369
4992
  const isError = !isComponent && base === "500";
@@ -4387,7 +5010,7 @@ function getRouteInfo(filePath, root) {
4387
5010
  routePath = "/" + routeParts.join("/");
4388
5011
  }
4389
5012
  return {
4390
- filePath,
5013
+ filePath: filePath2,
4391
5014
  routePath,
4392
5015
  pattern: routePath,
4393
5016
  paramNames: parts.flatMap((p) => {
@@ -4468,18 +5091,39 @@ if (!__app) {
4468
5091
  }
4469
5092
  // Native View Transitions around client-side navigation (progressive:
4470
5093
  // browsers without the API navigate normally, no polyfill, no CSS required).
4471
- function __navigate(pathname) {
4472
- const paint = () => start(__app, pathname);
5094
+ // F35: stash the CURRENT entry's scroll position into its history state
5095
+ // before a new push - the browser only restores scroll on full page loads; a
5096
+ // pjax swap would land wherever the swap left it.
5097
+ function __saveScroll() {
5098
+ try {
5099
+ const s = history.state || {};
5100
+ history.replaceState(Object.assign({}, s, { __rosetackScroll: window.scrollY }), '');
5101
+ } catch (e) { /* history state unavailable (file:// edge): best effort */ }
5102
+ }
5103
+ function __navigate(pathname, restore) {
5104
+ const paint = () => {
5105
+ const p = start(__app, pathname);
5106
+ if (restore) {
5107
+ // back/forward: restore the entry's scroll (top when it has none)
5108
+ const s = history.state || {};
5109
+ const y = typeof s.__rosetackScroll === 'number' ? s.__rosetackScroll : 0;
5110
+ return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
5111
+ }
5112
+ // a fresh navigation starts at the top, like a full page load
5113
+ window.scrollTo(0, 0);
5114
+ return p;
5115
+ };
4473
5116
  if (document.startViewTransition) {
4474
5117
  return document.startViewTransition(paint).updateCallbackDone;
4475
5118
  }
4476
5119
  return paint();
4477
5120
  }
4478
- window.addEventListener('popstate', () => __navigate(window.location.pathname));
5121
+ window.addEventListener('popstate', () => __navigate(window.location.pathname, true));
4479
5122
  document.addEventListener('click', (e) => {
4480
5123
  const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
4481
5124
  if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
4482
5125
  e.preventDefault();
5126
+ __saveScroll();
4483
5127
  history.pushState(null, '', a.getAttribute('href'));
4484
5128
  __navigate(window.location.pathname);
4485
5129
  }
@@ -4586,6 +5230,12 @@ function bootstrap() {
4586
5230
  return BOOTSTRAP_CACHE;
4587
5231
  }
4588
5232
  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'`;
5233
+ var BASELINE_SECURITY_HEADERS = {
5234
+ "x-content-type-options": "nosniff",
5235
+ "x-frame-options": "DENY",
5236
+ "referrer-policy": "strict-origin-when-cross-origin",
5237
+ "permissions-policy": "accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), fullscreen=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), serial=(), usb=(), xr-spatial-tracking=()"
5238
+ };
4589
5239
  var cspCache = null;
4590
5240
  var EXTERNAL_BOOTSTRAP_CACHE = null;
4591
5241
  function externalBootstrap() {
@@ -4619,7 +5269,11 @@ function mintNonce() {
4619
5269
  return btoa(raw);
4620
5270
  }
4621
5271
  function securityHeaders(client, nonce = "") {
4622
- if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
5272
+ const headers = { ...BASELINE_SECURITY_HEADERS };
5273
+ if (nonce) {
5274
+ headers["Content-Security-Policy"] = `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}`;
5275
+ return headers;
5276
+ }
4623
5277
  if (!cspCache || cspCache.for !== client) {
4624
5278
  const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(externalBootstrap(), "utf-8").digest("base64")}'`;
4625
5279
  cspCache = {
@@ -4627,7 +5281,8 @@ function securityHeaders(client, nonce = "") {
4627
5281
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`
4628
5282
  };
4629
5283
  }
4630
- return { "Content-Security-Policy": cspCache.value };
5284
+ headers["Content-Security-Policy"] = cspCache.value;
5285
+ return headers;
4631
5286
  }
4632
5287
  var FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
4633
5288
  var STYLES = `
@@ -4796,6 +5451,9 @@ Rules the compiler enforces (breaking one fails the build):
4796
5451
  $persist is $state backed by localStorage: let theme = $persist('light') \u2014
4797
5452
  the value survives reloads (SSR renders the initial; the client re-seeds
4798
5453
  from storage at boot).
5454
+ $derived is computed state: let sq = $derived(n * n) \u2014 a read-only getter
5455
+ that recomputes from the signals its expression reads; $setState on it is a
5456
+ build error. Top-level only (in a function body, use a plain const arrow).
4799
5457
  - A route param (pages/blog/[id].rose) is read as state too: declare it
4800
5458
  (\`let id = $state('1')\`) and read id() - the server overwrites the default
4801
5459
  with the URL's value, and export const params = { id: [...] } bakes those
@@ -4804,7 +5462,9 @@ Rules the compiler enforces (breaking one fails the build):
4804
5462
  synchronously inside its parent. Fetch in the page or the middleware and pass
4805
5463
  the value down as a prop.
4806
5464
  - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
4807
- trusted-HTML escape hatch - use it only for content you control. {@const name
5465
+ trusted-HTML escape hatch - use it only for content you control.
5466
+ {@debug a, b} logs those values (as they are AT that point in the render);
5467
+ bare {@debug} also breaks into the debugger. Neither emits HTML. {@const name
4808
5468
  = expr} is a template-level binding: it evaluates once and is visible to every
4809
5469
  expression that follows in the same scope (use it to name a computed value
4810
5470
  inside {#each} without re-evaluating, or to shorten a long expression).
@@ -4816,9 +5476,50 @@ Rules the compiler enforces (breaking one fails the build):
4816
5476
  {#key expr}...{/key} (re-creates the
4817
5477
  body whenever expr changes), {#boundary}...{:fallback}...{/boundary} (the
4818
5478
  fallback renders on a throw; {$boundaryError()?.message} reads the caught
4819
- error), {#island name="x"}...{/island} (partial hydration) and
5479
+ error), {#island name="x"}...{/island} (partial hydration) and
4820
5480
  {#defer}...{/defer} (progressive render; hold=N keeps the skeleton up at
4821
- least N ms). {:else} / {:else if} must sit inside an {#if} block.
5481
+ least N ms), and {#await promise}...{:then value}...{:catch error}...{/await}
5482
+ (the server renders the pending branch, the client flips to the resolved
5483
+ value once the promise settles, or to the caught error if it rejects; the
5484
+ {:then} / {:catch} names are in scope only inside their branch, and {:catch}
5485
+ is optional). There is NO {:else} branch of its own: a bare {:else} with no
5486
+ block around it is a build error - inside {#each} it means "the list is
5487
+ empty", inside {#if} it is the final else.
5488
+ - Keyed each: {#each todos() as t (t.id)} \u2014 the key makes wire() reconcile:
5489
+ rows whose key and rendered html are unchanged KEEP their DOM nodes (focus,
5490
+ unbound input text, loaded images survive; reorders become moves). Rows
5491
+ with handlers/actions/refs/transitions/components rebuild fresh. The key
5492
+ needs a named item \u2014 {#each xs as x (x.id)}, not a destructuring pattern.
5493
+ - Snippets: {#snippet name(a, b)}...{/snippet} defines a parameterized
5494
+ fragment; {@render name(x, y)} calls it and inlines the markup. Define the
5495
+ snippet BEFORE the render call (top-down execution order \u2014 the compiler
5496
+ rejects the reverse). Reactive content inside works per call.
5497
+ - Transitions: transition:fade (both directions), in:fade (enter only),
5498
+ out:fade (mounts at rest, leave only). Built-ins: fade, slide, fly, zoom,
5499
+ slide-up/down/left/right, scale, spin, blur, stagger; params via
5500
+ transition:fade={300} or transition:fade={duration: 300} (the trailing
5501
+ number wins), or the bare name (300 ms default). Custom: register
5502
+ globalThis.__rosetackTransitions.NAME = (el, duration, phase) => cleanup? \u2014
5503
+ a transition:NAME that is not a built-in falls through to it (phase
5504
+ 'both'/'in'/'out'; built-ins always win).
5505
+ - $actionPending() is true while a server action is in flight: use it to
5506
+ disable the submit button reactively ({#if $actionPending()}).
5507
+ - $setState('k', (x) => x + 1) supports a FUNCTIONAL UPDATER: when the new
5508
+ value is a function it receives the current value and returns the next one.
5509
+ (State that must literally store a function cannot use this form.)
5510
+ - <input type="number" bind:value={n}>: clearing the field stores 'null'
5511
+ (NOT 'NaN') so bound math (n() + 1) stays clean instead of going NaN. The
5512
+ empty field renders as '' on write-back.
5513
+ - Scroll listeners are passive by default (they cannot preventDefault), which
5514
+ keeps the constant scroll event off the main-thread critical path.
5515
+ - Scoped CSS: component <style> rules scope under the component. Use
5516
+ :global(X) to unscope one compound (.card :global(.md)); a selector made
5517
+ only of :global(...) groups emits fully unscoped (:global(body){...}).
5518
+ - animate:flip={duration: 300} (or animate:flip={300}) passes a DURATION
5519
+ param to the FLIP animation; the trailing number is parsed even though object
5520
+ params carry their own colons. Registered animation names work the same way.
5521
+ - <select multiple bind:value={arr}> binds an ARRAY of selected values
5522
+ (declare $state([])); state changes drive option.selected properties.
4822
5523
  - Two-way binding: <input bind:value={q}> / <input type="checkbox"
4823
5524
  bind:checked={on}> / <select bind:value={s}>. Numeric inputs coerce through
4824
5525
  valueAsNumber. Radio groups: <input type="radio" value="free"
@@ -4836,7 +5537,10 @@ Rules the compiler enforces (breaking one fails the build):
4836
5537
  update half re-runs when text changes; the param arrives JSON-parsed.
4837
5538
  - A <slot> with attributes is a named slot and must declare its name:
4838
5539
  <slot name="row" item={post} />. A named slot must be a DIRECT child of the
4839
- component tag - never inside another element or an {#if}/{#each} block.
5540
+ component tag, OR wrapped by a single {#if}/{#each}/{#boundary} block (F21:
5541
+ the block is reconstructed around the slot and the lifted content reads the
5542
+ parent scope, so a gated slot still projects). A named slot inside a plain
5543
+ wrapper element (a <div>, not a block) is still a build error.
4840
5544
  - Every component tag needs its matching close tag (or self-closes with />).
4841
5545
  - In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
4842
5546
  through. A <style> inside <head> is document CSS; a <style> in the body is
@@ -4907,12 +5611,45 @@ window., timers) belongs in onMount, and anything the predicate cannot see
4907
5611
  (inline on* attributes, javascript: URLs, eval) is reported by the build.
4908
5612
  `;
4909
5613
 
4910
- // src/cli/index.ts
4911
- import { Readable } from "stream";
4912
-
4913
5614
  // src/cli/edge.ts
4914
5615
  import { pathToFileURL as pathToFileURL2 } from "url";
4915
5616
  import { join as join3 } from "path";
5617
+
5618
+ // src/cli/shutdown.ts
5619
+ var shutdownHooks = [];
5620
+ var draining = null;
5621
+ globalThis.__rosetackOnShutdown = onShutdown;
5622
+ globalThis.__rosetackRunShutdownHooks = runShutdownHooks;
5623
+ function onShutdown(name, fn) {
5624
+ const hook = { name, fn };
5625
+ shutdownHooks.push(hook);
5626
+ return () => {
5627
+ const at = shutdownHooks.indexOf(hook);
5628
+ if (at !== -1) shutdownHooks.splice(at, 1);
5629
+ };
5630
+ }
5631
+ function runShutdownHooks(reason) {
5632
+ if (draining) return draining;
5633
+ draining = (async () => {
5634
+ const results = [];
5635
+ for (const hook of shutdownHooks.slice()) {
5636
+ try {
5637
+ await hook.fn();
5638
+ results.push({ name: hook.name, ok: true });
5639
+ } catch (err) {
5640
+ const message = err instanceof Error ? err.message : String(err);
5641
+ results.push({ name: hook.name, ok: false, error: message });
5642
+ console.error(`[rosetack] shutdown hook ${hook.name} failed (${reason}):`, message);
5643
+ }
5644
+ }
5645
+ return results;
5646
+ })().finally(() => {
5647
+ draining = null;
5648
+ });
5649
+ return draining;
5650
+ }
5651
+
5652
+ // src/cli/edge.ts
4916
5653
  function crossSiteWrite(request) {
4917
5654
  const m = request.method;
4918
5655
  if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
@@ -4967,7 +5704,8 @@ async function createEdgeHandler(outDir, preloaded) {
4967
5704
  }
4968
5705
  const pageHeaders2 = (pathname, nonce = "") => {
4969
5706
  const headers = {};
4970
- if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
5707
+ for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
5708
+ if (!headers["cache-control"]) headers["cache-control"] = "no-cache";
4971
5709
  const own = mod.headersFor?.(pathname);
4972
5710
  if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
4973
5711
  return headers;
@@ -4991,11 +5729,18 @@ async function createEdgeHandler(outDir, preloaded) {
4991
5729
  if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
4992
5730
  }
4993
5731
  if (mod.isApi(pathname)) {
5732
+ if (request.method !== "GET") {
5733
+ const fn = mod.invalidateRenderCache;
5734
+ if (typeof fn === "function") fn();
5735
+ }
4994
5736
  const apiRes = await mod.handleApi(request.method, pathname, request);
4995
5737
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
4996
5738
  }
4997
5739
  const form = request.method === "POST" ? await request.formData() : void 0;
4998
- if (form) mod.invalidateRenderCache?.();
5740
+ if (form) {
5741
+ const fn = mod.invalidateRenderCache;
5742
+ if (typeof fn === "function") fn();
5743
+ }
4999
5744
  if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
5000
5745
  const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
5001
5746
  const streamed = new Response(null, {
@@ -5031,6 +5776,16 @@ async function createEdgeHandler(outDir, preloaded) {
5031
5776
  };
5032
5777
  }
5033
5778
 
5779
+ // src/cli/origin.ts
5780
+ function requestOrigin(req, fallbackPort) {
5781
+ const rawProto = String(req.headers?.["x-forwarded-proto"] || "");
5782
+ const proto = rawProto.split(",")[0].trim();
5783
+ const scheme = proto === "https" || proto === "http" ? proto : "http";
5784
+ const rawHost = String(req.headers?.["x-forwarded-host"] || "");
5785
+ const host = rawHost.split(",")[0].trim() || req.headers?.host || `localhost:${fallbackPort}`;
5786
+ return `${scheme}://${host}`;
5787
+ }
5788
+
5034
5789
  // src/cli/index.ts
5035
5790
  function pickEncoding(req) {
5036
5791
  const ae = req.headers["accept-encoding"] || "";
@@ -5054,6 +5809,9 @@ function sendHtml(req, res, status, html, extraHeaders) {
5054
5809
  res.statusCode = status;
5055
5810
  res.setHeader("Content-Type", "text/html; charset=utf-8");
5056
5811
  res.setHeader("Vary", "Accept-Encoding");
5812
+ if (!Object.keys(extraHeaders || {}).some((k) => k.toLowerCase() === "cache-control")) {
5813
+ res.setHeader("Cache-Control", "no-cache");
5814
+ }
5057
5815
  if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
5058
5816
  let hash = 2166136261;
5059
5817
  for (let i = 0; i < html.length; i++) {
@@ -5288,7 +6046,7 @@ async function prerender(routes) {
5288
6046
  console.log(`prerendered ${routePath} -> ${path4.relative(process.cwd(), path4.join(routeDir, "index.html"))}`);
5289
6047
  };
5290
6048
  for (const info of routes) {
5291
- if (ssrModule.dynamicRoutes.includes(info.routePath)) {
6049
+ if ((ssrModule.prerenderSkipRoutes ?? []).includes(info.routePath)) {
5292
6050
  console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
5293
6051
  continue;
5294
6052
  }
@@ -5359,23 +6117,23 @@ function nonceFor(ssrModule, pathname) {
5359
6117
  return ssrModule.cspNonce?.(pathname) ? mintNonce() : "";
5360
6118
  }
5361
6119
  var isrBusy = /* @__PURE__ */ new Set();
5362
- function revalidateInBackground(routePath, filePath) {
5363
- if (isrBusy.has(filePath)) return;
5364
- isrBusy.add(filePath);
6120
+ function revalidateInBackground(routePath, filePath2) {
6121
+ if (isrBusy.has(filePath2)) return;
6122
+ isrBusy.add(filePath2);
5365
6123
  void (async () => {
5366
6124
  try {
5367
6125
  const ssrModule = await loadServer();
5368
6126
  ssrModule.setQuery?.({});
5369
6127
  const page = await ssrModule.renderPage(routePath);
5370
6128
  if (page.status === 200) {
5371
- await fs5.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
5372
- fileCache.delete(filePath);
6129
+ await fs5.promises.writeFile(filePath2, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
6130
+ fileCache.delete(filePath2);
5373
6131
  console.log(`rosetack: revalidated ${routePath} in the background`);
5374
6132
  }
5375
6133
  } catch (err) {
5376
6134
  console.error("rosetack: background revalidation failed for", routePath, err instanceof Error ? err.message : err);
5377
6135
  } finally {
5378
- isrBusy.delete(filePath);
6136
+ isrBusy.delete(filePath2);
5379
6137
  }
5380
6138
  })();
5381
6139
  }
@@ -5421,6 +6179,11 @@ function crossSiteWrite2(req) {
5421
6179
  }
5422
6180
  return null;
5423
6181
  }
6182
+ function writeAccessLine(req, res, bytes, tag, startedNs) {
6183
+ const ms = Number(process.hrtime.bigint() - (startedNs ?? process.hrtime.bigint())) / 1e6;
6184
+ const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1e3).toFixed(0)}us`;
6185
+ console.log(`${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ""} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
6186
+ }
5424
6187
  function withAccessLog(handler, tag) {
5425
6188
  return (req, res) => {
5426
6189
  const started = process.hrtime.bigint();
@@ -5435,11 +6198,7 @@ function withAccessLog(handler, tag) {
5435
6198
  if (chunk) bytes += Buffer.byteLength(chunk);
5436
6199
  return end(chunk, ...rest);
5437
6200
  };
5438
- res.on("finish", () => {
5439
- const ms = Number(process.hrtime.bigint() - started) / 1e6;
5440
- const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1e3).toFixed(0)}us`;
5441
- console.log(`${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ""} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
5442
- });
6201
+ res.on("finish", () => writeAccessLine(req, res, bytes, tag, started));
5443
6202
  handler(req, res);
5444
6203
  };
5445
6204
  }
@@ -5690,29 +6449,29 @@ function serveStatic(dir, isr = false, dev2 = false) {
5690
6449
  }
5691
6450
  let safe = path4.normalize(pathnameOf(req.url || "/")).replace(/^(\.\.(\/)?)+/, "");
5692
6451
  if (safe === "\\" || safe === "/") safe = "/";
5693
- let filePath = path4.join(dir, safe);
5694
- if (!fs5.existsSync(filePath) && ASSET_EXT.has(path4.extname(safe).toLowerCase())) {
6452
+ let filePath2 = path4.join(dir, safe);
6453
+ if (!fs5.existsSync(filePath2) && ASSET_EXT.has(path4.extname(safe).toLowerCase())) {
5695
6454
  const pubFile = path4.join(dir, "public", safe);
5696
- if (fs5.existsSync(pubFile)) filePath = pubFile;
6455
+ if (fs5.existsSync(pubFile)) filePath2 = pubFile;
5697
6456
  }
5698
- if (fs5.existsSync(filePath) && fs5.statSync(filePath).isDirectory()) {
5699
- filePath = path4.join(filePath, "index.html");
6457
+ if (fs5.existsSync(filePath2) && fs5.statSync(filePath2).isDirectory()) {
6458
+ filePath2 = path4.join(filePath2, "index.html");
5700
6459
  }
5701
6460
  if (/\.(?:br|gz)$/i.test(safe)) {
5702
- const base = filePath.replace(/\.(?:br|gz)$/i, "");
5703
- if (fs5.existsSync(base)) filePath = base;
6461
+ const base = filePath2.replace(/\.(?:br|gz)$/i, "");
6462
+ if (fs5.existsSync(base)) filePath2 = base;
5704
6463
  }
5705
6464
  const isAsset = ASSET_EXT.has(path4.extname(safe).toLowerCase());
5706
6465
  const isDynamic = !isAsset && ssrModule.dynamicRoutes?.includes(pathnameOf(req.url));
5707
- if (!isDynamic && fs5.existsSync(filePath) && fs5.statSync(filePath).isFile()) {
5708
- const st = fs5.statSync(filePath);
6466
+ if (!isDynamic && fs5.existsSync(filePath2) && fs5.statSync(filePath2).isFile()) {
6467
+ const st = fs5.statSync(filePath2);
5709
6468
  const rev = isAsset ? void 0 : (ssrModule.revalidate || []).find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
5710
6469
  if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1e3) {
5711
- revalidateInBackground(pathnameOf(req.url), filePath);
6470
+ revalidateInBackground(pathnameOf(req.url), filePath2);
5712
6471
  }
5713
- let entry = fileCache.get(filePath);
6472
+ let entry = fileCache.get(filePath2);
5714
6473
  if (!entry || entry.mtimeMs !== st.mtimeMs) {
5715
- const raw = fs5.readFileSync(filePath);
6474
+ const raw = fs5.readFileSync(filePath2);
5716
6475
  entry = {
5717
6476
  mtimeMs: st.mtimeMs,
5718
6477
  raw,
@@ -5720,9 +6479,9 @@ function serveStatic(dir, isr = false, dev2 = false) {
5720
6479
  gzip: zlib.gzipSync(raw, { level: 9 }),
5721
6480
  etag: `W/"${st.size}-${st.mtimeMs}"`
5722
6481
  };
5723
- fileCache.set(filePath, entry);
6482
+ fileCache.set(filePath2, entry);
5724
6483
  }
5725
- const ext = path4.extname(filePath);
6484
+ const ext = path4.extname(filePath2);
5726
6485
  const types = {
5727
6486
  ".html": "text/html",
5728
6487
  ".js": "application/javascript",
@@ -5854,21 +6613,26 @@ function queryOf(url) {
5854
6613
  }
5855
6614
  function listenFree(server, port, onReady) {
5856
6615
  const attempt = (p) => {
5857
- const onError = (err) => {
6616
+ const cleanup = () => {
5858
6617
  server.removeListener("error", onError);
6618
+ server.removeListener("listening", onListening);
6619
+ };
6620
+ const onError = (err) => {
6621
+ cleanup();
5859
6622
  if (err && err.code === "EADDRINUSE" && p - port < 20) {
5860
- console.log(`\u{1F339} port ${p} is in use - trying ${p + 1}`);
5861
6623
  attempt(p + 1);
5862
6624
  return;
5863
6625
  }
5864
6626
  console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
5865
6627
  process.exit(1);
5866
6628
  };
5867
- server.once("error", onError);
5868
- server.listen(p, () => {
5869
- server.removeListener("error", onError);
6629
+ const onListening = () => {
6630
+ cleanup();
5870
6631
  onReady(p);
5871
- });
6632
+ };
6633
+ server.once("error", onError);
6634
+ server.once("listening", onListening);
6635
+ server.listen(p);
5872
6636
  };
5873
6637
  attempt(port);
5874
6638
  }
@@ -5942,8 +6706,8 @@ async function serve() {
5942
6706
  }
5943
6707
  const cluster = (await import("node:cluster")).default;
5944
6708
  cluster.schedulingPolicy = cluster.SCHED_RR;
5945
- const os = await import("node:os");
5946
- const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
6709
+ const os2 = await import("node:os");
6710
+ const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os2.cpus().length);
5947
6711
  if (cluster.isPrimary) {
5948
6712
  const port = await freePort(Number(process.env.PORT) || 3e3);
5949
6713
  for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
@@ -6044,6 +6808,8 @@ async function serve() {
6044
6808
  return dynRouteSet;
6045
6809
  };
6046
6810
  const server = http.createServer(async (req, res) => {
6811
+ let bytesWritten = 0;
6812
+ const started = process.hrtime.bigint();
6047
6813
  try {
6048
6814
  if ((req.method === "GET" || req.method === "HEAD") && dynRoutesOf().has(pathnameOf(req.url || "/"))) {
6049
6815
  const handle = await edgeReady;
@@ -6053,8 +6819,9 @@ async function serve() {
6053
6819
  } catch {
6054
6820
  }
6055
6821
  }
6056
- const url = "http://" + (req.headers.host || `localhost:${PORT}`) + (req.url || "/");
6822
+ const url = requestOrigin(req, PORT) + (req.url || "/");
6057
6823
  const response = await handle(new Request(url, { method: req.method, headers: req.headers }));
6824
+ const access = () => writeAccessLine(req, res, bytesWritten, `w${process.pid}`, started);
6058
6825
  res.statusCode = response.status;
6059
6826
  response.headers.forEach((v, k) => res.setHeader(k, v));
6060
6827
  const htmlDoc = (response.headers.get("content-type") ?? "").startsWith("text/html");
@@ -6064,7 +6831,9 @@ async function serve() {
6064
6831
  const etag = 'W/"' + createHash2("sha1").update(raw).digest("base64url").slice(0, 24) + '"';
6065
6832
  if (req.headers["if-none-match"] === etag) {
6066
6833
  res.statusCode = 304;
6834
+ bytesWritten = 0;
6067
6835
  res.end();
6836
+ access();
6068
6837
  return;
6069
6838
  }
6070
6839
  const body = compress(enc, raw);
@@ -6072,12 +6841,19 @@ async function serve() {
6072
6841
  res.setHeader("Content-Encoding", enc);
6073
6842
  res.setHeader("Content-Length", String(body.length));
6074
6843
  res.end(body);
6844
+ bytesWritten = body.length;
6845
+ access();
6075
6846
  return;
6076
6847
  }
6077
6848
  if (response.body) {
6078
- Readable.fromWeb(response.body).pipe(res);
6849
+ const raw = Buffer.from(await response.arrayBuffer());
6850
+ bytesWritten = raw.length;
6851
+ res.end(raw);
6852
+ access();
6079
6853
  } else {
6080
6854
  res.end();
6855
+ bytesWritten = 0;
6856
+ access();
6081
6857
  }
6082
6858
  return;
6083
6859
  }
@@ -6109,7 +6885,9 @@ async function serve() {
6109
6885
  console.error("rosetack: plugin", p.name, "onShutdown failed:", err instanceof Error ? err.message : err);
6110
6886
  }
6111
6887
  }
6112
- server.close(() => process.exit(0));
6888
+ server.close(() => {
6889
+ void runShutdownHooks("worker signal").finally(() => process.exit(0));
6890
+ });
6113
6891
  server.closeIdleConnections?.();
6114
6892
  setTimeout(() => process.exit(0), 5e3).unref();
6115
6893
  };