rosetack 0.0.0-stage → 0.1.0
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/.github/workflows/ci.yml +72 -0
- package/.github/workflows/release.yml +122 -0
- package/LICENSE +21 -0
- package/benchmark.ts +227 -0
- package/deploy/Dockerfile.node +25 -0
- package/deploy/Dockerfile.static +34 -0
- package/deploy/api/rosetack.ts +29 -0
- package/deploy/docker-compose.yml +33 -0
- package/deploy/fly.toml +28 -0
- package/deploy/vercel.json +13 -0
- package/example/public/favicon.ico +0 -0
- package/example/public/logo.svg +148 -0
- package/example/public/rose-mark-black.png +0 -0
- package/example/public/rose-mark.png +0 -0
- package/example/public/rose-mono.png +0 -0
- package/example/rosetack.config.js +10 -0
- package/example/src/locales/en.json +8 -0
- package/example/src/locales/zh.json +8 -0
- package/example/src/pages/404.rose +15 -0
- package/example/src/pages/500.rose +10 -0
- package/example/src/pages/[lang]/about.rose +40 -0
- package/example/src/pages/_layout.rose +33 -0
- package/example/src/pages/_middleware.rose +37 -0
- package/example/src/pages/about.rose +67 -0
- package/example/src/pages/admin.rose +27 -0
- package/example/src/pages/api/hello.rose +19 -0
- package/example/src/pages/api/login.rose +55 -0
- package/example/src/pages/api/posts.rose +80 -0
- package/example/src/pages/api/secret.rose +14 -0
- package/example/src/pages/blog/[id].rose +25 -0
- package/example/src/pages/broken.rose +16 -0
- package/example/src/pages/fresh.rose +22 -0
- package/example/src/pages/garden.rose +27 -0
- package/example/src/pages/index.rose +84 -0
- package/example/src/pages/sign.rose +45 -0
- package/example/src/pages/thorn.rose +23 -0
- package/example/src/pages/vault.rose +14 -0
- package/go.mod +3 -0
- package/main.go +470 -0
- package/package.json +39 -4
- package/src/FRAMEWORK_VERSION +1 -0
- package/src/cli/edge.ts +127 -0
- package/src/cli/index.ts +777 -0
- package/src/cli/shell.ts +284 -0
- package/src/compiler/index.ts +1990 -0
- package/src/runtime/index.ts +624 -0
- package/tools/release-notes.mjs +113 -0
- package/tsconfig.json +17 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1990 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rosetack Compiler - Compile .rose components to SSR + client-resume JS
|
|
3
|
+
*
|
|
4
|
+
* Features: compile-time reactivity, zero-hydration resume, file-system
|
|
5
|
+
* routing, nested layouts, server data fetching ($data) with request cache.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import * as fs from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { pathToFileURL, fileURLToPath } from 'url';
|
|
11
|
+
import * as esbuild from 'esbuild';
|
|
12
|
+
|
|
13
|
+
const COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
14
|
+
const TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
15
|
+
// <head> block: per-route document metadata (title/meta/link), compiled
|
|
16
|
+
// without markers so the SSR output stays clean for <head> injection.
|
|
17
|
+
const HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
18
|
+
// <style> block: component CSS, scoped by a build-time attribute on the component's
|
|
19
|
+
// top-level elements and inlined into the document …
|
|
20
|
+
const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
21
|
+
const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\s*\(/g;
|
|
22
|
+
const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
23
|
+
const EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
|
|
24
|
+
const SLOT_RE = /<slot\s*\/?>/g;
|
|
25
|
+
// {#boundary}...{/boundary}: an error boundary - its content renders into its own string; a
|
|
26
|
+
// throw anywhere inside swaps in this fallback instead of failing the whole page.
|
|
27
|
+
const BOUNDARY_FALLBACK = '<p>This section failed to render.</p>';
|
|
28
|
+
// API route handlers are exported functions named by HTTP method (pages/api/*.rose).
|
|
29
|
+
const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
30
|
+
|
|
31
|
+
export interface CompileResult {
|
|
32
|
+
ssr: string;
|
|
33
|
+
client: string;
|
|
34
|
+
stateKeys: string[];
|
|
35
|
+
actionNames: string[];
|
|
36
|
+
/** scoped CSS from the component's <style> block ('' when it has none) */
|
|
37
|
+
style: string;
|
|
38
|
+
/** the component exports `params` (dynamic-route prerender enumeration) */
|
|
39
|
+
hasParams: boolean;
|
|
40
|
+
/** api route: the module source (handlers stay exported verbatim) */
|
|
41
|
+
api?: string;
|
|
42
|
+
/** HTTP method names the api route exports (GET/POST/...) */
|
|
43
|
+
apiMethods?: string[];
|
|
44
|
+
/** api route exports `prerender = true` (bake its GET body at build time) */
|
|
45
|
+
hasPrerender?: boolean;
|
|
46
|
+
/** the component reads the request context (getContext()): it is dynamic */
|
|
47
|
+
usesContext?: boolean;
|
|
48
|
+
/** the component exports `revalidate = N` (ISR window in seconds) */
|
|
49
|
+
revalidate?: number;
|
|
50
|
+
/** the component exports `csr = false` (document ships without the client bundle) */
|
|
51
|
+
csr?: boolean;
|
|
52
|
+
/** the component exports `prefetch = 'off' | 'hover' | 'viewport' | 'all'` (app-global link-prefetch strategy) */
|
|
53
|
+
prefetch?: string;
|
|
54
|
+
/** the component exports `bundle = 'inline' | 'split'` (app-global client bundle mode, P0 §1) */
|
|
55
|
+
bundle?: string;
|
|
56
|
+
/** innovation #29: the static analysis says this component needs the client bundle */
|
|
57
|
+
needsClient?: boolean;
|
|
58
|
+
/** innovation #31: WHY it needs the client - the rules that fired, for the build report */
|
|
59
|
+
clientReasons?: string[];
|
|
60
|
+
/**
|
|
61
|
+
* innovation #31: shapes that MIGHT need JavaScript but the syntactic
|
|
62
|
+
* predicate cannot prove, on a component that otherwise ships none (an
|
|
63
|
+
* inline on* attribute, a javascript: URL, eval/new Function). Warnings,
|
|
64
|
+
* never errors: the document still ships, but the build says it out loud.
|
|
65
|
+
*/
|
|
66
|
+
jsWarnings?: string[];
|
|
67
|
+
/** the component exports `headers = { ... }` (per-route response headers) */
|
|
68
|
+
headers?: Record<string, string>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface RouteInfo {
|
|
72
|
+
filePath: string;
|
|
73
|
+
routePath: string;
|
|
74
|
+
pattern: string;
|
|
75
|
+
paramNames: string[];
|
|
76
|
+
isLayout: boolean;
|
|
77
|
+
/** pages/404.rose: the not-found page, not a matchable route */
|
|
78
|
+
isNotFound: boolean;
|
|
79
|
+
/** pages/500.rose: the error page for routes whose render throws */
|
|
80
|
+
isError: boolean;
|
|
81
|
+
/** pages/api/*.rose: a Web-standard handler route, not an HTML page */
|
|
82
|
+
isApi: boolean;
|
|
83
|
+
/** pages/_middleware.rose: the request interceptor, not a route */
|
|
84
|
+
isMiddleware: boolean;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface Decl {
|
|
88
|
+
name: string;
|
|
89
|
+
kind: 'state' | 'data';
|
|
90
|
+
expr: string;
|
|
91
|
+
start: number;
|
|
92
|
+
end: number;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Rewrite bare state reads as getter calls: `count` -> `count()`.
|
|
97
|
+
*
|
|
98
|
+
* A regex cannot do this safely - it would rewrite state names inside string
|
|
99
|
+
* literals (`.get('name')` -> `.get('name()')`), template text, and comments.
|
|
100
|
+
* This scanner copies those verbatim and only rewrites identifier positions,
|
|
101
|
+
* keeping the original exclusions: not after [\w$.] (property access) and not
|
|
102
|
+
* before [\w$:(] (call, declaration, or object key).
|
|
103
|
+
*/
|
|
104
|
+
function callifyStateReads(script: string, names: string[]): string {
|
|
105
|
+
if (names.length === 0) return script;
|
|
106
|
+
const scan = (src: string): string => {
|
|
107
|
+
let out = '';
|
|
108
|
+
let i = 0;
|
|
109
|
+
while (i < src.length) {
|
|
110
|
+
const ch = src[i];
|
|
111
|
+
// string literal: copy verbatim
|
|
112
|
+
if (ch === "'" || ch === '"') {
|
|
113
|
+
let j = i + 1;
|
|
114
|
+
while (j < src.length && src[j] !== ch) {
|
|
115
|
+
if (src[j] === '\\') j++;
|
|
116
|
+
j++;
|
|
117
|
+
}
|
|
118
|
+
out += src.slice(i, Math.min(j + 1, src.length));
|
|
119
|
+
i = j + 1;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
// template literal: copy text verbatim, scan ${...} as code
|
|
123
|
+
if (ch === '`') {
|
|
124
|
+
out += ch;
|
|
125
|
+
i++;
|
|
126
|
+
while (i < src.length && src[i] !== '`') {
|
|
127
|
+
if (src[i] === '\\') {
|
|
128
|
+
out += src.slice(i, i + 2);
|
|
129
|
+
i += 2;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (src[i] === '$' && src[i + 1] === '{') {
|
|
133
|
+
let depth = 1;
|
|
134
|
+
let j = i + 2;
|
|
135
|
+
while (j < src.length && depth > 0) {
|
|
136
|
+
if (src[j] === '{') depth++;
|
|
137
|
+
else if (src[j] === '}') depth--;
|
|
138
|
+
if (depth === 0) break;
|
|
139
|
+
j++;
|
|
140
|
+
}
|
|
141
|
+
out += '${' + scan(src.slice(i + 2, j)) + '}';
|
|
142
|
+
i = j + 1;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
out += src[i];
|
|
146
|
+
i++;
|
|
147
|
+
}
|
|
148
|
+
out += '`';
|
|
149
|
+
i++;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
// comments: copy verbatim
|
|
153
|
+
if (ch === '/' && src[i + 1] === '/') {
|
|
154
|
+
const nl = src.indexOf('\n', i);
|
|
155
|
+
const end = nl === -1 ? src.length : nl;
|
|
156
|
+
out += src.slice(i, end);
|
|
157
|
+
i = end;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (ch === '/' && src[i + 1] === '*') {
|
|
161
|
+
const close = src.indexOf('*/', i + 2);
|
|
162
|
+
const end = close === -1 ? src.length : close + 2;
|
|
163
|
+
out += src.slice(i, end);
|
|
164
|
+
i = end;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// identifier: rewrite bare state reads only
|
|
168
|
+
if (/[A-Za-z_$]/.test(ch)) {
|
|
169
|
+
let j = i;
|
|
170
|
+
while (j < src.length && /[\w$]/.test(src[j])) j++;
|
|
171
|
+
const word = src.slice(i, j);
|
|
172
|
+
const prev = out.length ? out[out.length - 1] : '';
|
|
173
|
+
const next = src[j] ?? '';
|
|
174
|
+
const rewrite = names.includes(word)
|
|
175
|
+
&& !/[\w$.]/.test(prev)
|
|
176
|
+
&& !/[\w$:(]/.test(next);
|
|
177
|
+
out += rewrite ? `${word}()` : word;
|
|
178
|
+
i = j;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
out += ch;
|
|
182
|
+
i++;
|
|
183
|
+
}
|
|
184
|
+
return out;
|
|
185
|
+
};
|
|
186
|
+
return scan(script);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A plugin transforms a component's raw source before compilation sees it. */
|
|
190
|
+
export interface Plugin {
|
|
191
|
+
name: string;
|
|
192
|
+
transform(code: string, filePath: string): string | Promise<string>;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Plugins live in `<root>/rosetack.config.js` as the default export: an array
|
|
197
|
+
* of `{ name, transform }`, run over each component's raw source (template +
|
|
198
|
+
* script + style, before any parsing). ponytail: ONE hook - it covers macros,
|
|
199
|
+
* custom syntax, includes and auto-imports; add bundler/build hooks when a
|
|
200
|
+
* real plugin needs one. The import is cache-busted per build so a config
|
|
201
|
+
* edit takes effect on the dev server's next rebuild, and a missing file is
|
|
202
|
+
* simply "no plugins" (existence is checked first, so a config with a syntax
|
|
203
|
+
* error still fails loudly).
|
|
204
|
+
*/
|
|
205
|
+
export async function loadPlugins(root: string): Promise<Plugin[]> {
|
|
206
|
+
const file = path.join(root, 'rosetack.config.js');
|
|
207
|
+
if (!fs.existsSync(file)) return [];
|
|
208
|
+
const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
|
|
209
|
+
return (mod.default as Plugin[] | undefined) ?? [];
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = []): Promise<CompileResult> {
|
|
213
|
+
let source = await fs.promises.readFile(filePath, 'utf-8');
|
|
214
|
+
// Plugins (innovation #30) see the raw source first: whatever they return is what the
|
|
215
|
+
// compiler parses.
|
|
216
|
+
for (const p of plugins) {
|
|
217
|
+
try {
|
|
218
|
+
source = await p.transform(source, filePath);
|
|
219
|
+
} catch (err) {
|
|
220
|
+
throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// API route (pages/api/*.rose): no template, no state, no markers - the script's exported
|
|
225
|
+
// functions ARE the handlers …
|
|
226
|
+
if (isApi) {
|
|
227
|
+
const scriptMatch = source.match(COMPONENT_RE);
|
|
228
|
+
const rawScript = scriptMatch?.[1] ?? '';
|
|
229
|
+
const apiMethods = [...rawScript.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)]
|
|
230
|
+
.map((m) => m[1])
|
|
231
|
+
.filter((name) => HTTP_METHODS.has(name));
|
|
232
|
+
// a handler that reads the request context cannot be baked: the bag is
|
|
233
|
+
// per-request, a baked body would freeze one request's answer
|
|
234
|
+
const usesContext = /getContext\s*\(/.test(rawScript);
|
|
235
|
+
const hasPrerender = !usesContext && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript);
|
|
236
|
+
return {
|
|
237
|
+
ssr: '',
|
|
238
|
+
client: '',
|
|
239
|
+
stateKeys: [],
|
|
240
|
+
actionNames: [],
|
|
241
|
+
style: '',
|
|
242
|
+
hasParams: false,
|
|
243
|
+
api: `import { getContext } from './runtime.js';\n${rawScript.trim()}`,
|
|
244
|
+
apiMethods,
|
|
245
|
+
hasPrerender,
|
|
246
|
+
usesContext,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// strip the <style> block first: its CSS is scoped and inlined into the
|
|
251
|
+
// shell, and it must not leak into the template (or the <head> scan)
|
|
252
|
+
const styleMatch = source.match(STYLE_RE);
|
|
253
|
+
const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : '';
|
|
254
|
+
const sourceNoBlocks = source.replace(STYLE_RE, '');
|
|
255
|
+
|
|
256
|
+
const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
|
|
257
|
+
const rawScript = scriptMatch?.[1] ?? '';
|
|
258
|
+
// getContext() in the script makes the route dynamic: the request bag is per-request, so
|
|
259
|
+
// the build must not bake it and the servers must not answer it from a prerendered file.
|
|
260
|
+
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
|
|
261
|
+
// an exported `params` marks a dynamic route for prerender enumeration
|
|
262
|
+
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
263
|
+
// an exported `revalidate = N` opts the route into stale-while-revalidate: the baked file
|
|
264
|
+
// is served for up to N seconds …
|
|
265
|
+
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
266
|
+
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
|
|
267
|
+
// P1 (consultant report): an exported `prefetch = '...'` sets the app-global
|
|
268
|
+
// link-prefetch strategy - 'off', 'hover' …
|
|
269
|
+
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
270
|
+
const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
|
|
271
|
+
if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
|
|
272
|
+
throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
|
|
273
|
+
}
|
|
274
|
+
// P0 §1 (consultant report): the bundle mode - the fix for the large-app architecture
|
|
275
|
+
// gap.
|
|
276
|
+
const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
277
|
+
const bundle = bundleMatch ? bundleMatch[1] : undefined;
|
|
278
|
+
if (bundle && !['inline', 'split'].includes(bundle)) {
|
|
279
|
+
throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
|
|
280
|
+
}
|
|
281
|
+
// Innovation #29: the compiler decides zero-JS, not the developer. This is the same "does
|
|
282
|
+
// anything here need the client bundle" predicate that innovation #25 used to REFUSE …
|
|
283
|
+
const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
|
|
284
|
+
const csr: boolean | undefined = csrMatch ? csrMatch[1] !== 'false' : undefined;
|
|
285
|
+
if (csr === false) {
|
|
286
|
+
const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
|
|
287
|
+
if (dead) {
|
|
288
|
+
throw new Error(
|
|
289
|
+
`${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. ` +
|
|
290
|
+
`(Forms still work without JS: a native POST runs the server action.)`
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// An exported `headers = { ... }` sets this route's response headers (innovation #26) -
|
|
296
|
+
// the servers merge them OVER the framework defaults (the strict CSP) …
|
|
297
|
+
let headers: Record<string, string> | undefined;
|
|
298
|
+
const headersLiteral = extractObjectLiteral(rawScript, 'headers');
|
|
299
|
+
if (headersLiteral) {
|
|
300
|
+
let value: unknown;
|
|
301
|
+
try {
|
|
302
|
+
value = new Function(`return ${headersLiteral}`)();
|
|
303
|
+
} catch {
|
|
304
|
+
throw new Error(`${filePath}: export const headers must be an object literal`);
|
|
305
|
+
}
|
|
306
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value as object).some((v) => typeof v !== 'string')) {
|
|
307
|
+
throw new Error(`${filePath}: export const headers must be a flat map of string -> string`);
|
|
308
|
+
}
|
|
309
|
+
headers = value as Record<string, string>;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Top-level `export` statements (e.g. `export const params = {...}` for dynamic-route
|
|
313
|
+
// prerendering) are hoisted to module scope: the script body itself is embedded inside …
|
|
314
|
+
const { clean: scriptNoExports, exports: exportStmts, actions } = extractExports(rawScript);
|
|
315
|
+
const script = scriptNoExports;
|
|
316
|
+
const actionNames = new Set(actions.map((a) => a.name));
|
|
317
|
+
|
|
318
|
+
// Innovation #29: does anything in this component need the client bundle?
|
|
319
|
+
const clientReasons: string[] = [];
|
|
320
|
+
if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)'); // event wiring in the template
|
|
321
|
+
if (/<form[\s>]/.test(source)) clientReasons.push('a <form> (its in-place adopt is the enhancement)'); // a POST form
|
|
322
|
+
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
323
|
+
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`); // lifecycle / client-only APIs
|
|
324
|
+
if (actionNames.size > 0) { // a server action (form target or $action)
|
|
325
|
+
clientReasons.push(`server action${actionNames.size > 1 ? 's' : ''} (${[...actionNames].join(', ')})`);
|
|
326
|
+
}
|
|
327
|
+
const needsClient = clientReasons.length > 0;
|
|
328
|
+
|
|
329
|
+
// Innovation #31: the predicate is SYNTACTIC, so a component that ships no runtime is
|
|
330
|
+
// scanned for the shapes that would silently need one …
|
|
331
|
+
const jsWarnings: string[] = [];
|
|
332
|
+
if (!needsClient) {
|
|
333
|
+
if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
|
|
334
|
+
jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
|
|
335
|
+
}
|
|
336
|
+
if (/javascript:/i.test(source)) {
|
|
337
|
+
jsWarnings.push('a javascript: URL - it needs the bundle to run; link to a real route');
|
|
338
|
+
}
|
|
339
|
+
if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
|
|
340
|
+
jsWarnings.push('eval()/new Function() - client code the predicate cannot see');
|
|
341
|
+
}
|
|
342
|
+
// Browser-only globals. The script block is embedded inside render() on BOTH sides …
|
|
343
|
+
if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(rawScript)) {
|
|
344
|
+
jsWarnings.push('browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true');
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
|
|
349
|
+
// strip the <head> block so it never leaks into the page template
|
|
350
|
+
const headMatch = sourceNoBlocks.match(HEAD_RE);
|
|
351
|
+
const headContent = headMatch?.[1] ?? '';
|
|
352
|
+
const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, '');
|
|
353
|
+
const rawTemplate = templateMatch
|
|
354
|
+
? templateMatch[1]
|
|
355
|
+
: sourceNoHead.replace(COMPONENT_RE, '').trim();
|
|
356
|
+
// a component with styles carries its scope attribute on every top-level
|
|
357
|
+
// element, so its rules match only its own subtree
|
|
358
|
+
const template = scopedStyle
|
|
359
|
+
? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey)
|
|
360
|
+
: inlineImages(rawTemplate, publicDir);
|
|
361
|
+
|
|
362
|
+
// Extract state / data declarations with balanced-paren scanning
|
|
363
|
+
const decls = extractDecls(script);
|
|
364
|
+
const stateDecls = decls.filter((d) => d.kind === 'state');
|
|
365
|
+
|
|
366
|
+
// setter name per state: setCount
|
|
367
|
+
const setterNames = new Map<string, string>();
|
|
368
|
+
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
369
|
+
|
|
370
|
+
// Extract event bindings from original template. Handlers bound to a server action never
|
|
371
|
+
// reach the client registry: they compile to data-on-*="$action:name" and dispatch …
|
|
372
|
+
const eventBindings: Array<{ event: string; fn: string }> = [];
|
|
373
|
+
let em: RegExpExecArray | null;
|
|
374
|
+
EVENT_RE.lastIndex = 0;
|
|
375
|
+
while ((em = EVENT_RE.exec(template))) {
|
|
376
|
+
if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Remove declarations from script, rewrite $setState to setters
|
|
380
|
+
let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end] as [number, number]));
|
|
381
|
+
cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
|
|
382
|
+
const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, '');
|
|
383
|
+
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
384
|
+
return `${setter}(${val})`;
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
// on:event={fn} -> data-on-event="fn"; a handler that names a server action becomes
|
|
388
|
+
// data-on-event="$action:fn" (dispatched by $action); <slot /> -> block marker
|
|
389
|
+
const ssrTemplate = template
|
|
390
|
+
.replace(SLOT_RE, '{__slot__}')
|
|
391
|
+
.replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) =>
|
|
392
|
+
actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
|
|
393
|
+
|
|
394
|
+
// Replace bare state reads with getter calls (after decl removal). A plain regex would
|
|
395
|
+
// also rewrite state names inside string literals …
|
|
396
|
+
cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
|
|
397
|
+
|
|
398
|
+
const stateDeclsCode = decls
|
|
399
|
+
.map((d) => {
|
|
400
|
+
if (d.kind === 'state') {
|
|
401
|
+
return `const [${d.name}, ${setterNames.get(d.name)!}] = state("${d.name}", ${d.expr});`;
|
|
402
|
+
}
|
|
403
|
+
// $data: fetch only when this key has no value yet (server: always after
|
|
404
|
+
// clearRequestState; client: only on first visit or client-side nav)
|
|
405
|
+
const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
|
|
406
|
+
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
407
|
+
return `const __had_${d.name} = hasState("${d.name}");
|
|
408
|
+
const [${d.name}, set${capitalize(d.name)}] = state("${d.name}", null);
|
|
409
|
+
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
410
|
+
})
|
|
411
|
+
.join('\n');
|
|
412
|
+
|
|
413
|
+
const stateKeys = decls.map((d) => d.name);
|
|
414
|
+
|
|
415
|
+
const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0);
|
|
416
|
+
// head block: no markers (esc() inline) - the whole block re-renders per
|
|
417
|
+
// call, so one reactive closure drives document title/meta on navigation.
|
|
418
|
+
const compiledHead = headContent.trim() ? compileTemplate(headContent, '__hd', '__hc', null, 0, false) : '';
|
|
419
|
+
|
|
420
|
+
// Actions ship in the SSR module only; the client bundle gets every other
|
|
421
|
+
// export (params, sync helpers) but never an action body.
|
|
422
|
+
const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
|
|
423
|
+
const ssr = generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead);
|
|
424
|
+
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead);
|
|
425
|
+
|
|
426
|
+
return { ssr, client, stateKeys, actionNames: [...actionNames], style: scopedStyle, hasParams, usesContext, revalidate, csr, prefetch, bundle, needsClient, clientReasons, jsWarnings, headers };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Scope a component's CSS to its own subtree: every selector is prefixed
|
|
431
|
+
* with the component's scope attribute, recursing into @media/@supports.
|
|
432
|
+
* ponytail: no full CSS parser - comma lists only, and @keyframes blocks
|
|
433
|
+
* pass through unscoped (their from/to/to selectors are not selectors).
|
|
434
|
+
* Global element rules (:root/html/body) belong in the shell's STYLES.
|
|
435
|
+
*/
|
|
436
|
+
function scopeCss(css: string, key: string): string {
|
|
437
|
+
const attr = `[data-rosetack-c="${key}"]`;
|
|
438
|
+
const clean = css.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
439
|
+
let out = '';
|
|
440
|
+
let prelude = '';
|
|
441
|
+
let i = 0;
|
|
442
|
+
while (i < clean.length) {
|
|
443
|
+
const ch = clean[i];
|
|
444
|
+
if (ch === '{') {
|
|
445
|
+
let depth = 1;
|
|
446
|
+
let j = i + 1;
|
|
447
|
+
while (j < clean.length && depth > 0) {
|
|
448
|
+
if (clean[j] === '{') depth++;
|
|
449
|
+
else if (clean[j] === '}') depth--;
|
|
450
|
+
j++;
|
|
451
|
+
}
|
|
452
|
+
const block = clean.slice(i + 1, j - 1);
|
|
453
|
+
const sel = prelude.trim();
|
|
454
|
+
if (sel.startsWith('@')) {
|
|
455
|
+
// at-rule: keep the prelude, scope the inner rules (keyframes pass
|
|
456
|
+
// through: their 0%/from/to "selectors" are not selectors)
|
|
457
|
+
out += `${sel} { ${/^@(?:-[\w]+-)?keyframes/.test(sel) ? block : scopeCss(block, key)} }`;
|
|
458
|
+
} else if (sel) {
|
|
459
|
+
const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(', ');
|
|
460
|
+
out += `${scoped} { ${block} }`;
|
|
461
|
+
}
|
|
462
|
+
prelude = '';
|
|
463
|
+
i = j;
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
if (ch !== '}' && ch !== '\n' && ch !== '\r') prelude += ch;
|
|
467
|
+
else if (ch === '}') prelude = '';
|
|
468
|
+
i++;
|
|
469
|
+
}
|
|
470
|
+
return out.trim();
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Add the scope attribute to every top-level element of a template. Tag
|
|
475
|
+
* depth is tracked with quoted-attribute awareness, so elements inside a
|
|
476
|
+
* top-level {#if}/{#each} block are top-level at render time and get it too.
|
|
477
|
+
*/
|
|
478
|
+
function injectScopeAttr(template: string, key: string): string {
|
|
479
|
+
const attr = ` data-rosetack-c="${key}"`;
|
|
480
|
+
let out = '';
|
|
481
|
+
let depth = 0;
|
|
482
|
+
let i = 0;
|
|
483
|
+
while (i < template.length) {
|
|
484
|
+
const lt = template.indexOf('<', i);
|
|
485
|
+
if (lt === -1) {
|
|
486
|
+
out += template.slice(i);
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
out += template.slice(i, lt);
|
|
490
|
+
// scan one tag, respecting quoted attribute values
|
|
491
|
+
let j = lt + 1;
|
|
492
|
+
let quote = '';
|
|
493
|
+
while (j < template.length) {
|
|
494
|
+
const c = template[j];
|
|
495
|
+
if (quote) {
|
|
496
|
+
if (c === quote) quote = '';
|
|
497
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
498
|
+
else if (c === '>') break;
|
|
499
|
+
j++;
|
|
500
|
+
}
|
|
501
|
+
const tagText = template.slice(lt, j + 1); // includes < and >
|
|
502
|
+
const closing = /^<\//.test(tagText);
|
|
503
|
+
const nameMatch = tagText.match(/^<\/?([a-zA-Z][\w-]*)/);
|
|
504
|
+
const selfClosing = /\/>$/.test(tagText) || (nameMatch && VOID_TAGS.has(nameMatch[1].toLowerCase()));
|
|
505
|
+
if (nameMatch && !closing && depth === 0 && !selfClosing) {
|
|
506
|
+
// inject before the closing > (or before a trailing />)
|
|
507
|
+
const injectAt = tagText.endsWith('/>') ? tagText.length - 2 : tagText.length - 1;
|
|
508
|
+
out += tagText.slice(0, injectAt) + attr + tagText.slice(injectAt);
|
|
509
|
+
depth++;
|
|
510
|
+
} else {
|
|
511
|
+
out += tagText;
|
|
512
|
+
if (nameMatch) depth += closing ? -1 : selfClosing ? 0 : 1;
|
|
513
|
+
}
|
|
514
|
+
i = j + 1;
|
|
515
|
+
}
|
|
516
|
+
return out;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const VOID_TAGS = new Set(['img', 'br', 'hr', 'input', 'meta', 'link', 'source', 'wbr']);
|
|
520
|
+
|
|
521
|
+
// ponytail: tolerate leading indentation - .rose script blocks are indented
|
|
522
|
+
const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Lift top-level `export const/let/var/function` statements out of the script
|
|
526
|
+
* body. They must be self-contained (no references to state or template
|
|
527
|
+
* scope) - they exist for build-time consumers like dynamic-route `params`.
|
|
528
|
+
*
|
|
529
|
+
* Every exported ASYNC function is a SERVER-ONLY action (Next.js semantics:
|
|
530
|
+
* `export const params` and sync helpers stay shared, async exports are
|
|
531
|
+
* server code). `action` is the conventional name a <form method="POST">
|
|
532
|
+
* posts to; any other name is reachable from an event handler
|
|
533
|
+
* (`on:click={like}` compiles to `$action('like')`) or a hidden form field.
|
|
534
|
+
* Action bodies reach the SSR module but NEVER the client bundle.
|
|
535
|
+
*/
|
|
536
|
+
/**
|
|
537
|
+
* Extract an exported object literal (`export const headers = { ... }`) by
|
|
538
|
+
* name, with a balanced-brace scan so nested values survive the capture.
|
|
539
|
+
* Returns the raw literal text, or null when the export is absent.
|
|
540
|
+
*/
|
|
541
|
+
function extractObjectLiteral(script: string, name: string): string | null {
|
|
542
|
+
const m = new RegExp(`(?:^|\\n)\\s*export\\s+(?:const|let|var)\\s+${name}\\s*=\\s*`).exec(script);
|
|
543
|
+
if (!m) return null;
|
|
544
|
+
let i = m.index + m[0].length;
|
|
545
|
+
if (script[i] !== '{') return null;
|
|
546
|
+
const start = i;
|
|
547
|
+
let depth = 0;
|
|
548
|
+
for (; i < script.length; i++) {
|
|
549
|
+
const ch = script[i];
|
|
550
|
+
if (ch === '{') depth++;
|
|
551
|
+
else if (ch === '}') {
|
|
552
|
+
depth--;
|
|
553
|
+
if (depth === 0) {
|
|
554
|
+
i++;
|
|
555
|
+
break;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return script.slice(start, i);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }> } {
|
|
563
|
+
const stmts: string[] = [];
|
|
564
|
+
const actions: Array<{ name: string; stmt: string }> = [];
|
|
565
|
+
let out = '';
|
|
566
|
+
let pos = 0;
|
|
567
|
+
let m: RegExpExecArray | null;
|
|
568
|
+
EXPORT_RE.lastIndex = 0;
|
|
569
|
+
while ((m = EXPORT_RE.exec(script))) {
|
|
570
|
+
const kind = m[1]; // const/let/var, or undefined for function
|
|
571
|
+
const start = m.index + m[0].indexOf('export'); // skip leading indentation
|
|
572
|
+
let i = start + m[0].length - m[0].indexOf('export');
|
|
573
|
+
if (kind) {
|
|
574
|
+
// balanced scan: object/array literals, calls, arrows end at their
|
|
575
|
+
// matching close; primitive literals end at `;` or a plain newline.
|
|
576
|
+
let depth = 0;
|
|
577
|
+
while (i < script.length) {
|
|
578
|
+
const ch = script[i];
|
|
579
|
+
if (ch === '(' || ch === '{' || ch === '[') depth++;
|
|
580
|
+
else if (ch === ')' || ch === '}' || ch === ']') {
|
|
581
|
+
depth--;
|
|
582
|
+
if (depth === 0) {
|
|
583
|
+
i++;
|
|
584
|
+
break;
|
|
585
|
+
}
|
|
586
|
+
} else if (depth === 0 && ch === ';') {
|
|
587
|
+
i++;
|
|
588
|
+
break;
|
|
589
|
+
} else if (depth === 0 && ch === '\n') {
|
|
590
|
+
const rest = script.slice(i + 1);
|
|
591
|
+
if (!/^\s*[.([{+\-*/?:,=&|]/.test(rest)) {
|
|
592
|
+
i++;
|
|
593
|
+
break;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
i++;
|
|
597
|
+
}
|
|
598
|
+
if (script[i] === ';') i++;
|
|
599
|
+
} else {
|
|
600
|
+
// function declaration: skip the parameter list, balance the body
|
|
601
|
+
while (i < script.length && script[i] !== '{') i++;
|
|
602
|
+
let depth = 0;
|
|
603
|
+
while (i < script.length) {
|
|
604
|
+
const ch = script[i];
|
|
605
|
+
if (ch === '{') depth++;
|
|
606
|
+
else if (ch === '}') {
|
|
607
|
+
depth--;
|
|
608
|
+
if (depth === 0) {
|
|
609
|
+
i++;
|
|
610
|
+
break;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
i++;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
out += script.slice(pos, start);
|
|
617
|
+
const stmt = script.slice(start, i).trim();
|
|
618
|
+
const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
|
|
619
|
+
if (asyncFn) {
|
|
620
|
+
actions.push({ name: asyncFn[1], stmt }); // server-only: kept out of the client bundle
|
|
621
|
+
} else {
|
|
622
|
+
stmts.push(stmt);
|
|
623
|
+
}
|
|
624
|
+
pos = i;
|
|
625
|
+
}
|
|
626
|
+
out += script.slice(pos);
|
|
627
|
+
return { clean: out, exports: stmts.join('\n'), actions };
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function extractDecls(script: string): Decl[] {
|
|
631
|
+
const decls: Decl[] = [];
|
|
632
|
+
DECL_RE.lastIndex = 0;
|
|
633
|
+
let m: RegExpExecArray | null;
|
|
634
|
+
while ((m = DECL_RE.exec(script))) {
|
|
635
|
+
const open = m.index + m[0].length;
|
|
636
|
+
let depth = 1;
|
|
637
|
+
let i = open;
|
|
638
|
+
while (i < script.length && depth > 0) {
|
|
639
|
+
const ch = script[i];
|
|
640
|
+
if (ch === '(') depth++;
|
|
641
|
+
else if (ch === ')') depth--;
|
|
642
|
+
i++;
|
|
643
|
+
}
|
|
644
|
+
let end = i;
|
|
645
|
+
if (script[end] === ';') end++;
|
|
646
|
+
decls.push({
|
|
647
|
+
name: m[1],
|
|
648
|
+
kind: m[2] as 'state' | 'data',
|
|
649
|
+
expr: script.slice(open, i - 1).trim(),
|
|
650
|
+
start: m.index,
|
|
651
|
+
end,
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
return decls;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function removeRanges(text: string, ranges: Array<[number, number]>): string {
|
|
658
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
|
|
659
|
+
let out = '';
|
|
660
|
+
let pos = 0;
|
|
661
|
+
for (const [start, end] of sorted) {
|
|
662
|
+
out += text.slice(pos, start);
|
|
663
|
+
pos = end;
|
|
664
|
+
}
|
|
665
|
+
out += text.slice(pos);
|
|
666
|
+
return out;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Compile a .rose template to statements that build an HTML string with
|
|
671
|
+
* reactive markers, and push update closures into the shared `closes` array.
|
|
672
|
+
*
|
|
673
|
+
* Marker protocol (identical on server and client, so the client can adopt
|
|
674
|
+
* the SSR DOM instead of re-rendering it):
|
|
675
|
+
* text: <!--⟦m:K⟧-->value wire() updates the following text node
|
|
676
|
+
* if block: <!--⟦i:K⟧-->html<!--⟦/i:K⟧--> wire() inserts/removes the block
|
|
677
|
+
* each list: <!--⟦l:K⟧-->items<!--⟦/l:K⟧--> wire() rebuilds the list
|
|
678
|
+
* attr: name="value" data-b="K:name" wire() re-sets the attribute
|
|
679
|
+
*
|
|
680
|
+
* Text/attr values are HTML-escaped on the server; wire() writes raw values
|
|
681
|
+
* because DOM text nodes and attributes are not HTML-parsed.
|
|
682
|
+
*/
|
|
683
|
+
function compileTemplate(
|
|
684
|
+
template: string,
|
|
685
|
+
acc: string,
|
|
686
|
+
closes: string,
|
|
687
|
+
scope: string | null,
|
|
688
|
+
depth: number,
|
|
689
|
+
markers = true
|
|
690
|
+
): string {
|
|
691
|
+
let result = '';
|
|
692
|
+
let remaining = template;
|
|
693
|
+
let blockId = 0;
|
|
694
|
+
|
|
695
|
+
const nextId = () => `${depth}_${blockId++}`;
|
|
696
|
+
|
|
697
|
+
while (remaining.length > 0) {
|
|
698
|
+
const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/) as RegExpExecArray | null;
|
|
699
|
+
const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/) as RegExpExecArray | null;
|
|
700
|
+
const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/) as RegExpExecArray | null;
|
|
701
|
+
const exprMatch = remaining.match(/\{([^{}]+)\}/) as RegExpExecArray | null;
|
|
702
|
+
|
|
703
|
+
const candidates: Array<{ type: string; match: RegExpExecArray; index: number }> = [];
|
|
704
|
+
if (ifMatch?.index !== undefined) candidates.push({ type: 'if', match: ifMatch, index: ifMatch.index });
|
|
705
|
+
if (eachMatch?.index !== undefined) candidates.push({ type: 'each', match: eachMatch, index: eachMatch.index });
|
|
706
|
+
if (boundaryMatch?.index !== undefined) candidates.push({ type: 'boundary', match: boundaryMatch, index: boundaryMatch.index });
|
|
707
|
+
if (exprMatch?.index !== undefined) candidates.push({ type: 'expr', match: exprMatch, index: exprMatch.index });
|
|
708
|
+
const earliest = candidates.length > 0
|
|
709
|
+
? candidates.reduce((a, b) => (a.index <= b.index ? a : b))
|
|
710
|
+
: null;
|
|
711
|
+
|
|
712
|
+
if (!earliest) {
|
|
713
|
+
result += emitChunk(remaining, acc, closes, scope);
|
|
714
|
+
break;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
if (earliest.type === 'if') {
|
|
718
|
+
const [, cond, content] = earliest.match;
|
|
719
|
+
const before = remaining.substring(0, earliest.index);
|
|
720
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
721
|
+
const call = cond.trim().endsWith('()') ? cond.trim() : `${cond.trim()}()`;
|
|
722
|
+
const id = nextId();
|
|
723
|
+
const innerScope = scope ?? '__s';
|
|
724
|
+
// Inner markers live in the block's OWN closes array, so wiring an
|
|
725
|
+
// adopted/cloned block never re-touches the parent's markers.
|
|
726
|
+
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers);
|
|
727
|
+
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
|
|
728
|
+
if (markers) {
|
|
729
|
+
result += `const __c${id} = [];\n`;
|
|
730
|
+
result += `const __bh${id} = __b${id}(${scope ?? 'undefined'}, __c${id});\n`;
|
|
731
|
+
result += `const __i${id} = ${closes}.length;\n`;
|
|
732
|
+
result += `${closes}.push(() => (${call}) ? { html: __bh${id}, closes: __c${id} } : null);\n`;
|
|
733
|
+
result += `${acc} += "<!--\u27e6i:" + __i${id} + "\u27e7-->";\n`;
|
|
734
|
+
result += `{ const __r = ${closes}[__i${id}](); if (__r) ${acc} += __r.html; }\n`;
|
|
735
|
+
result += `${acc} += "<!--\u27e6/i:" + __i${id} + "\u27e7-->";\n`;
|
|
736
|
+
} else {
|
|
737
|
+
result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
|
|
738
|
+
}
|
|
739
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
740
|
+
} else if (earliest.type === 'each') {
|
|
741
|
+
const [, items, item, content] = earliest.match;
|
|
742
|
+
const before = remaining.substring(0, earliest.index);
|
|
743
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
744
|
+
const call = items.trim().endsWith('()') ? items.trim() : `${items.trim()}()`;
|
|
745
|
+
const id = nextId();
|
|
746
|
+
// Rename the item variable to the block's scope parameter
|
|
747
|
+
const scoped = content.trim().replace(new RegExp(`\\b${item}\\b`, 'g'), '__s');
|
|
748
|
+
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, markers);
|
|
749
|
+
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
|
|
750
|
+
if (markers) {
|
|
751
|
+
result += `const __i${id} = ${closes}.length;\n`;
|
|
752
|
+
result += `${closes}.push(() => (${call}).map((${item}) => { const __c = []; return { html: __b${id}(${item}, __c), closes: __c, scope: ${item} }; }));\n`;
|
|
753
|
+
result += `${acc} += "<!--\u27e6l:" + __i${id} + "\u27e7-->";\n`;
|
|
754
|
+
result += `${closes}[__i${id}]().forEach((__r) => { ${acc} += __r.html; });\n`;
|
|
755
|
+
result += `${acc} += "<!--\u27e6/l:" + __i${id} + "\u27e7-->";\n`;
|
|
756
|
+
} else {
|
|
757
|
+
result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');\n`;
|
|
758
|
+
}
|
|
759
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
760
|
+
} else if (earliest.type === 'boundary') {
|
|
761
|
+
const [, content] = earliest.match;
|
|
762
|
+
const before = remaining.substring(0, earliest.index);
|
|
763
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
764
|
+
const id = nextId();
|
|
765
|
+
// Error boundary: the content renders into its OWN string and is only appended on
|
|
766
|
+
// success - a throw anywhere inside swaps in the fallback …
|
|
767
|
+
const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers);
|
|
768
|
+
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
|
|
769
|
+
result += `let __bd${id} = '';\n`;
|
|
770
|
+
result += `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
|
|
771
|
+
result += `${acc} += __bd${id};\n`;
|
|
772
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
773
|
+
} else {
|
|
774
|
+
const [, expr] = earliest.match;
|
|
775
|
+
const trimmed = expr.trim();
|
|
776
|
+
const before = remaining.substring(0, earliest.index);
|
|
777
|
+
if (trimmed === '__slot__') {
|
|
778
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
779
|
+
result += compileSlot(acc);
|
|
780
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
// attr={expr} -> reactive attribute; otherwise a text marker
|
|
784
|
+
const attrMatch = before.match(/([\w-]+)=\s*$/);
|
|
785
|
+
if (attrMatch) {
|
|
786
|
+
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
787
|
+
if (lit) result += emitChunk(lit, acc, closes, scope);
|
|
788
|
+
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
|
|
789
|
+
} else {
|
|
790
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
791
|
+
result += emitText(trimmed, acc, closes, scope, markers);
|
|
792
|
+
}
|
|
793
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
return result;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/** Emit a static chunk (attributes are handled by the expr branch). */
|
|
801
|
+
function emitChunk(text: string, acc: string, closes: string, scope: string | null): string {
|
|
802
|
+
if (!text) return '';
|
|
803
|
+
return `${acc} += ${JSON.stringify(text)};\n`;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// --- Build-time image inlining ------------------------------------------- One fewer
|
|
807
|
+
// request per small local image: <img src="/logo.svg"> ships as a data URI inside the …
|
|
808
|
+
|
|
809
|
+
const IMG_RE = /<img\b(?:[^<>]|\{[^{}]*\})*>/g;
|
|
810
|
+
const IMG_MIME: Record<string, string> = {
|
|
811
|
+
'.png': 'image/png',
|
|
812
|
+
'.jpg': 'image/jpeg',
|
|
813
|
+
'.jpeg': 'image/jpeg',
|
|
814
|
+
'.gif': 'image/gif',
|
|
815
|
+
'.webp': 'image/webp',
|
|
816
|
+
'.svg': 'image/svg+xml',
|
|
817
|
+
'.ico': 'image/x-icon',
|
|
818
|
+
};
|
|
819
|
+
// ponytail: fixed 4 KB cap; make it configurable when a real app cares
|
|
820
|
+
const INLINE_IMG_MAX = 4096;
|
|
821
|
+
|
|
822
|
+
function inlineImages(template: string, publicDir: string): string {
|
|
823
|
+
return template.replace(IMG_RE, (tag) => {
|
|
824
|
+
const src = tag.match(/\bsrc="(\/[^"{}]+)"/); // static, site-root-relative only
|
|
825
|
+
if (!src) return tag; // reactive/remote/missing src: leave it alone
|
|
826
|
+
const ext = path.extname(src[1]).toLowerCase();
|
|
827
|
+
const mime = IMG_MIME[ext];
|
|
828
|
+
if (!mime) return tag;
|
|
829
|
+
let file: Buffer;
|
|
830
|
+
try {
|
|
831
|
+
file = fs.readFileSync(path.join(publicDir, src[1]));
|
|
832
|
+
} catch {
|
|
833
|
+
return tag; // not in public/ at build time: keep the URL, server 404s honestly
|
|
834
|
+
}
|
|
835
|
+
if (file.length > INLINE_IMG_MAX) return tag;
|
|
836
|
+
// SVG inlines as text (percent-encoded for #, ", %); binaries as base64
|
|
837
|
+
const uri = ext === '.svg'
|
|
838
|
+
? `data:image/svg+xml,${file.toString('utf-8').replace(/%/g, '%25').replace(/#/g, '%23').replace(/\{/g, '%7B').replace(/\}/g, '%7D').replace(/"/g, '%22')}`
|
|
839
|
+
: `data:${mime};base64,${file.toString('base64')}`;
|
|
840
|
+
return tag.replace(src[0], `src="${uri}"`);
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/** Emit a reactive text marker: <!--⟦m:K⟧-->escaped value. */
|
|
845
|
+
function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
|
|
846
|
+
const arg = scope ? `${scope}` : '';
|
|
847
|
+
if (!markers) {
|
|
848
|
+
// head block: inline escaped value, no marker comment (clean SSR html)
|
|
849
|
+
return `${acc} += esc(${expr});\n`;
|
|
850
|
+
}
|
|
851
|
+
return `${acc} += "<!--\u27e6m:" + (${closes}.push(${scope ? `(${scope})` : '()'} => (${expr})) - 1) + "\u27e7-->" + esc(${closes}[${closes}.length - 1](${arg}));\n`;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/** Emit a reactive attribute: name="value" data-b="K:name". */
|
|
855
|
+
function emitAttr(attr: string, expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
|
|
856
|
+
if (!markers) {
|
|
857
|
+
return `${acc} += '${attr}="' + esc(${expr}) + '"';\n`;
|
|
858
|
+
}
|
|
859
|
+
const arg = scope ? `${scope}` : '';
|
|
860
|
+
return `${acc} += '${attr}="' + esc(${closes}[${closes}.push(${scope ? `(${scope})` : '()'} => (${expr})) - 1](${arg})) + '" data-b="' + (${closes}.length - 1) + ':${attr}"';\n`;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* <slot /> -> inline the children html. The page rendered first with the same
|
|
865
|
+
* shared closes array, so the top-level wire() pass resolves its markers.
|
|
866
|
+
*/
|
|
867
|
+
function compileSlot(acc: string): string {
|
|
868
|
+
return `${acc} += String(children);\n`;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = ''): string {
|
|
872
|
+
// The head block renders to a clean html string (no markers) and is wrapped in an h
|
|
873
|
+
// marker pair: renderPage extracts it for <head> injection …
|
|
874
|
+
const headCode = headFn
|
|
875
|
+
? `
|
|
876
|
+
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
877
|
+
const __hi = closes.length;
|
|
878
|
+
closes.push(__head);
|
|
879
|
+
__html += "<!--\u27e6h:" + __hi + "\u27e7-->" + __head() + "<!--\u27e6/h:" + __hi + "\u27e7-->";`
|
|
880
|
+
: '';
|
|
881
|
+
return `
|
|
882
|
+
import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, $cookies, $sessionCookie, $store } from './runtime.js';
|
|
883
|
+
|
|
884
|
+
${exports}
|
|
885
|
+
|
|
886
|
+
export async function render(closes, children) {
|
|
887
|
+
${stateDeclsCode}
|
|
888
|
+
${script}
|
|
889
|
+
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
890
|
+
let __html = await __root(closes, children);${headCode}
|
|
891
|
+
return __html;
|
|
892
|
+
}
|
|
893
|
+
`;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function generateClient(
|
|
897
|
+
script: string,
|
|
898
|
+
templateFn: string,
|
|
899
|
+
stateDeclsCode: string,
|
|
900
|
+
eventBindings: Array<{ event: string; fn: string }>,
|
|
901
|
+
exports = '',
|
|
902
|
+
headFn = ''
|
|
903
|
+
): string {
|
|
904
|
+
// Handlers live on a shared global so one delegated listener per event
|
|
905
|
+
// type can dispatch for any component, including freshly cloned nodes.
|
|
906
|
+
const handlerRegistry = eventBindings.length > 0
|
|
907
|
+
? `Object.assign(__handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
|
|
908
|
+
: '';
|
|
909
|
+
const headCode = headFn
|
|
910
|
+
? `
|
|
911
|
+
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
912
|
+
const __hi = closes.length;
|
|
913
|
+
closes.push(__head);
|
|
914
|
+
__html += "<!--\u27e6h:" + __hi + "\u27e7-->" + __head() + "<!--\u27e6/h:" + __hi + "\u27e7-->";`
|
|
915
|
+
: '';
|
|
916
|
+
|
|
917
|
+
return `
|
|
918
|
+
import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, $cookies, $sessionCookie, $store } from './runtime.js';
|
|
919
|
+
|
|
920
|
+
${exports}
|
|
921
|
+
|
|
922
|
+
const __handlers = globalThis.__rosetack_handlers ?? (globalThis.__rosetack_handlers = {});
|
|
923
|
+
|
|
924
|
+
export async function render(closes, children) {
|
|
925
|
+
${stateDeclsCode}
|
|
926
|
+
${script}
|
|
927
|
+
${handlerRegistry}
|
|
928
|
+
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
929
|
+
let __html = await __root(closes, children);${headCode}
|
|
930
|
+
return __html;
|
|
931
|
+
}
|
|
932
|
+
`;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/** The layout chain for a component (deepest first): every layout file in an
|
|
936
|
+
* ancestor directory. Shared by compose(), the zero-JS decision (#29) and
|
|
937
|
+
* the build report (#31). */
|
|
938
|
+
const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
|
|
939
|
+
infos
|
|
940
|
+
.map((li, i) => ({ li, i }))
|
|
941
|
+
.filter(({ li }) => li.isLayout && isAncestorDir(li.filePath, infos[idx].filePath))
|
|
942
|
+
.sort((a, b) => b.li.filePath.length - a.li.filePath.length) // deepest first
|
|
943
|
+
.map(({ i }) => i);
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* Innovation #29's decision as a pure function: does this route's document
|
|
947
|
+
* ship without the client bundle? Shared by the route table (csr: false) and
|
|
948
|
+
* the build report (#31), so the report can never disagree with the build.
|
|
949
|
+
*/
|
|
950
|
+
const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number): boolean => {
|
|
951
|
+
if (compiled[i].csr === true) return false;
|
|
952
|
+
if (compiled[i].needsClient) return false;
|
|
953
|
+
// a layout needing the client bundles every document under it: its
|
|
954
|
+
// handlers would be dead code in a runtime-less document
|
|
955
|
+
return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
/**
|
|
959
|
+
* The build's zero-JS lint report (innovation #31): one line per route with
|
|
960
|
+
* its verdict and the exact reason - which component in the chain needs the
|
|
961
|
+
* client bundle and why, or that nothing does. Pure: the same inputs the
|
|
962
|
+
* route table is built from.
|
|
963
|
+
*/
|
|
964
|
+
export function buildReport(infos: RouteInfo[], compiled: CompileResult[]): string[] {
|
|
965
|
+
return infos
|
|
966
|
+
.map((info, i) => ({ info, i }))
|
|
967
|
+
.filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware)
|
|
968
|
+
.map(({ info, i }) => {
|
|
969
|
+
if (routeShipsNoJs(infos, compiled, i)) {
|
|
970
|
+
return `${info.routePath} zero-JS nothing in the chain needs the client`;
|
|
971
|
+
}
|
|
972
|
+
const why = [i, ...layoutsOf(infos, i)]
|
|
973
|
+
.filter((ci) => compiled[ci].needsClient)
|
|
974
|
+
.map((ci) => `${(compiled[ci].clientReasons ?? ['needs the client']).join(' + ')} in ${path.basename(infos[ci].filePath)}`)
|
|
975
|
+
.join('; ');
|
|
976
|
+
const forced = compiled[i].csr === true ? ' (csr = true forces the bundle)' : '';
|
|
977
|
+
return `${info.routePath} client JS ${why}${forced}`;
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
export async function buildProject(root: string, outDir: string): Promise<{ routes: RouteInfo[]; bundle: string }> {
|
|
982
|
+
await fs.promises.mkdir(outDir, { recursive: true });
|
|
983
|
+
|
|
984
|
+
// stale intermediates from an older build layout must not survive into the
|
|
985
|
+
// deploy dir (they used to live directly in outDir)
|
|
986
|
+
const stale = (await fs.promises.readdir(outDir)).filter((f) =>
|
|
987
|
+
/^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
988
|
+
await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
|
|
989
|
+
|
|
990
|
+
const files = await scanRoseFiles(root);
|
|
991
|
+
// Phase 0: a build that silently produces nothing is the worst possible failure mode (an
|
|
992
|
+
// empty dist/ deploys as a blank site).
|
|
993
|
+
if (files.length === 0) {
|
|
994
|
+
throw new Error(`no .rose pages found under ${path.join(root, 'src', 'pages')} - run rosetack from a project root, or pass one: rosetack build <dir>`);
|
|
995
|
+
}
|
|
996
|
+
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
997
|
+
// Plugins (innovation #30): rosetack.config.js at the project root, loaded
|
|
998
|
+
// fresh per build so the dev server's hot rebuild picks up config edits.
|
|
999
|
+
const plugins = await loadPlugins(root);
|
|
1000
|
+
// scope key: the component's path under pages/ (index, _layout, blog/[id])
|
|
1001
|
+
const scopeKeys = files.map((f) =>
|
|
1002
|
+
path.relative(path.join(root, 'src', 'pages'), f).replace(/\\/g, '/').replace(/\.rose$/, ''));
|
|
1003
|
+
const compiled = await Promise.all(
|
|
1004
|
+
files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins))
|
|
1005
|
+
);
|
|
1006
|
+
|
|
1007
|
+
// Every component's scoped CSS in one stylesheet, inlined into the shell:
|
|
1008
|
+
// styles ship inside the document like the JS bundle - zero requests.
|
|
1009
|
+
const styles = compiled.map((c) => c.style).filter(Boolean).join('\n');
|
|
1010
|
+
if (styles) await fs.promises.writeFile(path.join(outDir, 'styles.css'), styles);
|
|
1011
|
+
else await fs.promises.rm(path.join(outDir, 'styles.css'), { force: true });
|
|
1012
|
+
|
|
1013
|
+
// i18n (innovation #27): every JSON file in src/locales/ is a language. The dictionaries
|
|
1014
|
+
// are baked into BOTH bundles at build time …
|
|
1015
|
+
let locales: Record<string, Record<string, string>> = {};
|
|
1016
|
+
try {
|
|
1017
|
+
for (const f of await fs.promises.readdir(path.join(root, 'src', 'locales'))) {
|
|
1018
|
+
if (!f.endsWith('.json')) continue;
|
|
1019
|
+
locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, 'src', 'locales', f), 'utf-8'));
|
|
1020
|
+
}
|
|
1021
|
+
} catch {
|
|
1022
|
+
locales = {}; // no src/locales/: the app ships no translations
|
|
1023
|
+
}
|
|
1024
|
+
const defaultLocale = locales.en ? 'en' : Object.keys(locales).sort()[0] ?? 'en';
|
|
1025
|
+
const localesJson = JSON.stringify(locales).replace(/</g, '\\u003c');
|
|
1026
|
+
|
|
1027
|
+
// Intermediates (component modules, shared runtime, bundle entries) live in a build dir
|
|
1028
|
+
// that is removed before returning: both bundles are fully self-contained …
|
|
1029
|
+
const buildDir = path.join(outDir, '.build');
|
|
1030
|
+
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
1031
|
+
await fs.promises.mkdir(buildDir, { recursive: true });
|
|
1032
|
+
|
|
1033
|
+
// Shared runtime module, bundled once into client and server output. The runtime ships
|
|
1034
|
+
// WITH THE COMPILER …
|
|
1035
|
+
const runtimeEntry = fileURLToPath(new URL('../runtime/index.ts', import.meta.url));
|
|
1036
|
+
await esbuild.build({
|
|
1037
|
+
entryPoints: [runtimeEntry],
|
|
1038
|
+
bundle: true,
|
|
1039
|
+
outfile: path.join(buildDir, 'runtime.js'),
|
|
1040
|
+
format: 'esm',
|
|
1041
|
+
platform: 'browser',
|
|
1042
|
+
write: true,
|
|
1043
|
+
});
|
|
1044
|
+
|
|
1045
|
+
for (let i = 0; i < compiled.length; i++) {
|
|
1046
|
+
// api routes compile to a handler module (no render): still an
|
|
1047
|
+
// intermediate, still removed with the rest of the build dir
|
|
1048
|
+
const src = compiled[i].api ?? compiled[i].ssr;
|
|
1049
|
+
await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
|
|
1050
|
+
if (!infos[i].isApi) {
|
|
1051
|
+
await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
const pages = infos
|
|
1056
|
+
.map((info, i) => ({ info, i }))
|
|
1057
|
+
.filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware);
|
|
1058
|
+
|
|
1059
|
+
// API routes (pages/api/*.rose) dispatch handlers, never render HTML: they live in the
|
|
1060
|
+
// server bundle only and are excluded from the client route table entirely.
|
|
1061
|
+
const apiRoutes = infos
|
|
1062
|
+
.map((info, i) => ({ info, i }))
|
|
1063
|
+
.filter(({ info }) => info.isApi);
|
|
1064
|
+
|
|
1065
|
+
// Compose render chains: page wrapped by its layouts (deepest first)
|
|
1066
|
+
const compose = (idx: number): string => {
|
|
1067
|
+
let expr = `render_${idx}`;
|
|
1068
|
+
for (const i of layoutsOf(infos, idx)) {
|
|
1069
|
+
expr = `(async (closes, children) => await render_${i}(closes, await (${expr})(closes, children)))`;
|
|
1070
|
+
}
|
|
1071
|
+
return expr;
|
|
1072
|
+
};
|
|
1073
|
+
|
|
1074
|
+
// P0 §1 (consultant report): mode B. `export const bundle = 'split'` …
|
|
1075
|
+
const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? 'inline';
|
|
1076
|
+
const split = bundleMode === 'split';
|
|
1077
|
+
// The chain a route's chunk graph must load: the page first, then its layouts
|
|
1078
|
+
// deepest-first - exactly compose()'s nesting order …
|
|
1079
|
+
const chainOf = (idx: number): number[] => [idx, ...layoutsOf(infos, idx)];
|
|
1080
|
+
// Mode B's loader expression: literal dynamic imports (esbuild needs the paths statically
|
|
1081
|
+
// analyzable to emit one chunk per module) …
|
|
1082
|
+
const loaderInner = (idx: number): string =>
|
|
1083
|
+
`load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(', ')}])`;
|
|
1084
|
+
const loaderOf = (idx: number): string => `{ ${loaderInner(idx)} }`;
|
|
1085
|
+
|
|
1086
|
+
// Innovation #29: the compiler decides zero-JS, not the developer. A route ships no
|
|
1087
|
+
// client bundle - no runtime, no state script, zero JavaScript …
|
|
1088
|
+
const routeNoJs = (i: number): boolean => routeShipsNoJs(infos, compiled, i);
|
|
1089
|
+
|
|
1090
|
+
const serverImports = compiled
|
|
1091
|
+
.map((_, i) => {
|
|
1092
|
+
if (infos[i].isMiddleware) {
|
|
1093
|
+
// pages/_middleware.rose: server-only, imported as a namespace so a missing
|
|
1094
|
+
// `handle` export is simply "no middleware" (null), never a build error
|
|
1095
|
+
return `import * as middlewareMod from './comp-${i}.ssr.js';`;
|
|
1096
|
+
}
|
|
1097
|
+
if (infos[i].isApi) {
|
|
1098
|
+
// api route: import its HTTP-method handlers (aliased per component)
|
|
1099
|
+
const names = compiled[i].apiMethods ?? [];
|
|
1100
|
+
const handlerImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
|
|
1101
|
+
return handlerImports
|
|
1102
|
+
? `import { ${handlerImports} } from './comp-${i}.ssr.js';`
|
|
1103
|
+
: `import './comp-${i}.ssr.js';`;
|
|
1104
|
+
}
|
|
1105
|
+
// a page's server actions are imported alongside its render; layouts
|
|
1106
|
+
// and the 404 page never receive POSTs, so they never need one
|
|
1107
|
+
const isPage = !infos[i].isLayout && !infos[i].isNotFound;
|
|
1108
|
+
const names = isPage ? compiled[i].actionNames : [];
|
|
1109
|
+
const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
|
|
1110
|
+
return names.length > 0
|
|
1111
|
+
? `import { render as render_${i}, ${actionImports} } from './comp-${i}.ssr.js';`
|
|
1112
|
+
: `import { render as render_${i} } from './comp-${i}.ssr.js';`;
|
|
1113
|
+
})
|
|
1114
|
+
.join('\n');
|
|
1115
|
+
|
|
1116
|
+
// pages/404.rose renders for unmatched routes (SSR + client), wrapped in
|
|
1117
|
+
// its layouts like any other page; absent -> the built-in plain 404.
|
|
1118
|
+
const nfIdx = infos.findIndex((info) => info.isNotFound);
|
|
1119
|
+
const notFoundRender = nfIdx >= 0 ? (split ? loaderOf(nfIdx) : compose(nfIdx)) : 'null';
|
|
1120
|
+
|
|
1121
|
+
// pages/500.rose renders for routes whose render throws (a dead $data source, a bad
|
|
1122
|
+
// expression): the page degrades instead of crashing the response …
|
|
1123
|
+
const errIdx = infos.findIndex((info) => info.isError);
|
|
1124
|
+
const errorRender = errIdx >= 0 ? (split ? loaderOf(errIdx) : compose(errIdx)) : 'null';
|
|
1125
|
+
|
|
1126
|
+
// pages/_middleware.rose: the request interceptor (absent -> null).
|
|
1127
|
+
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
1128
|
+
|
|
1129
|
+
const serverRoutes = pages
|
|
1130
|
+
.map(({ info, i }) => {
|
|
1131
|
+
// actions: name -> imported fn, so a POST's __action field …
|
|
1132
|
+
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(', ');
|
|
1133
|
+
// csr: false rides on the route so renderPage/renderPageStream can drop the state
|
|
1134
|
+
// script + bundle from the document …
|
|
1135
|
+
if (compiled[i].csr === false) {
|
|
1136
|
+
const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
|
|
1137
|
+
if (needy !== undefined) {
|
|
1138
|
+
throw new Error(
|
|
1139
|
+
`${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle ` +
|
|
1140
|
+
`(event wiring, onMount/onCleanup, refresh() or a server action).`
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
const csrFlag = routeNoJs(i) ? ', csr: false' : '';
|
|
1145
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${csrFlag} }`;
|
|
1146
|
+
})
|
|
1147
|
+
.join(',\n ');
|
|
1148
|
+
|
|
1149
|
+
const serverEntry = `
|
|
1150
|
+
${serverImports}
|
|
1151
|
+
import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, setStoreTransport, applyStorePatch } from './runtime.js';
|
|
1152
|
+
|
|
1153
|
+
// i18n (innovation #27): the dictionaries baked at build time from
|
|
1154
|
+
// src/locales/*.json. A route segment named [lang] is the locale: the value
|
|
1155
|
+
// must name one of these dictionaries, and $t resolves keys against it.
|
|
1156
|
+
setLocales(${localesJson}, '${defaultLocale}');
|
|
1157
|
+
|
|
1158
|
+
// Phase 2: the store transport. Under "rosetack serve" every worker is its
|
|
1159
|
+
// own process with its own dist/server.js module, so a $store write must
|
|
1160
|
+
// travel: this worker -> primary -> every other worker. process.send exists
|
|
1161
|
+
// only inside cluster workers, so a single-process runner (dev, preview,
|
|
1162
|
+
// the edge adapter) keeps the transport null and $store stays plain
|
|
1163
|
+
// per-process state - the documented boundary, not a bug.
|
|
1164
|
+
if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
1165
|
+
setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
|
|
1166
|
+
process.on('message', (msg) => {
|
|
1167
|
+
if (msg && msg.type === 'rosetack:store') applyStorePatch(msg.name, msg.value);
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
export { localeList };
|
|
1172
|
+
export const defaultLocale = '${defaultLocale}';
|
|
1173
|
+
|
|
1174
|
+
// Route params maps, re-exported for the build's prerender step: routePath
|
|
1175
|
+
// -> the component's exported params (a static map or a function). Reading
|
|
1176
|
+
// them through the server bundle keeps the deploy dir free of component
|
|
1177
|
+
// modules - both bundles are self-contained, nothing else may ship. Only
|
|
1178
|
+
// components that actually export params appear here (a missing export
|
|
1179
|
+
// means the dynamic route renders on demand).
|
|
1180
|
+
${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join('\n')}
|
|
1181
|
+
|
|
1182
|
+
export const routeParams = {
|
|
1183
|
+
${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(',\n ')}
|
|
1184
|
+
};
|
|
1185
|
+
|
|
1186
|
+
// Routes whose component reads the request context (getContext()): the bag
|
|
1187
|
+
// is per-request, so these are dynamic - the build never bakes them and the
|
|
1188
|
+
// servers never answer them from a prerendered file. Public routes keep the
|
|
1189
|
+
// static fast path (file cache, ETag/304, streaming) untouched.
|
|
1190
|
+
export const dynamicRoutes = [
|
|
1191
|
+
${pages.filter(({ i }) => compiled[i].usesContext).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
1192
|
+
];
|
|
1193
|
+
|
|
1194
|
+
// Which api routes opt into build-time baking (export const prerender = true):
|
|
1195
|
+
// routePath -> boolean. The build calls the GET handler once and writes the
|
|
1196
|
+
// body to dist/, so the Go single binary serves read-only APIs without Node.
|
|
1197
|
+
${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join('\n')}
|
|
1198
|
+
|
|
1199
|
+
export const apiPrerender = {
|
|
1200
|
+
${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : 'false'}`).join(',\n ')}
|
|
1201
|
+
};
|
|
1202
|
+
|
|
1203
|
+
// Stale-while-revalidate windows (export const revalidate = N): the build
|
|
1204
|
+
// bakes these routes like any other, and the preview server serves the
|
|
1205
|
+
// baked file for up to N seconds - after which the next request is answered
|
|
1206
|
+
// STALE (instant, from disk) while a background pass re-renders and swaps
|
|
1207
|
+
// the file (ISR, innovation #24). Routes that read the request context are
|
|
1208
|
+
// excluded: they render per request and have no baked file to revalidate.
|
|
1209
|
+
// The dev server ignores the window (it rebuilds on change), the edge
|
|
1210
|
+
// adapter renders live (always fresh), and the Go binary serves the baked
|
|
1211
|
+
// file forever - the same static-half boundary as page POSTs.
|
|
1212
|
+
export const revalidate = [
|
|
1213
|
+
${pages.filter(({ i }) => compiled[i].revalidate !== undefined && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(',\n ')}
|
|
1214
|
+
];
|
|
1215
|
+
|
|
1216
|
+
// pages/_middleware.rose: a Web-standard request handler that runs before
|
|
1217
|
+
// every render on the server (pages, POSTs, api calls alike). Returning a
|
|
1218
|
+
// Response short-circuits the whole request - a redirect, an auth wall, a
|
|
1219
|
+
// rewrite; returning nothing continues, and getContext() hands the
|
|
1220
|
+
// per-request bag to $data, server actions and api handlers. Absent -> null,
|
|
1221
|
+
// and the servers keep their static fast paths.
|
|
1222
|
+
export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
|
|
1223
|
+
|
|
1224
|
+
// Routes whose DOCUMENTS ship without the client bundle (innovation #25,
|
|
1225
|
+
// decided by the compiler since #29): HTML + CSS only - no runtime, no
|
|
1226
|
+
// state script, zero JavaScript for whoever lands on them. The compiler
|
|
1227
|
+
// picks these automatically: a route whose whole chain needs nothing from
|
|
1228
|
+
// the client (no event wiring, no lifecycle, no action, no form) is a
|
|
1229
|
+
// content route. An exported "csr = true" forces the bundle back in; an
|
|
1230
|
+
// exported "csr = false" is the same decision, asserted. The route's render
|
|
1231
|
+
// function still rides in the client bundle, so a client-side navigation
|
|
1232
|
+
// from an interactive page paints it normally and a static deploy's SPA
|
|
1233
|
+
// fallback can render it too; only the document is JS-free.
|
|
1234
|
+
// isNoJs() lets the servers keep these routes on the buffered path: a
|
|
1235
|
+
// streamed no-JS document would carry the shell's default <title> (the
|
|
1236
|
+
// route head is applied client-side at boot, and there is no client).
|
|
1237
|
+
export const noJsRoutes = [
|
|
1238
|
+
${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(',\n ')}
|
|
1239
|
+
];
|
|
1240
|
+
|
|
1241
|
+
export function isNoJs(pathname) {
|
|
1242
|
+
return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
// Per-route response headers (innovation #26): a route exporting a headers
|
|
1246
|
+
// map carries them into every response the servers write for it, merged
|
|
1247
|
+
// OVER the framework defaults (the strict CSP) - so an app can tighten or
|
|
1248
|
+
// relax the policy per route. Absent -> null, and the servers keep sending
|
|
1249
|
+
// the defaults alone.
|
|
1250
|
+
export const routeHeaders = [
|
|
1251
|
+
${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(',\n ')}
|
|
1252
|
+
];
|
|
1253
|
+
|
|
1254
|
+
export function headersFor(pathname) {
|
|
1255
|
+
const hit = routeHeaders.find((r) => matchRoute(r.pattern, pathname));
|
|
1256
|
+
return hit ? hit.headers : null;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// A Web-standard Request from whatever the host provides: the edge adapter
|
|
1260
|
+
// passes one already; the Node server passes its IncomingMessage (plus the
|
|
1261
|
+
// already-parsed FormData for POSTs, so middleware can read form fields).
|
|
1262
|
+
function toWebRequest(raw, form) {
|
|
1263
|
+
if (raw instanceof Request) return raw;
|
|
1264
|
+
const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
|
|
1265
|
+
if (form) init.body = form;
|
|
1266
|
+
return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// Runs the middleware (if the project has one) for this request and returns
|
|
1270
|
+
// its short-circuit Response, or null to continue. The servers call this
|
|
1271
|
+
// EXACTLY ONCE per request, before anything else: it resets the per-request
|
|
1272
|
+
// context bag and the middleware fills it via getContext(), which $data,
|
|
1273
|
+
// server actions and api handlers then read while rendering. rawReq: the
|
|
1274
|
+
// host's request (Node IncomingMessage or a Web-standard Request); form:
|
|
1275
|
+
// the already-parsed FormData of a POST.
|
|
1276
|
+
export async function runMiddleware(rawReq, form) {
|
|
1277
|
+
resetRequestContext();
|
|
1278
|
+
if (!middleware || !rawReq) return null;
|
|
1279
|
+
const res = await middleware(toWebRequest(rawReq, form));
|
|
1280
|
+
return res || null;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
const routes = [
|
|
1284
|
+
${serverRoutes}
|
|
1285
|
+
];
|
|
1286
|
+
|
|
1287
|
+
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
|
|
1288
|
+
// render HTML and never reach the client bundle. The middleware ran before
|
|
1289
|
+
// this (the servers call runMiddleware() first), so handlers can read
|
|
1290
|
+
// getContext() for auth without re-running anything.
|
|
1291
|
+
const apiRoutes = [
|
|
1292
|
+
${apiRoutes.map(({ info, i }) => {
|
|
1293
|
+
const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(', ');
|
|
1294
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', handlers: { ${handlers} } }`;
|
|
1295
|
+
}).join(',\n ')}
|
|
1296
|
+
];
|
|
1297
|
+
|
|
1298
|
+
// pages/404.rose (with its layouts) or null -> built-in plain 404
|
|
1299
|
+
const notFound = ${notFoundRender};
|
|
1300
|
+
|
|
1301
|
+
// pages/500.rose (with its layouts) or null -> built-in plain 500: a route
|
|
1302
|
+
// whose render throws degrades to this instead of failing the response.
|
|
1303
|
+
const errorPage = ${errorRender};
|
|
1304
|
+
|
|
1305
|
+
// Paint a fallback page (404/500) and serialize its state.
|
|
1306
|
+
async function renderFallback(pathname, render) {
|
|
1307
|
+
const { html, head } = extractHead(await render([], ''));
|
|
1308
|
+
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
1309
|
+
return { html, state, head };
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
export function matchRoute(pattern, pathname) {
|
|
1313
|
+
const patternParts = pattern.split('/');
|
|
1314
|
+
const pathParts = pathname.split('/');
|
|
1315
|
+
if (patternParts.length !== pathParts.length) return false;
|
|
1316
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
1317
|
+
if (patternParts[i].startsWith(':')) continue;
|
|
1318
|
+
if (patternParts[i] !== pathParts[i]) return false;
|
|
1319
|
+
}
|
|
1320
|
+
return true;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
// Head blocks (one per component in the route chain) are pulled out of the
|
|
1324
|
+
// page html: the shell injects them into <head>, and the client re-applies
|
|
1325
|
+
// them on navigation. Document order is page-first, so the shell's keyed
|
|
1326
|
+
// merge lets a page override its layouts. The EMPTY marker pair stays in the
|
|
1327
|
+
// body so the client's wire() still finds the block: at boot it adopts the
|
|
1328
|
+
// shell-injected elements in place (marked with the same keys, so no
|
|
1329
|
+
// duplicates) and keeps the head reactive.
|
|
1330
|
+
function extractHead(rendered) {
|
|
1331
|
+
const head = [];
|
|
1332
|
+
const html = rendered.replace(/<!--\u27e6h:(\\d+)\u27e7-->([\\s\\S]*?)<!--\u27e6\\/h:\\1\u27e7-->/g, (_, id, content) => {
|
|
1333
|
+
head.push(content);
|
|
1334
|
+
return '<!--\u27e6h:' + id + '\u27e7--><!--\u27e6/h:' + id + '\u27e7-->';
|
|
1335
|
+
});
|
|
1336
|
+
return { html, head };
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
// form: the submitted FormData of a progressive-enhancement POST. The
|
|
1340
|
+
// selected server action runs first and returns a state patch (e.g.
|
|
1341
|
+
// { guests: [...] }); seeding those keys BEFORE the render makes state()
|
|
1342
|
+
// adopt them, so the response is the page as it looks AFTER the action -
|
|
1343
|
+
// with or without JS. A __action field picks the action by name (default
|
|
1344
|
+
// 'action', the conventional <form method="POST"> target); a click handler
|
|
1345
|
+
// bound to an action ($action('like')) sends the same field.
|
|
1346
|
+
// A route whose render throws degrades to pages/500.rose (status 500) - or
|
|
1347
|
+
// the built-in plain 500 - instead of failing the whole response.
|
|
1348
|
+
// The middleware does NOT run here: the servers run it once per request via
|
|
1349
|
+
// runMiddleware() (which also seeds the request context), so a page render
|
|
1350
|
+
// never re-runs it.
|
|
1351
|
+
export async function renderPage(pathname, form) {
|
|
1352
|
+
clearRequestState();
|
|
1353
|
+
for (const route of routes) {
|
|
1354
|
+
if (matchRoute(route.pattern, pathname)) {
|
|
1355
|
+
const patternParts = route.pattern.split('/');
|
|
1356
|
+
const pathParts = pathname.split('/');
|
|
1357
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
1358
|
+
if (patternParts[i].startsWith(':')) {
|
|
1359
|
+
setState(patternParts[i].slice(1), pathParts[i]);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
// i18n (innovation #27): a [lang] segment naming no dictionary is a
|
|
1363
|
+
// 404 - the URL is the contract, and rendering the page with fallback
|
|
1364
|
+
// strings would serve duplicate content under a bogus language
|
|
1365
|
+
const langIdx = patternParts.indexOf(':lang');
|
|
1366
|
+
if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
|
|
1367
|
+
if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
|
|
1368
|
+
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404 };
|
|
1369
|
+
}
|
|
1370
|
+
if (form && route.actions) {
|
|
1371
|
+
const fn = route.actions[form.get('__action') || 'action'];
|
|
1372
|
+
if (fn) {
|
|
1373
|
+
const patch = await fn(form);
|
|
1374
|
+
if (patch && typeof patch === 'object') {
|
|
1375
|
+
for (const key of Object.keys(patch)) setState(key, patch[key]);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
let rendered;
|
|
1380
|
+
try {
|
|
1381
|
+
rendered = extractHead(await route.render([], ''));
|
|
1382
|
+
} catch (err) {
|
|
1383
|
+
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
1384
|
+
if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
|
|
1385
|
+
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500 };
|
|
1386
|
+
}
|
|
1387
|
+
// __route tells the bootstrap which route this document was rendered for.
|
|
1388
|
+
// A static-file server may serve another route's document (SPA fallback);
|
|
1389
|
+
// the bootstrap then client-renders instead of adopting mismatched DOM.
|
|
1390
|
+
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
1391
|
+
// csr (innovation #25, auto since #29): false when the compiler found
|
|
1392
|
+
// nothing in the route's chain that needs the client (or the route
|
|
1393
|
+
// asserted csr = false) - the document ships no runtime, no state
|
|
1394
|
+
// script, zero JavaScript. Every other route keeps the bundle. The
|
|
1395
|
+
// caller passes this straight to the shell as js.
|
|
1396
|
+
return { html: rendered.html, state, head: rendered.head, status: 200, csr: route.csr !== false };
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
if (notFound) {
|
|
1400
|
+
return { ...(await renderFallback(pathname, notFound)), status: 404 };
|
|
1401
|
+
}
|
|
1402
|
+
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404 };
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
// Would renderPageStream handle this path? (matched route = stream, anything
|
|
1406
|
+
// else = buffered 404/500). Lets the servers pick the path before headers.
|
|
1407
|
+
export function canStream(pathname) {
|
|
1408
|
+
return routes.some((route) => {
|
|
1409
|
+
if (!matchRoute(route.pattern, pathname)) return false;
|
|
1410
|
+
// i18n (innovation #27): an unknown locale must answer 404, and a
|
|
1411
|
+
// streamed response cannot change its status - so it takes the buffered
|
|
1412
|
+
// path (renderPage returns the real 404), never the streaming one
|
|
1413
|
+
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
1414
|
+
return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// === API routes ===
|
|
1419
|
+
// The /api namespace answers JSON, never HTML: an API client that hits an
|
|
1420
|
+
// unknown path must not receive the SPA shell. Handlers receive a
|
|
1421
|
+
// Web-standard Request and return a plain object (serialized as JSON, 200),
|
|
1422
|
+
// a Response (passed through), or nothing (204). A method the route does
|
|
1423
|
+
// not export answers 405 with an Allow header. Same code path on the Node
|
|
1424
|
+
// server and the edge adapter - Response is a global in both.
|
|
1425
|
+
export function isApi(pathname) {
|
|
1426
|
+
return pathname === '/api' || pathname.startsWith('/api/');
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
function toResponse(out) {
|
|
1430
|
+
if (out instanceof Response) return out;
|
|
1431
|
+
if (out === undefined || out === null) return new Response(null, { status: 204 });
|
|
1432
|
+
return new Response(JSON.stringify(out), {
|
|
1433
|
+
status: 200,
|
|
1434
|
+
headers: { 'content-type': 'application/json' },
|
|
1435
|
+
});
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
export async function handleApi(method, pathname, request) {
|
|
1439
|
+
for (const route of apiRoutes) {
|
|
1440
|
+
if (matchRoute(route.pattern, pathname)) {
|
|
1441
|
+
const fn = route.handlers[method];
|
|
1442
|
+
if (!fn) {
|
|
1443
|
+
return new Response(JSON.stringify({ error: 'method not allowed' }), {
|
|
1444
|
+
status: 405,
|
|
1445
|
+
headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
return toResponse(await fn(request));
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
1452
|
+
status: 404,
|
|
1453
|
+
headers: { 'content-type': 'application/json' },
|
|
1454
|
+
});
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
// === Streaming SSR ===
|
|
1458
|
+
// The static shell (doctype, <head>, body + container open) flushes BEFORE
|
|
1459
|
+
// the - possibly slow - render completes: the first byte leaves in
|
|
1460
|
+
// microseconds instead of after every $data resolves. The route HTML, the
|
|
1461
|
+
// state script, and the inlined bundle follow as later chunks of one chunked
|
|
1462
|
+
// response - still exactly one request.
|
|
1463
|
+
// The route's <head> tags are NOT in the streamed document: the client
|
|
1464
|
+
// applies them at boot from the body's head markers, so JS users see the
|
|
1465
|
+
// correct head immediately; no-JS consumers of streamed responses get the
|
|
1466
|
+
// static shell head (prerendered files stay complete documents).
|
|
1467
|
+
// Returns 200 (matched; a render throw degrades to the error-page body) or
|
|
1468
|
+
// 404 (unmatched - nothing written, so the caller can still buffer).
|
|
1469
|
+
export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
1470
|
+
clearRequestState();
|
|
1471
|
+
for (const route of routes) {
|
|
1472
|
+
if (matchRoute(route.pattern, pathname)) {
|
|
1473
|
+
const patternParts = route.pattern.split('/');
|
|
1474
|
+
const pathParts = pathname.split('/');
|
|
1475
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
1476
|
+
if (patternParts[i].startsWith(':')) {
|
|
1477
|
+
setState(patternParts[i].slice(1), pathParts[i]);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
// i18n: an unknown locale must 404 BEFORE the shell flushes - a
|
|
1481
|
+
// streamed response cannot change its status afterwards
|
|
1482
|
+
const langIdx = patternParts.indexOf(':lang');
|
|
1483
|
+
if (langIdx >= 0 && !isLocale(pathParts[langIdx])) return 404;
|
|
1484
|
+
write(shellOpen);
|
|
1485
|
+
let html;
|
|
1486
|
+
try {
|
|
1487
|
+
html = extractHead(await route.render([], '')).html;
|
|
1488
|
+
} catch (err) {
|
|
1489
|
+
// the shell is already on the wire: degrade to the error page BODY
|
|
1490
|
+
// (the status stays 200 - a real 500 needs the buffered path, which
|
|
1491
|
+
// the server picks for routes known-broken at build time)
|
|
1492
|
+
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
1493
|
+
html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
|
|
1494
|
+
}
|
|
1495
|
+
write(html);
|
|
1496
|
+
// csr: false (innovation #25, auto since #29): a no-JS route's document
|
|
1497
|
+
// ends here - no state script, no inlined bundle. (The servers keep
|
|
1498
|
+
// these routes off the streaming path so their <head> is complete;
|
|
1499
|
+
// this is the correctness floor if one streams anyway.)
|
|
1500
|
+
if (route.csr === false) {
|
|
1501
|
+
write('</div>\\n</body>\\n</html>');
|
|
1502
|
+
return 200;
|
|
1503
|
+
}
|
|
1504
|
+
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
1505
|
+
write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
|
|
1506
|
+
return 200;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
return 404;
|
|
1510
|
+
}
|
|
1511
|
+
`;
|
|
1512
|
+
await fs.promises.writeFile(path.join(buildDir, 'server-entry.js'), serverEntry);
|
|
1513
|
+
await esbuild.build({
|
|
1514
|
+
entryPoints: [path.join(buildDir, 'server-entry.js')],
|
|
1515
|
+
bundle: true,
|
|
1516
|
+
outfile: path.join(outDir, 'server.js'),
|
|
1517
|
+
format: 'esm',
|
|
1518
|
+
platform: 'node',
|
|
1519
|
+
write: true,
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
// api routes and the middleware have no client module: they are server-only handlers /
|
|
1523
|
+
// interceptors.
|
|
1524
|
+
const clientImports = split ? '' : compiled
|
|
1525
|
+
.map((_, i) => ({ i }))
|
|
1526
|
+
.filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware)
|
|
1527
|
+
.map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`)
|
|
1528
|
+
.join('\n');
|
|
1529
|
+
|
|
1530
|
+
const clientRoutes = pages
|
|
1531
|
+
.map(({ info, i }) => (split
|
|
1532
|
+
? `{ pattern: '${info.pattern}', ${loaderInner(i)} }`
|
|
1533
|
+
: `{ pattern: '${info.pattern}', render: ${compose(i)} }`))
|
|
1534
|
+
.join(',\n ');
|
|
1535
|
+
|
|
1536
|
+
// P1 (consultant report): the app-global prefetch strategy, declared once (the root
|
|
1537
|
+
// layout) as `export const prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
|
|
1538
|
+
const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? 'all';
|
|
1539
|
+
|
|
1540
|
+
const clientEntry = `
|
|
1541
|
+
${clientImports}
|
|
1542
|
+
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, setLocales, isLocale } from './runtime.js';
|
|
1543
|
+
|
|
1544
|
+
// i18n (innovation #27): the dictionaries baked at build time - the client
|
|
1545
|
+
// renders any locale from the bundle, so switching language costs zero
|
|
1546
|
+
// requests (the same bet as the inlined route table).
|
|
1547
|
+
setLocales(${localesJson}, '${defaultLocale}');
|
|
1548
|
+
|
|
1549
|
+
const routes = [
|
|
1550
|
+
${clientRoutes}
|
|
1551
|
+
];
|
|
1552
|
+
|
|
1553
|
+
// === Mode B (P0 §1): lazy route chunks ===
|
|
1554
|
+
// Split mode's registry entries arrive without a render function: loadChain
|
|
1555
|
+
// loads the route's module graph (the page plus its layouts, one chunk per
|
|
1556
|
+
// module, the shared runtime in its own vendor chunk) in parallel and
|
|
1557
|
+
// composes it at runtime - the exact nesting compose() built at compile
|
|
1558
|
+
// time for inline mode. getRender memoizes the composed function on the
|
|
1559
|
+
// entry, so a chunk loads once per session; inline mode's entries are the
|
|
1560
|
+
// render functions themselves, so the helper is a pass-through there.
|
|
1561
|
+
const loadChain = async (loaders) => {
|
|
1562
|
+
const mods = await Promise.all(loaders.map((load) => load()));
|
|
1563
|
+
let expr = (closes, children) => mods[0].render(closes, children);
|
|
1564
|
+
for (let k = 1; k < mods.length; k++) {
|
|
1565
|
+
const inner = expr;
|
|
1566
|
+
const outer = mods[k].render;
|
|
1567
|
+
expr = async (closes, children) => await outer(closes, await inner(closes, children));
|
|
1568
|
+
}
|
|
1569
|
+
return { render: expr };
|
|
1570
|
+
};
|
|
1571
|
+
const getRender = async (route) => {
|
|
1572
|
+
if (typeof route === 'function') return route; // inline mode: the render itself
|
|
1573
|
+
return (route.render ??= (await route.load()).render);
|
|
1574
|
+
};
|
|
1575
|
+
|
|
1576
|
+
// pages/404.rose (with its layouts) or null -> built-in plain 404
|
|
1577
|
+
const notFound = ${notFoundRender};
|
|
1578
|
+
|
|
1579
|
+
// pages/500.rose (with its layouts) or null -> built-in plain 500: a route
|
|
1580
|
+
// whose render throws on the client degrades to this instead of breaking
|
|
1581
|
+
// navigation.
|
|
1582
|
+
const errorPage = ${errorRender};
|
|
1583
|
+
|
|
1584
|
+
// Paint a fallback page (404/500) into the container, wired like any render.
|
|
1585
|
+
async function paintFallback(container, page, builtin) {
|
|
1586
|
+
resetEffects();
|
|
1587
|
+
clearRequestState();
|
|
1588
|
+
clearMounts(); // a failed render leaves stale mounts behind
|
|
1589
|
+
// inline mode passes the render itself; split mode passes a loader
|
|
1590
|
+
const render = page ? await getRender(page) : null;
|
|
1591
|
+
if (render) {
|
|
1592
|
+
const closes = [];
|
|
1593
|
+
const html = await render(closes, '');
|
|
1594
|
+
container.innerHTML = html;
|
|
1595
|
+
wire(container, closes);
|
|
1596
|
+
bindEvents(container);
|
|
1597
|
+
flushMounts();
|
|
1598
|
+
return;
|
|
1599
|
+
}
|
|
1600
|
+
container.innerHTML = builtin;
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
export function matchRoute(pattern, pathname) {
|
|
1604
|
+
const patternParts = pattern.split('/');
|
|
1605
|
+
const pathParts = pathname.split('/');
|
|
1606
|
+
if (patternParts.length !== pathParts.length) return false;
|
|
1607
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
1608
|
+
if (patternParts[i].startsWith(':')) continue;
|
|
1609
|
+
if (patternParts[i] !== pathParts[i]) return false;
|
|
1610
|
+
}
|
|
1611
|
+
return true;
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
// === Link prefetch ===
|
|
1615
|
+
// Hover / focus / touch an internal link and the target route renders NOW -
|
|
1616
|
+
// $data included - against a throwaway signal map. The click that follows
|
|
1617
|
+
// paints from the cached HTML: no await, no request, no spinner. SvelteKit
|
|
1618
|
+
// and Qwik prefetch data only; rosetack prefetches the whole render because
|
|
1619
|
+
// the inlined bundle already contains every route.
|
|
1620
|
+
// ponytail: the cache holds either a result or the in-flight promise (dedupes
|
|
1621
|
+
// hover storms); one isolated render runs at a time so signal-map swapping
|
|
1622
|
+
// stays correct without any merging logic. Entries are single-use: a consumed
|
|
1623
|
+
// entry disappears from the cache, which is also how tests observe a hit.
|
|
1624
|
+
// P1 (consultant report), three guards for link-heavy pages:
|
|
1625
|
+
// 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
|
|
1626
|
+
// 'viewport' | 'all'" (root layout); 'all' is the original behavior.
|
|
1627
|
+
// ponytail: app-global, not per-route - per-route would carry the mode
|
|
1628
|
+
// in each document's shell.
|
|
1629
|
+
// 2. budget - renders are serialized by the queue, so "concurrency" is 1;
|
|
1630
|
+
// the budget caps the QUEUE: a hover storm past it drops the excess
|
|
1631
|
+
// instead of rendering fifty routes nobody clicks.
|
|
1632
|
+
// 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
|
|
1633
|
+
// is evicted first (Map iteration order; entries are single-use, so
|
|
1634
|
+
// insertion order IS the recency order).
|
|
1635
|
+
let prefetchMode = ${JSON.stringify(prefetchMode)};
|
|
1636
|
+
export function setPrefetchMode(mode) { prefetchMode = mode; }
|
|
1637
|
+
const PREFETCH_BUDGET = 8;
|
|
1638
|
+
const PREFETCH_MAX_CACHED = 4;
|
|
1639
|
+
const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
|
|
1640
|
+
let prefetchQueue = Promise.resolve();
|
|
1641
|
+
let prefetchPending = 0;
|
|
1642
|
+
|
|
1643
|
+
function applyParams(route, pathname) {
|
|
1644
|
+
const patternParts = route.pattern.split('/');
|
|
1645
|
+
const pathParts = pathname.split('/');
|
|
1646
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
1647
|
+
if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
export function prefetch(pathname, source = 'hover') {
|
|
1652
|
+
if (prefetchMode === 'off') return;
|
|
1653
|
+
if (prefetchMode === 'hover' && source !== 'hover') return;
|
|
1654
|
+
if (prefetchMode === 'viewport' && source !== 'viewport') return;
|
|
1655
|
+
if (prefetchCache.has(pathname)) return;
|
|
1656
|
+
if (pathname === location.pathname) return; // already here: nothing to prefetch
|
|
1657
|
+
const route = routes.find((r) => matchRoute(r.pattern, pathname));
|
|
1658
|
+
if (!route) return;
|
|
1659
|
+
if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
|
|
1660
|
+
const p = prefetchQueue.then(async () => {
|
|
1661
|
+
try {
|
|
1662
|
+
// the isolated render also captures the onMount callbacks the route
|
|
1663
|
+
// queued and the onCleanup disposers it registered: the paint that
|
|
1664
|
+
// consumes this entry replays the mounts after wiring and adopts the
|
|
1665
|
+
// cleanups, so the prefetched route's timers are disposed on the next
|
|
1666
|
+
// navigation like any live route's
|
|
1667
|
+
const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
|
|
1668
|
+
applyParams(route, pathname);
|
|
1669
|
+
const closes = [];
|
|
1670
|
+
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
1671
|
+
const html = await render(closes, '');
|
|
1672
|
+
return { html, closes };
|
|
1673
|
+
});
|
|
1674
|
+
const entry = { ...result, state, mounts, cleanups };
|
|
1675
|
+
prefetchCache.set(pathname, entry); // promise -> result
|
|
1676
|
+
// evict oldest-first; in-flight promises are never evicted (evicting
|
|
1677
|
+
// one would only force a duplicate render)
|
|
1678
|
+
while (prefetchCache.size > PREFETCH_MAX_CACHED) {
|
|
1679
|
+
const oldest = prefetchCache.keys().next().value;
|
|
1680
|
+
if (prefetchCache.get(oldest) instanceof Promise) break;
|
|
1681
|
+
prefetchCache.delete(oldest);
|
|
1682
|
+
}
|
|
1683
|
+
return entry;
|
|
1684
|
+
} catch {
|
|
1685
|
+
prefetchCache.delete(pathname); // failed: the next hover retries
|
|
1686
|
+
return null;
|
|
1687
|
+
} finally {
|
|
1688
|
+
prefetchPending--;
|
|
1689
|
+
}
|
|
1690
|
+
});
|
|
1691
|
+
prefetchPending++;
|
|
1692
|
+
prefetchCache.set(pathname, p);
|
|
1693
|
+
prefetchQueue = p;
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
export function prefetchStats() {
|
|
1697
|
+
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
// One delegated listener per event type on the app container: survives DOM
|
|
1701
|
+
// swaps and cloned blocks, so handlers never need re-binding. A handler
|
|
1702
|
+
// compiled from a server action (data-on-*="$action:name") dispatches to
|
|
1703
|
+
// $action instead of the local handler registry.
|
|
1704
|
+
const DELEGATED = ['click', 'input', 'change', 'submit'];
|
|
1705
|
+
function bindEvents(container) {
|
|
1706
|
+
if (container.__rosetack_bound) return;
|
|
1707
|
+
container.__rosetack_bound = true;
|
|
1708
|
+
for (const ev of DELEGATED) {
|
|
1709
|
+
container.addEventListener(ev, (e) => {
|
|
1710
|
+
const el = e.target.closest('[data-on-' + ev + ']');
|
|
1711
|
+
if (!el || !container.contains(el)) return;
|
|
1712
|
+
const fn = el.getAttribute('data-on-' + ev);
|
|
1713
|
+
if (fn.startsWith('$action:')) return $action(fn.slice(8), e);
|
|
1714
|
+
const h = globalThis.__rosetack_handlers[fn];
|
|
1715
|
+
if (h) h(e);
|
|
1716
|
+
});
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
// === Server actions from any event ===
|
|
1721
|
+
// POST the body to the current route and adopt the response in place: the
|
|
1722
|
+
// server runs the selected action, seeds its state patch, and re-renders, so
|
|
1723
|
+
// the swapped DOM is the page as it looks AFTER the action - one request, no
|
|
1724
|
+
// reload, and wire() patches only the marked nodes (no re-render). The
|
|
1725
|
+
// bootstrap's <form method="POST"> interception goes through the same door.
|
|
1726
|
+
async function postForm(body) {
|
|
1727
|
+
const res = await fetch(location.pathname, { method: 'POST', body });
|
|
1728
|
+
const html = await res.text();
|
|
1729
|
+
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
1730
|
+
const next = doc.getElementById('app');
|
|
1731
|
+
const st = doc.getElementById('__rosetack_state');
|
|
1732
|
+
const paint = () => {
|
|
1733
|
+
const container = document.getElementById('app');
|
|
1734
|
+
adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
|
|
1735
|
+
};
|
|
1736
|
+
if (document.startViewTransition) document.startViewTransition(paint);
|
|
1737
|
+
else paint();
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
// Call a page's server action by name from any event handler:
|
|
1741
|
+
// <button on:click={like}> compiles to $action('like'). Without JS the
|
|
1742
|
+
// binding is inert - the progressive-enhancement story stays with forms.
|
|
1743
|
+
export async function $action(name, e) {
|
|
1744
|
+
if (e && e.preventDefault) e.preventDefault();
|
|
1745
|
+
const body = new FormData();
|
|
1746
|
+
body.append('__action', name);
|
|
1747
|
+
return postForm(body);
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
export { postForm };
|
|
1751
|
+
|
|
1752
|
+
// initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
|
|
1753
|
+
// the existing nodes and bind events. initial=false: client-side navigation -
|
|
1754
|
+
// re-render the route chain from scratch and wire the fresh DOM.
|
|
1755
|
+
export async function start(container, pathname, initial) {
|
|
1756
|
+
clearMounts(); // stale mounts from a failed render never fire
|
|
1757
|
+
if (initial) {
|
|
1758
|
+
const el = document.getElementById('__rosetack_state');
|
|
1759
|
+
if (el) resumeState(el.textContent);
|
|
1760
|
+
}
|
|
1761
|
+
for (const route of routes) {
|
|
1762
|
+
if (matchRoute(route.pattern, pathname)) {
|
|
1763
|
+
// i18n: an unknown locale paints the 404 page, same as the server
|
|
1764
|
+
// (before the prefetch check: a cached entry for a bogus locale is
|
|
1765
|
+
// discarded, never painted)
|
|
1766
|
+
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
1767
|
+
if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {
|
|
1768
|
+
await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
// Prefetched on hover/focus/touch: the render already ran, so paint its
|
|
1772
|
+
// HTML and adopt its signal entries - events then patch the very nodes
|
|
1773
|
+
// we wire, and no $data re-runs on click.
|
|
1774
|
+
let hit = initial ? undefined : prefetchCache.get(pathname);
|
|
1775
|
+
if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
|
|
1776
|
+
if (hit) {
|
|
1777
|
+
prefetchCache.delete(pathname); // single-use: the next hover refetches
|
|
1778
|
+
resetEffects();
|
|
1779
|
+
restoreState(hit.state);
|
|
1780
|
+
container.innerHTML = hit.html;
|
|
1781
|
+
wire(container, hit.closes);
|
|
1782
|
+
bindEvents(container);
|
|
1783
|
+
hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
|
|
1784
|
+
adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
if (!initial) {
|
|
1788
|
+
resetEffects();
|
|
1789
|
+
clearRequestState();
|
|
1790
|
+
}
|
|
1791
|
+
applyParams(route, pathname);
|
|
1792
|
+
const closes = [];
|
|
1793
|
+
let html;
|
|
1794
|
+
try {
|
|
1795
|
+
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
1796
|
+
html = await render(closes, '');
|
|
1797
|
+
} catch {
|
|
1798
|
+
// the route itself is broken: degrade to pages/500.rose (or the
|
|
1799
|
+
// built-in plain 500) instead of leaving the container empty
|
|
1800
|
+
await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
1801
|
+
return;
|
|
1802
|
+
}
|
|
1803
|
+
if (!initial) container.innerHTML = html;
|
|
1804
|
+
wire(container, closes);
|
|
1805
|
+
bindEvents(container);
|
|
1806
|
+
flushMounts();
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
// unmatched route: pages/404.rose renders (with its head + interactivity),
|
|
1811
|
+
// else the built-in plain 404
|
|
1812
|
+
await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
// Adopt a server-rendered response in place - the JS-enabled half of
|
|
1816
|
+
// progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
|
|
1817
|
+
// via fetch and hands the response here. The DOM is swapped and wired with
|
|
1818
|
+
// the same zero-render trick as boot: re-run the route's render to rebuild
|
|
1819
|
+
// the marker closures, wire them against the adopted nodes. The page never
|
|
1820
|
+
// re-renders visibly, no hydration payload, no second request beyond the POST.
|
|
1821
|
+
export async function adopt(container, html, stateJson) {
|
|
1822
|
+
resetEffects();
|
|
1823
|
+
clearRequestState();
|
|
1824
|
+
clearMounts(); // stale mounts from a failed render never fire
|
|
1825
|
+
resumeState(stateJson);
|
|
1826
|
+
container.innerHTML = html;
|
|
1827
|
+
// keep the embedded state in sync so a later SPA-fallback check agrees
|
|
1828
|
+
const st = document.getElementById('__rosetack_state');
|
|
1829
|
+
if (st) st.textContent = stateJson;
|
|
1830
|
+
for (const route of routes) {
|
|
1831
|
+
if (matchRoute(route.pattern, location.pathname)) {
|
|
1832
|
+
applyParams(route, location.pathname);
|
|
1833
|
+
const closes = [];
|
|
1834
|
+
try {
|
|
1835
|
+
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
1836
|
+
await render(closes, '');
|
|
1837
|
+
} catch {
|
|
1838
|
+
// the adopted response's route is broken (e.g. the action's page
|
|
1839
|
+
// throws): keep the swapped DOM but skip wiring it
|
|
1840
|
+
return;
|
|
1841
|
+
}
|
|
1842
|
+
wire(container, closes);
|
|
1843
|
+
bindEvents(container);
|
|
1844
|
+
flushMounts();
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
// === refresh() implementation ===
|
|
1850
|
+
// Re-render the current route in place: the client half of router.refresh()
|
|
1851
|
+
// (Next.js) / invalidateAll() (SvelteKit). Same machinery as a client-side
|
|
1852
|
+
// navigation to the current path - $data re-runs, state re-seeds from the
|
|
1853
|
+
// fresh render, wire() patches the marked nodes - but a refresh never lands
|
|
1854
|
+
// a prefetch entry: a hover from a minute ago is exactly what it exists to
|
|
1855
|
+
// bypass. Zero requests: the render (and its $data) runs in the page.
|
|
1856
|
+
// ponytail: state resets like navigation (no per-key retention); add
|
|
1857
|
+
// retention when an app needs refresh-without-losing-input.
|
|
1858
|
+
setRefreshHook(async () => {
|
|
1859
|
+
prefetchCache.delete(location.pathname);
|
|
1860
|
+
await start(document.getElementById('app'), location.pathname, false);
|
|
1861
|
+
});
|
|
1862
|
+
`;
|
|
1863
|
+
await fs.promises.writeFile(path.join(buildDir, 'client-entry.js'), clientEntry);
|
|
1864
|
+
if (split) {
|
|
1865
|
+
// Mode B (P0 §1): esbuild code splitting. One chunk per route module, the shared
|
|
1866
|
+
// runtime in its own vendor chunk …
|
|
1867
|
+
await fs.promises.rm(path.join(outDir, 'chunks'), { recursive: true, force: true });
|
|
1868
|
+
await esbuild.build({
|
|
1869
|
+
entryPoints: [path.join(buildDir, 'client-entry.js')],
|
|
1870
|
+
bundle: true,
|
|
1871
|
+
format: 'esm',
|
|
1872
|
+
platform: 'browser',
|
|
1873
|
+
minify: true,
|
|
1874
|
+
splitting: true,
|
|
1875
|
+
outdir: outDir,
|
|
1876
|
+
entryNames: 'client',
|
|
1877
|
+
chunkNames: 'chunks/[name]-[hash]',
|
|
1878
|
+
write: true,
|
|
1879
|
+
});
|
|
1880
|
+
} else {
|
|
1881
|
+
await esbuild.build({
|
|
1882
|
+
entryPoints: [path.join(buildDir, 'client-entry.js')],
|
|
1883
|
+
bundle: true,
|
|
1884
|
+
outfile: path.join(outDir, 'client.js'),
|
|
1885
|
+
format: 'esm',
|
|
1886
|
+
platform: 'browser',
|
|
1887
|
+
minify: true,
|
|
1888
|
+
write: true,
|
|
1889
|
+
});
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
// the deploy dir now holds only real artifacts
|
|
1893
|
+
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
1894
|
+
|
|
1895
|
+
const publicDir = path.join(root, 'public');
|
|
1896
|
+
if (fs.existsSync(publicDir)) {
|
|
1897
|
+
const outPublic = path.join(outDir, 'public');
|
|
1898
|
+
await fs.promises.mkdir(outPublic, { recursive: true });
|
|
1899
|
+
const assets = await fs.promises.readdir(publicDir);
|
|
1900
|
+
await Promise.all(
|
|
1901
|
+
assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
|
|
1902
|
+
);
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
// Innovation #31: the build's zero-JS lint report - every route, its verdict, and the
|
|
1906
|
+
// reason.
|
|
1907
|
+
console.log('rosetack zero-JS report:');
|
|
1908
|
+
for (const line of buildReport(infos, compiled)) console.log(' ' + line);
|
|
1909
|
+
for (const { info, i } of pages) {
|
|
1910
|
+
if (!routeShipsNoJs(infos, compiled, i)) continue;
|
|
1911
|
+
for (const ci of [i, ...layoutsOf(infos, i)]) {
|
|
1912
|
+
for (const w of compiled[ci].jsWarnings ?? []) {
|
|
1913
|
+
console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
async function scanRoseFiles(root: string): Promise<string[]> {
|
|
1922
|
+
const pagesDir = path.join(root, 'src', 'pages');
|
|
1923
|
+
if (!fs.existsSync(pagesDir)) return [];
|
|
1924
|
+
|
|
1925
|
+
async function scan(dir: string): Promise<string[]> {
|
|
1926
|
+
const entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
|
1927
|
+
const files: string[] = [];
|
|
1928
|
+
for (const entry of entries) {
|
|
1929
|
+
const full = path.join(dir, entry.name);
|
|
1930
|
+
if (entry.isDirectory()) files.push(...(await scan(full)));
|
|
1931
|
+
else if (entry.name.endsWith('.rose')) files.push(full);
|
|
1932
|
+
}
|
|
1933
|
+
return files;
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
return scan(pagesDir);
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
function isAncestorDir(layoutPath: string, pagePath: string): boolean {
|
|
1940
|
+
const layoutDir = path.dirname(layoutPath);
|
|
1941
|
+
const pageDir = path.dirname(pagePath);
|
|
1942
|
+
return pageDir === layoutDir || pageDir.startsWith(layoutDir + path.sep);
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
function getRouteInfo(filePath: string, root: string): RouteInfo {
|
|
1946
|
+
const pagesDir = path.join(root, 'src', 'pages');
|
|
1947
|
+
const relative = path.relative(pagesDir, filePath).replace(/\\/g, '/');
|
|
1948
|
+
const withoutExt = relative.replace(/\.rose$/, '');
|
|
1949
|
+
const base = path.posix.basename(withoutExt);
|
|
1950
|
+
const isLayout = base === '_layout';
|
|
1951
|
+
const isNotFound = base === '404';
|
|
1952
|
+
const isError = base === '500';
|
|
1953
|
+
// pages/api/*.rose: Web-standard handler routes (JSON in, JSON out), never
|
|
1954
|
+
// HTML pages - they dispatch by method and never reach the client bundle.
|
|
1955
|
+
const isApi = withoutExt === 'api' || withoutExt.startsWith('api/');
|
|
1956
|
+
// pages/_middleware.rose: the request interceptor. It runs before every render and is not
|
|
1957
|
+
// a route: it matches nothing and never reaches the client bundle.
|
|
1958
|
+
const isMiddleware = withoutExt === '_middleware';
|
|
1959
|
+
|
|
1960
|
+
let parts = withoutExt.split('/').filter((p) => p !== '_layout');
|
|
1961
|
+
// a trailing `index` segment names its directory (blog/index -> /blog,
|
|
1962
|
+
// api/index -> /api); only the root index collapses to '/'
|
|
1963
|
+
if (parts.length > 1 && parts[parts.length - 1] === 'index') parts = parts.slice(0, -1);
|
|
1964
|
+
const routeParts = parts.map((part) =>
|
|
1965
|
+
part.startsWith('[') && part.endsWith(']') ? `:${part.slice(1, -1)}` : part
|
|
1966
|
+
);
|
|
1967
|
+
|
|
1968
|
+
let routePath: string;
|
|
1969
|
+
if (routeParts.length === 0 || (routeParts.length === 1 && routeParts[0] === 'index')) {
|
|
1970
|
+
routePath = '/';
|
|
1971
|
+
} else {
|
|
1972
|
+
routePath = '/' + routeParts.join('/');
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
return {
|
|
1976
|
+
filePath,
|
|
1977
|
+
routePath,
|
|
1978
|
+
pattern: routePath,
|
|
1979
|
+
paramNames: parts.filter((p) => p.startsWith('[') && p.endsWith(']')).map((p) => p.slice(1, -1)),
|
|
1980
|
+
isLayout,
|
|
1981
|
+
isNotFound,
|
|
1982
|
+
isError,
|
|
1983
|
+
isApi,
|
|
1984
|
+
isMiddleware,
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
function capitalize(s: string): string {
|
|
1989
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
1990
|
+
}
|