rosetack 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-cli/compiler.mjs +1391 -131
- package/dist-cli/edge.mjs +45 -10
- package/dist-cli/rosetack.mjs +1865 -254
- package/dist-cli/runtime.mjs +194 -13
- package/dist-cli/test.mjs +1466 -175
- package/package.json +1 -1
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +9 -1
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +149 -7
- package/src/cli/prod-server.ts +324 -0
- package/src/cli/prompt.ts +47 -19
- package/src/cli/shell.ts +39 -6
- package/src/compiler/index.ts +1188 -64
- package/src/runtime/index.ts +215 -13
package/src/compiler/index.ts
CHANGED
|
@@ -12,14 +12,14 @@ const COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
|
12
12
|
const TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
13
13
|
const HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
14
14
|
const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
15
|
-
const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
15
|
+
const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
|
|
16
16
|
const DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
17
17
|
const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
18
18
|
const EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
|
|
19
|
-
const SLOT_RE = /<slot\s
|
|
19
|
+
const SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
|
|
20
20
|
/** A named slot: `<slot name="row" item={post} />` . The lookahead
|
|
21
21
|
* keeps the plain `<slot />` out of it - that one is the default slot. */
|
|
22
|
-
const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)
|
|
22
|
+
const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
|
|
23
23
|
|
|
24
24
|
// Encode a named slot tag as the template expression `__slot('row', [['item', (post)]])` - array pairs.
|
|
25
25
|
function encodeSlotCall(attrs: string): string {
|
|
@@ -55,6 +55,8 @@ export interface CompileResult {
|
|
|
55
55
|
usesContext?: boolean;
|
|
56
56
|
/** the component exports `revalidate = N` (ISR window in seconds) */
|
|
57
57
|
revalidate?: number;
|
|
58
|
+
/** the component exports `cache = N` (per-request render memo, seconds) */
|
|
59
|
+
cache?: number;
|
|
58
60
|
/** the component exports `csr = false` (document ships without the client bundle) */
|
|
59
61
|
csr?: boolean;
|
|
60
62
|
/**
|
|
@@ -147,7 +149,7 @@ export interface RouteInfo {
|
|
|
147
149
|
|
|
148
150
|
interface Decl {
|
|
149
151
|
name: string;
|
|
150
|
-
kind: 'state' | 'data';
|
|
152
|
+
kind: 'state' | 'data' | 'kv' | 'persist';
|
|
151
153
|
expr: string;
|
|
152
154
|
start: number;
|
|
153
155
|
end: number;
|
|
@@ -707,19 +709,48 @@ function nodeOnlyImports(importStmts: string): string[] {
|
|
|
707
709
|
* the state declarations, so the arrow closes over the same `count()`/`setN`
|
|
708
710
|
* the rest of the page uses.
|
|
709
711
|
*/
|
|
710
|
-
function wireEventBindings(template: string, actionNames: Set<string>): {
|
|
712
|
+
function wireEventBindings(template: string, actionNames: Set<string>, filePath = '<template>'): {
|
|
711
713
|
template: string;
|
|
712
714
|
bindings: Array<{ event: string; fn: string }>;
|
|
713
715
|
} {
|
|
714
716
|
const bindings: Array<{ event: string; fn: string }> = [];
|
|
715
717
|
let out = '';
|
|
716
718
|
let rest = template;
|
|
719
|
+
const TARGET_MODS: Record<string, string> = { window: 'w', document: 'd' };
|
|
720
|
+
const MOD_PRE: Record<string, (p: string) => string> = {
|
|
721
|
+
preventDefault: () => 'e.preventDefault()',
|
|
722
|
+
stopPropagation: () => 'e.stopPropagation()',
|
|
723
|
+
self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`,
|
|
724
|
+
};
|
|
725
|
+
const MOD_POST: Record<string, (p: string) => string> = {
|
|
726
|
+
once: (p) => `const __o = e.target && e.target.closest ? e.target.closest('[data-${p}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${p}-' + e.type);`,
|
|
727
|
+
};
|
|
728
|
+
const KNOWN_MODS: string[] = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
|
|
717
729
|
for (;;) {
|
|
718
|
-
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
730
|
+
const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
|
|
719
731
|
if (!m) {
|
|
720
732
|
out += rest;
|
|
721
733
|
break;
|
|
722
734
|
}
|
|
735
|
+
const mods = m[2] ? m[2].slice(1).split('|') : [];
|
|
736
|
+
const targets = mods.filter((mod) => TARGET_MODS[mod]);
|
|
737
|
+
if (targets.length > 1) {
|
|
738
|
+
throw new RoseError(
|
|
739
|
+
'E-TEMPLATE',
|
|
740
|
+
`${filePath}: on:${m[1]} carries both |${targets.join(' and |')}`,
|
|
741
|
+
{ hint: 'a handler binds to one target - the element (default), |window or |document' },
|
|
742
|
+
);
|
|
743
|
+
}
|
|
744
|
+
const prefix = targets.length ? 'on' + TARGET_MODS[targets[0]] : 'on';
|
|
745
|
+
for (const mod of mods) {
|
|
746
|
+
if (!KNOWN_MODS.includes(mod)) {
|
|
747
|
+
throw new RoseError(
|
|
748
|
+
'E-TEMPLATE',
|
|
749
|
+
`${filePath}: unknown event modifier |${mod}`,
|
|
750
|
+
{ 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` },
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
723
754
|
out += rest.slice(0, m.index);
|
|
724
755
|
let i = m.index + m[0].length;
|
|
725
756
|
let depth = 1;
|
|
@@ -741,7 +772,24 @@ function wireEventBindings(template: string, actionNames: Set<string>): {
|
|
|
741
772
|
i++;
|
|
742
773
|
}
|
|
743
774
|
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
744
|
-
|
|
775
|
+
const wrap = (body: string): string => {
|
|
776
|
+
if (!mods.length) return body;
|
|
777
|
+
const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
|
|
778
|
+
const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
|
|
779
|
+
return `(e) => {${pre.length ? ' ' + pre.join('; ') + ';' : ''} (${body})(e);${post.length ? ' ' + post.join('; ') + ';' : ''} }`;
|
|
780
|
+
};
|
|
781
|
+
if (mods.length && actionNames.has(expr)) {
|
|
782
|
+
throw new RoseError(
|
|
783
|
+
'E-TEMPLATE',
|
|
784
|
+
`${filePath}: event modifiers are not supported on the server action ${expr}`,
|
|
785
|
+
{ hint: '$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action' },
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
if (mods.length) {
|
|
789
|
+
const name = `__h${bindings.length}`;
|
|
790
|
+
out += `data-${prefix}-${m[1]}="${name}"`;
|
|
791
|
+
bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
|
|
792
|
+
} else if (actionNames.has(expr)) {
|
|
745
793
|
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
746
794
|
} else if (/^\w+$/.test(expr)) {
|
|
747
795
|
out += `data-on-${m[1]}="${expr}"`;
|
|
@@ -913,6 +961,8 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
913
961
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
914
962
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
915
963
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
|
|
964
|
+
const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
|
|
965
|
+
const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : undefined;
|
|
916
966
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
917
967
|
const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
|
|
918
968
|
if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
|
|
@@ -1022,6 +1072,7 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
1022
1072
|
}
|
|
1023
1073
|
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
1024
1074
|
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`);
|
|
1075
|
+
if (source.includes('{#defer')) clientReasons.push('{#defer} progressive content');
|
|
1025
1076
|
const needsClient = clientReasons.length > 0;
|
|
1026
1077
|
|
|
1027
1078
|
const jsWarnings: string[] = [];
|
|
@@ -1053,7 +1104,7 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
1053
1104
|
: inlineImages(rawTemplate, publicDir);
|
|
1054
1105
|
|
|
1055
1106
|
const decls = extractDecls(script);
|
|
1056
|
-
const stateDecls = decls.filter((d) => d.kind === 'state');
|
|
1107
|
+
const stateDecls = decls.filter((d) => d.kind === 'state' || d.kind === 'kv' || d.kind === 'persist');
|
|
1057
1108
|
|
|
1058
1109
|
const setterNames = new Map<string, string>();
|
|
1059
1110
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
@@ -1065,6 +1116,17 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
1065
1116
|
}
|
|
1066
1117
|
const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
|
|
1067
1118
|
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
1119
|
+
if (d.kind === 'persist') {
|
|
1120
|
+
return `const [${d.name}, ${setterNames.get(d.name)!}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
|
|
1121
|
+
}
|
|
1122
|
+
if (d.kind === 'kv') {
|
|
1123
|
+
const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
|
|
1124
|
+
const fnExpr = mTtl ? mTtl[1] : d.expr;
|
|
1125
|
+
const ttl = mTtl ? mTtl[2] : '300';
|
|
1126
|
+
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1127
|
+
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1128
|
+
if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify('__kvh:' + scopeKey + ':' + d.name)}, ${fnExpr}, ${ttl}));`;
|
|
1129
|
+
}
|
|
1068
1130
|
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1069
1131
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1070
1132
|
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
@@ -1093,19 +1155,142 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1093
1155
|
const dataDeclsCode = nestedDecls.filter((d) => d.kind === 'data').map(declCode).join('\n');
|
|
1094
1156
|
|
|
1095
1157
|
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
1096
|
-
const
|
|
1097
|
-
|
|
1158
|
+
const imgDefaulted = templateCalled
|
|
1159
|
+
.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"')
|
|
1160
|
+
.replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"')
|
|
1161
|
+
const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
|
|
1098
1162
|
|
|
1099
1163
|
const stateKeys = decls.map((d) => d.name);
|
|
1100
1164
|
|
|
1165
|
+
const bindBindings: Array<{ event: string; fn: string }> = [];
|
|
1166
|
+
let bindCounter = 0;
|
|
1167
|
+
const bindExpanded = wired.template.replace(
|
|
1168
|
+
/\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
|
|
1169
|
+
(whole, kind: string, name: string) => {
|
|
1170
|
+
if (!stateKeys.includes(name)) {
|
|
1171
|
+
throw new Error(
|
|
1172
|
+
`${filePath}: bind:${kind}={${name}} must name a $state declaration` +
|
|
1173
|
+
(stateKeys.length ? ` (state keys here: ${stateKeys.join(', ')})` : ' (this file declares no $state)'),
|
|
1174
|
+
);
|
|
1175
|
+
}
|
|
1176
|
+
if (kind === 'this') return ` data-bind-this="${name}"`;
|
|
1177
|
+
const setter = setterNames.get(name)!;
|
|
1178
|
+
const evt = kind === 'checked' ? 'change' : 'input';
|
|
1179
|
+
const hname = `__rvbind_${scopeKey.replace(/\W/g, '_')}_${bindCounter++}`;
|
|
1180
|
+
bindBindings.push({
|
|
1181
|
+
event: evt,
|
|
1182
|
+
fn:
|
|
1183
|
+
kind === 'checked'
|
|
1184
|
+
? `${hname}: (e) => ${setter}(e.target.checked)`
|
|
1185
|
+
: `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`,
|
|
1186
|
+
});
|
|
1187
|
+
const evtAttr = kind === 'checked'
|
|
1188
|
+
? ` data-on-change="${hname}"`
|
|
1189
|
+
: ` data-on-input="${hname}" data-on-change="${hname}"`;
|
|
1190
|
+
return ` ${kind}={${name}()}${evtAttr}`;
|
|
1191
|
+
},
|
|
1192
|
+
);
|
|
1193
|
+
|
|
1101
1194
|
const comps = new Map(roseImports.map((r) => {
|
|
1102
1195
|
const abs = path.resolve(path.dirname(filePath), r.specifier);
|
|
1103
1196
|
const hit = registry.get(abs)!;
|
|
1104
1197
|
return [r.name, { index: hit.index, slots: hit.slots }] as const;
|
|
1105
1198
|
}));
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1108
|
-
|
|
1199
|
+
const groupBindings: Array<{ event: string; fn: string }> = [];
|
|
1200
|
+
let groupCounter = 0;
|
|
1201
|
+
const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1202
|
+
const groupExpanded = (() => {
|
|
1203
|
+
if (!bindExpanded.includes('bind:group')) return bindExpanded;
|
|
1204
|
+
let out = '';
|
|
1205
|
+
let pos = 0;
|
|
1206
|
+
let m: RegExpExecArray | null;
|
|
1207
|
+
TAG_SCAN_RE.lastIndex = 0;
|
|
1208
|
+
while ((m = TAG_SCAN_RE.exec(bindExpanded))) {
|
|
1209
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1210
|
+
const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
|
|
1211
|
+
if (!gm) continue;
|
|
1212
|
+
const name = gm[1];
|
|
1213
|
+
if (!stateKeys.includes(name)) {
|
|
1214
|
+
throw new RoseError(
|
|
1215
|
+
'E-TEMPLATE',
|
|
1216
|
+
`${filePath}: bind:group={${name}} must name a $state declaration`,
|
|
1217
|
+
{ hint: 'the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let ' + name + ' = $state("")' },
|
|
1218
|
+
);
|
|
1219
|
+
}
|
|
1220
|
+
if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
|
|
1221
|
+
throw new RoseError(
|
|
1222
|
+
'E-TEMPLATE',
|
|
1223
|
+
`${filePath}: bind:group is for radio and checkbox inputs`,
|
|
1224
|
+
{ 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([]))' },
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
|
|
1228
|
+
const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
|
|
1229
|
+
if (!vm || /\{/.test(vm[0])) {
|
|
1230
|
+
throw new RoseError(
|
|
1231
|
+
'E-TEMPLATE',
|
|
1232
|
+
`${filePath}: a bind:group input needs a static value attribute`,
|
|
1233
|
+
{ hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' },
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
if (/\schecked\s*=/.test(attrs)) {
|
|
1237
|
+
throw new RoseError(
|
|
1238
|
+
'E-TEMPLATE',
|
|
1239
|
+
`${filePath}: a bind:group input cannot also carry checked=`,
|
|
1240
|
+
{ hint: 'the group state alone decides which inputs are checked' },
|
|
1241
|
+
);
|
|
1242
|
+
}
|
|
1243
|
+
const setter = setterNames.get(name)!;
|
|
1244
|
+
const hname = `__rvbg_${scopeKey.replace(/\W/g, '_')}_${groupCounter++}`;
|
|
1245
|
+
const groupValue = JSON.stringify(vm[1] ?? vm[2]);
|
|
1246
|
+
const checkedExpr = isArrayGroup
|
|
1247
|
+
? `${name}().includes(${groupValue})`
|
|
1248
|
+
: `${name}() === ${groupValue}`;
|
|
1249
|
+
const handlerBody = isArrayGroup
|
|
1250
|
+
? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))`
|
|
1251
|
+
: `${setter}(e.target.value)`;
|
|
1252
|
+
groupBindings.push({ event: 'change', fn: `${hname}: (e) => { ${handlerBody}; }` });
|
|
1253
|
+
const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
|
|
1254
|
+
out += bindExpanded.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1255
|
+
pos = m.index + whole.length;
|
|
1256
|
+
}
|
|
1257
|
+
if (pos === 0) return bindExpanded;
|
|
1258
|
+
out += bindExpanded.slice(pos);
|
|
1259
|
+
return out;
|
|
1260
|
+
})();
|
|
1261
|
+
const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
|
|
1262
|
+
const useExpanded = groupExpanded.replace(
|
|
1263
|
+
/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
|
|
1264
|
+
(_w, name: string, hasParam: string | undefined, expr: string) =>
|
|
1265
|
+
hasParam
|
|
1266
|
+
? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}`
|
|
1267
|
+
: ` data-use="${name}"`,
|
|
1268
|
+
);
|
|
1269
|
+
const classExpanded = expandClassDirectives(useExpanded, filePath);
|
|
1270
|
+
const styleExpanded = expandStyleDirectives(classExpanded, filePath);
|
|
1271
|
+
const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
|
|
1272
|
+
const elseExpanded = expandIfElse(keyExpanded);
|
|
1273
|
+
const deferExpanded = expandDeferBlocks(elseExpanded);
|
|
1274
|
+
const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
|
|
1275
|
+
const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded
|
|
1276
|
+
.replace(SLOT_NAMED_RE, (_w: unknown, attrs: string, fallback: string) => {
|
|
1277
|
+
const call = `{__slot(${encodeSlotCall(attrs)})}`;
|
|
1278
|
+
if (fallback) {
|
|
1279
|
+
if (/\{[^{}]*\}/.test(fallback)) {
|
|
1280
|
+
throw new RoseError(
|
|
1281
|
+
'E-TEMPLATE',
|
|
1282
|
+
`${filePath}: slot fallback content must be static markup`,
|
|
1283
|
+
{ 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' },
|
|
1284
|
+
);
|
|
1285
|
+
}
|
|
1286
|
+
return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
|
|
1287
|
+
}
|
|
1288
|
+
return call;
|
|
1289
|
+
})
|
|
1290
|
+
.replace(SLOT_RE, (_w: unknown, fallback: string) =>
|
|
1291
|
+
fallback && fallback.trim()
|
|
1292
|
+
? `{__slotDefault(${JSON.stringify(fallback)})}`
|
|
1293
|
+
: '{__slot__}'), comps);
|
|
1109
1294
|
assertKnownDirectives(ssrTemplate, filePath);
|
|
1110
1295
|
const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0, true, comps);
|
|
1111
1296
|
const compiledHead = headContent.trim() ? compileHead(headContent) : '';
|
|
@@ -1116,8 +1301,8 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1116
1301
|
const isMiddleware = path.basename(filePath) === '_middleware.rose';
|
|
1117
1302
|
const ssr = isMiddleware
|
|
1118
1303
|
? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
|
|
1119
|
-
: generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1120
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
1304
|
+
: generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1305
|
+
const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
1121
1306
|
|
|
1122
1307
|
return {
|
|
1123
1308
|
ssr: rewriteRoseImports(ssr, 'ssr'),
|
|
@@ -1129,6 +1314,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1129
1314
|
hasParams,
|
|
1130
1315
|
usesContext,
|
|
1131
1316
|
revalidate,
|
|
1317
|
+
cache: cacheSeconds,
|
|
1132
1318
|
csr,
|
|
1133
1319
|
shell,
|
|
1134
1320
|
buffer,
|
|
@@ -1364,6 +1550,21 @@ export function extractExports(script: string): { clean: string; exports: string
|
|
|
1364
1550
|
return { clean: out, exports: stmts.join('\n'), actions, props, guard: guards.join('\n') };
|
|
1365
1551
|
}
|
|
1366
1552
|
|
|
1553
|
+
const REGEX_PRECEDERS = new Set('(,=:[!&|?{};+-*%<>~^'.split(''));
|
|
1554
|
+
function isRegexStart(src: string, i: number): boolean {
|
|
1555
|
+
let j = i - 1;
|
|
1556
|
+
while (j >= 0 && /\s/.test(src[j])) j--;
|
|
1557
|
+
if (j < 0) return true;
|
|
1558
|
+
const p = src[j];
|
|
1559
|
+
if (REGEX_PRECEDERS.has(p)) return true;
|
|
1560
|
+
if (/[A-Za-z0-9_$]/.test(p)) {
|
|
1561
|
+
const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
|
|
1562
|
+
if (!w) return false;
|
|
1563
|
+
return ['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else'].includes(w[1]);
|
|
1564
|
+
}
|
|
1565
|
+
return false;
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1367
1568
|
function extractDecls(script: string): Decl[] {
|
|
1368
1569
|
const decls: Decl[] = [];
|
|
1369
1570
|
DECL_RE.lastIndex = 0;
|
|
@@ -1401,7 +1602,7 @@ function extractDecls(script: string): Decl[] {
|
|
|
1401
1602
|
if (script[end] === ';') end++;
|
|
1402
1603
|
decls.push({
|
|
1403
1604
|
name: m[1],
|
|
1404
|
-
kind: m[2] as 'state' | 'data',
|
|
1605
|
+
kind: m[2] as 'state' | 'data' | 'persist',
|
|
1405
1606
|
expr: script.slice(open, i - 1).trim(),
|
|
1406
1607
|
start: m.index,
|
|
1407
1608
|
end,
|
|
@@ -1452,6 +1653,21 @@ function braceDepthAt(src: string, index: number): number {
|
|
|
1452
1653
|
i = close === -1 ? src.length : close + 2;
|
|
1453
1654
|
continue;
|
|
1454
1655
|
}
|
|
1656
|
+
if (ch === '/' && isRegexStart(src, i)) {
|
|
1657
|
+
i++;
|
|
1658
|
+
let inClass = false;
|
|
1659
|
+
while (i < index) {
|
|
1660
|
+
const c2 = src[i];
|
|
1661
|
+
if (c2 === '\\') { i += 2; continue; }
|
|
1662
|
+
if (inClass) { if (c2 === ']') inClass = false; i++; continue; }
|
|
1663
|
+
if (c2 === '[') { inClass = true; i++; continue; }
|
|
1664
|
+
if (c2 === '/') { i++; break; }
|
|
1665
|
+
if (c2 === '\n') break;
|
|
1666
|
+
i++;
|
|
1667
|
+
}
|
|
1668
|
+
while (i < index && /[a-z]/.test(src[i])) i++;
|
|
1669
|
+
continue;
|
|
1670
|
+
}
|
|
1455
1671
|
if (ch === '{') depth++;
|
|
1456
1672
|
else if (ch === '}') depth--;
|
|
1457
1673
|
i++;
|
|
@@ -1484,12 +1700,444 @@ function autoCall(expr: string): string {
|
|
|
1484
1700
|
* Returns a RegExpExecArray-shaped value (index + capture groups in the
|
|
1485
1701
|
* same order the old regexes produced) so the call sites are unchanged.
|
|
1486
1702
|
*/
|
|
1487
|
-
|
|
1703
|
+
|
|
1704
|
+
const DEFER_ENABLED = true;
|
|
1705
|
+
|
|
1706
|
+
/**
|
|
1707
|
+
* F4 ({#key} block): `{#key expr}body{/key}` re-creates the body whenever
|
|
1708
|
+
* `expr` changes - the escape hatch for DOM whose local state must reset
|
|
1709
|
+
* (a form re-keyed by its subject, a chart re-keyed by its dataset).
|
|
1710
|
+
* Pure compiler sugar: it desugars to `{#each [expr] as __rvkv}body{/each}` -
|
|
1711
|
+
* the each's items closure reads expr, so any dependency change re-runs the
|
|
1712
|
+
* map and rebuilds every node, which IS key semantics. Zero runtime change.
|
|
1713
|
+
* Unclosed blocks fail loudly here instead of rendering as prose.
|
|
1714
|
+
*/
|
|
1715
|
+
function expandKeyBlocks(template: string, filePath: string): string {
|
|
1716
|
+
if (!template.includes('{#key')) return template;
|
|
1717
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1718
|
+
const OPEN_RE = /\{#key\s+([^}]+)\}/g;
|
|
1719
|
+
OPEN_RE.lastIndex = 0;
|
|
1720
|
+
const openM = OPEN_RE.exec(template);
|
|
1721
|
+
if (!openM) return template;
|
|
1722
|
+
const expr = openM[1].trim();
|
|
1723
|
+
const bodyStart = openM.index + openM[0].length;
|
|
1724
|
+
const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
|
|
1725
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1726
|
+
let depth = 1;
|
|
1727
|
+
let closeAt = -1;
|
|
1728
|
+
let tm: RegExpExecArray | null;
|
|
1729
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
1730
|
+
if (tm[0].startsWith('{#')) { depth++; continue; }
|
|
1731
|
+
depth--;
|
|
1732
|
+
if (depth === 0) { closeAt = tm.index; break; }
|
|
1733
|
+
}
|
|
1734
|
+
if (closeAt < 0) {
|
|
1735
|
+
throw new RoseError(
|
|
1736
|
+
'E-TEMPLATE',
|
|
1737
|
+
`${filePath}: {#key ${expr}} is never closed`,
|
|
1738
|
+
{ hint: 'every {#key} needs its {/key}' },
|
|
1739
|
+
);
|
|
1740
|
+
}
|
|
1741
|
+
template =
|
|
1742
|
+
template.slice(0, openM.index) +
|
|
1743
|
+
`{#each [${expr}] as __rvkv}` +
|
|
1744
|
+
template.slice(bodyStart, closeAt) +
|
|
1745
|
+
'{/each}' +
|
|
1746
|
+
template.slice(closeAt + '{/key}'.length);
|
|
1747
|
+
}
|
|
1748
|
+
return template;
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
/**
|
|
1752
|
+
* F2 (ergonomics): `{:else}` and `{:else if cond}` on {#if} blocks - the
|
|
1753
|
+
* branch syntax every other template language has, retracted here after the
|
|
1754
|
+
* author judged the earlier refusal over-strict. One pass walks every {#if}
|
|
1755
|
+
* block, splits its TOP-LEVEL `{:else}` chain (nested blocks' elses are
|
|
1756
|
+
* theirs), and re-emits the block as complementary {#if}s:
|
|
1757
|
+
* {#if A}a{:else}b{/if} -> {#if A}a{/if}{#if !(A)}b{/if}
|
|
1758
|
+
* {#if A}a{:else if B}b{:else}c{/if}
|
|
1759
|
+
* -> {#if A}a{/if}{#if !(A)}{#if B}b{/if}{#if !(B)}c{/if}{/if}
|
|
1760
|
+
* Zero new runtime, zero new marker kinds: wire()/ifMark already adopt and
|
|
1761
|
+
* flip both shapes, and each condition re-evaluates - free for the pure
|
|
1762
|
+
* state reads that are the only legal condition kind here. Runs BEFORE
|
|
1763
|
+
* defer expansion (so a {:else} inside a {#defer} body lands on expanded
|
|
1764
|
+
* ground) and repeated until stable, because nested ifs with their own
|
|
1765
|
+
* elses surface one level per pass. Defer bodies are transparent to the
|
|
1766
|
+
* depth walk on purpose: {#defer} is not a block kind, and every {#if}
|
|
1767
|
+
* inside it is balanced on its own.
|
|
1768
|
+
*/
|
|
1769
|
+
function expandIfElseOnce(template: string): { template: string; changed: boolean } {
|
|
1770
|
+
const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
|
|
1771
|
+
let out = '';
|
|
1772
|
+
let pos = 0;
|
|
1773
|
+
let changed = false;
|
|
1774
|
+
for (;;) {
|
|
1775
|
+
const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
|
|
1776
|
+
if (!openM) { out += template.slice(pos); break; }
|
|
1777
|
+
const kind = openM[1];
|
|
1778
|
+
const head = openM[2];
|
|
1779
|
+
const start = pos + openM.index;
|
|
1780
|
+
const cond = kind === 'if' ? head.trim() : '';
|
|
1781
|
+
const bodyStart = start + openM[0].length;
|
|
1782
|
+
out += template.slice(pos, start);
|
|
1783
|
+
|
|
1784
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1785
|
+
let depth = 1;
|
|
1786
|
+
let closeAt = -1;
|
|
1787
|
+
let closeLen = 0;
|
|
1788
|
+
const elses: Array<{ at: number; len: number; cond: string | null }> = [];
|
|
1789
|
+
let tm: RegExpExecArray | null;
|
|
1790
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
1791
|
+
const tok = tm[0];
|
|
1792
|
+
if (tok.startsWith('{:else')) {
|
|
1793
|
+
if (depth === 1) {
|
|
1794
|
+
const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
|
|
1795
|
+
elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
|
|
1796
|
+
}
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
if (tok.startsWith('{#')) { depth++; continue; }
|
|
1800
|
+
depth--;
|
|
1801
|
+
if (depth === 0) { closeAt = tm.index; closeLen = tok.length; break; }
|
|
1802
|
+
}
|
|
1803
|
+
if (closeAt < 0 || elses.length === 0) {
|
|
1804
|
+
out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
|
|
1805
|
+
if (closeAt < 0) break;
|
|
1806
|
+
pos = closeAt + closeLen;
|
|
1807
|
+
continue;
|
|
1808
|
+
}
|
|
1809
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1810
|
+
if (kind === 'each') {
|
|
1811
|
+
const lastBare = [...elses].reverse().find((e) => e.cond === null);
|
|
1812
|
+
if (!lastBare) {
|
|
1813
|
+
out += template.slice(start, closeAt + closeLen);
|
|
1814
|
+
pos = closeAt + closeLen;
|
|
1815
|
+
continue;
|
|
1816
|
+
}
|
|
1817
|
+
const relLast = lastBare.at - bodyStart;
|
|
1818
|
+
const eachBody = body.slice(0, relLast);
|
|
1819
|
+
const elseBody = body.slice(relLast + lastBare.len);
|
|
1820
|
+
const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, '').trim();
|
|
1821
|
+
out += template.slice(start, bodyStart) + eachBody + '{/each}'
|
|
1822
|
+
+ `{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
|
|
1823
|
+
pos = closeAt + closeLen;
|
|
1824
|
+
changed = true;
|
|
1825
|
+
continue;
|
|
1826
|
+
}
|
|
1827
|
+
const branches: Array<{ cond: string | null; body: string }> = [];
|
|
1828
|
+
let cursor = 0;
|
|
1829
|
+
for (let i = 0; i < elses.length; i++) {
|
|
1830
|
+
const e = elses[i];
|
|
1831
|
+
const rel = e.at - bodyStart;
|
|
1832
|
+
branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
|
|
1833
|
+
cursor = rel + e.len;
|
|
1834
|
+
}
|
|
1835
|
+
branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
|
|
1836
|
+
const first = branches.shift()!;
|
|
1837
|
+
const build = (bs: Array<{ cond: string | null; body: string }>): string => {
|
|
1838
|
+
if (!bs.length) return '';
|
|
1839
|
+
const head = bs[0];
|
|
1840
|
+
const rest = bs.slice(1);
|
|
1841
|
+
if (head.cond == null) return head.body;
|
|
1842
|
+
let s = `{#if ${head.cond}}${head.body}{/if}`;
|
|
1843
|
+
if (rest.length) s += `{#if !(${head.cond})}` + build(rest) + `{/if}`;
|
|
1844
|
+
return s;
|
|
1845
|
+
};
|
|
1846
|
+
let emitted = `{#if ${cond}}${first.body}{/if}`;
|
|
1847
|
+
if (branches.length) emitted += `{#if !(${cond})}` + build(branches) + `{/if}`;
|
|
1848
|
+
out += emitted;
|
|
1849
|
+
pos = closeAt + closeLen;
|
|
1850
|
+
changed = true;
|
|
1851
|
+
}
|
|
1852
|
+
return { template: out, changed };
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
/**
|
|
1856
|
+
* F2c (class: directive): `class:NAME={expr}` merges with the tag's static
|
|
1857
|
+
* class into ONE reactive class attribute whose closure concatenates the
|
|
1858
|
+
* static value plus each conditional segment - one attrMark, one data-b
|
|
1859
|
+
* marker, all conditions re-evaluated together on every toggle. This runs
|
|
1860
|
+
* AFTER callifyTemplateExprs, so the expressions arrive pre-callified and
|
|
1861
|
+
* are re-emitted verbatim inside a template literal. A tag that already
|
|
1862
|
+
* carries a REACTIVE class={...} cannot merge (two writers, one attribute)
|
|
1863
|
+
* and fails here, at the .rose file.
|
|
1864
|
+
*/
|
|
1865
|
+
function expandClassDirectives(template: string, filePath: string): string {
|
|
1866
|
+
if (!template.includes('class:')) return template;
|
|
1867
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1868
|
+
let out = '';
|
|
1869
|
+
let pos = 0;
|
|
1870
|
+
let m: RegExpExecArray | null;
|
|
1871
|
+
TAG_RE.lastIndex = 0;
|
|
1872
|
+
while ((m = TAG_RE.exec(template))) {
|
|
1873
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1874
|
+
if (!attrs.includes('class:')) continue;
|
|
1875
|
+
const pairs: Array<{ name: string; expr: string; start: number; end: number }> = [];
|
|
1876
|
+
const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
|
|
1877
|
+
let nm: RegExpExecArray | null;
|
|
1878
|
+
while ((nm = NAME_RE.exec(attrs))) {
|
|
1879
|
+
let i = nm.index + nm[0].length;
|
|
1880
|
+
let depth = 1;
|
|
1881
|
+
while (i < attrs.length && depth > 0) {
|
|
1882
|
+
const ch = attrs[i];
|
|
1883
|
+
if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
|
|
1884
|
+
if (ch === '{') depth++;
|
|
1885
|
+
else if (ch === '}') depth--;
|
|
1886
|
+
i++;
|
|
1887
|
+
}
|
|
1888
|
+
if (depth !== 0) {
|
|
1889
|
+
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' });
|
|
1890
|
+
}
|
|
1891
|
+
pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1892
|
+
}
|
|
1893
|
+
const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1894
|
+
const clsM = clsRe.exec(attrs);
|
|
1895
|
+
if (clsM && clsM[2].startsWith('{')) {
|
|
1896
|
+
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="..."' });
|
|
1897
|
+
}
|
|
1898
|
+
const staticCls = clsM ? (clsM[3] ?? clsM[4] ?? '') : '';
|
|
1899
|
+
let closure = `(${JSON.stringify(staticCls)}`;
|
|
1900
|
+
for (const p of pairs) {
|
|
1901
|
+
closure += `+((${p.expr})?${JSON.stringify(' ' + p.name)}:'')`;
|
|
1902
|
+
}
|
|
1903
|
+
closure += `)`;
|
|
1904
|
+
let newAttrs = attrs;
|
|
1905
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1906
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1907
|
+
}
|
|
1908
|
+
if (clsM) {
|
|
1909
|
+
newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
|
|
1910
|
+
} else {
|
|
1911
|
+
newAttrs = ` class={${closure}}` + newAttrs;
|
|
1912
|
+
}
|
|
1913
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1914
|
+
pos = m.index + whole.length;
|
|
1915
|
+
}
|
|
1916
|
+
if (pos === 0) return template;
|
|
1917
|
+
out += template.slice(pos);
|
|
1918
|
+
return out;
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/**
|
|
1922
|
+
* F2f (style: directive): `style:PROP={expr}` merges with the tag's static
|
|
1923
|
+
* style into ONE reactive style attribute - the overrides are appended AFTER
|
|
1924
|
+
* the static declarations, so CSS last-wins makes them authoritative, exactly
|
|
1925
|
+
* the expected precedence. Same quote-aware tag scanner and same
|
|
1926
|
+
* reactive-class={...} conflict rule as expandClassDirectives.
|
|
1927
|
+
*/
|
|
1928
|
+
function expandStyleDirectives(template: string, filePath: string): string {
|
|
1929
|
+
if (!template.includes('style:')) return template;
|
|
1930
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1931
|
+
let out = '';
|
|
1932
|
+
let pos = 0;
|
|
1933
|
+
let m: RegExpExecArray | null;
|
|
1934
|
+
TAG_RE.lastIndex = 0;
|
|
1935
|
+
while ((m = TAG_RE.exec(template))) {
|
|
1936
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1937
|
+
if (!attrs.includes('style:')) continue;
|
|
1938
|
+
const pairs: Array<{ prop: string; expr: string; start: number; end: number }> = [];
|
|
1939
|
+
const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
|
|
1940
|
+
let nm: RegExpExecArray | null;
|
|
1941
|
+
while ((nm = NAME_RE.exec(attrs))) {
|
|
1942
|
+
let i = nm.index + nm[0].length;
|
|
1943
|
+
let depth = 1;
|
|
1944
|
+
while (i < attrs.length && depth > 0) {
|
|
1945
|
+
const ch = attrs[i];
|
|
1946
|
+
if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
|
|
1947
|
+
if (ch === '{') depth++;
|
|
1948
|
+
else if (ch === '}') depth--;
|
|
1949
|
+
i++;
|
|
1950
|
+
}
|
|
1951
|
+
if (depth !== 0) {
|
|
1952
|
+
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' });
|
|
1953
|
+
}
|
|
1954
|
+
pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1955
|
+
}
|
|
1956
|
+
const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1957
|
+
const stM = styleRe.exec(attrs);
|
|
1958
|
+
if (stM && stM[2].startsWith('{')) {
|
|
1959
|
+
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}' });
|
|
1960
|
+
}
|
|
1961
|
+
const staticStyle = stM ? (stM[3] ?? stM[4] ?? '') : '';
|
|
1962
|
+
let closure = `${JSON.stringify(staticStyle.endsWith(';') || staticStyle === '' ? staticStyle : staticStyle + ';')}`;
|
|
1963
|
+
for (const p of pairs) {
|
|
1964
|
+
closure += `+${JSON.stringify(p.prop + ':')}+(${p.expr})+';'`;
|
|
1965
|
+
}
|
|
1966
|
+
let newAttrs = attrs;
|
|
1967
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1968
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1969
|
+
}
|
|
1970
|
+
if (stM) {
|
|
1971
|
+
newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
|
|
1972
|
+
} else {
|
|
1973
|
+
newAttrs = ` style={${closure}}` + newAttrs;
|
|
1974
|
+
}
|
|
1975
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1976
|
+
pos = m.index + whole.length;
|
|
1977
|
+
}
|
|
1978
|
+
if (pos === 0) return template;
|
|
1979
|
+
out += template.slice(pos);
|
|
1980
|
+
return out;
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
/**
|
|
1984
|
+
* F11 (boundary {:fallback}): extracts each {#boundary} block's top-level
|
|
1985
|
+
* `{:fallback}` segment and encodes it as a base64 `__fb` attribute on the
|
|
1986
|
+
* boundary opener — base64 so the encoded markup survives every `[^}]*`
|
|
1987
|
+
* attr scan downstream. The dispatch decodes it and compiles the fallback
|
|
1988
|
+
* like any block (reactive exprs supported). Nested boundaries surface one
|
|
1989
|
+
* level per pass; a stray {:fallback} is left for assertKnownDirectives.
|
|
1990
|
+
*/
|
|
1991
|
+
function expandBoundaryFallbacks(template: string, filePath: string): string {
|
|
1992
|
+
if (!template.includes('{:fallback')) return template;
|
|
1993
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1994
|
+
const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
|
|
1995
|
+
let out = '';
|
|
1996
|
+
let pos = 0;
|
|
1997
|
+
let changed = false;
|
|
1998
|
+
let tm: RegExpExecArray | null;
|
|
1999
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
2000
|
+
if (tm[0] !== '{#boundary}') continue;
|
|
2001
|
+
const start = tm.index;
|
|
2002
|
+
const bodyStart = start + tm[0].length;
|
|
2003
|
+
let depth = 1;
|
|
2004
|
+
let closeAt = -1;
|
|
2005
|
+
let tm2: RegExpExecArray | null;
|
|
2006
|
+
while ((tm2 = TOK_RE.exec(template))) {
|
|
2007
|
+
if (tm2[0] === '{#boundary}') { depth++; continue; }
|
|
2008
|
+
if (tm2[0] === '{/boundary}') { depth--; if (depth === 0) { closeAt = tm2.index; break; } }
|
|
2009
|
+
}
|
|
2010
|
+
if (closeAt < 0) break;
|
|
2011
|
+
const body = template.slice(bodyStart, closeAt);
|
|
2012
|
+
const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
|
|
2013
|
+
const kindStack = ['boundary'];
|
|
2014
|
+
let d = 1;
|
|
2015
|
+
let fbAt = -1;
|
|
2016
|
+
let fbLen = 0;
|
|
2017
|
+
let tm3: RegExpExecArray | null;
|
|
2018
|
+
BTOK2.lastIndex = 0;
|
|
2019
|
+
while ((tm3 = BTOK2.exec(body))) {
|
|
2020
|
+
const tok = tm3[0];
|
|
2021
|
+
if (tok === '{:fallback}') {
|
|
2022
|
+
const top = kindStack[kindStack.length - 1];
|
|
2023
|
+
if (top !== 'boundary') {
|
|
2024
|
+
throw new RoseError(
|
|
2025
|
+
'E-TEMPLATE',
|
|
2026
|
+
`${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
|
|
2027
|
+
{ hint: 'move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent' },
|
|
2028
|
+
);
|
|
2029
|
+
}
|
|
2030
|
+
if (fbAt >= 0) {
|
|
2031
|
+
throw new RoseError('E-TEMPLATE', `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: 'remove the extra {:fallback} segment' });
|
|
2032
|
+
}
|
|
2033
|
+
fbAt = tm3.index;
|
|
2034
|
+
fbLen = tok.length;
|
|
2035
|
+
continue;
|
|
2036
|
+
}
|
|
2037
|
+
if (tok.startsWith('{#')) { d++; kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]); continue; }
|
|
2038
|
+
d--; kindStack.pop();
|
|
2039
|
+
}
|
|
2040
|
+
if (fbAt < 0) continue;
|
|
2041
|
+
const custom = body.slice(0, fbAt);
|
|
2042
|
+
const fbMarkup = body.slice(fbAt + fbLen);
|
|
2043
|
+
const b64 = Buffer.from(fbMarkup, 'utf-8').toString('base64');
|
|
2044
|
+
out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + '{/boundary}';
|
|
2045
|
+
pos = closeAt + '{/boundary}'.length;
|
|
2046
|
+
changed = true;
|
|
2047
|
+
}
|
|
2048
|
+
if (!changed) break;
|
|
2049
|
+
template = out + template.slice(pos);
|
|
2050
|
+
}
|
|
2051
|
+
return template;
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
function expandIfElse(template: string): string { for (let pass = 0; pass < 10; pass++) {
|
|
2055
|
+
if (!/\{:else\b/.test(template)) return template;
|
|
2056
|
+
const r = expandIfElseOnce(template);
|
|
2057
|
+
template = r.template;
|
|
2058
|
+
if (!r.changed) return template;
|
|
2059
|
+
}
|
|
2060
|
+
return template;
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
function expandDeferBlocks(template: string): { template: string; count: number; holds: number[] } {
|
|
2064
|
+
if (!DEFER_ENABLED) {
|
|
2065
|
+
const openRe = /\{#defer(?:\s+hold=\\d+)?\}/g;
|
|
2066
|
+
let out = '';
|
|
2067
|
+
let dpos = 0;
|
|
2068
|
+
for (;;) {
|
|
2069
|
+
openRe.lastIndex = dpos;
|
|
2070
|
+
const openM = openRe.exec(template);
|
|
2071
|
+
if (!openM) break;
|
|
2072
|
+
const openAt = openM.index;
|
|
2073
|
+
const openLen = openM[0].length;
|
|
2074
|
+
const closeAt = template.indexOf('{/defer}', openAt + openLen);
|
|
2075
|
+
if (closeAt < 0) break;
|
|
2076
|
+
out += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
|
|
2077
|
+
dpos = closeAt + 8;
|
|
2078
|
+
}
|
|
2079
|
+
return { template: dpos === 0 ? template : out, count: 0, holds: [] };
|
|
2080
|
+
}
|
|
2081
|
+
let count = 0;
|
|
2082
|
+
const holds: number[] = [];
|
|
2083
|
+
let out = '';
|
|
2084
|
+
let pos = 0;
|
|
2085
|
+
const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
|
|
2086
|
+
for (;;) {
|
|
2087
|
+
openRe.lastIndex = pos;
|
|
2088
|
+
const openM = openRe.exec(template);
|
|
2089
|
+
if (!openM) break;
|
|
2090
|
+
const openAt = openM.index;
|
|
2091
|
+
const openLen = openM[0].length;
|
|
2092
|
+
const hold = openM[1] ? Number(openM[1]) : 0;
|
|
2093
|
+
let depth = 1;
|
|
2094
|
+
let i = openAt + openLen;
|
|
2095
|
+
let closeAt = -1;
|
|
2096
|
+
while (i < template.length) {
|
|
2097
|
+
openRe.lastIndex = i;
|
|
2098
|
+
const nextOpenM = openRe.exec(template);
|
|
2099
|
+
const nextOpen = nextOpenM ? nextOpenM.index : -1;
|
|
2100
|
+
const nextClose = template.indexOf('{/defer}', i);
|
|
2101
|
+
if (nextClose < 0) break;
|
|
2102
|
+
if (nextOpen >= 0 && nextOpen < nextClose) { depth++; i = nextOpen + nextOpenM![0].length; continue; }
|
|
2103
|
+
depth--;
|
|
2104
|
+
if (depth === 0) { closeAt = nextClose; break; }
|
|
2105
|
+
i = nextClose + 8;
|
|
2106
|
+
}
|
|
2107
|
+
if (closeAt < 0) break;
|
|
2108
|
+
const content = template.slice(openAt + openLen, closeAt);
|
|
2109
|
+
holds.push(hold);
|
|
2110
|
+
const n = ++count;
|
|
2111
|
+
out += template.slice(pos, openAt);
|
|
2112
|
+
out += '{#if __rvDefer' + n + '()}' + content + '{/if}' + '\n' +
|
|
2113
|
+
'{#if !__rvDefer' + n + '()}<div class="rv-defer-loading"></div>{/if}';
|
|
2114
|
+
pos = closeAt + 8;
|
|
2115
|
+
}
|
|
2116
|
+
if (count === 0) return { template, count: 0, holds: [] };
|
|
2117
|
+
out += template.slice(pos);
|
|
2118
|
+
return { template: out, count, holds };
|
|
2119
|
+
}
|
|
2120
|
+
|
|
2121
|
+
function deferBootCode(count: number, holds: number[] = []): string {
|
|
2122
|
+
let code = '';
|
|
2123
|
+
for (let n = 1; n <= count; n++) {
|
|
2124
|
+
code += 'const [__rvDefer' + n + ', set__rvDefer' + n + '] = state("__rvdefer' + n + '", false);\n';
|
|
2125
|
+
const hold = holds[n - 1] || 0;
|
|
2126
|
+
code += hold > 0
|
|
2127
|
+
? 'onMount(function () { setTimeout(function () { set__rvDefer' + n + '(true); }, ' + hold + '); });\n'
|
|
2128
|
+
: 'onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer' + n + '(true); }); }); });\n';
|
|
2129
|
+
}
|
|
2130
|
+
return code;
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
function findBlock(src: string, kind: 'if' | 'each' | 'boundary' | 'island'): RegExpExecArray | null {
|
|
1488
2134
|
const head = kind === 'boundary'
|
|
1489
|
-
? /\{#boundary
|
|
2135
|
+
? /\{#boundary(?:\s+([^}]*))?\}/g
|
|
1490
2136
|
: kind === 'if'
|
|
1491
2137
|
? /\{#if\s+([^}]+)\}/g
|
|
1492
|
-
:
|
|
2138
|
+
: kind === 'island'
|
|
2139
|
+
? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g
|
|
2140
|
+
: /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
|
|
1493
2141
|
const closeRe = new RegExp(`\\{/${kind}\\}`, 'g');
|
|
1494
2142
|
let open: RegExpExecArray | null;
|
|
1495
2143
|
while ((open = head.exec(src))) {
|
|
@@ -1511,7 +2159,9 @@ function findBlock(src: string, kind: 'if' | 'each' | 'boundary'): RegExpExecArr
|
|
|
1511
2159
|
i = nextClose.index + nextClose[0].length;
|
|
1512
2160
|
if (--depth === 0) {
|
|
1513
2161
|
const content = src.slice(afterOpen, nextClose.index);
|
|
1514
|
-
const groups = kind === 'boundary' ? [
|
|
2162
|
+
const groups = kind === 'boundary' ? [open[1] ?? '', content]
|
|
2163
|
+
: kind === 'island' ? [open[1] ?? '', open[2] ?? '', content]
|
|
2164
|
+
: kind === 'if' ? [open[1], content] : [open[1], open[2], open[3] ?? '', content];
|
|
1515
2165
|
const arr = [src.slice(start, i), ...groups] as unknown as RegExpExecArray;
|
|
1516
2166
|
(arr as any).index = start;
|
|
1517
2167
|
return arr;
|
|
@@ -1591,7 +2241,7 @@ function compileHead(head: string): string {
|
|
|
1591
2241
|
* Adversarial probing found all three in one afternoon; a template compiler
|
|
1592
2242
|
* that emits broken code silently is the worst failure mode it has.
|
|
1593
2243
|
*/
|
|
1594
|
-
const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary']);
|
|
2244
|
+
const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary', 'island']);
|
|
1595
2245
|
function assertKnownDirectives(template: string, filePath: string): void {
|
|
1596
2246
|
const rawRanges: Array<[number, number]> = [];
|
|
1597
2247
|
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
@@ -1625,21 +2275,28 @@ function assertKnownDirectives(template: string, filePath: string): void {
|
|
|
1625
2275
|
if (word === 'else') {
|
|
1626
2276
|
throw new RoseError(
|
|
1627
2277
|
'E-TEMPLATE',
|
|
1628
|
-
`${filePath}: {:else}
|
|
1629
|
-
{ file: filePath, line: lineAt(template, m), hint: '
|
|
2278
|
+
`${filePath}: a stray {:else} with no {#if} above it`,
|
|
2279
|
+
{ file: filePath, line: lineAt(template, m), hint: '{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}' },
|
|
2280
|
+
);
|
|
2281
|
+
}
|
|
2282
|
+
if (word === 'fallback') {
|
|
2283
|
+
throw new RoseError(
|
|
2284
|
+
'E-TEMPLATE',
|
|
2285
|
+
`${filePath}: a stray {:fallback} with no {#boundary} above it`,
|
|
2286
|
+
{ file: filePath, line: lineAt(template, m), hint: '{:fallback} belongs directly inside a {#boundary} ... {/boundary} block' },
|
|
1630
2287
|
);
|
|
1631
2288
|
}
|
|
1632
2289
|
throw new RoseError(
|
|
1633
2290
|
'E-TEMPLATE',
|
|
1634
2291
|
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
1635
|
-
{ file: filePath, line: lineAt(template, m), hint:
|
|
2292
|
+
{ file: filePath, line: lineAt(template, m), hint: 'rosetack templates support {#if}/{:else}, {#each} and {#boundary}' },
|
|
1636
2293
|
);
|
|
1637
2294
|
}
|
|
1638
|
-
const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
|
|
2295
|
+
const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
|
|
1639
2296
|
while ((m = OPENER_RE.exec(template))) {
|
|
1640
2297
|
if (inRaw(m.index)) continue;
|
|
1641
2298
|
const [, kind, head] = m;
|
|
1642
|
-
if (kind === 'each' && !/\bas\s+(\w+)
|
|
2299
|
+
if (kind === 'each' && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
|
|
1643
2300
|
throw new RoseError(
|
|
1644
2301
|
'E-TEMPLATE',
|
|
1645
2302
|
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
@@ -1720,12 +2377,16 @@ function compileTemplate(
|
|
|
1720
2377
|
scope: string | null,
|
|
1721
2378
|
depth: number,
|
|
1722
2379
|
markers = true,
|
|
1723
|
-
comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map()
|
|
2380
|
+
comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map(),
|
|
2381
|
+
islandDepth = 0
|
|
1724
2382
|
): string {
|
|
1725
2383
|
let result = '';
|
|
1726
2384
|
let remaining = template;
|
|
1727
2385
|
let blockId = 0;
|
|
1728
2386
|
|
|
2387
|
+
const islandsMode = /\{#island\b/.test(template);
|
|
2388
|
+
const effMarkers = markers && (!islandsMode || islandDepth > 0);
|
|
2389
|
+
|
|
1729
2390
|
const nextId = () => `${depth}_${blockId++}`;
|
|
1730
2391
|
|
|
1731
2392
|
while (remaining.length > 0) {
|
|
@@ -1737,11 +2398,13 @@ function compileTemplate(
|
|
|
1737
2398
|
? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) as unknown as RegExpExecArray
|
|
1738
2399
|
: null;
|
|
1739
2400
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
2401
|
+
const islandMatch = findBlock(remaining, 'island');
|
|
1740
2402
|
|
|
1741
2403
|
const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
|
|
1742
2404
|
if (ifMatch?.index !== undefined) candidates.push({ type: 'if', match: ifMatch, index: ifMatch.index });
|
|
1743
2405
|
if (eachMatch?.index !== undefined) candidates.push({ type: 'each', match: eachMatch, index: eachMatch.index });
|
|
1744
2406
|
if (boundaryMatch?.index !== undefined) candidates.push({ type: 'boundary', match: boundaryMatch, index: boundaryMatch.index });
|
|
2407
|
+
if (islandMatch?.index !== undefined) candidates.push({ type: 'island', match: islandMatch, index: islandMatch.index });
|
|
1745
2408
|
if (exprMatch?.index !== undefined) candidates.push({ type: 'expr', match: exprMatch, index: exprMatch.index });
|
|
1746
2409
|
if (compTag) candidates.push({ type: 'comp', match: exprMatch!, index: compTag.start, tag: compTag });
|
|
1747
2410
|
const earliest = candidates.length > 0
|
|
@@ -1781,48 +2444,66 @@ function compileTemplate(
|
|
|
1781
2444
|
const call = autoCall(cond);
|
|
1782
2445
|
const id = nextId();
|
|
1783
2446
|
const innerScope = scope ?? '__s';
|
|
1784
|
-
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1,
|
|
2447
|
+
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, effMarkers, comps, islandDepth);
|
|
1785
2448
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
|
|
1786
|
-
if (
|
|
2449
|
+
if (effMarkers) {
|
|
1787
2450
|
result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ''});\n`;
|
|
1788
2451
|
} else {
|
|
1789
2452
|
result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
|
|
1790
2453
|
}
|
|
1791
2454
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1792
2455
|
} else if (earliest.type === 'each') {
|
|
1793
|
-
const [, items, item, content] = earliest.match;
|
|
2456
|
+
const [, items, item, index, content] = earliest.match;
|
|
1794
2457
|
const before = remaining.substring(0, earliest.index);
|
|
1795
2458
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1796
2459
|
const call = autoCall(items);
|
|
1797
2460
|
const id = nextId();
|
|
1798
|
-
const
|
|
2461
|
+
const isDestructure = /^[{[]/.test(item);
|
|
2462
|
+
const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, 'g');
|
|
2463
|
+
const indexRe = index ? new RegExp(`\\b${index}\\b`, 'g') : null;
|
|
1799
2464
|
let scoped = '';
|
|
1800
2465
|
let lastSpan = 0;
|
|
1801
2466
|
for (const s of templateExprSpans(content.trim())) {
|
|
1802
|
-
|
|
2467
|
+
let expr = itemRe ? s.expr.replace(itemRe, '__s') : s.expr;
|
|
2468
|
+
if (indexRe) expr = expr.replace(indexRe, '__i');
|
|
2469
|
+
scoped += content.trim().slice(lastSpan, s.start) + '{' + expr + '}';
|
|
1803
2470
|
lastSpan = s.end + 1;
|
|
1804
2471
|
}
|
|
1805
2472
|
scoped += content.trim().slice(lastSpan);
|
|
1806
|
-
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1,
|
|
1807
|
-
|
|
1808
|
-
|
|
2473
|
+
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth);
|
|
2474
|
+
const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
|
|
2475
|
+
result += `const __b${id} = (__s, __c${index ? ', __i' : ''}) => { let h = ''; ${body} return h; };\n`;
|
|
2476
|
+
if (effMarkers) {
|
|
1809
2477
|
result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});\n`;
|
|
1810
2478
|
} else {
|
|
1811
|
-
|
|
2479
|
+
const param = isDestructure ? '__s' : item;
|
|
2480
|
+
result += `${acc} += (${call}).map((${param}${index ? ', __i' : ''}) => __b${id}(${param}, []${index ? ', __i' : ''}))).join('');\n`;
|
|
1812
2481
|
}
|
|
1813
2482
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1814
2483
|
} else if (earliest.type === 'boundary') {
|
|
1815
|
-
const [, content] = earliest.match;
|
|
2484
|
+
const [, fbAttr, content] = earliest.match;
|
|
2485
|
+
let fallbackSrc = '';
|
|
2486
|
+
if (fbAttr) {
|
|
2487
|
+
const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
|
|
2488
|
+
if (fbM) fallbackSrc = Buffer.from(fbM[1], 'base64').toString('utf-8');
|
|
2489
|
+
}
|
|
2490
|
+
const custom = content;
|
|
1816
2491
|
const before = remaining.substring(0, earliest.index);
|
|
1817
2492
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1818
2493
|
const id = nextId();
|
|
1819
|
-
const catchesAction = /\$action:|<form[\s>]/.test(
|
|
1820
|
-
const inner = compileTemplate(
|
|
2494
|
+
const catchesAction = /\$action:|<form[\s>]/.test(custom);
|
|
2495
|
+
const inner = compileTemplate(custom.trim(), 'h', closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
1821
2496
|
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
|
|
2497
|
+
let fbBlock = '';
|
|
2498
|
+
if (fallbackSrc.trim()) {
|
|
2499
|
+
const fbInner = compileTemplate(fallbackSrc.trim(), 'h', closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
2500
|
+
fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };\n`;
|
|
2501
|
+
}
|
|
2502
|
+
result += fbBlock;
|
|
1822
2503
|
result += `let __bd${id} = '';\n`;
|
|
1823
2504
|
result += catchesAction
|
|
1824
|
-
? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }\n`
|
|
1825
|
-
: `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
|
|
2505
|
+
? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : '$boundaryFallback(e)'}; }\n`
|
|
2506
|
+
: `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
|
|
1826
2507
|
result += `${acc} += __bd${id};\n`;
|
|
1827
2508
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1828
2509
|
} else if (earliest.type === 'comp') {
|
|
@@ -1843,7 +2524,7 @@ function compileTemplate(
|
|
|
1843
2524
|
const { def, named } = splitSlots(childrenSrc);
|
|
1844
2525
|
const hasChildren = def.trim().length > 0;
|
|
1845
2526
|
if (hasChildren) {
|
|
1846
|
-
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1,
|
|
2527
|
+
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1, effMarkers, comps, islandDepth)} return h; };\n`;
|
|
1847
2528
|
}
|
|
1848
2529
|
const slotFns = named.map(([nm, src]) => {
|
|
1849
2530
|
const decl = entry.slots.find((s) => s.name === nm);
|
|
@@ -1858,11 +2539,12 @@ function compileTemplate(
|
|
|
1858
2539
|
}
|
|
1859
2540
|
content = out + content.slice(lastSpan);
|
|
1860
2541
|
}
|
|
1861
|
-
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1,
|
|
2542
|
+
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth)} return h; }`;
|
|
1862
2543
|
});
|
|
1863
2544
|
const propsObj = parseCompAttrs(tag.attrs)
|
|
1864
2545
|
.filter((a) => a.name !== 'slot')
|
|
1865
2546
|
.map((a) => {
|
|
2547
|
+
if (a.kind === 'spread') return `...(${a.value})`;
|
|
1866
2548
|
const key = a.name.startsWith('on:') ? `on${capitalize(a.name.slice(3))}` : a.name;
|
|
1867
2549
|
const val = a.kind === 'expr' ? `(${a.value})` : a.kind === 'str' ? JSON.stringify(a.value) : 'true';
|
|
1868
2550
|
return `${JSON.stringify(key)}: ${val}`;
|
|
@@ -1871,20 +2553,47 @@ function compileTemplate(
|
|
|
1871
2553
|
const childrenArg = hasChildren ? `__ch${id}(${scope ?? 'undefined'}, ${closes})` : `''`;
|
|
1872
2554
|
result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(', ')} });\n`;
|
|
1873
2555
|
remaining = rest;
|
|
2556
|
+
} else if (earliest.type === 'island') {
|
|
2557
|
+
const [, name, hydrate, content] = earliest.match;
|
|
2558
|
+
const before = remaining.substring(0, earliest.index);
|
|
2559
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2560
|
+
const hydrateAttr = hydrate === 'visible' || hydrate === 'idle'
|
|
2561
|
+
? ` data-rv-island-hydrate="${hydrate}"`
|
|
2562
|
+
: '';
|
|
2563
|
+
result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ''}"${hydrateAttr}>`)};\n`;
|
|
2564
|
+
const inner = compileTemplate(content.trim(), 'h', '__c', scope, depth + 1, markers, comps, islandDepth + 1);
|
|
2565
|
+
result += inner;
|
|
2566
|
+
result += `${acc} += '</div>';\n`;
|
|
2567
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1874
2568
|
} else {
|
|
1875
2569
|
const [, expr] = earliest.match;
|
|
1876
2570
|
const trimmed = expr.trim();
|
|
1877
2571
|
const before = remaining.substring(0, earliest.index);
|
|
2572
|
+
const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
|
|
2573
|
+
if (constMatch) {
|
|
2574
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2575
|
+
result += `const ${constMatch[1]} = (${constMatch[2].trim()});\n`;
|
|
2576
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2577
|
+
continue;
|
|
2578
|
+
}
|
|
1878
2579
|
if (trimmed === '__slot__') {
|
|
1879
2580
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1880
2581
|
result += compileSlot(acc);
|
|
1881
2582
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1882
2583
|
continue;
|
|
1883
2584
|
}
|
|
1884
|
-
const
|
|
2585
|
+
const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
|
|
2586
|
+
if (slotDefault) {
|
|
2587
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2588
|
+
result += `${acc} += __slotDefault(children, ${slotDefault[1]});\n`;
|
|
2589
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2590
|
+
continue;
|
|
2591
|
+
}
|
|
2592
|
+
const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
|
|
1885
2593
|
if (slotCall) {
|
|
1886
2594
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1887
|
-
|
|
2595
|
+
const fb = slotCall[4] ? `, ${slotCall[4]}` : '';
|
|
2596
|
+
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});\n`;
|
|
1888
2597
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1889
2598
|
continue;
|
|
1890
2599
|
}
|
|
@@ -1892,7 +2601,7 @@ function compileTemplate(
|
|
|
1892
2601
|
if (rawMatch) {
|
|
1893
2602
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1894
2603
|
const expr = rawMatch[1].trim();
|
|
1895
|
-
if (!
|
|
2604
|
+
if (!effMarkers) {
|
|
1896
2605
|
result += `${acc} += String(${expr} ?? '');\n`;
|
|
1897
2606
|
} else {
|
|
1898
2607
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
@@ -1905,12 +2614,12 @@ function compileTemplate(
|
|
|
1905
2614
|
if (attrMatch) {
|
|
1906
2615
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
1907
2616
|
if (lit) result += emitChunk(lit, acc, closes, scope);
|
|
1908
|
-
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope,
|
|
2617
|
+
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
|
|
1909
2618
|
} else {
|
|
1910
2619
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1911
2620
|
const after = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1912
2621
|
const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith('{');
|
|
1913
|
-
result += emitText(trimmed, acc, closes, scope,
|
|
2622
|
+
result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
|
|
1914
2623
|
}
|
|
1915
2624
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1916
2625
|
}
|
|
@@ -1986,13 +2695,19 @@ function findClose(src: string, from: number, name: string): number {
|
|
|
1986
2695
|
return -1;
|
|
1987
2696
|
}
|
|
1988
2697
|
|
|
1989
|
-
interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool'; value: string }
|
|
2698
|
+
interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool' | 'spread'; value: string }
|
|
1990
2699
|
|
|
1991
2700
|
/** Parse a component tag's attributes into prop={expr} / prop="lit" / bool. */
|
|
1992
2701
|
function parseCompAttrs(attrs: string): CompAttr[] {
|
|
1993
2702
|
const out: CompAttr[] = [];
|
|
1994
2703
|
let i = 0;
|
|
1995
2704
|
while (i < attrs.length) {
|
|
2705
|
+
const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
|
|
2706
|
+
if (spread) {
|
|
2707
|
+
out.push({ name: '...', kind: 'spread', value: spread[1].trim() });
|
|
2708
|
+
i += spread[0].length;
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
1996
2711
|
const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
|
|
1997
2712
|
if (!nm) break;
|
|
1998
2713
|
i += nm[0].length;
|
|
@@ -2146,6 +2861,40 @@ const IMG_MIME: Record<string, string> = {
|
|
|
2146
2861
|
};
|
|
2147
2862
|
const INLINE_IMG_MAX = 4096;
|
|
2148
2863
|
|
|
2864
|
+
import { readImageSize } from "../cli/image-size";
|
|
2865
|
+
import { scanContentDir, renderMarkdown, buildRss } from "../cli/content";
|
|
2866
|
+
|
|
2867
|
+
/**
|
|
2868
|
+
* A4 (responsive variants): the sibling `name.wNNN.ext` files of a local
|
|
2869
|
+
* image (e.g. `hero.jpg` with `hero.w400.jpg` / `hero.w800.jpg` next to it
|
|
2870
|
+
* in public/) become a sorted srcset on the URL-kept <img>. Zero-dependency
|
|
2871
|
+
* by design - the variants themselves are plain files, generated by whatever
|
|
2872
|
+
* resizer the app prefers (oboext ships tools/make-variants.mjs). Author-set
|
|
2873
|
+
* srcset/sizes always win; no variants means no attribute, byte-identical.
|
|
2874
|
+
*/
|
|
2875
|
+
function listImageVariants(publicDir: string, url: string): Array<{ url: string; width: number }> {
|
|
2876
|
+
const ext = path.extname(url);
|
|
2877
|
+
const base = path.basename(url, ext);
|
|
2878
|
+
const dirUrl = url.slice(0, url.length - (base + ext).length);
|
|
2879
|
+
let entries: string[];
|
|
2880
|
+
try {
|
|
2881
|
+
entries = fs.readdirSync(path.join(publicDir, path.dirname(url)));
|
|
2882
|
+
} catch {
|
|
2883
|
+
return [];
|
|
2884
|
+
}
|
|
2885
|
+
const re = new RegExp(
|
|
2886
|
+
'^' + base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\.w(\\d+)' + ext.replace('.', '\\.') + '$',
|
|
2887
|
+
'i',
|
|
2888
|
+
);
|
|
2889
|
+
const out: Array<{ url: string; width: number }> = [];
|
|
2890
|
+
for (const e of entries) {
|
|
2891
|
+
const m = re.exec(e);
|
|
2892
|
+
const width = m ? Number(m[1]) : 0;
|
|
2893
|
+
if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
|
|
2894
|
+
}
|
|
2895
|
+
return out.sort((a, b) => a.width - b.width);
|
|
2896
|
+
}
|
|
2897
|
+
|
|
2149
2898
|
function inlineImages(template: string, publicDir: string): string {
|
|
2150
2899
|
return template.replace(IMG_RE, (tag) => {
|
|
2151
2900
|
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
@@ -2153,17 +2902,29 @@ function inlineImages(template: string, publicDir: string): string {
|
|
|
2153
2902
|
const ext = path.extname(src[1]).toLowerCase();
|
|
2154
2903
|
const mime = IMG_MIME[ext];
|
|
2155
2904
|
if (!mime) return tag;
|
|
2905
|
+
const rel = src[1].replace(/^\/public(?=\/)/, '');
|
|
2906
|
+
const filePath = path.join(publicDir, rel);
|
|
2156
2907
|
let file: Buffer;
|
|
2157
2908
|
try {
|
|
2158
|
-
file = fs.readFileSync(
|
|
2909
|
+
file = fs.readFileSync(filePath);
|
|
2159
2910
|
} catch {
|
|
2160
2911
|
return tag;
|
|
2161
2912
|
}
|
|
2162
|
-
|
|
2913
|
+
const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
|
|
2914
|
+
const dims = authorDims ? null : readImageSize(filePath);
|
|
2915
|
+
const withDims = (t: string): string =>
|
|
2916
|
+
dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
|
|
2917
|
+
if (file.length > INLINE_IMG_MAX) {
|
|
2918
|
+
const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
|
|
2919
|
+
const variants = hasSS ? [] : listImageVariants(publicDir, rel);
|
|
2920
|
+
if (!variants.length) return withDims(tag);
|
|
2921
|
+
const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(', ');
|
|
2922
|
+
return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
|
|
2923
|
+
}
|
|
2163
2924
|
const uri = ext === '.svg'
|
|
2164
2925
|
? `data:image/svg+xml,${file.toString('utf-8').replace(/%/g, '%25').replace(/#/g, '%23').replace(/\{/g, '%7B').replace(/\}/g, '%7D').replace(/"/g, '%22')}`
|
|
2165
2926
|
: `data:${mime};base64,${file.toString('base64')}`;
|
|
2166
|
-
return tag.replace(src[0], `src="${uri}"`);
|
|
2927
|
+
return withDims(tag.replace(src[0], `src="${uri}"`));
|
|
2167
2928
|
});
|
|
2168
2929
|
}
|
|
2169
2930
|
|
|
@@ -2184,12 +2945,17 @@ function emitText(expr: string, acc: string, closes: string, scope: string | nul
|
|
|
2184
2945
|
}
|
|
2185
2946
|
|
|
2186
2947
|
/** Emit a reactive attribute through the runtime's attrMark(). */
|
|
2948
|
+
const BOOLEAN_ATTRS = new Set(['checked', 'disabled', 'readonly', 'required', 'selected', 'multiple', 'autofocus', 'open']);
|
|
2949
|
+
|
|
2187
2950
|
function emitAttr(attr: string, expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
|
|
2188
2951
|
if (!markers) {
|
|
2189
2952
|
return `${acc} += '${attr}="' + esc(${expr}) + '"';\n`;
|
|
2190
2953
|
}
|
|
2191
2954
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
2192
2955
|
const arg = scope ? `, ${scope}` : '';
|
|
2956
|
+
if (BOOLEAN_ATTRS.has(attr)) {
|
|
2957
|
+
return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
|
|
2958
|
+
}
|
|
2193
2959
|
return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
|
|
2194
2960
|
}
|
|
2195
2961
|
|
|
@@ -2201,7 +2967,7 @@ function compileSlot(acc: string): string {
|
|
|
2201
2967
|
return `${acc} += String(children);\n`;
|
|
2202
2968
|
}
|
|
2203
2969
|
|
|
2204
|
-
const RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
|
|
2970
|
+
const 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';`;
|
|
2205
2971
|
|
|
2206
2972
|
const API_RUNTIME_HELPERS = RUNTIME_IMPORTS
|
|
2207
2973
|
.replace(/^import\s*\{/, '')
|
|
@@ -2230,7 +2996,16 @@ const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
2230
2996
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
2231
2997
|
return { o, fn };
|
|
2232
2998
|
};
|
|
2233
|
-
const __slotBlock = (closes, sl, name, pairs) =>
|
|
2999
|
+
const __slotBlock = (closes, sl, name, pairs, fallback) => {
|
|
3000
|
+
const hit = __slot(sl, name, pairs);
|
|
3001
|
+
if (hit) return slotBlockMark(closes, hit);
|
|
3002
|
+
return fallback || '';
|
|
3003
|
+
};
|
|
3004
|
+
const __slotDefault = (children, fallback) => {
|
|
3005
|
+
const c = children == null ? '' : String(children);
|
|
3006
|
+
if (c.trim()) return c;
|
|
3007
|
+
return fallback || '';
|
|
3008
|
+
};`;
|
|
2234
3009
|
|
|
2235
3010
|
function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = '', props: Array<{ name: string; def: string | null }> = [], namedSlots = false, imports = '', isComponent = false, guard = '', hasActions = false, dataDeclsCode = ''): string {
|
|
2236
3011
|
const headCode = headFn
|
|
@@ -2535,6 +3310,9 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2535
3310
|
const buildDir = path.join(outDir, '.build');
|
|
2536
3311
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
2537
3312
|
await fs.promises.mkdir(buildDir, { recursive: true });
|
|
3313
|
+
const contentSrcCands = [path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'cli', 'content.ts'), path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'cli', 'content.ts')];
|
|
3314
|
+
const contentSrc = contentSrcCands.find((c) => fs.existsSync(c)) ?? contentSrcCands[0];
|
|
3315
|
+
fs.copyFileSync(contentSrc, path.join(buildDir, 'content-md.ts'));
|
|
2538
3316
|
|
|
2539
3317
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
2540
3318
|
if (runtimePlugins.length > 0) {
|
|
@@ -2664,13 +3442,13 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2664
3442
|
const dir = path.posix.dirname(rel);
|
|
2665
3443
|
const prefix = dir === '.' ? '/' : '/' + dir;
|
|
2666
3444
|
const flags = routeShellOff(infos, compiled, i) ? ', { shell: false }' : '';
|
|
2667
|
-
return { prefix, render:
|
|
3445
|
+
return { prefix, render: compose(i), flags };
|
|
2668
3446
|
})
|
|
2669
3447
|
.sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2670
3448
|
const notFoundTable = `[\n${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join('\n')}\n]`;
|
|
2671
3449
|
|
|
2672
3450
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
2673
|
-
const errorRender = errIdx >= 0 ?
|
|
3451
|
+
const errorRender = errIdx >= 0 ? compose(errIdx) : 'null';
|
|
2674
3452
|
|
|
2675
3453
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
2676
3454
|
|
|
@@ -2707,7 +3485,9 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2707
3485
|
|
|
2708
3486
|
const serverEntry = `
|
|
2709
3487
|
${serverImports}
|
|
2710
|
-
import {
|
|
3488
|
+
import { renderMarkdown } from './content-md.ts';
|
|
3489
|
+
import crypto from 'node:crypto';
|
|
3490
|
+
import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
|
|
2711
3491
|
${runtimePlugins.length > 0
|
|
2712
3492
|
? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
|
|
2713
3493
|
: `// no plugin declares a runtime hook, so there is no plugins
|
|
@@ -2801,6 +3581,235 @@ export const revalidate = [
|
|
|
2801
3581
|
${pages.filter(({ i }) => compiled[i].revalidate !== undefined && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(',\n ')}
|
|
2802
3582
|
];
|
|
2803
3583
|
|
|
3584
|
+
// Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
|
|
3585
|
+
export const routeCaches = [
|
|
3586
|
+
${pages.filter(({ i }) => compiled[i].cache !== undefined).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(',\n ')}
|
|
3587
|
+
];
|
|
3588
|
+
const __dynCache = new Map();
|
|
3589
|
+
export function invalidateRenderCache(): void {
|
|
3590
|
+
__dynCache.clear();
|
|
3591
|
+
}
|
|
3592
|
+
// Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
|
|
3593
|
+
const __kvStore = new Map<string, { v: unknown; exp: number }>();
|
|
3594
|
+
// Content collections: src/content/<coll>/*.md scanned once at build time,
|
|
3595
|
+
|
|
3596
|
+
const contentCollections = ${JSON.stringify(scanContentDir(path.join(root, 'src', 'content')))};
|
|
3597
|
+
export const kv = {
|
|
3598
|
+
get(key: string): unknown {
|
|
3599
|
+
const e = __kvStore.get(key);
|
|
3600
|
+
if (!e) return undefined;
|
|
3601
|
+
if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
|
|
3602
|
+
return e.v;
|
|
3603
|
+
},
|
|
3604
|
+
set(key: string, value: unknown, ttlSeconds = 300): void {
|
|
3605
|
+
if (__kvStore.size > 1000) {
|
|
3606
|
+
const cutoff = Date.now();
|
|
3607
|
+
for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
|
|
3608
|
+
if (__kvStore.size > 2000) __kvStore.clear();
|
|
3609
|
+
}
|
|
3610
|
+
__kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
|
|
3611
|
+
},
|
|
3612
|
+
del(key: string): void { __kvStore.delete(key); },
|
|
3613
|
+
has(key: string): boolean {
|
|
3614
|
+
const e = __kvStore.get(key);
|
|
3615
|
+
return !!e && e.exp >= Date.now();
|
|
3616
|
+
},
|
|
3617
|
+
};
|
|
3618
|
+
globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
|
|
3619
|
+
globalThis.__rosetackContent = {
|
|
3620
|
+
list: (coll: string, filter?: { tag: string }) => {
|
|
3621
|
+
let items = contentCollections[coll] ?? [];
|
|
3622
|
+
if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
|
|
3623
|
+
return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
|
|
3624
|
+
},
|
|
3625
|
+
rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
|
|
3626
|
+
return buildRss(contentCollections[coll] ?? [], opts);
|
|
3627
|
+
},
|
|
3628
|
+
get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
|
|
3629
|
+
const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
|
|
3630
|
+
if (!e) return null;
|
|
3631
|
+
return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
|
|
3632
|
+
},
|
|
3633
|
+
};
|
|
3634
|
+
|
|
3635
|
+
const v = {
|
|
3636
|
+
validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
|
|
3637
|
+
const errors: Record<string, string> = {};
|
|
3638
|
+
const values: Record<string, unknown> = {};
|
|
3639
|
+
for (const [field, ruleList] of Object.entries(rules)) {
|
|
3640
|
+
let val = body[field];
|
|
3641
|
+
for (const rule of ruleList) {
|
|
3642
|
+
if (val === undefined || val === null || val === "") {
|
|
3643
|
+
if (rule === "required") errors[field] = field + " is required";
|
|
3644
|
+
else if (rule.startsWith("default:")) val = rule.slice(8);
|
|
3645
|
+
continue;
|
|
3646
|
+
}
|
|
3647
|
+
if (rule === "string") val = String(val);
|
|
3648
|
+
else if (rule === "trim") val = String(val).trim();
|
|
3649
|
+
else if (rule === "number") {
|
|
3650
|
+
const num = Number(val);
|
|
3651
|
+
if (Number.isNaN(num)) errors[field] = field + " must be a number";
|
|
3652
|
+
else val = num;
|
|
3653
|
+
} else if (rule === "email") {
|
|
3654
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
|
|
3655
|
+
} else if (rule.startsWith("min:")) {
|
|
3656
|
+
const min = Number(rule.slice(4));
|
|
3657
|
+
if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
|
|
3658
|
+
} else if (rule.startsWith("max:")) {
|
|
3659
|
+
const max = Number(rule.slice(4));
|
|
3660
|
+
if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
values[field] = val;
|
|
3664
|
+
}
|
|
3665
|
+
return { ok: Object.keys(errors).length === 0, errors, values };
|
|
3666
|
+
},
|
|
3667
|
+
};
|
|
3668
|
+
|
|
3669
|
+
const jobs = {
|
|
3670
|
+
_timers: new Map<string, ReturnType<typeof setInterval>>(),
|
|
3671
|
+
every(name: string, seconds: number, fn: () => void | Promise<void>): void {
|
|
3672
|
+
if (this._timers.has(name)) return;
|
|
3673
|
+
const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
|
|
3674
|
+
this._timers.set(name, t as any);
|
|
3675
|
+
},
|
|
3676
|
+
cancel(name: string): void {
|
|
3677
|
+
const t = this._timers.get(name);
|
|
3678
|
+
if (t) { clearInterval(t); this._timers.delete(name); }
|
|
3679
|
+
},
|
|
3680
|
+
cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
|
|
3681
|
+
};
|
|
3682
|
+
|
|
3683
|
+
function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
|
|
3684
|
+
const encoder = new TextEncoder();
|
|
3685
|
+
const stream = new ReadableStream({
|
|
3686
|
+
async start(controller) {
|
|
3687
|
+
let closed = false;
|
|
3688
|
+
const send = (event: string, data: unknown) => {
|
|
3689
|
+
if (closed) return;
|
|
3690
|
+
controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
|
|
3691
|
+
};
|
|
3692
|
+
try {
|
|
3693
|
+
await handler(send);
|
|
3694
|
+
} finally {
|
|
3695
|
+
closed = true;
|
|
3696
|
+
try { controller.close(); } catch { }
|
|
3697
|
+
}
|
|
3698
|
+
},
|
|
3699
|
+
});
|
|
3700
|
+
return new Response(stream, {
|
|
3701
|
+
headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
|
|
3702
|
+
});
|
|
3703
|
+
}
|
|
3704
|
+
globalThis.__rosetackExtras = { v, jobs, sse };
|
|
3705
|
+
const auth = {
|
|
3706
|
+
hashPassword(password: string): string {
|
|
3707
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
3708
|
+
const hash = crypto.scryptSync(password, salt, 32).toString("hex");
|
|
3709
|
+
return salt + ":" + hash;
|
|
3710
|
+
},
|
|
3711
|
+
verifyPassword(password: string, stored: string): boolean {
|
|
3712
|
+
const [salt, hash] = stored.split(":");
|
|
3713
|
+
if (!salt || !hash) return false;
|
|
3714
|
+
return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
|
|
3715
|
+
},
|
|
3716
|
+
signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
|
|
3717
|
+
const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
|
|
3718
|
+
const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3719
|
+
return payload + "." + sig;
|
|
3720
|
+
},
|
|
3721
|
+
verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
|
|
3722
|
+
const dot = token.lastIndexOf(".");
|
|
3723
|
+
if (dot < 0) return null;
|
|
3724
|
+
const payload = token.slice(0, dot);
|
|
3725
|
+
const sig = token.slice(dot + 1);
|
|
3726
|
+
const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3727
|
+
try {
|
|
3728
|
+
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
|
|
3729
|
+
} catch { return null; }
|
|
3730
|
+
try {
|
|
3731
|
+
const data = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
3732
|
+
if (data.exp < Date.now()) return null;
|
|
3733
|
+
return data as T;
|
|
3734
|
+
} catch { return null; }
|
|
3735
|
+
},
|
|
3736
|
+
csrfToken(secret: string, sessionId: string): string {
|
|
3737
|
+
return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
|
|
3738
|
+
},
|
|
3739
|
+
verifyCsrf(token: string, secret: string, sessionId: string): boolean {
|
|
3740
|
+
try {
|
|
3741
|
+
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
|
|
3742
|
+
} catch { return false; }
|
|
3743
|
+
},
|
|
3744
|
+
};
|
|
3745
|
+
globalThis.__rosetackAuth = auth;
|
|
3746
|
+
|
|
3747
|
+
export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
|
|
3748
|
+
const hit = kv.get(key);
|
|
3749
|
+
if (hit !== undefined) return hit;
|
|
3750
|
+
const v = await compute();
|
|
3751
|
+
if (v !== undefined) kv.set(key, v, ttlSeconds);
|
|
3752
|
+
return v;
|
|
3753
|
+
}
|
|
3754
|
+
export function isCachedRoute(pathname: string): boolean {
|
|
3755
|
+
return routeCaches.some((r) => matchRoute(r.pattern, pathname));
|
|
3756
|
+
}
|
|
3757
|
+
export function invalidatePath(pathname: string): number {
|
|
3758
|
+
let n = 0;
|
|
3759
|
+
for (const key of [...__dynCache.keys()]) {
|
|
3760
|
+
if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
|
|
3761
|
+
}
|
|
3762
|
+
return n;
|
|
3763
|
+
}
|
|
3764
|
+
export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
|
|
3765
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3766
|
+
if (!cfg) return null;
|
|
3767
|
+
let h = 0x811c9dc5;
|
|
3768
|
+
const c = cookieHeader || '';
|
|
3769
|
+
for (let i = 0; i < c.length; i++) {
|
|
3770
|
+
h ^= c.charCodeAt(i);
|
|
3771
|
+
h = (h * 0x01000193) >>> 0;
|
|
3772
|
+
}
|
|
3773
|
+
const hit = __dynCache.get(pathname + '|' + h.toString(16));
|
|
3774
|
+
return hit && hit.expires > Date.now() ? hit.page : null;
|
|
3775
|
+
}
|
|
3776
|
+
export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
|
|
3777
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3778
|
+
if (!cfg) return renderPage(pathname);
|
|
3779
|
+
let h = 0x811c9dc5;
|
|
3780
|
+
for (let i = 0; i < cookieHeader.length; i++) {
|
|
3781
|
+
h ^= cookieHeader.charCodeAt(i);
|
|
3782
|
+
h = (h * 0x01000193) >>> 0;
|
|
3783
|
+
}
|
|
3784
|
+
const key = pathname + '|' + h.toString(16);
|
|
3785
|
+
const hit = __dynCache.get(key);
|
|
3786
|
+
if (hit && hit.expires > Date.now()) {
|
|
3787
|
+
__dynCache.delete(key);
|
|
3788
|
+
__dynCache.set(key, hit);
|
|
3789
|
+
return hit.page;
|
|
3790
|
+
}
|
|
3791
|
+
// Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
|
|
3792
|
+
if (hit && !hit.refreshing) {
|
|
3793
|
+
hit.refreshing = true;
|
|
3794
|
+
renderPage(pathname).then((fresh: any) => {
|
|
3795
|
+
if (fresh.status === 200 && !fresh.redirect) {
|
|
3796
|
+
__dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
|
|
3797
|
+
} else {
|
|
3798
|
+
__dynCache.delete(key);
|
|
3799
|
+
}
|
|
3800
|
+
}).catch(() => { __dynCache.delete(key); });
|
|
3801
|
+
return hit.page;
|
|
3802
|
+
}
|
|
3803
|
+
const page = await renderPage(pathname);
|
|
3804
|
+
if (page.status === 200 && !page.redirect) {
|
|
3805
|
+
__dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
|
|
3806
|
+
if (__dynCache.size > 300) {
|
|
3807
|
+
__dynCache.delete(__dynCache.keys().next().value as string);
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
return page;
|
|
3811
|
+
}
|
|
3812
|
+
|
|
2804
3813
|
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
2805
3814
|
export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
|
|
2806
3815
|
|
|
@@ -2915,7 +3924,14 @@ export function docAttrs(pathname) {
|
|
|
2915
3924
|
|
|
2916
3925
|
// Paint a fallback page (404/500) and serialize its state.
|
|
2917
3926
|
async function renderFallback(pathname, render) {
|
|
2918
|
-
|
|
3927
|
+
// Split mode: the not-found entry's render is a loader object — resolve it through getRender (which memoizes the composed function) exactly like.
|
|
3928
|
+
let fn = render;
|
|
3929
|
+
if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
|
|
3930
|
+
|
|
3931
|
+
// { render } once the route's chunk graph is loaded
|
|
3932
|
+
fn = (await fn.load()).render;
|
|
3933
|
+
}
|
|
3934
|
+
const { html, head } = extractHead(await fn([], ''));
|
|
2919
3935
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2920
3936
|
return { html, state, head, ...docAttrs(pathname) };
|
|
2921
3937
|
}
|
|
@@ -3022,8 +4038,27 @@ export async function renderPage(pathname, form) {
|
|
|
3022
4038
|
return await notFoundPage(pathname);
|
|
3023
4039
|
}
|
|
3024
4040
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
3025
|
-
|
|
3026
|
-
|
|
4041
|
+
// F10: in dev the response body carries the real error — message, file:line and the fix hint.
|
|
4042
|
+
let devDetail = '';
|
|
4043
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
4044
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
4045
|
+
const file = esc(String(err.file || ''));
|
|
4046
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
4047
|
+
const hint = esc(String(err.hint || ''));
|
|
4048
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
4049
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
4050
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
4051
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
4052
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
4053
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
4054
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
4055
|
+
+ '</div>';
|
|
4056
|
+
}
|
|
4057
|
+
if (errorPage) {
|
|
4058
|
+
const fb = await renderFallback(pathname, errorPage);
|
|
4059
|
+
return { ...fb, html: fb.html + devDetail, status: 500 };
|
|
4060
|
+
}
|
|
4061
|
+
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
3027
4062
|
}
|
|
3028
4063
|
// __route tells the bootstrap which route this document was rendered for.
|
|
3029
4064
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
@@ -3130,7 +4165,24 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3130
4165
|
} catch (err) {
|
|
3131
4166
|
|
|
3132
4167
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
3133
|
-
|
|
4168
|
+
// F10: dev carries the real error in the body here too — the shell
|
|
4169
|
+
// is out, so the detail rides after the error page body.
|
|
4170
|
+
let devDetail = '';
|
|
4171
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
4172
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
4173
|
+
const file = esc(String(err.file || ''));
|
|
4174
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
4175
|
+
const hint = esc(String(err.hint || ''));
|
|
4176
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
4177
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
4178
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
4179
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
4180
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
4181
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
4182
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
4183
|
+
+ '</div>';
|
|
4184
|
+
}
|
|
4185
|
+
html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
|
|
3134
4186
|
}
|
|
3135
4187
|
write(html);
|
|
3136
4188
|
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
@@ -3148,6 +4200,43 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3148
4200
|
return 404;
|
|
3149
4201
|
}
|
|
3150
4202
|
`;
|
|
4203
|
+
try {
|
|
4204
|
+
const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
|
|
4205
|
+
const uniq = [...new Set(patterns)].sort();
|
|
4206
|
+
const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
|
|
4207
|
+
const paramsOf = (pattern: string): string[] =>
|
|
4208
|
+
(pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
|
|
4209
|
+
const paramSig = uniq
|
|
4210
|
+
.map((p) => {
|
|
4211
|
+
const ps = paramsOf(p);
|
|
4212
|
+
if (!ps.length) return "";
|
|
4213
|
+
return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
|
|
4214
|
+
})
|
|
4215
|
+
.join("");
|
|
4216
|
+
const outDirTs = path.join(root, "src", ".rosetack");
|
|
4217
|
+
await fs.promises.mkdir(outDirTs, { recursive: true });
|
|
4218
|
+
const srcLines = [
|
|
4219
|
+
"// GENERATED by rosetack build - do not edit.",
|
|
4220
|
+
"export type RoutePath = " + lit + ";",
|
|
4221
|
+
"export const routePatterns = " + JSON.stringify(uniq) + " as const;",
|
|
4222
|
+
"export type RouteParams = {",
|
|
4223
|
+
paramSig,
|
|
4224
|
+
"};",
|
|
4225
|
+
"/** Build a URL from a route pattern and its params. */",
|
|
4226
|
+
"export function url(",
|
|
4227
|
+
" path: RoutePath,",
|
|
4228
|
+
" params: RouteParams[keyof RouteParams] = {} as never,",
|
|
4229
|
+
"): string {",
|
|
4230
|
+
" let out = path as string;",
|
|
4231
|
+
" for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
|
|
4232
|
+
" out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
|
|
4233
|
+
" }",
|
|
4234
|
+
" return out;",
|
|
4235
|
+
"}",
|
|
4236
|
+
].join("\n") + "\n";
|
|
4237
|
+
await fs.promises.writeFile(path.join(outDirTs, "routes.ts"), srcLines);
|
|
4238
|
+
} catch { /* types are a convenience: never fail the build over them */ }
|
|
4239
|
+
|
|
3151
4240
|
await fs.promises.writeFile(path.join(buildDir, 'server-entry.js'), serverEntry);
|
|
3152
4241
|
await esbuild.build({
|
|
3153
4242
|
entryPoints: [path.join(buildDir, 'server-entry.js')],
|
|
@@ -3159,6 +4248,25 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3159
4248
|
...TS_LOADER,
|
|
3160
4249
|
});
|
|
3161
4250
|
|
|
4251
|
+
await esbuild.build({
|
|
4252
|
+
entryPoints: [(() => {
|
|
4253
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
4254
|
+
for (const cand of [path.join(here, '..', 'cli', 'prod-server.ts'), path.join(here, '..', 'src', 'cli', 'prod-server.ts')]) {
|
|
4255
|
+
if (fs.existsSync(cand)) return cand;
|
|
4256
|
+
}
|
|
4257
|
+
return path.join(here, '..', 'cli', 'prod-server.ts');
|
|
4258
|
+
})()],
|
|
4259
|
+
bundle: true,
|
|
4260
|
+
outfile: path.join(outDir, 'prod.mjs'),
|
|
4261
|
+
format: 'esm',
|
|
4262
|
+
platform: 'node',
|
|
4263
|
+
write: true,
|
|
4264
|
+
banner: {
|
|
4265
|
+
js: "import { createRequire } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = createRequire(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);"
|
|
4266
|
+
},
|
|
4267
|
+
...TS_LOADER,
|
|
4268
|
+
});
|
|
4269
|
+
|
|
3162
4270
|
const clientImports = split ? '' : compiled
|
|
3163
4271
|
.map((_, i) => ({ i }))
|
|
3164
4272
|
.filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i))
|
|
@@ -3201,7 +4309,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3201
4309
|
|
|
3202
4310
|
const clientEntry = `
|
|
3203
4311
|
${clientImports}
|
|
3204
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
|
|
4312
|
+
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';
|
|
3205
4313
|
|
|
3206
4314
|
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
3207
4315
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
@@ -3422,6 +4530,8 @@ export async function $action(name, e) {
|
|
|
3422
4530
|
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
3423
4531
|
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
3424
4532
|
}
|
|
4533
|
+
// 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.
|
|
4534
|
+
setActionDispatcher($action);
|
|
3425
4535
|
|
|
3426
4536
|
export { postForm };
|
|
3427
4537
|
|
|
@@ -3453,6 +4563,16 @@ async function __withOwner(container, fn) {
|
|
|
3453
4563
|
setFxOwner(null);
|
|
3454
4564
|
}
|
|
3455
4565
|
}
|
|
4566
|
+
// View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
|
|
4567
|
+
async function __swap(container, html) {
|
|
4568
|
+
const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
4569
|
+
if (typeof document.startViewTransition === 'function' && !reduce) {
|
|
4570
|
+
const vt = document.startViewTransition(() => { container.innerHTML = html; });
|
|
4571
|
+
await vt.updateCallbackDone.catch(() => {});
|
|
4572
|
+
} else {
|
|
4573
|
+
container.innerHTML = html;
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
3456
4576
|
|
|
3457
4577
|
export async function start(container, pathname, initial) {
|
|
3458
4578
|
clearMounts(); // stale mounts from a failed render never fire
|
|
@@ -3475,7 +4595,7 @@ ${langDirBlock}
|
|
|
3475
4595
|
prefetchCache.delete(pathname);
|
|
3476
4596
|
__navReset(container);
|
|
3477
4597
|
restoreState(hit.state);
|
|
3478
|
-
container
|
|
4598
|
+
await __swap(container, hit.html);
|
|
3479
4599
|
await __withOwner(container, () => {
|
|
3480
4600
|
wire(container, hit.closes);
|
|
3481
4601
|
bindEvents(container);
|
|
@@ -3500,15 +4620,18 @@ ${langDirBlock}
|
|
|
3500
4620
|
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
3501
4621
|
|
|
3502
4622
|
|
|
4623
|
+
console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
|
|
3503
4624
|
broken = true;
|
|
3504
4625
|
return;
|
|
3505
4626
|
}
|
|
3506
|
-
if (!initial) container
|
|
4627
|
+
if (!initial) await __swap(container, html);
|
|
3507
4628
|
wire(container, closes);
|
|
3508
4629
|
bindEvents(container);
|
|
3509
4630
|
flushMounts();
|
|
3510
4631
|
});
|
|
3511
4632
|
if (signal === 'notFound') {
|
|
4633
|
+
// T17: a client-side render of a $data route without a prefetch entry has no data source (the server fills the context bag) - the correct.
|
|
4634
|
+
if (!initial) { try { location.assign(pathname); return; } catch { } }
|
|
3512
4635
|
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
3513
4636
|
return;
|
|
3514
4637
|
}
|
|
@@ -3595,6 +4718,7 @@ setRefreshHook(async () => {
|
|
|
3595
4718
|
format: 'esm',
|
|
3596
4719
|
platform: 'browser',
|
|
3597
4720
|
minify: true,
|
|
4721
|
+
|
|
3598
4722
|
write: true,
|
|
3599
4723
|
...TS_LOADER,
|
|
3600
4724
|
});
|