rosetack 0.1.1 → 0.1.3
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/deploy/cloudflare/functions/[[path]].ts +61 -0
- package/deploy/cloudflare/wrangler.toml +14 -0
- package/deploy/k8s/rosetack.yaml +107 -0
- package/deploy/netlify/functions/rosetack.ts +38 -0
- package/deploy/netlify.toml +17 -0
- package/devtools/devtools.html +7 -0
- package/devtools/devtools.js +1 -0
- package/devtools/manifest.json +8 -0
- package/devtools/panel.html +28 -0
- package/devtools/panel.js +54 -0
- package/dist-cli/compiler.mjs +1346 -492
- package/dist-cli/edge.mjs +152 -41
- package/dist-cli/rosetack.mjs +1974 -606
- package/dist-cli/runtime.mjs +205 -40
- package/dist-cli/test.mjs +1425 -508
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/edge.ts +76 -61
- package/src/cli/index.ts +516 -293
- package/src/cli/prompt.ts +130 -0
- package/src/cli/shell.ts +113 -65
- package/src/cli/test.ts +9 -70
- package/src/compiler/errors.ts +74 -0
- package/src/compiler/index.ts +1514 -839
- package/src/runtime/index.ts +255 -150
- package/src/types/rosetack.d.ts +18 -59
- package/templates/admin/package.json +14 -0
- package/templates/admin/rosetack.config.js +1 -0
- package/templates/admin/src/pages/_middleware.rose +33 -0
- package/templates/admin/src/pages/api/items.rose +37 -0
- package/templates/admin/src/pages/api/login.rose +25 -0
- package/templates/admin/src/pages/index.rose +79 -0
- package/templates/api/package.json +14 -0
- package/templates/api/rosetack.config.js +1 -0
- package/templates/api/src/pages/api/health.rose +7 -0
- package/templates/api/src/pages/api/items.rose +46 -0
- package/templates/api/src/pages/api/login.rose +24 -0
- package/templates/api/src/pages/index.rose +25 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/rosetack.config.js +1 -0
- package/templates/blog/src/pages/404.rose +2 -0
- package/templates/blog/src/pages/_layout.rose +42 -0
- package/templates/blog/src/pages/_middleware.rose +74 -0
- package/templates/blog/src/pages/admin.rose +85 -0
- package/templates/blog/src/pages/api/login.rose +46 -0
- package/templates/blog/src/pages/api/posts/[id].rose +37 -0
- package/templates/blog/src/pages/api/posts.rose +72 -0
- package/templates/blog/src/pages/index.rose +31 -0
- package/templates/blog/src/pages/post/[id].rose +36 -0
- package/templates/site/package.json +14 -0
- package/templates/site/rosetack.config.js +1 -0
- package/templates/site/src/pages/404.rose +2 -0
- package/templates/site/src/pages/_layout.rose +40 -0
- package/templates/site/src/pages/about.rose +6 -0
- package/templates/site/src/pages/index.rose +13 -0
- package/templates/site/src/pages/pricing.rose +8 -0
package/src/compiler/index.ts
CHANGED
|
@@ -1,25 +1,17 @@
|
|
|
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
|
-
*/
|
|
1
|
+
// rosetack Compiler - Compile .rose components to SSR + client-resume JS
|
|
7
2
|
|
|
8
3
|
import * as fs from 'fs';
|
|
9
4
|
import * as path from 'path';
|
|
10
5
|
import { pathToFileURL, fileURLToPath } from 'url';
|
|
11
6
|
import * as esbuild from 'esbuild';
|
|
7
|
+
import { RoseError, lineOf, lineAt } from './errors.js';
|
|
8
|
+
export { RoseError, lineOf, lineAt, errorInfo } from './errors.js';
|
|
9
|
+
export type { RoseErrorInfo } from './errors.js';
|
|
12
10
|
|
|
13
11
|
const COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
14
12
|
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
13
|
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
14
|
const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
21
|
-
// A declaration's initializer may carry TypeScript: a type argument (`$state<Record<string,
|
|
22
|
-
// Post>>(...)`) and/or a cast (`$state(0) as Counter`).
|
|
23
15
|
const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
24
16
|
const DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
25
17
|
const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
@@ -29,26 +21,17 @@ const SLOT_RE = /<slot\s*\/?>/g;
|
|
|
29
21
|
* keeps the plain `<slot />` out of it - that one is the default slot. */
|
|
30
22
|
const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
|
|
31
23
|
|
|
32
|
-
|
|
33
|
-
* Encode a named slot tag as the template expression
|
|
34
|
-
* `__slot('row', [['item', (post)]])` - array pairs, because the template
|
|
35
|
-
* scanner matches `{...}` without nested braces.
|
|
36
|
-
*/
|
|
24
|
+
// Encode a named slot tag as the template expression `__slot('row', [['item', (post)]])` - array pairs.
|
|
37
25
|
function encodeSlotCall(attrs: string): string {
|
|
38
26
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
|
|
39
|
-
if (!name) throw new
|
|
27
|
+
if (!name) throw new RoseError('E-TEMPLATE', '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
|
|
40
28
|
const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)]
|
|
41
29
|
.filter((m) => m[1] !== 'name')
|
|
42
30
|
.map((m) => `['${m[1]}', (${m[2].trim()})]`);
|
|
43
31
|
return `${JSON.stringify(name)}, [${pairs.join(', ')}]`;
|
|
44
32
|
}
|
|
45
|
-
// {#boundary}...{/boundary}: an error boundary - its content renders into its own string; a
|
|
46
|
-
// throw anywhere inside swaps in a fallback instead of failing the whole page.
|
|
47
33
|
const BOUNDARY_FALLBACK = '<p>This section failed to render.</p>';
|
|
48
|
-
// API route handlers are exported functions named by HTTP method (pages/api/*.rose).
|
|
49
34
|
const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
50
|
-
// A .rose <script> block is TypeScript: interfaces, annotations, `as`, generics. The
|
|
51
|
-
// compiler's intermediates therefore hold TypeScript, and esbuild must STRIP the types …
|
|
52
35
|
const TS_LOADER = { loader: { '.js': 'ts' as const } };
|
|
53
36
|
|
|
54
37
|
export interface CompileResult {
|
|
@@ -74,8 +57,38 @@ export interface CompileResult {
|
|
|
74
57
|
revalidate?: number;
|
|
75
58
|
/** the component exports `csr = false` (document ships without the client bundle) */
|
|
76
59
|
csr?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* The component exports `shell = false`: keep the client bundle (this route
|
|
62
|
+
* still needs it - comments widgets, third-party scripts) but drop the
|
|
63
|
+
* shell's demo dressing - the #app wrapper and STYLES_MIN. A real app ships
|
|
64
|
+
* its own theme CSS; the scaffold's `body{padding:2rem}` / pink links then
|
|
65
|
+
* outrank it on equal specificity. Same escape the zero-JS branch has, for
|
|
66
|
+
* routes that cannot go JS-free.
|
|
67
|
+
*/
|
|
68
|
+
shell?: boolean;
|
|
69
|
+
/**
|
|
70
|
+
* P0-2 (bug report): the component exports `buffer = true` - render it per
|
|
71
|
+
* request on the BUFFERED path instead of streaming. A streamed response
|
|
72
|
+
* commits its status and headers before the body exists, so an onResponse
|
|
73
|
+
* hook cannot see (let alone replace) the document and a route that fails
|
|
74
|
+
* mid-render still answers 200. This is the explicit opt-out: the route
|
|
75
|
+
* keeps the exact same features, it just refuses to trade them for TTFB.
|
|
76
|
+
* Implies dynamic: a baked file on disk is the one path a hook can never
|
|
77
|
+
* run on, so `buffer = true` routes are never prerendered.
|
|
78
|
+
*/
|
|
79
|
+
buffer?: boolean;
|
|
80
|
+
/**
|
|
81
|
+
* The script calls `redirect()` or `notFound()` (the control-flow pair).
|
|
82
|
+
* Both are thrown signals whose answer is the RESPONSE's status - a 30x
|
|
83
|
+
* with a Location, or a real 404 - and a streamed response has committed
|
|
84
|
+
* its status before the render runs. Such a route is therefore buffered
|
|
85
|
+
* by construction, exactly like `buffer = true`, and never prerendered.
|
|
86
|
+
*/
|
|
87
|
+
controlSignal?: boolean;
|
|
77
88
|
/** the component exports `prefetch = 'off' | 'hover' | 'viewport' | 'all'` (app-global link-prefetch strategy) */
|
|
78
89
|
prefetch?: string;
|
|
90
|
+
/** The component exports `vitals = true` (app-global web-vitals reporting) */
|
|
91
|
+
vitals?: boolean;
|
|
79
92
|
/** the component exports `bundle = 'inline' | 'split'` (app-global client bundle mode) */
|
|
80
93
|
bundle?: string;
|
|
81
94
|
/** The static analysis says this component needs the client bundle */
|
|
@@ -156,7 +169,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
156
169
|
let i = 0;
|
|
157
170
|
while (i < src.length) {
|
|
158
171
|
const ch = src[i];
|
|
159
|
-
// string literal: copy verbatim
|
|
160
172
|
if (ch === "'" || ch === '"') {
|
|
161
173
|
let j = i + 1;
|
|
162
174
|
while (j < src.length && src[j] !== ch) {
|
|
@@ -167,7 +179,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
167
179
|
i = j + 1;
|
|
168
180
|
continue;
|
|
169
181
|
}
|
|
170
|
-
// template literal: copy text verbatim, scan ${...} as code
|
|
171
182
|
if (ch === '`') {
|
|
172
183
|
out += ch;
|
|
173
184
|
i++;
|
|
@@ -197,7 +208,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
197
208
|
i++;
|
|
198
209
|
continue;
|
|
199
210
|
}
|
|
200
|
-
// comments: copy verbatim
|
|
201
211
|
if (ch === '/' && src[i + 1] === '/') {
|
|
202
212
|
const nl = src.indexOf('\n', i);
|
|
203
213
|
const end = nl === -1 ? src.length : nl;
|
|
@@ -212,7 +222,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
212
222
|
i = end;
|
|
213
223
|
continue;
|
|
214
224
|
}
|
|
215
|
-
// identifier: rewrite bare state reads only
|
|
216
225
|
if (/[A-Za-z_$]/.test(ch)) {
|
|
217
226
|
let j = i;
|
|
218
227
|
while (j < src.length && /[\w$]/.test(src[j])) j++;
|
|
@@ -244,26 +253,297 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
244
253
|
*/
|
|
245
254
|
function callifyTemplateExprs(template: string, names: string[]): string {
|
|
246
255
|
if (names.length === 0) return template;
|
|
247
|
-
|
|
248
|
-
|
|
256
|
+
let out = '';
|
|
257
|
+
let last = 0;
|
|
258
|
+
for (const s of templateExprSpans(template)) {
|
|
259
|
+
out += template.slice(last, s.start) + '{' + callifyStateReads(s.expr, names) + '}';
|
|
260
|
+
last = s.end + 1;
|
|
261
|
+
}
|
|
262
|
+
return out + template.slice(last);
|
|
249
263
|
}
|
|
250
264
|
|
|
251
265
|
/**
|
|
252
|
-
* The
|
|
253
|
-
*
|
|
254
|
-
*
|
|
266
|
+
* The spans of a template's top-level `{ ... }` expressions, literal-aware.
|
|
267
|
+
*
|
|
268
|
+
* A flat `[^{}]+` regex cannot see that `{q() ? `a ${q()}` : 'b'}` is ONE
|
|
269
|
+
* expression: it matched the `{q()}` inside the template literal instead, so
|
|
270
|
+
* the compiler rewrote THAT and left the rest as prose - the served document
|
|
271
|
+
* carried `Search: $rose` where the title should have said `Search: rose`.
|
|
272
|
+
* A wrong page with no error anywhere is the worst failure mode a template
|
|
273
|
+
* compiler has, so the scan below walks the source once, skipping quoted
|
|
274
|
+
* strings and template literals (whose own `${ ... }` holes are balanced
|
|
275
|
+
* separately), and reports the expression a reader sees.
|
|
276
|
+
*
|
|
277
|
+
* Shared by every pass that must agree on where an expression ends: the
|
|
278
|
+
* compiler itself, the state-read rewrite, the {#each} item rename and the
|
|
279
|
+
* named-slot prop rewrite.
|
|
255
280
|
*/
|
|
281
|
+
export function templateExprSpans(src: string): Array<{ start: number; end: number; expr: string }> {
|
|
282
|
+
const spans: Array<{ start: number; end: number; expr: string }> = [];
|
|
283
|
+
let i = 0;
|
|
284
|
+
while (i < src.length) {
|
|
285
|
+
if (src[i] === '{') {
|
|
286
|
+
const end = scanExprEnd(src, i);
|
|
287
|
+
if (end > i + 1) {
|
|
288
|
+
spans.push({ start: i, end, expr: src.slice(i + 1, end) });
|
|
289
|
+
i = end + 1;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
i++;
|
|
294
|
+
}
|
|
295
|
+
return spans;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The index of the `}` that closes the `{` at `open`, or -1 when it never does. */
|
|
299
|
+
function scanExprEnd(src: string, open: number): number {
|
|
300
|
+
let depth = 0;
|
|
301
|
+
let i = open;
|
|
302
|
+
while (i < src.length) {
|
|
303
|
+
const ch = src[i];
|
|
304
|
+
if (ch === "'" || ch === '"') {
|
|
305
|
+
i = skipQuoted(src, i);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (ch === '`') {
|
|
309
|
+
i = skipTemplate(src, i);
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
if (ch === '{') depth++;
|
|
313
|
+
else if (ch === '}' && --depth === 0) return i;
|
|
314
|
+
i++;
|
|
315
|
+
}
|
|
316
|
+
return -1;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Just past the closing quote of the string literal that starts at `i`. */
|
|
320
|
+
function skipQuoted(src: string, i: number): number {
|
|
321
|
+
const q = src[i];
|
|
322
|
+
let j = i + 1;
|
|
323
|
+
while (j < src.length) {
|
|
324
|
+
if (src[j] === '\\') {
|
|
325
|
+
j += 2;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (src[j] === q) return j + 1;
|
|
329
|
+
j++;
|
|
330
|
+
}
|
|
331
|
+
return j;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Just past the closing backtick of the template literal at `i`, `${ }` holes balanced. */
|
|
335
|
+
function skipTemplate(src: string, i: number): number {
|
|
336
|
+
let j = i + 1;
|
|
337
|
+
while (j < src.length) {
|
|
338
|
+
const ch = src[j];
|
|
339
|
+
if (ch === '\\') {
|
|
340
|
+
j += 2;
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (ch === '`') return j + 1;
|
|
344
|
+
if (ch === '$' && src[j + 1] === '{') {
|
|
345
|
+
const end = scanExprEnd(src, j + 1);
|
|
346
|
+
j = end < 0 ? src.length : end + 1;
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
j++;
|
|
350
|
+
}
|
|
351
|
+
return j;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// The literal that starts at `i`, if any: a quoted string, a template literal, or - the one that keeps derailing scanners - a REGEX literal.
|
|
355
|
+
function skipLiteral(src: string, i: number): number | null {
|
|
356
|
+
const q = src[i];
|
|
357
|
+
if (q === '"' || q === "'") return skipQuoted(src, i);
|
|
358
|
+
if (q === '`') return skipTemplate(src, i);
|
|
359
|
+
if (q !== '/') return null;
|
|
360
|
+
if (src[i + 1] === '/' || src[i + 1] === '*') return null;
|
|
361
|
+
let b = i - 1;
|
|
362
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
363
|
+
if (b >= 0) {
|
|
364
|
+
if (!'(,=:[!&|?{};+-*%~^'.includes(src[b])) {
|
|
365
|
+
const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? '';
|
|
366
|
+
if (!['return', 'typeof', 'case', 'in', 'of', 'new', 'delete', 'void', 'do', 'else', 'instanceof', 'yield', 'await'].includes(word)) return null;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
let j = i + 1;
|
|
370
|
+
let inClass = false;
|
|
371
|
+
while (j < src.length) {
|
|
372
|
+
const c = src[j];
|
|
373
|
+
if (c === '\\') { j += 2; continue; }
|
|
374
|
+
if (c === '\n') return null;
|
|
375
|
+
if (inClass) { if (c === ']') inClass = false; }
|
|
376
|
+
else if (c === '[') inClass = true;
|
|
377
|
+
else if (c === '/') { j++; break; }
|
|
378
|
+
j++;
|
|
379
|
+
}
|
|
380
|
+
if (j > src.length) return null;
|
|
381
|
+
while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
|
|
382
|
+
return j;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// 's scanners are syntactic, and prose is not code: the demo's own "the same zero-JS document." (a sentence ending).
|
|
386
|
+
function stripComments(src: string): string {
|
|
387
|
+
let out = '';
|
|
388
|
+
let i = 0;
|
|
389
|
+
while (i < src.length) {
|
|
390
|
+
const lit = skipLiteral(src, i);
|
|
391
|
+
if (lit !== null) {
|
|
392
|
+
out += src.slice(i, lit);
|
|
393
|
+
i = lit;
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
if (src.startsWith('//', i)) {
|
|
397
|
+
while (i < src.length && src[i] !== '\n') i++;
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
if (src.startsWith('/*', i)) {
|
|
401
|
+
i += 2;
|
|
402
|
+
while (i < src.length && !src.startsWith('*/', i)) i++;
|
|
403
|
+
i = Math.min(i + 2, src.length);
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
if (src.startsWith('<!--', i)) {
|
|
407
|
+
i += 4;
|
|
408
|
+
while (i < src.length && !src.startsWith('-->', i)) i++;
|
|
409
|
+
i = Math.min(i + 3, src.length);
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
out += src[i++];
|
|
413
|
+
}
|
|
414
|
+
return out;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Q1 (bug report): the zero-JS scanner cried wolf on the standard isomorphic guard.
|
|
418
|
+
function stripGuardedBranches(src: string): string {
|
|
419
|
+
const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
|
|
420
|
+
const ws = (i: number): number => { while (i < src.length && /\s/.test(src[i])) i++; return i; };
|
|
421
|
+
const ternaryColon = (q: number): number => {
|
|
422
|
+
let depth = 0;
|
|
423
|
+
let i = q + 1;
|
|
424
|
+
while (i < src.length) {
|
|
425
|
+
const c = src[i];
|
|
426
|
+
const lit = skipLiteral(src, i);
|
|
427
|
+
if (lit !== null) { i = lit; continue; }
|
|
428
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
429
|
+
else if (c === ')' || c === ']' || c === '}') { depth--; if (depth < 0) return -1; }
|
|
430
|
+
else if (depth === 0 && c === ':') return i;
|
|
431
|
+
else if (depth === 0 && c === '?') { const inner = ternaryColon(i); if (inner < 0) return -1; i = inner + 1; continue; }
|
|
432
|
+
i++;
|
|
433
|
+
}
|
|
434
|
+
return -1;
|
|
435
|
+
};
|
|
436
|
+
const exprEnd = (i: number): number => {
|
|
437
|
+
let depth = 0;
|
|
438
|
+
while (i < src.length) {
|
|
439
|
+
const c = src[i];
|
|
440
|
+
const lit = skipLiteral(src, i);
|
|
441
|
+
if (lit !== null) { i = lit; continue; }
|
|
442
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
443
|
+
else if (c === ')' || c === ']' || c === '}') { if (depth === 0) return i; depth--; }
|
|
444
|
+
else if (depth === 0 && (c === ',' || c === ';')) return i;
|
|
445
|
+
else if (depth === 0 && c === '?') { const inner = ternaryColon(i); if (inner < 0) return src.length; i = inner + 1; continue; }
|
|
446
|
+
i++;
|
|
447
|
+
}
|
|
448
|
+
return src.length;
|
|
449
|
+
};
|
|
450
|
+
const braceEnd = (b: number): number => {
|
|
451
|
+
let depth = 0;
|
|
452
|
+
let i = b;
|
|
453
|
+
while (i < src.length) {
|
|
454
|
+
const c = src[i];
|
|
455
|
+
const lit = skipLiteral(src, i);
|
|
456
|
+
if (lit !== null) { i = lit; continue; }
|
|
457
|
+
if (c === '{') depth++;
|
|
458
|
+
else if (c === '}') { depth--; if (depth === 0) return i; }
|
|
459
|
+
i++;
|
|
460
|
+
}
|
|
461
|
+
return src.length;
|
|
462
|
+
};
|
|
463
|
+
const stmtEnd = (i: number): number => {
|
|
464
|
+
let depth = 0;
|
|
465
|
+
while (i < src.length) {
|
|
466
|
+
const c = src[i];
|
|
467
|
+
const lit = skipLiteral(src, i);
|
|
468
|
+
if (lit !== null) { i = lit; continue; }
|
|
469
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
470
|
+
else if (c === ')' || c === ']' || c === '}') { if (depth === 0) return i; depth--; }
|
|
471
|
+
else if (depth === 0 && (c === ';' || c === '\n')) return i;
|
|
472
|
+
i++;
|
|
473
|
+
}
|
|
474
|
+
return src.length;
|
|
475
|
+
};
|
|
476
|
+
const isIfGuard = (src: string, at: number): boolean => {
|
|
477
|
+
let b = at - 1;
|
|
478
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
479
|
+
if (b < 0 || src[b] !== '(') return false;
|
|
480
|
+
b--;
|
|
481
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
482
|
+
return b >= 1 && src[b] === 'f' && src[b - 1] === 'i' && (b < 2 || !/[\w$]/.test(src[b - 2]));
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
const blanks: Array<[number, number]> = [];
|
|
486
|
+
let i = 0;
|
|
487
|
+
while (i < src.length) {
|
|
488
|
+
const lit = skipLiteral(src, i);
|
|
489
|
+
if (lit !== null) { i = lit; continue; }
|
|
490
|
+
GUARD.lastIndex = i;
|
|
491
|
+
const m = GUARD.exec(src);
|
|
492
|
+
if (!m) { i++; continue; }
|
|
493
|
+
const browserAfter = m[1] === '!==';
|
|
494
|
+
const j = ws(i + m[0].length);
|
|
495
|
+
const two = src.slice(j, j + 2);
|
|
496
|
+
if (two === '&&' && browserAfter) {
|
|
497
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
498
|
+
} else if (two === '||' && !browserAfter) {
|
|
499
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
500
|
+
} else if (src[j] === '?') {
|
|
501
|
+
const colon = ternaryColon(j);
|
|
502
|
+
if (colon < 0) {
|
|
503
|
+
if (browserAfter) blanks.push([j + 1, src.length]);
|
|
504
|
+
} else if (browserAfter) {
|
|
505
|
+
blanks.push([j + 1, colon]);
|
|
506
|
+
} else {
|
|
507
|
+
blanks.push([colon + 1, exprEnd(colon + 1)]);
|
|
508
|
+
}
|
|
509
|
+
} else if (src[j] === ')' && isIfGuard(src, i)) {
|
|
510
|
+
let bodyEnd: number;
|
|
511
|
+
const k = ws(j + 1);
|
|
512
|
+
if (src[k] === '{') {
|
|
513
|
+
bodyEnd = braceEnd(k);
|
|
514
|
+
if (browserAfter) blanks.push([k + 1, bodyEnd]);
|
|
515
|
+
} else {
|
|
516
|
+
bodyEnd = stmtEnd(k);
|
|
517
|
+
if (browserAfter) blanks.push([k, bodyEnd]);
|
|
518
|
+
}
|
|
519
|
+
const after = ws(bodyEnd + 1);
|
|
520
|
+
if (src.startsWith('else', after)) {
|
|
521
|
+
const e = ws(after + 4);
|
|
522
|
+
if (src[e] === '{') {
|
|
523
|
+
const close = braceEnd(e);
|
|
524
|
+
if (!browserAfter) blanks.push([e + 1, close]);
|
|
525
|
+
} else {
|
|
526
|
+
const stop = stmtEnd(e);
|
|
527
|
+
if (!browserAfter) blanks.push([e, stop]);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
i = j;
|
|
532
|
+
}
|
|
533
|
+
if (blanks.length === 0) return src;
|
|
534
|
+
const out = [...src];
|
|
535
|
+
for (const [a, b] of blanks) {
|
|
536
|
+
for (let k = a; k < b && k < out.length; k++) if (out[k] !== '\n') out[k] = ' ';
|
|
537
|
+
}
|
|
538
|
+
return out.join('');
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// The <script> block of a .rose source, verbatim.
|
|
256
542
|
export function scriptOf(source: string): string | null {
|
|
257
543
|
return source.match(COMPONENT_RE)?.[1] ?? null;
|
|
258
544
|
}
|
|
259
545
|
|
|
260
|
-
|
|
261
|
-
* The per-request bag the runtime hooks receive. Web-standard on purpose:
|
|
262
|
-
* the same object reaches a hook on the Node server, the preview server and
|
|
263
|
-
* the edge adapter, so hook code is written once and runs everywhere.
|
|
264
|
-
* `state` is scratch space - one hook writes, a later hook (or the page,
|
|
265
|
-
* through getContext()) reads.
|
|
266
|
-
*/
|
|
546
|
+
// The per-request bag the runtime hooks receive.
|
|
267
547
|
export interface RequestHookContext {
|
|
268
548
|
request: Request;
|
|
269
549
|
url: URL;
|
|
@@ -272,18 +552,15 @@ export interface RequestHookContext {
|
|
|
272
552
|
state: Record<string, unknown>;
|
|
273
553
|
}
|
|
274
554
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
* module that declares it, so its imports must load in the target runtime
|
|
285
|
-
* (Node and edge both): keep node-only code out of rosetack.config.js.
|
|
286
|
-
*/
|
|
555
|
+
|
|
556
|
+
export interface StoreBridge {
|
|
557
|
+
/** Install the sender: every $store write in this worker calls it. Pass null to detach. */
|
|
558
|
+
install(send: ((name: string, value: unknown) => void) | null): void;
|
|
559
|
+
/** Apply a patch that arrived from another process or machine. */
|
|
560
|
+
deliver(name: string, value: unknown): void;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
|
|
287
564
|
export interface Plugin {
|
|
288
565
|
name: string;
|
|
289
566
|
transform?(code: string, filePath: string): string | Promise<string>;
|
|
@@ -291,26 +568,13 @@ export interface Plugin {
|
|
|
291
568
|
onRequest?(ctx: RequestHookContext): Response | void | Promise<Response | void>;
|
|
292
569
|
/** After the response exists, before it is sent. Return a Response to replace it. */
|
|
293
570
|
onResponse?(ctx: RequestHookContext, res: Response): Response | void | Promise<Response | void>;
|
|
294
|
-
/** Worker start: open a connection pool, warm a cache. */
|
|
295
|
-
onServe?(meta: { port: number; workers: number }): void | Promise<void>;
|
|
571
|
+
/** Worker start: open a connection pool, warm a cache, install a cross-machine store driver. */
|
|
572
|
+
onServe?(meta: { port: number; workers: number; store: StoreBridge }): void | Promise<void>;
|
|
296
573
|
/** Worker drain, before exit: close the pool. */
|
|
297
574
|
onShutdown?(): void | Promise<void>;
|
|
298
575
|
}
|
|
299
576
|
|
|
300
|
-
|
|
301
|
-
* The i18n half of rosetack.config.js - a named export beside the
|
|
302
|
-
* plugins:
|
|
303
|
-
*
|
|
304
|
-
* export const i18n = { preload: ['en', 'zh'] };
|
|
305
|
-
*
|
|
306
|
-
* `preload` lists the locales baked into the CLIENT bundle. The default is
|
|
307
|
-
* every locale: a language switch then costs zero requests, which is the
|
|
308
|
-
* one-request bet taken to its conclusion. An app with many languages lists
|
|
309
|
-
* the ones it wants inline; the rest are written to dist/locales/<lang>.json
|
|
310
|
-
* and fetched on first use (ensureLocale in the runtime). The SERVER bundle
|
|
311
|
-
* always carries every locale - it renders any language on demand, and its
|
|
312
|
-
* size is nobody's hot path.
|
|
313
|
-
*/
|
|
577
|
+
|
|
314
578
|
export interface I18nConfig {
|
|
315
579
|
preload?: string[];
|
|
316
580
|
}
|
|
@@ -320,20 +584,7 @@ export interface rosetackConfig {
|
|
|
320
584
|
i18n: I18nConfig;
|
|
321
585
|
}
|
|
322
586
|
|
|
323
|
-
|
|
324
|
-
* Plugins live in `<root>/rosetack.config.js` as the default export: an array
|
|
325
|
-
* of `{ name, transform, onRequest, onResponse, onServe, onShutdown }`.
|
|
326
|
-
* `transform` runs over each component's raw source (template + script +
|
|
327
|
-
* style, before any parsing) at build time; the runtime hooks are bundled
|
|
328
|
-
* into dist/server.js by build() below. trade-off: transform alone covers
|
|
329
|
-
* macros, custom syntax, includes and auto-imports - a transform can rewrite
|
|
330
|
-
* anything, including the script block; the request/serve hooks cover auth,
|
|
331
|
-
* logging and lifecycle, which no source rewrite can express. The import is
|
|
332
|
-
* cache-busted per build so a config edit takes effect on the dev server's
|
|
333
|
-
* next rebuild, and a missing file is simply "no config" (existence is
|
|
334
|
-
* checked first, so a config with a syntax error still fails loudly).
|
|
335
|
-
* One import, one evaluation: the i18n options ride in the same module.
|
|
336
|
-
*/
|
|
587
|
+
|
|
337
588
|
export async function loadConfig(root: string): Promise<rosetackConfig> {
|
|
338
589
|
const file = path.join(root, 'rosetack.config.js');
|
|
339
590
|
if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
|
|
@@ -374,25 +625,29 @@ export type RoseRegistry = Map<string, { index: number; scopeKey: string; slots:
|
|
|
374
625
|
*/
|
|
375
626
|
function resolveRoseImports(script: string, fromFile: string, registry: RoseRegistry): { script: string; imports: Array<{ name: string; specifier: string; index: number }> } {
|
|
376
627
|
const imports: Array<{ name: string; specifier: string; index: number }> = [];
|
|
377
|
-
const resolve = (spec: string): { index: number; scopeKey: string } => {
|
|
628
|
+
const resolve = (spec: string, at: number): { index: number; scopeKey: string } => {
|
|
378
629
|
const abs = path.resolve(path.dirname(fromFile), spec);
|
|
379
630
|
const hit = registry.get(abs);
|
|
380
631
|
if (!hit) {
|
|
381
|
-
throw new
|
|
632
|
+
throw new RoseError(
|
|
633
|
+
'E-IMPORT',
|
|
634
|
+
`${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
|
|
635
|
+
{
|
|
636
|
+
file: fromFile,
|
|
637
|
+
line: lineOf(script, at),
|
|
638
|
+
hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`,
|
|
639
|
+
},
|
|
640
|
+
);
|
|
382
641
|
}
|
|
383
642
|
return hit;
|
|
384
643
|
};
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
|
|
388
|
-
const hit = resolve(spec);
|
|
644
|
+
let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at: number) => {
|
|
645
|
+
const hit = resolve(spec, at);
|
|
389
646
|
imports.push({ name, specifier: spec, index: hit.index });
|
|
390
647
|
return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
|
|
391
648
|
});
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
|
|
395
|
-
const hit = resolve(spec);
|
|
649
|
+
rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at: number) => {
|
|
650
|
+
const hit = resolve(spec, at);
|
|
396
651
|
const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? 'render';
|
|
397
652
|
imports.push({ name: alias, specifier: spec, index: hit.index });
|
|
398
653
|
return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
|
|
@@ -410,6 +665,97 @@ function rewriteRoseImports(script: string, kind: 'ssr' | 'client'): string {
|
|
|
410
665
|
return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
|
|
411
666
|
}
|
|
412
667
|
|
|
668
|
+
/**
|
|
669
|
+
* The specifiers that can never reach a browser
|
|
670
|
+
* bundle. Node builtins by prefix, plus the database drivers the docs tell
|
|
671
|
+
* you to use - the packages a rosetack app reaches for on the server and
|
|
672
|
+
* nowhere else.
|
|
673
|
+
*
|
|
674
|
+
* Trade-off: a specifier list, not a resolver. A package that merely LOOKS
|
|
675
|
+
* server-side but bundles fine for the browser still builds (nothing is
|
|
676
|
+
* lost); the list only has to catch what esbuild's browser platform would
|
|
677
|
+
* refuse anyway, which is what turns a cryptic failure into a clear one.
|
|
678
|
+
*/
|
|
679
|
+
const NODE_ONLY_SPEC = /^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream|child_process|worker_threads|dns|cluster|better-sqlite3|sqlite3|pg|mysql2|mongodb|redis|ioredis)$)/;
|
|
680
|
+
|
|
681
|
+
/** The node-only specifiers among a module's hoisted imports (type imports excluded: esbuild erases them). */
|
|
682
|
+
function nodeOnlyImports(importStmts: string): string[] {
|
|
683
|
+
const out: string[] = [];
|
|
684
|
+
for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
|
|
685
|
+
if (m[1]) continue;
|
|
686
|
+
if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
|
|
687
|
+
}
|
|
688
|
+
return out;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* `on:event={fn}` -> `data-on-event="fn"`, plus the handler registry entries
|
|
693
|
+
* the client module needs. One pass, two outputs, so the attribute and the
|
|
694
|
+
* registry can never disagree.
|
|
695
|
+
*
|
|
696
|
+
* Brace-aware on purpose: a flat `on:(\w+)=\{([^}]+)\}` stopped at the FIRST
|
|
697
|
+
* `}`, so an inline arrow (`on:click={() => $setState('n', n() + 1)}`) was
|
|
698
|
+
* truncated at its own closing brace - which emitted
|
|
699
|
+
* `Object.assign(handlers, { () => ... })` (a syntax error in the generated
|
|
700
|
+
* module) and left a stray `}` in the markup. The scan below balances braces
|
|
701
|
+
* and skips string and template literals, exactly like templateExprSpans.
|
|
702
|
+
*
|
|
703
|
+
* A handler that names a server action becomes `data-on-event="$action:name"`
|
|
704
|
+
* and never reaches the client registry (the body is server-only). An inline
|
|
705
|
+
* handler gets a synthetic name (`__hN`) and rides the registry as
|
|
706
|
+
* `__hN: <expr>`: the registry statement is emitted inside render(), after
|
|
707
|
+
* the state declarations, so the arrow closes over the same `count()`/`setN`
|
|
708
|
+
* the rest of the page uses.
|
|
709
|
+
*/
|
|
710
|
+
function wireEventBindings(template: string, actionNames: Set<string>): {
|
|
711
|
+
template: string;
|
|
712
|
+
bindings: Array<{ event: string; fn: string }>;
|
|
713
|
+
} {
|
|
714
|
+
const bindings: Array<{ event: string; fn: string }> = [];
|
|
715
|
+
let out = '';
|
|
716
|
+
let rest = template;
|
|
717
|
+
for (;;) {
|
|
718
|
+
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
719
|
+
if (!m) {
|
|
720
|
+
out += rest;
|
|
721
|
+
break;
|
|
722
|
+
}
|
|
723
|
+
out += rest.slice(0, m.index);
|
|
724
|
+
let i = m.index + m[0].length;
|
|
725
|
+
let depth = 1;
|
|
726
|
+
while (i < rest.length) {
|
|
727
|
+
const ch = rest[i];
|
|
728
|
+
if (ch === '"' || ch === "'") {
|
|
729
|
+
i = skipQuoted(rest, i);
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
if (ch === '`') {
|
|
733
|
+
i = skipTemplate(rest, i);
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
if (ch === '{') depth++;
|
|
737
|
+
else if (ch === '}') {
|
|
738
|
+
depth--;
|
|
739
|
+
if (depth === 0) break;
|
|
740
|
+
}
|
|
741
|
+
i++;
|
|
742
|
+
}
|
|
743
|
+
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
744
|
+
if (actionNames.has(expr)) {
|
|
745
|
+
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
746
|
+
} else if (/^\w+$/.test(expr)) {
|
|
747
|
+
out += `data-on-${m[1]}="${expr}"`;
|
|
748
|
+
bindings.push({ event: m[1], fn: expr });
|
|
749
|
+
} else {
|
|
750
|
+
const name = `__h${bindings.length}`;
|
|
751
|
+
out += `data-on-${m[1]}="${name}"`;
|
|
752
|
+
bindings.push({ event: m[1], fn: `${name}: ${expr}` });
|
|
753
|
+
}
|
|
754
|
+
rest = rest.slice(i + 1);
|
|
755
|
+
}
|
|
756
|
+
return { template: out, bindings };
|
|
757
|
+
}
|
|
758
|
+
|
|
413
759
|
/**
|
|
414
760
|
* Pre-scan a file's template for its slot declarations -
|
|
415
761
|
* `<slot name="row" item={post}>` -> { name: 'row', props: ['item'] }.
|
|
@@ -423,10 +769,9 @@ function scanSlotDecls(filePath: string): Array<{ name: string; props: string[]
|
|
|
423
769
|
} catch {
|
|
424
770
|
return [];
|
|
425
771
|
}
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
const
|
|
429
|
-
const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, '').replace(COMPONENT_RE, '').trim();
|
|
772
|
+
const noScript = src.replace(COMPONENT_RE, '');
|
|
773
|
+
const noBlocks = noScript.replace(STYLE_RE, '');
|
|
774
|
+
const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, '').trim();
|
|
430
775
|
const out: Array<{ name: string; props: string[] }> = [];
|
|
431
776
|
for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
|
|
432
777
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
|
|
@@ -478,37 +823,40 @@ function hoistImports(script: string): { imports: string; rest: string } {
|
|
|
478
823
|
}
|
|
479
824
|
rest.push(line);
|
|
480
825
|
}
|
|
481
|
-
if (buf) imports.push(buf.join('\n'));
|
|
826
|
+
if (buf) imports.push(buf.join('\n'));
|
|
482
827
|
return { imports: imports.join('\n'), rest: rest.join('\n') };
|
|
483
828
|
}
|
|
484
829
|
|
|
485
830
|
export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = [], registry: RoseRegistry = new Map()): Promise<CompileResult> {
|
|
486
831
|
let source = await fs.promises.readFile(filePath, 'utf-8');
|
|
487
|
-
// Plugins see the raw source first: whatever they return is what the compiler parses.
|
|
488
832
|
for (const p of plugins) {
|
|
489
|
-
// a runtime-only plugin (onRequest/onServe, no transform) has nothing to
|
|
490
|
-
// rewrite - it must not break the build for lacking a build-time hook
|
|
491
833
|
if (!p.transform) continue;
|
|
492
834
|
try {
|
|
493
835
|
source = await p.transform(source, filePath);
|
|
494
836
|
} catch (err) {
|
|
495
|
-
throw new
|
|
837
|
+
throw new RoseError(
|
|
838
|
+
'E-PLUGIN',
|
|
839
|
+
`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
840
|
+
{ file: filePath, hint: 'the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)' },
|
|
841
|
+
);
|
|
496
842
|
}
|
|
497
843
|
}
|
|
498
844
|
|
|
499
|
-
// API route (pages/api/*.rose): no template, no state, no markers - the script's exported
|
|
500
|
-
// functions ARE the handlers …
|
|
501
845
|
if (isApi) {
|
|
502
846
|
const scriptMatch = source.match(COMPONENT_RE);
|
|
503
847
|
const rawScript = scriptMatch?.[1] ?? '';
|
|
504
848
|
const apiMethods = [...rawScript.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)]
|
|
505
849
|
.map((m) => m[1])
|
|
506
850
|
.filter((name) => HTTP_METHODS.has(name));
|
|
507
|
-
// a handler that reads the request context cannot be baked: the bag is
|
|
508
|
-
// per-request, a baked body would freeze one request's answer
|
|
509
851
|
const usesContext = /getContext\s*\(/.test(rawScript);
|
|
510
852
|
const hasPrerender = !usesContext && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript);
|
|
511
853
|
const hoisted = hoistImports(resolveRoseImports(rawScript, filePath, registry).script);
|
|
854
|
+
const ownRuntimeImports = new Set(
|
|
855
|
+
[...rawScript.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)]
|
|
856
|
+
.flatMap((m) => m[1].split(',').map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
|
|
857
|
+
);
|
|
858
|
+
const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
|
|
859
|
+
const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(', ')} } from './runtime.js';\n` : '';
|
|
512
860
|
return {
|
|
513
861
|
ssr: '',
|
|
514
862
|
client: '',
|
|
@@ -517,77 +865,105 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
517
865
|
guardName: null,
|
|
518
866
|
style: '',
|
|
519
867
|
hasParams: false,
|
|
520
|
-
api:
|
|
868
|
+
api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
|
|
521
869
|
apiMethods,
|
|
522
870
|
hasPrerender,
|
|
523
871
|
usesContext,
|
|
524
872
|
};
|
|
525
873
|
}
|
|
526
874
|
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
const styleMatch =
|
|
875
|
+
const sourceNoScript = source.replace(COMPONENT_RE, '');
|
|
876
|
+
const sourceNoHead = sourceNoScript.replace(HEAD_RE, '');
|
|
877
|
+
const styleMatch = sourceNoHead.match(STYLE_RE);
|
|
530
878
|
const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : '';
|
|
531
|
-
const sourceNoBlocks =
|
|
879
|
+
const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, '');
|
|
532
880
|
|
|
533
|
-
const scriptMatch =
|
|
534
|
-
// Resolve `import Card from '../components/Card.rose'` against the build registry before
|
|
535
|
-
// anything else looks at the script: the rewritten specifier (a `__rose_N__` placeholder) …
|
|
881
|
+
const scriptMatch = source.match(COMPONENT_RE);
|
|
536
882
|
const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? '', filePath, registry);
|
|
537
883
|
const rawScript = roseResolved.script;
|
|
538
884
|
const roseImports = roseResolved.imports;
|
|
539
|
-
// The imports (a component import above all) belong at module scope,
|
|
540
|
-
// not inside render() - hoisted here, emitted by the generators.
|
|
541
885
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
542
|
-
|
|
543
|
-
|
|
886
|
+
if (path.basename(filePath) !== '_middleware.rose') {
|
|
887
|
+
for (const spec of nodeOnlyImports(importStmts)) {
|
|
888
|
+
const at = importStmts.indexOf(spec);
|
|
889
|
+
throw new RoseError(
|
|
890
|
+
'E-NODE-ONLY',
|
|
891
|
+
`${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. ` +
|
|
892
|
+
`This module's script ships to the client (its $data bodies included), so move the import to ` +
|
|
893
|
+
`src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows ` +
|
|
894
|
+
`travel to the page through getContext() / $data.`,
|
|
895
|
+
{
|
|
896
|
+
file: filePath,
|
|
897
|
+
line: at >= 0 ? lineOf(importStmts, at) : undefined,
|
|
898
|
+
hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`,
|
|
899
|
+
},
|
|
900
|
+
);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
544
903
|
const isComponent = registry.get(filePath)?.scopeKey.startsWith('components/') ?? false;
|
|
545
|
-
// Boundary, stated loudly at build time: a component renders INSIDE its parent's template
|
|
546
|
-
// phase, which is synchronous by design (that is what keeps wire …
|
|
547
904
|
if (isComponent && /\$data\s*\(/.test(rawScript)) {
|
|
548
|
-
throw new
|
|
905
|
+
throw new RoseError(
|
|
906
|
+
'E-EXPORT',
|
|
549
907
|
`${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. ` +
|
|
550
|
-
`Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}
|
|
908
|
+
`Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
|
|
909
|
+
{ file: filePath, hint: 'move the fetch to the page (or the middleware) and pass the value down as a prop' },
|
|
551
910
|
);
|
|
552
911
|
}
|
|
553
|
-
|
|
554
|
-
// the build must not bake it and the servers must not answer it from a prerendered file.
|
|
555
|
-
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
|
|
556
|
-
// an exported `params` marks a dynamic route for prerender enumeration
|
|
912
|
+
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
|
|
557
913
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
558
|
-
// an exported `revalidate = N` opts the route into stale-while-revalidate: the baked file
|
|
559
|
-
// is served for up to N seconds …
|
|
560
914
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
561
915
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
|
|
562
|
-
// P1: an exported `prefetch = '...'` sets the app-global link-prefetch strategy - 'off',
|
|
563
|
-
// 'hover' …
|
|
564
916
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
565
917
|
const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
|
|
566
918
|
if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
|
|
567
|
-
throw new
|
|
919
|
+
throw new RoseError(
|
|
920
|
+
'E-EXPORT',
|
|
921
|
+
`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
|
|
922
|
+
{ file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" },
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
|
|
926
|
+
const vitals = vitalsMatch ? vitalsMatch[1].trim() === 'true' : undefined;
|
|
927
|
+
if (vitalsMatch && !vitals) {
|
|
928
|
+
throw new RoseError(
|
|
929
|
+
'E-EXPORT',
|
|
930
|
+
`${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
|
|
931
|
+
{ file: filePath, line: lineAt(rawScript, vitalsMatch), hint: 'omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app' },
|
|
932
|
+
);
|
|
568
933
|
}
|
|
569
|
-
// The bundle mode - the fix for the large-app architecture gap. 'inline' (the default) is
|
|
570
|
-
// the single-document mode: the whole client bundle rides inside the HTML, one request …
|
|
571
934
|
const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
572
935
|
const bundle = bundleMatch ? bundleMatch[1] : undefined;
|
|
573
936
|
if (bundle && !['inline', 'split'].includes(bundle)) {
|
|
574
|
-
throw new
|
|
937
|
+
throw new RoseError(
|
|
938
|
+
'E-EXPORT',
|
|
939
|
+
`${filePath}: export const bundle must be 'inline' or 'split'`,
|
|
940
|
+
{ file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" },
|
|
941
|
+
);
|
|
575
942
|
}
|
|
576
|
-
// The compiler decides zero-JS, not the developer. This is the same "does anything here
|
|
577
|
-
// need the client bundle" predicate that Used to REFUSE `csr = false`: event wiring in the …
|
|
578
943
|
const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
|
|
579
944
|
const csr: boolean | undefined = csrMatch ? csrMatch[1] !== 'false' : undefined;
|
|
945
|
+
const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
|
|
946
|
+
const shell: boolean | undefined = shellMatch ? shellMatch[1] !== 'false' : undefined;
|
|
947
|
+
const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
|
|
948
|
+
const buffer: boolean | undefined = bufferMatch ? bufferMatch[1] !== 'false' : undefined;
|
|
949
|
+
const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || undefined;
|
|
580
950
|
if (csr === false) {
|
|
581
951
|
const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
|
|
582
952
|
if (dead) {
|
|
583
|
-
|
|
953
|
+
const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? undefined) ? source : rawScript;
|
|
954
|
+
throw new RoseError(
|
|
955
|
+
'E-EXPORT',
|
|
584
956
|
`${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. ` +
|
|
585
|
-
`(Forms still work without JS: a native POST runs the server action.)
|
|
957
|
+
`(Forms still work without JS: a native POST runs the server action.)`,
|
|
958
|
+
{
|
|
959
|
+
file: filePath,
|
|
960
|
+
line: lineAt(deadSrc, dead),
|
|
961
|
+
hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle',
|
|
962
|
+
},
|
|
586
963
|
);
|
|
587
964
|
}
|
|
588
965
|
}
|
|
589
966
|
|
|
590
|
-
// An exported `headers = { ... }` sets this route's response headers
|
|
591
967
|
let headers: Record<string, string> | undefined;
|
|
592
968
|
const headersLiteral = extractObjectLiteral(rawScript, 'headers');
|
|
593
969
|
if (headersLiteral) {
|
|
@@ -595,16 +971,22 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
595
971
|
try {
|
|
596
972
|
value = new Function(`return ${headersLiteral}`)();
|
|
597
973
|
} catch {
|
|
598
|
-
throw new
|
|
974
|
+
throw new RoseError(
|
|
975
|
+
'E-EXPORT',
|
|
976
|
+
`${filePath}: export const headers must be an object literal`,
|
|
977
|
+
{ file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" },
|
|
978
|
+
);
|
|
599
979
|
}
|
|
600
980
|
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value as object).some((v) => typeof v !== 'string')) {
|
|
601
|
-
throw new
|
|
981
|
+
throw new RoseError(
|
|
982
|
+
'E-EXPORT',
|
|
983
|
+
`${filePath}: export const headers must be a flat map of string -> string`,
|
|
984
|
+
{ file: filePath, hint: 'every value must be a string literal (a number or an array fails here instead of shipping verbatim)' },
|
|
985
|
+
);
|
|
602
986
|
}
|
|
603
987
|
headers = value as Record<string, string>;
|
|
604
988
|
}
|
|
605
989
|
|
|
606
|
-
// An exported `csp = { nonce: true }` switches this route from the hashed policy to a
|
|
607
|
-
// per-request nonce . The hash is the stronger default
|
|
608
990
|
let cspNonce: boolean | undefined;
|
|
609
991
|
const cspLiteral = extractObjectLiteral(rawScript, 'csp');
|
|
610
992
|
if (cspLiteral) {
|
|
@@ -612,154 +994,131 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
612
994
|
try {
|
|
613
995
|
value = new Function(`return ${cspLiteral}`)();
|
|
614
996
|
} catch {
|
|
615
|
-
throw new
|
|
997
|
+
throw new RoseError(
|
|
998
|
+
'E-EXPORT',
|
|
999
|
+
`${filePath}: export const csp must be an object literal`,
|
|
1000
|
+
{ file: filePath, hint: 'write it as one literal: export const csp = { nonce: true }' },
|
|
1001
|
+
);
|
|
616
1002
|
}
|
|
617
1003
|
const nonce = (value as { nonce?: unknown } | null)?.nonce;
|
|
618
1004
|
if (nonce !== undefined && typeof nonce !== 'boolean') {
|
|
619
|
-
throw new
|
|
1005
|
+
throw new RoseError(
|
|
1006
|
+
'E-EXPORT',
|
|
1007
|
+
`${filePath}: csp.nonce must be a boolean`,
|
|
1008
|
+
{ file: filePath, hint: 'csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)' },
|
|
1009
|
+
);
|
|
620
1010
|
}
|
|
621
1011
|
cspNonce = nonce === true;
|
|
622
1012
|
}
|
|
623
1013
|
|
|
624
|
-
// Top-level `export` statements (e.g. `export const params = {...}` for dynamic-route
|
|
625
|
-
// prerendering) are hoisted to module scope: the script body itself is embedded inside …
|
|
626
1014
|
const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
|
|
627
1015
|
const script = scriptNoExports;
|
|
628
1016
|
const actionNames = new Set(actions.map((a) => a.name));
|
|
629
1017
|
|
|
630
|
-
// Does anything in this component need the client bundle?
|
|
631
1018
|
const clientReasons: string[] = [];
|
|
632
|
-
if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)');
|
|
633
|
-
if (/<form[
|
|
634
|
-
|
|
635
|
-
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`); // lifecycle / client-only APIs
|
|
636
|
-
if (actionNames.size > 0) { // a server action (form target or $action)
|
|
637
|
-
clientReasons.push(`server action${actionNames.size > 1 ? 's' : ''} (${[...actionNames].join(', ')})`);
|
|
1019
|
+
if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)');
|
|
1020
|
+
if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
|
|
1021
|
+
clientReasons.push('a form bound to a client dispatch ($action)');
|
|
638
1022
|
}
|
|
1023
|
+
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
1024
|
+
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`);
|
|
639
1025
|
const needsClient = clientReasons.length > 0;
|
|
640
1026
|
|
|
641
|
-
// The predicate is SYNTACTIC, so a component that ships no runtime is scanned for the
|
|
642
|
-
// shapes that would silently need one …
|
|
643
1027
|
const jsWarnings: string[] = [];
|
|
644
1028
|
if (!needsClient) {
|
|
645
|
-
|
|
1029
|
+
const codeOnly = stripComments(source);
|
|
1030
|
+
const scriptCodeOnly = stripComments(rawScript);
|
|
1031
|
+
const scriptScannable = stripGuardedBranches(scriptCodeOnly);
|
|
1032
|
+
if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
|
|
646
1033
|
jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
|
|
647
1034
|
}
|
|
648
|
-
if (/javascript:/i.test(
|
|
1035
|
+
if (/javascript:/i.test(codeOnly)) {
|
|
649
1036
|
jsWarnings.push('a javascript: URL - it needs the bundle to run; link to a real route');
|
|
650
1037
|
}
|
|
651
|
-
if (/\b(?:eval|new Function)\s*\(/.test(
|
|
1038
|
+
if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
|
|
652
1039
|
jsWarnings.push('eval()/new Function() - client code the predicate cannot see');
|
|
653
1040
|
}
|
|
654
|
-
|
|
655
|
-
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)) {
|
|
1041
|
+
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(scriptScannable)) {
|
|
656
1042
|
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');
|
|
657
1043
|
}
|
|
658
1044
|
}
|
|
659
1045
|
|
|
660
1046
|
const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
|
|
661
|
-
|
|
662
|
-
const headMatch = sourceNoBlocks.match(HEAD_RE);
|
|
663
|
-
const headContent = headMatch?.[1] ?? '';
|
|
664
|
-
const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, '');
|
|
1047
|
+
const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? '';
|
|
665
1048
|
const rawTemplate = templateMatch
|
|
666
1049
|
? templateMatch[1]
|
|
667
|
-
:
|
|
668
|
-
// a component with styles carries its scope attribute on every top-level
|
|
669
|
-
// element, so its rules match only its own subtree
|
|
1050
|
+
: sourceNoBlocks.replace(COMPONENT_RE, '').trim();
|
|
670
1051
|
const template = scopedStyle
|
|
671
1052
|
? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey)
|
|
672
1053
|
: inlineImages(rawTemplate, publicDir);
|
|
673
1054
|
|
|
674
|
-
// Extract state / data declarations with balanced-paren scanning
|
|
675
1055
|
const decls = extractDecls(script);
|
|
676
1056
|
const stateDecls = decls.filter((d) => d.kind === 'state');
|
|
677
1057
|
|
|
678
|
-
// setter name per state: setCount
|
|
679
1058
|
const setterNames = new Map<string, string>();
|
|
680
1059
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
681
1060
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
1061
|
+
const declCode = (d: (typeof decls)[number]): string => {
|
|
1062
|
+
const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
|
|
1063
|
+
if (d.kind === 'state') {
|
|
1064
|
+
return `const [${d.name}, ${setterNames.get(d.name)!}] = state(${JSON.stringify(key)}, ${d.expr});`;
|
|
1065
|
+
}
|
|
1066
|
+
const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
|
|
1067
|
+
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
1068
|
+
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1069
|
+
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1070
|
+
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
1071
|
+
};
|
|
1072
|
+
|
|
1073
|
+
const nestedDecls: (typeof decls)[number][] = [];
|
|
1074
|
+
let spliced = '';
|
|
1075
|
+
let pos = 0;
|
|
1076
|
+
decls.forEach((d, i) => {
|
|
1077
|
+
const top = braceDepthAt(script, d.start) === 0;
|
|
1078
|
+
if (!top) nestedDecls.push(d);
|
|
1079
|
+
spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : '');
|
|
1080
|
+
pos = d.end;
|
|
1081
|
+
});
|
|
1082
|
+
spliced += script.slice(pos);
|
|
690
1083
|
|
|
691
|
-
|
|
692
|
-
let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end] as [number, number]));
|
|
693
|
-
cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
|
|
1084
|
+
let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
|
|
694
1085
|
const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, '');
|
|
695
1086
|
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
696
1087
|
return `${setter}(${val})`;
|
|
697
1088
|
});
|
|
698
|
-
|
|
699
|
-
// Replace bare state reads with getter calls (after decl removal). A plain regex would
|
|
700
|
-
// also rewrite state names inside string literals …
|
|
701
1089
|
cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
|
|
1090
|
+
cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
|
|
702
1091
|
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
1092
|
+
const stateDeclsCode = nestedDecls.filter((d) => d.kind === 'state').map(declCode).join('\n');
|
|
1093
|
+
const dataDeclsCode = nestedDecls.filter((d) => d.kind === 'data').map(declCode).join('\n');
|
|
706
1094
|
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
const
|
|
710
|
-
.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
|
|
711
|
-
.replace(SLOT_RE, '{__slot__}')
|
|
712
|
-
.replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) =>
|
|
713
|
-
actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
|
|
714
|
-
|
|
715
|
-
const stateDeclsCode = decls
|
|
716
|
-
.map((d) => {
|
|
717
|
-
// A component's state keys are namespaced by its file, so two components that both declare
|
|
718
|
-
// `let open = $state(false)` no longer share one signal …
|
|
719
|
-
const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
|
|
720
|
-
if (d.kind === 'state') {
|
|
721
|
-
return `const [${d.name}, ${setterNames.get(d.name)!}] = state(${JSON.stringify(key)}, ${d.expr});`;
|
|
722
|
-
}
|
|
723
|
-
// $data: fetch only when this key has no value yet (server: always after
|
|
724
|
-
// clearRequestState; client: only on first visit or client-side nav)
|
|
725
|
-
const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
|
|
726
|
-
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
727
|
-
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
728
|
-
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
729
|
-
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
730
|
-
})
|
|
731
|
-
.join('\n');
|
|
1095
|
+
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
1096
|
+
const wired = wireEventBindings(templateCalled, actionNames);
|
|
1097
|
+
const eventBindings = wired.bindings;
|
|
732
1098
|
|
|
733
1099
|
const stateKeys = decls.map((d) => d.name);
|
|
734
1100
|
|
|
735
|
-
// The local name -> module map for the components this file imports, handed to the
|
|
736
|
-
// template compiler so `<Card title={x}>` becomes a call to the imported module's render() …
|
|
737
1101
|
const comps = new Map(roseImports.map((r) => {
|
|
738
1102
|
const abs = path.resolve(path.dirname(filePath), r.specifier);
|
|
739
1103
|
const hit = registry.get(abs)!;
|
|
740
1104
|
return [r.name, { index: hit.index, slots: hit.slots }] as const;
|
|
741
1105
|
}));
|
|
1106
|
+
const ssrTemplate = rewriteQuotedExprAttrs(wired.template
|
|
1107
|
+
.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
|
|
1108
|
+
.replace(SLOT_RE, '{__slot__}'), comps);
|
|
1109
|
+
assertKnownDirectives(ssrTemplate, filePath);
|
|
742
1110
|
const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0, true, comps);
|
|
743
|
-
|
|
744
|
-
// call, so one reactive closure drives document title/meta on navigation.
|
|
745
|
-
const compiledHead = headContent.trim() ? compileTemplate(headContent, '__hd', '__hc', null, 0, false) : '';
|
|
746
|
-
// A named slot in the template needs the __slot() helper in the module.
|
|
1111
|
+
const compiledHead = headContent.trim() ? compileHead(headContent) : '';
|
|
747
1112
|
const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
|
|
748
1113
|
|
|
749
|
-
// Actions ship in the SSR module only; the client bundle gets every other
|
|
750
|
-
// export (params, sync helpers) but never an action body.
|
|
751
1114
|
const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
|
|
752
|
-
// The guard is emitted at the SSR module's scope, beside the actions it fronts …
|
|
753
1115
|
const ssrGuard = guard ? `\n${guard}` : '';
|
|
754
|
-
// pages/_middleware.rose is a hook module, not a route: no template, no state, no head.
|
|
755
1116
|
const isMiddleware = path.basename(filePath) === '_middleware.rose';
|
|
756
1117
|
const ssr = isMiddleware
|
|
757
1118
|
? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
|
|
758
|
-
: generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
|
|
759
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
|
|
1119
|
+
: generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1120
|
+
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
760
1121
|
|
|
761
|
-
// One rewrite for both bundles and every branch above: the `__rose_N__` placeholder
|
|
762
|
-
// resolves to this bundle's own module path …
|
|
763
1122
|
return {
|
|
764
1123
|
ssr: rewriteRoseImports(ssr, 'ssr'),
|
|
765
1124
|
client: rewriteRoseImports(client, 'client'),
|
|
@@ -771,7 +1130,11 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
771
1130
|
usesContext,
|
|
772
1131
|
revalidate,
|
|
773
1132
|
csr,
|
|
1133
|
+
shell,
|
|
1134
|
+
buffer,
|
|
1135
|
+
controlSignal,
|
|
774
1136
|
prefetch,
|
|
1137
|
+
vitals,
|
|
775
1138
|
bundle,
|
|
776
1139
|
needsClient,
|
|
777
1140
|
clientReasons,
|
|
@@ -825,8 +1188,6 @@ function scopeCss(css: string, key: string): string {
|
|
|
825
1188
|
const block = clean.slice(i + 1, j - 1);
|
|
826
1189
|
const sel = prelude.trim();
|
|
827
1190
|
if (sel.startsWith('@')) {
|
|
828
|
-
// at-rule: keep the prelude, scope the inner rules (keyframes pass
|
|
829
|
-
// through: their 0%/from/to "selectors" are not selectors)
|
|
830
1191
|
out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
|
|
831
1192
|
} else if (sel) {
|
|
832
1193
|
const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(',');
|
|
@@ -860,7 +1221,6 @@ function injectScopeAttr(template: string, key: string): string {
|
|
|
860
1221
|
break;
|
|
861
1222
|
}
|
|
862
1223
|
out += template.slice(i, lt);
|
|
863
|
-
// scan one tag, respecting quoted attribute values
|
|
864
1224
|
let j = lt + 1;
|
|
865
1225
|
let quote = '';
|
|
866
1226
|
while (j < template.length) {
|
|
@@ -871,12 +1231,11 @@ function injectScopeAttr(template: string, key: string): string {
|
|
|
871
1231
|
else if (c === '>') break;
|
|
872
1232
|
j++;
|
|
873
1233
|
}
|
|
874
|
-
const tagText = template.slice(lt, j + 1);
|
|
1234
|
+
const tagText = template.slice(lt, j + 1);
|
|
875
1235
|
const closing = /^<\//.test(tagText);
|
|
876
1236
|
const nameMatch = tagText.match(/^<\/?([a-zA-Z][\w-]*)/);
|
|
877
1237
|
const selfClosing = /\/>$/.test(tagText) || (nameMatch && VOID_TAGS.has(nameMatch[1].toLowerCase()));
|
|
878
1238
|
if (nameMatch && !closing && depth === 0 && !selfClosing) {
|
|
879
|
-
// inject before the closing > (or before a trailing />)
|
|
880
1239
|
const injectAt = tagText.endsWith('/>') ? tagText.length - 2 : tagText.length - 1;
|
|
881
1240
|
out += tagText.slice(0, injectAt) + attr + tagText.slice(injectAt);
|
|
882
1241
|
depth++;
|
|
@@ -891,7 +1250,6 @@ function injectScopeAttr(template: string, key: string): string {
|
|
|
891
1250
|
|
|
892
1251
|
const VOID_TAGS = new Set(['img', 'br', 'hr', 'input', 'meta', 'link', 'source', 'wbr']);
|
|
893
1252
|
|
|
894
|
-
// Trade-off: tolerate leading indentation - .rose script blocks are indented
|
|
895
1253
|
const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
|
|
896
1254
|
|
|
897
1255
|
/**
|
|
@@ -932,28 +1290,20 @@ function extractObjectLiteral(script: string, name: string): string | null {
|
|
|
932
1290
|
return script.slice(start, i);
|
|
933
1291
|
}
|
|
934
1292
|
|
|
935
|
-
// Exported for `rosetack check`: it synthesizes a module declaration for every imported
|
|
936
|
-
// .rose component from the SAME prop parse the compiler uses …
|
|
937
1293
|
export function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }>; props: Array<{ name: string; def: string | null }>; guard: string } {
|
|
938
1294
|
const stmts: string[] = [];
|
|
939
1295
|
const actions: Array<{ name: string; stmt: string }> = [];
|
|
940
|
-
// `export let` is a PROP, not a module-scope value - it is read from the caller's props
|
|
941
|
-
// object per invocation.
|
|
942
1296
|
const props: Array<{ name: string; def: string | null }> = [];
|
|
943
|
-
// `export async function beforeAction(name, form)` is the page's action GUARD - it runs
|
|
944
|
-
// before every action and vetoes with an ActionError.
|
|
945
1297
|
const guards: string[] = [];
|
|
946
1298
|
let out = '';
|
|
947
1299
|
let pos = 0;
|
|
948
1300
|
let m: RegExpExecArray | null;
|
|
949
1301
|
EXPORT_RE.lastIndex = 0;
|
|
950
1302
|
while ((m = EXPORT_RE.exec(script))) {
|
|
951
|
-
const kind = m[1];
|
|
952
|
-
const start = m.index + m[0].indexOf('export');
|
|
1303
|
+
const kind = m[1];
|
|
1304
|
+
const start = m.index + m[0].indexOf('export');
|
|
953
1305
|
let i = start + m[0].length - m[0].indexOf('export');
|
|
954
1306
|
if (kind) {
|
|
955
|
-
// balanced scan: object/array literals, calls, arrows end at their
|
|
956
|
-
// matching close; primitive literals end at `;` or a plain newline.
|
|
957
1307
|
let depth = 0;
|
|
958
1308
|
while (i < script.length) {
|
|
959
1309
|
const ch = script[i];
|
|
@@ -978,7 +1328,6 @@ export function extractExports(script: string): { clean: string; exports: string
|
|
|
978
1328
|
}
|
|
979
1329
|
if (script[i] === ';') i++;
|
|
980
1330
|
} else {
|
|
981
|
-
// function declaration: skip the parameter list, balance the body
|
|
982
1331
|
while (i < script.length && script[i] !== '{') i++;
|
|
983
1332
|
let depth = 0;
|
|
984
1333
|
while (i < script.length) {
|
|
@@ -999,15 +1348,13 @@ export function extractExports(script: string): { clean: string; exports: string
|
|
|
999
1348
|
const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
|
|
1000
1349
|
const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
|
|
1001
1350
|
if (anyFn?.[1] === 'beforeAction') {
|
|
1002
|
-
guards.push(stmt);
|
|
1351
|
+
guards.push(stmt);
|
|
1003
1352
|
} else if (asyncFn) {
|
|
1004
|
-
actions.push({ name: asyncFn[1], stmt });
|
|
1353
|
+
actions.push({ name: asyncFn[1], stmt });
|
|
1005
1354
|
} else if (kind === 'let') {
|
|
1006
|
-
// A prop. The declaration never reaches module scope - the generated render reads it from
|
|
1007
|
-
// the props object (with this default) …
|
|
1008
1355
|
const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
|
|
1009
1356
|
if (pm) props.push({ name: pm[1], def: pm[2]?.trim() ?? null });
|
|
1010
|
-
else stmts.push(stmt);
|
|
1357
|
+
else stmts.push(stmt);
|
|
1011
1358
|
} else {
|
|
1012
1359
|
stmts.push(stmt);
|
|
1013
1360
|
}
|
|
@@ -1022,8 +1369,6 @@ function extractDecls(script: string): Decl[] {
|
|
|
1022
1369
|
DECL_RE.lastIndex = 0;
|
|
1023
1370
|
let m: RegExpExecArray | null;
|
|
1024
1371
|
while ((m = DECL_RE.exec(script))) {
|
|
1025
|
-
// The regex matched up to `$state`/`$data`; what follows is an optional type-argument
|
|
1026
|
-
// list and then the call.
|
|
1027
1372
|
let j = m.index + m[0].length;
|
|
1028
1373
|
const skipSpace = () => { while (j < script.length && /\s/.test(script[j])) j++; };
|
|
1029
1374
|
skipSpace();
|
|
@@ -1035,12 +1380,12 @@ function extractDecls(script: string): Decl[] {
|
|
|
1035
1380
|
else if (ch === '>' && script[j - 1] !== '=') {
|
|
1036
1381
|
depth--;
|
|
1037
1382
|
if (depth === 0) { j++; break; }
|
|
1038
|
-
} else if (ch === '=' && script[j + 1] === '>') j++;
|
|
1383
|
+
} else if (ch === '=' && script[j + 1] === '>') j++;
|
|
1039
1384
|
j++;
|
|
1040
1385
|
}
|
|
1041
1386
|
skipSpace();
|
|
1042
1387
|
}
|
|
1043
|
-
if (script[j] !== '(') continue;
|
|
1388
|
+
if (script[j] !== '(') continue;
|
|
1044
1389
|
const open = j + 1;
|
|
1045
1390
|
let depth = 1;
|
|
1046
1391
|
let i = open;
|
|
@@ -1065,50 +1410,307 @@ function extractDecls(script: string): Decl[] {
|
|
|
1065
1410
|
return decls;
|
|
1066
1411
|
}
|
|
1067
1412
|
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1413
|
+
/**
|
|
1414
|
+
* Brace depth at `index`, with strings, template literals and comments
|
|
1415
|
+
* skipped so their braces never count. A declaration at depth 0 is a
|
|
1416
|
+
* top-level statement of the script: it may be replaced where it stands
|
|
1417
|
+
* (BUG.md 2026.9.22 - the TDZ fix). Anything deeper lives inside a function
|
|
1418
|
+
* body (an onMount callback) and must keep its scope.
|
|
1419
|
+
*/
|
|
1420
|
+
function braceDepthAt(src: string, index: number): number {
|
|
1421
|
+
let depth = 0;
|
|
1422
|
+
let i = 0;
|
|
1423
|
+
while (i < index) {
|
|
1424
|
+
const ch = src[i];
|
|
1425
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
1426
|
+
const quote = ch;
|
|
1427
|
+
i++;
|
|
1428
|
+
while (i < index) {
|
|
1429
|
+
if (src[i] === '\\') { i += 2; continue; }
|
|
1430
|
+
if (src[i] === quote) { i++; break; }
|
|
1431
|
+
if (quote === '`' && src[i] === '$' && src[i + 1] === '{') {
|
|
1432
|
+
let d = 1;
|
|
1433
|
+
i += 2;
|
|
1434
|
+
while (i < index && d > 0) {
|
|
1435
|
+
if (src[i] === '{') d++;
|
|
1436
|
+
else if (src[i] === '}') d--;
|
|
1437
|
+
i++;
|
|
1438
|
+
}
|
|
1439
|
+
continue;
|
|
1440
|
+
}
|
|
1441
|
+
i++;
|
|
1442
|
+
}
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
if (ch === '/' && src[i + 1] === '/') {
|
|
1446
|
+
const nl = src.indexOf('\n', i);
|
|
1447
|
+
i = nl === -1 ? src.length : nl;
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
if (ch === '/' && src[i + 1] === '*') {
|
|
1451
|
+
const close = src.indexOf('*/', i + 2);
|
|
1452
|
+
i = close === -1 ? src.length : close + 2;
|
|
1453
|
+
continue;
|
|
1454
|
+
}
|
|
1455
|
+
if (ch === '{') depth++;
|
|
1456
|
+
else if (ch === '}') depth--;
|
|
1457
|
+
i++;
|
|
1075
1458
|
}
|
|
1076
|
-
|
|
1077
|
-
|
|
1459
|
+
return depth;
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// Compile a .rose template to statements that build an HTML string with reactive markers, and push update closures into the shared `closes` array.
|
|
1463
|
+
|
|
1464
|
+
|
|
1465
|
+
function autoCall(expr: string): string {
|
|
1466
|
+
const e = expr.trim();
|
|
1467
|
+
return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/**
|
|
1471
|
+
* Find a `{#if ...}...{/if}`, `{#each ... as x}...{/each}` or
|
|
1472
|
+
* `{#boundary}...{/boundary}` block, NESTING-AWARE: the close tag that
|
|
1473
|
+
* ends the block is the one that BALANCES the opens inside it.
|
|
1474
|
+
*
|
|
1475
|
+
* A non-greedy regex cannot tell the two apart - it stops at the first
|
|
1476
|
+
* close tag, which is the INNER block's. The outer block then ends early,
|
|
1477
|
+
* its own close tag is left in the stream as prose, and the inner open
|
|
1478
|
+
* (now unclosed inside the truncated content) falls through to the
|
|
1479
|
+
* expression matcher and compiles to `(#if ...)` - the cryptic
|
|
1480
|
+
* "Unexpected #if" esbuild error. The scan below counts same-kind opens
|
|
1481
|
+
* as it walks, so an `{#if}` inside an `{#if}` (or an `{#each}` inside
|
|
1482
|
+
* an `{#each}`) is content, not a terminator.
|
|
1483
|
+
*
|
|
1484
|
+
* Returns a RegExpExecArray-shaped value (index + capture groups in the
|
|
1485
|
+
* same order the old regexes produced) so the call sites are unchanged.
|
|
1486
|
+
*/
|
|
1487
|
+
function findBlock(src: string, kind: 'if' | 'each' | 'boundary'): RegExpExecArray | null {
|
|
1488
|
+
const head = kind === 'boundary'
|
|
1489
|
+
? /\{#boundary\}/g
|
|
1490
|
+
: kind === 'if'
|
|
1491
|
+
? /\{#if\s+([^}]+)\}/g
|
|
1492
|
+
: /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
|
|
1493
|
+
const closeRe = new RegExp(`\\{/${kind}\\}`, 'g');
|
|
1494
|
+
let open: RegExpExecArray | null;
|
|
1495
|
+
while ((open = head.exec(src))) {
|
|
1496
|
+
const start = open.index;
|
|
1497
|
+
const afterOpen = start + open[0].length;
|
|
1498
|
+
let depth = 1;
|
|
1499
|
+
let i = afterOpen;
|
|
1500
|
+
for (;;) {
|
|
1501
|
+
head.lastIndex = i;
|
|
1502
|
+
closeRe.lastIndex = i;
|
|
1503
|
+
const nextOpen = head.exec(src);
|
|
1504
|
+
const nextClose = closeRe.exec(src);
|
|
1505
|
+
if (!nextClose) break;
|
|
1506
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
1507
|
+
depth++;
|
|
1508
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
1509
|
+
continue;
|
|
1510
|
+
}
|
|
1511
|
+
i = nextClose.index + nextClose[0].length;
|
|
1512
|
+
if (--depth === 0) {
|
|
1513
|
+
const content = src.slice(afterOpen, nextClose.index);
|
|
1514
|
+
const groups = kind === 'boundary' ? [content] : kind === 'if' ? [open[1], content] : [open[1], open[2], content];
|
|
1515
|
+
const arr = [src.slice(start, i), ...groups] as unknown as RegExpExecArray;
|
|
1516
|
+
(arr as any).index = start;
|
|
1517
|
+
return arr;
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
head.lastIndex = afterOpen;
|
|
1521
|
+
}
|
|
1522
|
+
return null;
|
|
1078
1523
|
}
|
|
1079
1524
|
|
|
1080
1525
|
/**
|
|
1081
|
-
* Compile a .
|
|
1082
|
-
*
|
|
1526
|
+
* Compile a <head> block. Same template rules as the body - `{expr}` escapes,
|
|
1527
|
+
* `{#if}`/`{#each}`/`{@html}` all work - with two exceptions:
|
|
1083
1528
|
*
|
|
1084
|
-
*
|
|
1085
|
-
*
|
|
1086
|
-
*
|
|
1087
|
-
*
|
|
1088
|
-
*
|
|
1089
|
-
*
|
|
1529
|
+
* - the interior of a `<style>`, `<script>` or `<noscript>` element is RAW
|
|
1530
|
+
* TEXT, not template source. CSS braces are not rosetack expressions
|
|
1531
|
+
* (`<style>.a { color: red }</style>` read as one giant `{...}` expression
|
|
1532
|
+
* and broke the build the first time a route shipped a head-level style),
|
|
1533
|
+
* and a `<script>`'s own syntax has the same problem.
|
|
1534
|
+
* - an HTML comment is a NOTE, not content: it is dropped. A note that
|
|
1535
|
+
* mentions `<style>` ("ship a <style> here") must not be able to move where
|
|
1536
|
+
* the stylesheet starts, and the server's head merge reads this output.
|
|
1090
1537
|
*
|
|
1091
|
-
*
|
|
1092
|
-
*
|
|
1538
|
+
* Each markup segment compiles with its own depth so the block helper names
|
|
1539
|
+
* (`__b0_0`) can never collide inside the one head function they share.
|
|
1540
|
+
*/
|
|
1541
|
+
function compileHead(head: string): string {
|
|
1542
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
|
|
1543
|
+
let out = '';
|
|
1544
|
+
let buf = '';
|
|
1545
|
+
let seg = 0;
|
|
1546
|
+
let i = 0;
|
|
1547
|
+
const flush = () => {
|
|
1548
|
+
if (buf.trim()) out += compileTemplate(buf, '__hd', '__hc', null, seg++, false);
|
|
1549
|
+
buf = '';
|
|
1550
|
+
};
|
|
1551
|
+
while (i < head.length) {
|
|
1552
|
+
if (head.startsWith('<!--', i)) {
|
|
1553
|
+
const end = head.indexOf('-->', i + 4);
|
|
1554
|
+
i = end < 0 ? head.length : end + 3;
|
|
1555
|
+
continue;
|
|
1556
|
+
}
|
|
1557
|
+
RAW_OPEN.lastIndex = i;
|
|
1558
|
+
const open = RAW_OPEN.exec(head);
|
|
1559
|
+
if (open) {
|
|
1560
|
+
const tag = open[1].toLowerCase();
|
|
1561
|
+
const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
|
|
1562
|
+
const gt = closeAt < 0 ? -1 : head.indexOf('>', closeAt);
|
|
1563
|
+
const end = gt < 0 ? head.length : gt + 1;
|
|
1564
|
+
flush();
|
|
1565
|
+
out += emitChunk(head.slice(i, end), '__hd', '__hc', null);
|
|
1566
|
+
i = end;
|
|
1567
|
+
continue;
|
|
1568
|
+
}
|
|
1569
|
+
buf += head[i++];
|
|
1570
|
+
}
|
|
1571
|
+
flush();
|
|
1572
|
+
return out;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
/**
|
|
1576
|
+
* - "errors an agent can fix" - closed on a real
|
|
1577
|
+
* failure from the field. A template directive rosetack does not implement
|
|
1578
|
+
* used to reach esbuild as generated code and die THERE: the oboext port
|
|
1579
|
+
* wrote `{:else}` (the branch syntax every other template language has and
|
|
1580
|
+
* rosetack deliberately does not - `prompt.ts` says so in one line) and got
|
|
1581
|
+
* `dist/.build/comp-12.ssr.js:87: ERROR: Unexpected ":"` - a file the author
|
|
1582
|
+
* never wrote, a construct never named, a fix never suggested. An unknown
|
|
1583
|
+
* directive is now a build error at the .rose file, with the line, the
|
|
1584
|
+
* construct and the rosetack shape that replaces it.
|
|
1093
1585
|
*
|
|
1094
|
-
*
|
|
1095
|
-
* and
|
|
1096
|
-
*
|
|
1097
|
-
*
|
|
1098
|
-
*
|
|
1586
|
+
* The known set is exactly what findBlock matches: `{#if}`, `{#each}`,
|
|
1587
|
+
* `{#boundary}` and their closers. There is no `{:...}` directive at all.
|
|
1588
|
+
* The same gate catches the two shapes findBlock cannot match at all - an
|
|
1589
|
+
* `{#each}` with no `as <name>` and an opener with no closer - which used to
|
|
1590
|
+
* reach esbuild the same way (`Unexpected "#each"`, `Unexpected "#if"`).
|
|
1591
|
+
* Adversarial probing found all three in one afternoon; a template compiler
|
|
1592
|
+
* that emits broken code silently is the worst failure mode it has.
|
|
1099
1593
|
*/
|
|
1594
|
+
const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary']);
|
|
1595
|
+
function assertKnownDirectives(template: string, filePath: string): void {
|
|
1596
|
+
const rawRanges: Array<[number, number]> = [];
|
|
1597
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
1598
|
+
let raw: RegExpExecArray | null;
|
|
1599
|
+
while ((raw = RAW_OPEN.exec(template))) {
|
|
1600
|
+
const tag = raw[1].toLowerCase();
|
|
1601
|
+
const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
|
|
1602
|
+
const gt = closeAt < 0 ? -1 : template.indexOf('>', closeAt);
|
|
1603
|
+
const end = gt < 0 ? template.length : gt + 1;
|
|
1604
|
+
rawRanges.push([raw.index, end]);
|
|
1605
|
+
RAW_OPEN.lastIndex = end;
|
|
1606
|
+
}
|
|
1607
|
+
const COMMENT_RE = /<!--[\s\S]*?-->/g;
|
|
1608
|
+
let note: RegExpExecArray | null;
|
|
1609
|
+
while ((note = COMMENT_RE.exec(template))) rawRanges.push([note.index, note.index + note[0].length]);
|
|
1610
|
+
rawRanges.sort((a, b) => a[0] - b[0]);
|
|
1611
|
+
const inRaw = (idx: number): boolean => rawRanges.some(([s, e]) => idx >= s && idx < e);
|
|
1612
|
+
const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
|
|
1613
|
+
let m: RegExpExecArray | null;
|
|
1614
|
+
while ((m = DIRECTIVE_RE.exec(template))) {
|
|
1615
|
+
if (inRaw(m.index)) continue;
|
|
1616
|
+
const [, sigil, word] = m;
|
|
1617
|
+
if (sigil === '/' && KNOWN_CLOSERS.has(word)) continue;
|
|
1618
|
+
if (sigil === '/') {
|
|
1619
|
+
throw new RoseError(
|
|
1620
|
+
'E-TEMPLATE',
|
|
1621
|
+
`${filePath}: {/${word}} does not close anything`,
|
|
1622
|
+
{ file: filePath, line: lineAt(template, m), hint: 'the closers are {/if}, {/each} and {/boundary} - one per block you opened' },
|
|
1623
|
+
);
|
|
1624
|
+
}
|
|
1625
|
+
if (word === 'else') {
|
|
1626
|
+
throw new RoseError(
|
|
1627
|
+
'E-TEMPLATE',
|
|
1628
|
+
`${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
|
|
1629
|
+
{ file: filePath, line: lineAt(template, m), hint: 'nest a second {#if}: {#if cond}A{/if}{#if !cond}B{/if} - the negation of the first condition IS the else' },
|
|
1630
|
+
);
|
|
1631
|
+
}
|
|
1632
|
+
throw new RoseError(
|
|
1633
|
+
'E-TEMPLATE',
|
|
1634
|
+
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
1635
|
+
{ file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary} - and there is no {:else}: nest a second {#if} with the negated condition" },
|
|
1636
|
+
);
|
|
1637
|
+
}
|
|
1638
|
+
const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
|
|
1639
|
+
while ((m = OPENER_RE.exec(template))) {
|
|
1640
|
+
if (inRaw(m.index)) continue;
|
|
1641
|
+
const [, kind, head] = m;
|
|
1642
|
+
if (kind === 'each' && !/\bas\s+(\w+)\s*$/.test(head)) {
|
|
1643
|
+
throw new RoseError(
|
|
1644
|
+
'E-TEMPLATE',
|
|
1645
|
+
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
1646
|
+
{ file: filePath, line: lineAt(template, m), hint: 'write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)' },
|
|
1647
|
+
);
|
|
1648
|
+
}
|
|
1649
|
+
const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, 'g');
|
|
1650
|
+
const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, 'g');
|
|
1651
|
+
let depth = 1;
|
|
1652
|
+
let i = m.index + m[0].length;
|
|
1653
|
+
for (;;) {
|
|
1654
|
+
OPEN_RE.lastIndex = i;
|
|
1655
|
+
CLOSE_RE.lastIndex = i;
|
|
1656
|
+
const nextOpen = OPEN_RE.exec(template);
|
|
1657
|
+
const nextClose = CLOSE_RE.exec(template);
|
|
1658
|
+
if (!nextClose) break;
|
|
1659
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
1660
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
1661
|
+
continue;
|
|
1662
|
+
}
|
|
1663
|
+
i = nextClose.index + nextClose[0].length;
|
|
1664
|
+
if (--depth === 0) break;
|
|
1665
|
+
}
|
|
1666
|
+
if (depth !== 0) {
|
|
1667
|
+
throw new RoseError(
|
|
1668
|
+
'E-TEMPLATE',
|
|
1669
|
+
`${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
|
|
1670
|
+
{ file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` },
|
|
1671
|
+
);
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1100
1675
|
|
|
1101
1676
|
/**
|
|
1102
|
-
*
|
|
1103
|
-
*
|
|
1104
|
-
*
|
|
1105
|
-
*
|
|
1106
|
-
*
|
|
1107
|
-
* `{
|
|
1677
|
+
* A QUOTED attribute whose value carries an expression - `class="{x}"`,
|
|
1678
|
+
* `style="color:{c};"`, `href="/p{id}"` - used to be compiled as if the value
|
|
1679
|
+
* were body text: the reactive markers landed INSIDE the attribute
|
|
1680
|
+
* (`class="<!--⟦m:0⟧-->yes<!--⟦/m:0⟧-->"`), a class list no selector matches,
|
|
1681
|
+
* and no wire pass can repair it (markers inside an attribute value are not
|
|
1682
|
+
* nodes). The real CMS writes `style="background:{p.enabled ? ...};"` on
|
|
1683
|
+
* every row, so this was not exotic. The unquoted form (`class={x}`) has
|
|
1684
|
+
* always compiled correctly through attrMark(); this pass rewrites the quoted
|
|
1685
|
+
* form into a single equivalent expression - `class={('yes')}`,
|
|
1686
|
+
* `style={('background:' + (p.enabled ? …) + ';')}` - so there is ONE
|
|
1687
|
+
* attribute path in the compiler instead of two, one of them broken.
|
|
1688
|
+
*
|
|
1689
|
+
* Component tags keep their own attribute parser (a quoted value is a string
|
|
1690
|
+
* prop there, by design), and a value holding a template literal is left
|
|
1691
|
+
* alone: rewriting it would need the literal-aware scanner the value does not
|
|
1692
|
+
* have, and the old path was no better.
|
|
1108
1693
|
*/
|
|
1109
|
-
function
|
|
1110
|
-
const
|
|
1111
|
-
return
|
|
1694
|
+
function rewriteQuotedExprAttrs(template: string, comps: Map<string, unknown>): string {
|
|
1695
|
+
const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
|
|
1696
|
+
return template.replace(TAG_RE, (tag: string, name: string, attrs: string, selfClose: string) => {
|
|
1697
|
+
if (comps.has(name) || !/\{/.test(attrs)) return tag;
|
|
1698
|
+
const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole: string, attr: string, value: string) => {
|
|
1699
|
+
if (!/\{/.test(value) || value.includes('`')) return whole;
|
|
1700
|
+
const spans = templateExprSpans(value);
|
|
1701
|
+
if (spans.length === 0) return whole;
|
|
1702
|
+
let expr = '';
|
|
1703
|
+
let last = 0;
|
|
1704
|
+
for (const s of spans) {
|
|
1705
|
+
if (last < s.start) expr += (expr ? ' + ' : '') + JSON.stringify(value.slice(last, s.start));
|
|
1706
|
+
expr += (expr ? ' + ' : '') + `(${s.expr})`;
|
|
1707
|
+
last = s.end + 1;
|
|
1708
|
+
}
|
|
1709
|
+
if (last < value.length) expr += (expr ? ' + ' : '') + JSON.stringify(value.slice(last));
|
|
1710
|
+
return `${attr}={${expr}}`;
|
|
1711
|
+
});
|
|
1712
|
+
return `<${name}${rewritten}${selfClose ? ' /' : ''}>`;
|
|
1713
|
+
});
|
|
1112
1714
|
}
|
|
1113
1715
|
|
|
1114
1716
|
function compileTemplate(
|
|
@@ -1127,10 +1729,13 @@ function compileTemplate(
|
|
|
1127
1729
|
const nextId = () => `${depth}_${blockId++}`;
|
|
1128
1730
|
|
|
1129
1731
|
while (remaining.length > 0) {
|
|
1130
|
-
const ifMatch = remaining
|
|
1131
|
-
const eachMatch = remaining
|
|
1132
|
-
const boundaryMatch = remaining
|
|
1133
|
-
const
|
|
1732
|
+
const ifMatch = findBlock(remaining, 'if');
|
|
1733
|
+
const eachMatch = findBlock(remaining, 'each');
|
|
1734
|
+
const boundaryMatch = findBlock(remaining, 'boundary');
|
|
1735
|
+
const firstExpr = templateExprSpans(remaining)[0];
|
|
1736
|
+
const exprMatch = firstExpr
|
|
1737
|
+
? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) as unknown as RegExpExecArray
|
|
1738
|
+
: null;
|
|
1134
1739
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
1135
1740
|
|
|
1136
1741
|
const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
|
|
@@ -1143,6 +1748,27 @@ function compileTemplate(
|
|
|
1143
1748
|
? candidates.reduce((a, b) => (a.index <= b.index ? a : b))
|
|
1144
1749
|
: null;
|
|
1145
1750
|
|
|
1751
|
+
const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
|
|
1752
|
+
const rawHit = rawOpenRe.exec(remaining);
|
|
1753
|
+
if (rawHit && earliest && rawHit.index < earliest.index) {
|
|
1754
|
+
const tag = rawHit[1].toLowerCase();
|
|
1755
|
+
const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
|
|
1756
|
+
const gt = closeAt < 0 ? -1 : remaining.indexOf('>', closeAt);
|
|
1757
|
+
const end = gt < 0 ? remaining.length : gt + 1;
|
|
1758
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
1759
|
+
remaining = remaining.substring(end);
|
|
1760
|
+
continue;
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
const noteAt = remaining.indexOf('<!--');
|
|
1764
|
+
if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
|
|
1765
|
+
const noteEnd = remaining.indexOf('-->', noteAt + 4);
|
|
1766
|
+
const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
|
|
1767
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
1768
|
+
remaining = remaining.substring(end);
|
|
1769
|
+
continue;
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1146
1772
|
if (!earliest) {
|
|
1147
1773
|
result += emitChunk(remaining, acc, closes, scope);
|
|
1148
1774
|
break;
|
|
@@ -1155,14 +1781,9 @@ function compileTemplate(
|
|
|
1155
1781
|
const call = autoCall(cond);
|
|
1156
1782
|
const id = nextId();
|
|
1157
1783
|
const innerScope = scope ?? '__s';
|
|
1158
|
-
// Inner markers live in the block's OWN closes array, so wiring an
|
|
1159
|
-
// adopted/cloned block never re-touches the parent's markers.
|
|
1160
1784
|
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers, comps);
|
|
1161
1785
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
|
|
1162
1786
|
if (markers) {
|
|
1163
|
-
// The content renders the FIRST time the block shows, never before - see the
|
|
1164
|
-
// runtime's ifMark for why the eager version crashed `{#if
|
|
1165
|
-
// user()}{user().name}{/if}`.
|
|
1166
1787
|
result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ''});\n`;
|
|
1167
1788
|
} else {
|
|
1168
1789
|
result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
|
|
@@ -1174,10 +1795,14 @@ function compileTemplate(
|
|
|
1174
1795
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1175
1796
|
const call = autoCall(items);
|
|
1176
1797
|
const id = nextId();
|
|
1177
|
-
// Rename the item variable to the block's scope parameter - INSIDE EXPRESSIONS ONLY.
|
|
1178
1798
|
const itemRe = new RegExp(`\\b${item}\\b`, 'g');
|
|
1179
|
-
|
|
1180
|
-
|
|
1799
|
+
let scoped = '';
|
|
1800
|
+
let lastSpan = 0;
|
|
1801
|
+
for (const s of templateExprSpans(content.trim())) {
|
|
1802
|
+
scoped += content.trim().slice(lastSpan, s.start) + '{' + s.expr.replace(itemRe, '__s') + '}';
|
|
1803
|
+
lastSpan = s.end + 1;
|
|
1804
|
+
}
|
|
1805
|
+
scoped += content.trim().slice(lastSpan);
|
|
1181
1806
|
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, markers, comps);
|
|
1182
1807
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
|
|
1183
1808
|
if (markers) {
|
|
@@ -1191,8 +1816,6 @@ function compileTemplate(
|
|
|
1191
1816
|
const before = remaining.substring(0, earliest.index);
|
|
1192
1817
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1193
1818
|
const id = nextId();
|
|
1194
|
-
// Error boundary: the content renders into its OWN string and is only appended on
|
|
1195
|
-
// success - a throw anywhere inside swaps in the fallback …
|
|
1196
1819
|
const catchesAction = /\$action:|<form[\s>]/.test(content);
|
|
1197
1820
|
const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers, comps);
|
|
1198
1821
|
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
|
|
@@ -1203,7 +1826,6 @@ function compileTemplate(
|
|
|
1203
1826
|
result += `${acc} += __bd${id};\n`;
|
|
1204
1827
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1205
1828
|
} else if (earliest.type === 'comp') {
|
|
1206
|
-
// <Card prop={x}>...</Card> -> Card(closes, children, props, slots).
|
|
1207
1829
|
const tag = earliest.tag!;
|
|
1208
1830
|
if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
|
|
1209
1831
|
const entry = comps.get(tag.name)!;
|
|
@@ -1214,40 +1836,38 @@ function compileTemplate(
|
|
|
1214
1836
|
rest = remaining.substring(tag.end);
|
|
1215
1837
|
} else {
|
|
1216
1838
|
const closeIdx = findClose(remaining, tag.end, tag.name);
|
|
1217
|
-
if (closeIdx < 0) throw new
|
|
1839
|
+
if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${tag.name}> - every component tag needs its matching close tag`, { hint: `add the matching </${tag.name}> (or close the tag with /> when it takes no children)` });
|
|
1218
1840
|
childrenSrc = remaining.substring(tag.end, closeIdx);
|
|
1219
1841
|
rest = remaining.substring(closeIdx + tag.name.length + 3);
|
|
1220
1842
|
}
|
|
1221
1843
|
const { def, named } = splitSlots(childrenSrc);
|
|
1222
|
-
// Default children render at CALL time with the enclosing scope (inside an {#each}
|
|
1223
|
-
// that scope is the item), exactly like a layout's children.
|
|
1224
1844
|
const hasChildren = def.trim().length > 0;
|
|
1225
1845
|
if (hasChildren) {
|
|
1226
1846
|
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1, markers, comps)} return h; };\n`;
|
|
1227
1847
|
}
|
|
1228
|
-
// Named slots are functions of the object the child passes in AND of a marker array
|
|
1229
|
-
// of their own: their content is a block scoped to that object (see SLOT_HELPER) …
|
|
1230
1848
|
const slotFns = named.map(([nm, src]) => {
|
|
1231
1849
|
const decl = entry.slots.find((s) => s.name === nm);
|
|
1232
1850
|
let content = src;
|
|
1233
1851
|
for (const p of decl?.props ?? []) {
|
|
1234
|
-
|
|
1235
|
-
|
|
1852
|
+
const pRe = new RegExp(`\\b${p}\\b`, 'g');
|
|
1853
|
+
let out = '';
|
|
1854
|
+
let lastSpan = 0;
|
|
1855
|
+
for (const s of templateExprSpans(content)) {
|
|
1856
|
+
out += content.slice(lastSpan, s.start) + '{' + s.expr.replace(pRe, `__s.${p}`) + '}';
|
|
1857
|
+
lastSpan = s.end + 1;
|
|
1858
|
+
}
|
|
1859
|
+
content = out + content.slice(lastSpan);
|
|
1236
1860
|
}
|
|
1237
1861
|
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1, markers, comps)} return h; }`;
|
|
1238
1862
|
});
|
|
1239
1863
|
const propsObj = parseCompAttrs(tag.attrs)
|
|
1240
1864
|
.filter((a) => a.name !== 'slot')
|
|
1241
1865
|
.map((a) => {
|
|
1242
|
-
// on:click={fn} is an event outward: the child receives it as the `onClick` prop
|
|
1243
|
-
// and calls it - no extra machinery, a prop is a function like any other value.
|
|
1244
1866
|
const key = a.name.startsWith('on:') ? `on${capitalize(a.name.slice(3))}` : a.name;
|
|
1245
1867
|
const val = a.kind === 'expr' ? `(${a.value})` : a.kind === 'str' ? JSON.stringify(a.value) : 'true';
|
|
1246
1868
|
return `${JSON.stringify(key)}: ${val}`;
|
|
1247
1869
|
})
|
|
1248
1870
|
.join(', ');
|
|
1249
|
-
// The imported binding IS the child's render function (a default `import Card from
|
|
1250
|
-
// '...rose'` compiles to `import { render as Card }`), so the call is direct …
|
|
1251
1871
|
const childrenArg = hasChildren ? `__ch${id}(${scope ?? 'undefined'}, ${closes})` : `''`;
|
|
1252
1872
|
result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(', ')} });\n`;
|
|
1253
1873
|
remaining = rest;
|
|
@@ -1261,18 +1881,26 @@ function compileTemplate(
|
|
|
1261
1881
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1262
1882
|
continue;
|
|
1263
1883
|
}
|
|
1264
|
-
// <slot name="x" item={post}> -> the child's named slot, rendered from the parent's
|
|
1265
|
-
// content with the object the child passes in.
|
|
1266
1884
|
const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
|
|
1267
1885
|
if (slotCall) {
|
|
1268
1886
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1269
|
-
// The slot renders markup, so it is concatenated raw - esc() would turn the
|
|
1270
|
-
// parent's own elements into text.
|
|
1271
1887
|
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);\n`;
|
|
1272
1888
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1273
1889
|
continue;
|
|
1274
1890
|
}
|
|
1275
|
-
|
|
1891
|
+
const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
|
|
1892
|
+
if (rawMatch) {
|
|
1893
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1894
|
+
const expr = rawMatch[1].trim();
|
|
1895
|
+
if (!markers) {
|
|
1896
|
+
result += `${acc} += String(${expr} ?? '');\n`;
|
|
1897
|
+
} else {
|
|
1898
|
+
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
1899
|
+
result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ''});\n`;
|
|
1900
|
+
}
|
|
1901
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1902
|
+
continue;
|
|
1903
|
+
}
|
|
1276
1904
|
const attrMatch = before.match(/([\w-]+)=\s*$/);
|
|
1277
1905
|
if (attrMatch) {
|
|
1278
1906
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
@@ -1280,8 +1908,6 @@ function compileTemplate(
|
|
|
1280
1908
|
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
|
|
1281
1909
|
} else {
|
|
1282
1910
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1283
|
-
// A marker whose value is followed by LITERAL TEXT needs an end marker: the wire
|
|
1284
|
-
// patches the text node after the start marker …
|
|
1285
1911
|
const after = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1286
1912
|
const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith('{');
|
|
1287
1913
|
result += emitText(trimmed, acc, closes, scope, markers, pair);
|
|
@@ -1305,11 +1931,7 @@ interface CompTag {
|
|
|
1305
1931
|
selfClosing: boolean;
|
|
1306
1932
|
}
|
|
1307
1933
|
|
|
1308
|
-
|
|
1309
|
-
* Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside
|
|
1310
|
-
* an attribute expression (`title={a > b}`) does not end the tag. Returns the
|
|
1311
|
-
* index just past `>`, or -1 when the tag is never closed.
|
|
1312
|
-
*/
|
|
1934
|
+
// Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside an attribute expression (`title={a > b}`) does not end the tag.
|
|
1313
1935
|
function scanTagEnd(src: string, start: number): number {
|
|
1314
1936
|
let j = start + 1;
|
|
1315
1937
|
let quote = '';
|
|
@@ -1418,7 +2040,7 @@ function rejectNestedSlot(src: string, outer: string): void {
|
|
|
1418
2040
|
if (end < 0) return;
|
|
1419
2041
|
const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
|
|
1420
2042
|
if (hit && nm[1] !== '/') {
|
|
1421
|
-
throw new
|
|
2043
|
+
throw new RoseError('E-TEMPLATE', `slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`, { hint: 'move the inner <slot> out of the outer one - a slot is a direct child of the component tag, never nested in another slot' });
|
|
1422
2044
|
}
|
|
1423
2045
|
i = end;
|
|
1424
2046
|
}
|
|
@@ -1480,7 +2102,7 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
|
|
|
1480
2102
|
if (!selfClosing && !isVoid) elemDepth++;
|
|
1481
2103
|
const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
|
|
1482
2104
|
if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
|
|
1483
|
-
throw new
|
|
2105
|
+
throw new RoseError('E-TEMPLATE', `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
|
|
1484
2106
|
}
|
|
1485
2107
|
if (slotName) {
|
|
1486
2108
|
const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '');
|
|
@@ -1488,11 +2110,9 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
|
|
|
1488
2110
|
named.set(slotName, (named.get(slotName) ?? '') + stripped);
|
|
1489
2111
|
} else {
|
|
1490
2112
|
const closeIdx = findClose(src, end, nm[2]);
|
|
1491
|
-
if (closeIdx < 0) throw new
|
|
2113
|
+
if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
|
|
1492
2114
|
const tail = `</${nm[2]}>`;
|
|
1493
2115
|
const inner = src.slice(end, closeIdx);
|
|
1494
|
-
// The same rule one level down: a slot= INSIDE a named slot's
|
|
1495
|
-
// content is nested too, and the child would silently never call it.
|
|
1496
2116
|
rejectNestedSlot(inner, slotName);
|
|
1497
2117
|
named.set(slotName, (named.get(slotName) ?? '') + stripped + inner + tail);
|
|
1498
2118
|
elemDepth = Math.max(0, elemDepth - 1);
|
|
@@ -1514,9 +2134,6 @@ function emitChunk(text: string, acc: string, closes: string, scope: string | nu
|
|
|
1514
2134
|
return `${acc} += ${JSON.stringify(text)};\n`;
|
|
1515
2135
|
}
|
|
1516
2136
|
|
|
1517
|
-
// --- Build-time image inlining ------------------------------------------- One fewer
|
|
1518
|
-
// request per small local image: <img src="/logo.svg"> ships as a data URI inside the …
|
|
1519
|
-
|
|
1520
2137
|
const IMG_RE = /<img\b(?:[^<>]|\{[^{}]*\})*>/g;
|
|
1521
2138
|
const IMG_MIME: Record<string, string> = {
|
|
1522
2139
|
'.png': 'image/png',
|
|
@@ -1527,13 +2144,12 @@ const IMG_MIME: Record<string, string> = {
|
|
|
1527
2144
|
'.svg': 'image/svg+xml',
|
|
1528
2145
|
'.ico': 'image/x-icon',
|
|
1529
2146
|
};
|
|
1530
|
-
// Trade-off: fixed 4 KB cap; make it configurable when a real app cares
|
|
1531
2147
|
const INLINE_IMG_MAX = 4096;
|
|
1532
2148
|
|
|
1533
2149
|
function inlineImages(template: string, publicDir: string): string {
|
|
1534
2150
|
return template.replace(IMG_RE, (tag) => {
|
|
1535
|
-
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
1536
|
-
if (!src) return tag;
|
|
2151
|
+
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
2152
|
+
if (!src) return tag;
|
|
1537
2153
|
const ext = path.extname(src[1]).toLowerCase();
|
|
1538
2154
|
const mime = IMG_MIME[ext];
|
|
1539
2155
|
if (!mime) return tag;
|
|
@@ -1541,10 +2157,9 @@ function inlineImages(template: string, publicDir: string): string {
|
|
|
1541
2157
|
try {
|
|
1542
2158
|
file = fs.readFileSync(path.join(publicDir, src[1]));
|
|
1543
2159
|
} catch {
|
|
1544
|
-
return tag;
|
|
2160
|
+
return tag;
|
|
1545
2161
|
}
|
|
1546
2162
|
if (file.length > INLINE_IMG_MAX) return tag;
|
|
1547
|
-
// SVG inlines as text (percent-encoded for #, ", %); binaries as base64
|
|
1548
2163
|
const uri = ext === '.svg'
|
|
1549
2164
|
? `data:image/svg+xml,${file.toString('utf-8').replace(/%/g, '%25').replace(/#/g, '%23').replace(/\{/g, '%7B').replace(/\}/g, '%7D').replace(/"/g, '%22')}`
|
|
1550
2165
|
: `data:${mime};base64,${file.toString('base64')}`;
|
|
@@ -1560,7 +2175,6 @@ function inlineImages(template: string, publicDir: string): string {
|
|
|
1560
2175
|
*/
|
|
1561
2176
|
function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true, pair = false): string {
|
|
1562
2177
|
if (!markers) {
|
|
1563
|
-
// head block: inline escaped value, no marker comment (clean SSR html)
|
|
1564
2178
|
return `${acc} += esc(${expr});\n`;
|
|
1565
2179
|
}
|
|
1566
2180
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
@@ -1587,9 +2201,14 @@ function compileSlot(acc: string): string {
|
|
|
1587
2201
|
return `${acc} += String(children);\n`;
|
|
1588
2202
|
}
|
|
1589
2203
|
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
const
|
|
2204
|
+
const RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
|
|
2205
|
+
|
|
2206
|
+
const API_RUNTIME_HELPERS = RUNTIME_IMPORTS
|
|
2207
|
+
.replace(/^import\s*\{/, '')
|
|
2208
|
+
.replace(/\}\s*from[\s\S]*$/, '')
|
|
2209
|
+
.split(',')
|
|
2210
|
+
.map((s) => s.trim())
|
|
2211
|
+
.filter(Boolean);
|
|
1593
2212
|
|
|
1594
2213
|
/**
|
|
1595
2214
|
* `export let title = 'x'` -> a per-invocation const read from the
|
|
@@ -1604,8 +2223,6 @@ function propsCode(props: Array<{ name: string; def: string | null }>): string {
|
|
|
1604
2223
|
.join('\n');
|
|
1605
2224
|
}
|
|
1606
2225
|
|
|
1607
|
-
// The named-slot helpers, identical in both bundles . __slot resolves the parent's slot
|
|
1608
|
-
// function and builds the object its <slot name item={...}> declared …
|
|
1609
2226
|
const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
1610
2227
|
const fn = sl[name];
|
|
1611
2228
|
if (typeof fn !== 'function') return null;
|
|
@@ -1613,27 +2230,16 @@ const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
1613
2230
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
1614
2231
|
return { o, fn };
|
|
1615
2232
|
};
|
|
1616
|
-
const __slotBlock = (closes, sl, name, pairs) =>
|
|
1617
|
-
const hit = __slot(sl, name, pairs);
|
|
1618
|
-
const idx = closes.length;
|
|
1619
|
-
closes.push(() => {
|
|
1620
|
-
if (!hit) return null;
|
|
1621
|
-
const c = [];
|
|
1622
|
-
return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
|
|
1623
|
-
});
|
|
1624
|
-
return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
|
|
1625
|
-
};`;
|
|
2233
|
+
const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
|
|
1626
2234
|
|
|
1627
|
-
function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = '', props: Array<{ name: string; def: string | null }> = [], namedSlots = false, imports = '', isComponent = false, guard = ''): string {
|
|
1628
|
-
// The head block renders to a clean html string (no markers) and is wrapped in an h
|
|
1629
|
-
// marker pair: renderPage extracts it for <head> injection …
|
|
2235
|
+
function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = '', props: Array<{ name: string; def: string | null }> = [], namedSlots = false, imports = '', isComponent = false, guard = '', hasActions = false, dataDeclsCode = ''): string {
|
|
1630
2236
|
const headCode = headFn
|
|
1631
2237
|
? `
|
|
1632
2238
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
1633
2239
|
__html += headMark(closes, __head);`
|
|
1634
2240
|
: '';
|
|
1635
|
-
|
|
1636
|
-
|
|
2241
|
+
const actionState = hasActions ? `
|
|
2242
|
+
const $setState = (key, value) => setState(key, value);` : '';
|
|
1637
2243
|
return `
|
|
1638
2244
|
${RUNTIME_IMPORTS}
|
|
1639
2245
|
|
|
@@ -1641,6 +2247,7 @@ ${imports}
|
|
|
1641
2247
|
|
|
1642
2248
|
${exports}
|
|
1643
2249
|
${guard}
|
|
2250
|
+
${actionState}
|
|
1644
2251
|
|
|
1645
2252
|
${namedSlots ? SLOT_HELPER : ''}
|
|
1646
2253
|
|
|
@@ -1648,12 +2255,11 @@ export ${isComponent ? 'function' : 'async function'} render(closes, children, _
|
|
|
1648
2255
|
${props.length > 0 ? 'const __p = __props || {};' : ''}
|
|
1649
2256
|
${namedSlots ? 'const __sl = __slots || {};' : ''}
|
|
1650
2257
|
${propsCode(props)}
|
|
2258
|
+
${script}
|
|
1651
2259
|
${stateDeclsCode}
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
// every path that is not a server action's re-render - see the runtime).
|
|
2260
|
+
${dataDeclsCode}
|
|
2261
|
+
|
|
1655
2262
|
${isComponent ? '' : 'applyStateDeltas();'}
|
|
1656
|
-
${script}
|
|
1657
2263
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1658
2264
|
let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
|
|
1659
2265
|
return __html;
|
|
@@ -1671,13 +2277,15 @@ function generateClient(
|
|
|
1671
2277
|
props: Array<{ name: string; def: string | null }> = [],
|
|
1672
2278
|
namedSlots = false,
|
|
1673
2279
|
imports = '',
|
|
1674
|
-
isComponent = false
|
|
2280
|
+
isComponent = false,
|
|
2281
|
+
dataDeclsCode = ''
|
|
1675
2282
|
): string {
|
|
1676
|
-
// Handlers live on a shared global (the runtime's `handlers` registry) so one delegated
|
|
1677
|
-
// listener per event type can dispatch for any component, including freshly cloned nodes.
|
|
1678
2283
|
const handlerRegistry = eventBindings.length > 0
|
|
1679
2284
|
? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
|
|
1680
2285
|
: '';
|
|
2286
|
+
const clientSetState = eventBindings.length > 0
|
|
2287
|
+
? `const $setState = (key, value) => setState(key, value);`
|
|
2288
|
+
: '';
|
|
1681
2289
|
const headCode = headFn
|
|
1682
2290
|
? `
|
|
1683
2291
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
@@ -1690,15 +2298,16 @@ ${RUNTIME_IMPORTS}
|
|
|
1690
2298
|
${imports}
|
|
1691
2299
|
|
|
1692
2300
|
${exports}
|
|
1693
|
-
|
|
2301
|
+
${clientSetState ? `\n${clientSetState}\n` : ''}
|
|
1694
2302
|
${namedSlots ? SLOT_HELPER : ''}
|
|
1695
2303
|
|
|
1696
2304
|
export ${isComponent ? 'function' : 'async function'} render(closes, children, __props, __slots) {
|
|
1697
2305
|
${props.length > 0 ? 'const __p = __props || {};' : ''}
|
|
1698
2306
|
${namedSlots ? 'const __sl = __slots || {};' : ''}
|
|
1699
2307
|
${propsCode(props)}
|
|
1700
|
-
${stateDeclsCode}
|
|
1701
2308
|
${script}
|
|
2309
|
+
${stateDeclsCode}
|
|
2310
|
+
${dataDeclsCode}
|
|
1702
2311
|
${handlerRegistry}
|
|
1703
2312
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1704
2313
|
let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
|
|
@@ -1714,7 +2323,7 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
|
|
|
1714
2323
|
infos
|
|
1715
2324
|
.map((li, i) => ({ li, i }))
|
|
1716
2325
|
.filter(({ li }) => li.isLayout && isAncestorDir(li.filePath, infos[idx].filePath))
|
|
1717
|
-
.sort((a, b) => b.li.filePath.length - a.li.filePath.length)
|
|
2326
|
+
.sort((a, b) => b.li.filePath.length - a.li.filePath.length)
|
|
1718
2327
|
.map(({ i }) => i);
|
|
1719
2328
|
|
|
1720
2329
|
/**
|
|
@@ -1725,11 +2334,12 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
|
|
|
1725
2334
|
const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number): boolean => {
|
|
1726
2335
|
if (compiled[i].csr === true) return false;
|
|
1727
2336
|
if (compiled[i].needsClient) return false;
|
|
1728
|
-
// a layout needing the client bundles every document under it: its
|
|
1729
|
-
// handlers would be dead code in a runtime-less document
|
|
1730
2337
|
return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
|
|
1731
2338
|
};
|
|
1732
2339
|
|
|
2340
|
+
const routeShellOff = (infos: RouteInfo[], compiled: CompileResult[], i: number): boolean =>
|
|
2341
|
+
compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
|
|
2342
|
+
|
|
1733
2343
|
/**
|
|
1734
2344
|
* The build's zero-JS lint report: one line per route with
|
|
1735
2345
|
* its verdict and the exact reason - which component in the chain needs the
|
|
@@ -1753,11 +2363,72 @@ export function buildReport(infos: RouteInfo[], compiled: CompileResult[]): stri
|
|
|
1753
2363
|
});
|
|
1754
2364
|
}
|
|
1755
2365
|
|
|
2366
|
+
/**
|
|
2367
|
+
* The mount entry - the migration door. A foreign
|
|
2368
|
+
* page (the legacy half of a micro-frontend, or an old app adopting rosetack
|
|
2369
|
+
* one route at a time) marks containers and includes this one file:
|
|
2370
|
+
*
|
|
2371
|
+
* <div data-rosetack="/checkout"></div>
|
|
2372
|
+
* <script type="module" src="/mount.js"></script>
|
|
2373
|
+
*
|
|
2374
|
+
* Each container fetches its route's own document - the same one-request,
|
|
2375
|
+
* zero-hydration shape a standalone page gets - adopts the server's DOM in
|
|
2376
|
+
* place, and navigates inside itself: the host page keeps its URL, its
|
|
2377
|
+
* history, its <head> and every node outside the container. It imports the
|
|
2378
|
+
* same /client.js the documents use (mode B's entry, or the inline build's
|
|
2379
|
+
* bundle), so there is no second runtime and no hydration.
|
|
2380
|
+
*
|
|
2381
|
+
* Written verbatim, not minified: it ships once per app (not once per
|
|
2382
|
+
* document) and the servers compress it like any other asset. The cost to a
|
|
2383
|
+
* normal rosetack document is zero bytes - nothing references it unless the
|
|
2384
|
+
* host page does.
|
|
2385
|
+
*/
|
|
2386
|
+
const MOUNT_ENTRY = `
|
|
2387
|
+
import { start, postForm } from '/client.js';
|
|
2388
|
+
|
|
2389
|
+
for (const el of document.querySelectorAll('[data-rosetack]')) {
|
|
2390
|
+
const route = el.getAttribute('data-rosetack');
|
|
2391
|
+
const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
|
|
2392
|
+
const parsed = new DOMParser().parseFromString(doc, 'text/html');
|
|
2393
|
+
// A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
|
|
2394
|
+
const app = parsed.getElementById('app');
|
|
2395
|
+
if (app) {
|
|
2396
|
+
el.innerHTML = app.innerHTML;
|
|
2397
|
+
} else {
|
|
2398
|
+
for (const node of Array.from(parsed.body.children)) {
|
|
2399
|
+
if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
// start() resumes from #__rosetack_state (zero hydration), so the state
|
|
2403
|
+
|
|
2404
|
+
const state = parsed.getElementById('__rosetack_state');
|
|
2405
|
+
if (state) el.appendChild(state);
|
|
2406
|
+
|
|
2407
|
+
const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
|
|
2408
|
+
await start(el, route, rendered === route);
|
|
2409
|
+
if (state) state.remove();
|
|
2410
|
+
|
|
2411
|
+
el.addEventListener('click', (e) => {
|
|
2412
|
+
const a = e.target.closest && e.target.closest('a[href^="/"]');
|
|
2413
|
+
if (!a || !el.contains(a)) return;
|
|
2414
|
+
e.preventDefault();
|
|
2415
|
+
el.setAttribute('data-rosetack', a.getAttribute('href'));
|
|
2416
|
+
start(el, a.getAttribute('href'), false);
|
|
2417
|
+
});
|
|
2418
|
+
// Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
|
|
2419
|
+
el.addEventListener('submit', (e) => {
|
|
2420
|
+
const f = e.target;
|
|
2421
|
+
if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
|
|
2422
|
+
if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
|
|
2423
|
+
e.preventDefault();
|
|
2424
|
+
postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
|
|
2425
|
+
});
|
|
2426
|
+
}
|
|
2427
|
+
`;
|
|
2428
|
+
|
|
1756
2429
|
export async function buildProject(root: string, outDir: string): Promise<{ routes: RouteInfo[]; bundle: string }> {
|
|
1757
2430
|
await fs.promises.mkdir(outDir, { recursive: true });
|
|
1758
2431
|
|
|
1759
|
-
// stale intermediates from an older build layout must not survive into the
|
|
1760
|
-
// deploy dir (they used to live directly in outDir)
|
|
1761
2432
|
const stale = (await fs.promises.readdir(outDir)).filter((f) =>
|
|
1762
2433
|
/^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
1763
2434
|
await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
|
|
@@ -1765,23 +2436,20 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
1765
2436
|
const pageFiles = await scanRoseFiles(root);
|
|
1766
2437
|
const compFiles = await scanComponentFiles(root);
|
|
1767
2438
|
const files = [...pageFiles, ...compFiles];
|
|
1768
|
-
// A build that silently produces nothing is the worst possible failure mode (an empty
|
|
1769
|
-
// dist/ deploys as a blank site).
|
|
1770
2439
|
if (pageFiles.length === 0) {
|
|
1771
|
-
throw new
|
|
2440
|
+
throw new RoseError(
|
|
2441
|
+
'E-ROUTE',
|
|
2442
|
+
`no .rose pages found under ${path.join(root, 'src', 'pages')} - run rosetack from a project root, or pass one: rosetack build <dir>`,
|
|
2443
|
+
{ file: path.join(root, 'src', 'pages'), hint: 'create src/pages/index.rose in that directory (or run the command from the project root)' },
|
|
2444
|
+
);
|
|
1772
2445
|
}
|
|
1773
2446
|
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
1774
|
-
// rosetack.config.js: the plugins and the i18n options , loaded fresh per build so the dev
|
|
1775
|
-
// server's hot rebuild picks up config edits.
|
|
1776
2447
|
const config = await loadConfig(root);
|
|
1777
2448
|
const plugins = config.plugins;
|
|
1778
|
-
// scope key: the component's path under pages/ (index, _layout, blog/[id])
|
|
1779
2449
|
const scopeKeys = files.map((f, i) => {
|
|
1780
2450
|
const base = infos[i].isComponent ? path.join(root, 'src') : path.join(root, 'src', 'pages');
|
|
1781
2451
|
return path.relative(base, f).replace(/\\/g, '/').replace(/\.rose$/, '');
|
|
1782
2452
|
});
|
|
1783
|
-
// The build-wide import registry: absolute path -> module index, scope key, and the named
|
|
1784
|
-
// slots the component declares.
|
|
1785
2453
|
const registry: RoseRegistry = new Map(
|
|
1786
2454
|
files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
|
|
1787
2455
|
);
|
|
@@ -1789,8 +2457,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
1789
2457
|
files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
|
|
1790
2458
|
);
|
|
1791
2459
|
|
|
1792
|
-
// A component that needs the client drags every page that imports it into the client
|
|
1793
|
-
// bundle - the page renders it, so it must be able to resume it.
|
|
1794
2460
|
const importsOf = new Map<number, number[]>();
|
|
1795
2461
|
files.forEach((_, i) => {
|
|
1796
2462
|
const list: number[] = [];
|
|
@@ -1801,8 +2467,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
1801
2467
|
}
|
|
1802
2468
|
importsOf.set(i, list);
|
|
1803
2469
|
});
|
|
1804
|
-
// The walk reports WHICH dependency needs the client, so the build's lint
|
|
1805
|
-
// line names the component instead of the page.
|
|
1806
2470
|
const needyDep = (i: number, seen = new Set<number>()): string | null => {
|
|
1807
2471
|
if (compiled[i].needsClient) return path.basename(files[i]);
|
|
1808
2472
|
if (seen.has(i)) return null;
|
|
@@ -1822,8 +2486,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
1822
2486
|
}
|
|
1823
2487
|
});
|
|
1824
2488
|
|
|
1825
|
-
// Reachability: a component no page (transitively) imports ships in neither
|
|
1826
|
-
// bundle - not the server's, not the client's.
|
|
1827
2489
|
const reachable = new Set<number>();
|
|
1828
2490
|
const visit = (i: number) => {
|
|
1829
2491
|
if (reachable.has(i)) return;
|
|
@@ -1838,16 +2500,12 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
1838
2500
|
if (!infos[i].isComponent) visit(i);
|
|
1839
2501
|
});
|
|
1840
2502
|
|
|
1841
|
-
// Every component's scoped CSS in one stylesheet, inlined into the shell:
|
|
1842
|
-
// styles ship inside the document like the JS bundle - zero requests.
|
|
1843
2503
|
const styles = compiled
|
|
1844
2504
|
.map((c, i) => (reachable.has(i) ? c.style : ''))
|
|
1845
2505
|
.filter(Boolean).join('\n');
|
|
1846
2506
|
if (styles) await fs.promises.writeFile(path.join(outDir, 'styles.css'), styles);
|
|
1847
2507
|
else await fs.promises.rm(path.join(outDir, 'styles.css'), { force: true });
|
|
1848
2508
|
|
|
1849
|
-
// i18n: every JSON file in src/locales/ is a language. The dictionaries are baked into
|
|
1850
|
-
// BOTH bundles at build time …
|
|
1851
2509
|
let locales: Record<string, Record<string, string>> = {};
|
|
1852
2510
|
try {
|
|
1853
2511
|
for (const f of await fs.promises.readdir(path.join(root, 'src', 'locales'))) {
|
|
@@ -1855,13 +2513,11 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
1855
2513
|
locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, 'src', 'locales', f), 'utf-8'));
|
|
1856
2514
|
}
|
|
1857
2515
|
} catch {
|
|
1858
|
-
locales = {};
|
|
2516
|
+
locales = {};
|
|
1859
2517
|
}
|
|
1860
2518
|
const defaultLocale = locales.en ? 'en' : Object.keys(locales).sort()[0] ?? 'en';
|
|
1861
2519
|
const localesJson = JSON.stringify(locales).replace(/</g, '\\u003c');
|
|
1862
2520
|
|
|
1863
|
-
// Which dictionaries ride in the CLIENT bundle. Default: all of them, so a locale switch
|
|
1864
|
-
// stays a zero-request navigation.
|
|
1865
2521
|
const preload: string[] = config.i18n.preload ?? Object.keys(locales);
|
|
1866
2522
|
const packed = Object.keys(locales).filter((l) => !preload.includes(l));
|
|
1867
2523
|
for (const l of preload) {
|
|
@@ -1876,22 +2532,14 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
1876
2532
|
const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
|
|
1877
2533
|
const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, '\\u003c');
|
|
1878
2534
|
|
|
1879
|
-
// Intermediates (component modules, shared runtime, bundle entries) live in a build dir
|
|
1880
|
-
// that is removed before returning: both bundles are fully self-contained …
|
|
1881
2535
|
const buildDir = path.join(outDir, '.build');
|
|
1882
2536
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
1883
2537
|
await fs.promises.mkdir(buildDir, { recursive: true });
|
|
1884
2538
|
|
|
1885
|
-
// The runtime half of the plugins. A transform already ran at build time (in
|
|
1886
|
-
// compileComponent); onRequest/onResponse must run per request INSIDE the server bundle …
|
|
1887
2539
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
1888
2540
|
if (runtimePlugins.length > 0) {
|
|
1889
|
-
// Relative from .build/, so the build works from any cwd (`rosetack build <dir>` from
|
|
1890
|
-
// elsewhere).
|
|
1891
2541
|
const configRel = path.relative(buildDir, path.join(root, 'rosetack.config.js')).replace(/\\/g, '/');
|
|
1892
|
-
await fs.promises.writeFile(path.join(buildDir, 'plugins.js'),
|
|
1893
|
-
// Bundled into dist/server.js: these hooks run per request on every server
|
|
1894
|
-
// (Node, dev/preview, edge). Transform hooks already ran at build time.
|
|
2542
|
+
await fs.promises.writeFile(path.join(buildDir, 'plugins.js'), `
|
|
1895
2543
|
import config from ${JSON.stringify(configRel)};
|
|
1896
2544
|
|
|
1897
2545
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -1904,12 +2552,10 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1904
2552
|
`);
|
|
1905
2553
|
}
|
|
1906
2554
|
|
|
1907
|
-
// Shared runtime module, bundled once into client and server output. The runtime ships
|
|
1908
|
-
// WITH THE COMPILER …
|
|
1909
2555
|
const runtimeEntry = ['../runtime/index.ts', '../src/runtime/index.ts']
|
|
1910
2556
|
.map((rel) => fileURLToPath(new URL(rel, import.meta.url)))
|
|
1911
2557
|
.find((p) => fs.existsSync(p));
|
|
1912
|
-
if (!runtimeEntry) throw new
|
|
2558
|
+
if (!runtimeEntry) throw new RoseError('E-INTERNAL', 'rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler', { hint: 'the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout' });
|
|
1913
2559
|
await esbuild.build({
|
|
1914
2560
|
entryPoints: [runtimeEntry],
|
|
1915
2561
|
bundle: true,
|
|
@@ -1920,8 +2566,6 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1920
2566
|
});
|
|
1921
2567
|
|
|
1922
2568
|
for (let i = 0; i < compiled.length; i++) {
|
|
1923
|
-
// api routes compile to a handler module (no render): still an
|
|
1924
|
-
// intermediate, still removed with the rest of the build dir
|
|
1925
2569
|
const src = compiled[i].api ?? compiled[i].ssr;
|
|
1926
2570
|
await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
|
|
1927
2571
|
if (!infos[i].isApi) {
|
|
@@ -1931,15 +2575,46 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1931
2575
|
|
|
1932
2576
|
const pages = infos
|
|
1933
2577
|
.map((info, i) => ({ info, i }))
|
|
1934
|
-
.filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
|
|
2578
|
+
.filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
|
|
2579
|
+
// Specificity order, by route specificity: a literal segment
|
|
2580
|
+
// beats a param, a param beats a catch-all, and an optional catch-all
|
|
2581
|
+
// (which also matches the parent path) goes last. Without this a root
|
|
2582
|
+
// `[[...slug]]` - the shape a CMS's public site is written as - would
|
|
2583
|
+
// match EVERY pathname first and shadow every real route. The order is
|
|
2584
|
+
// stable within a class, so an app without catch-alls is unchanged.
|
|
2585
|
+
.sort((a, b) => {
|
|
2586
|
+
const rank = (pattern: string): number[] => {
|
|
2587
|
+
const segs = pattern.split('/');
|
|
2588
|
+
return [
|
|
2589
|
+
segs.filter((s) => s.startsWith('**')).length,
|
|
2590
|
+
segs.filter((s) => s.startsWith('*')).length,
|
|
2591
|
+
segs.filter((s) => s.startsWith(':')).length,
|
|
2592
|
+
];
|
|
2593
|
+
};
|
|
2594
|
+
const ra = rank(a.info.pattern);
|
|
2595
|
+
const rb = rank(b.info.pattern);
|
|
2596
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2597
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2598
|
+
});
|
|
1935
2599
|
|
|
1936
|
-
// API routes (pages/api/*.rose) dispatch handlers, never render HTML: they live in the
|
|
1937
|
-
// server bundle only and are excluded from the client route table entirely.
|
|
1938
2600
|
const apiRoutes = infos
|
|
1939
2601
|
.map((info, i) => ({ info, i }))
|
|
1940
|
-
.filter(({ info }) => info.isApi)
|
|
2602
|
+
.filter(({ info }) => info.isApi)
|
|
2603
|
+
.sort((a, b) => {
|
|
2604
|
+
const rank = (pattern: string): number[] => {
|
|
2605
|
+
const segs = pattern.split('/');
|
|
2606
|
+
return [
|
|
2607
|
+
segs.filter((s) => s.startsWith('**')).length,
|
|
2608
|
+
segs.filter((s) => s.startsWith('*')).length,
|
|
2609
|
+
segs.filter((s) => s.startsWith(':')).length,
|
|
2610
|
+
];
|
|
2611
|
+
};
|
|
2612
|
+
const ra = rank(a.info.pattern);
|
|
2613
|
+
const rb = rank(b.info.pattern);
|
|
2614
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2615
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2616
|
+
});
|
|
1941
2617
|
|
|
1942
|
-
// Compose render chains: page wrapped by its layouts (deepest first)
|
|
1943
2618
|
const compose = (idx: number): string => {
|
|
1944
2619
|
let expr = `render_${idx}`;
|
|
1945
2620
|
for (const i of layoutsOf(infos, idx)) {
|
|
@@ -1948,45 +2623,31 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1948
2623
|
return expr;
|
|
1949
2624
|
};
|
|
1950
2625
|
|
|
1951
|
-
// Mode B. `export const bundle = 'split'` (declared once, the root layout) turns every
|
|
1952
|
-
// route's client module into its own chunk: the document references /client.js externally …
|
|
1953
2626
|
const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? 'inline';
|
|
1954
2627
|
const split = bundleMode === 'split';
|
|
1955
|
-
// The chain a route's chunk graph must load: the page first, then its layouts
|
|
1956
|
-
// deepest-first - exactly compose()'s nesting order …
|
|
1957
2628
|
const chainOf = (idx: number): number[] => [idx, ...layoutsOf(infos, idx)];
|
|
1958
|
-
// Mode B's loader expression: literal dynamic imports (esbuild needs the paths statically
|
|
1959
|
-
// analyzable to emit one chunk per module) …
|
|
1960
2629
|
const loaderInner = (idx: number): string =>
|
|
1961
2630
|
`load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(', ')}])`;
|
|
1962
2631
|
const loaderOf = (idx: number): string => `{ ${loaderInner(idx)} }`;
|
|
1963
2632
|
|
|
1964
|
-
// The compiler decides zero-JS, not the developer. A route ships no client bundle - no
|
|
1965
|
-
// runtime, no state script, zero JavaScript …
|
|
1966
2633
|
const routeNoJs = (i: number): boolean => routeShipsNoJs(infos, compiled, i);
|
|
1967
2634
|
|
|
1968
2635
|
const serverImports = compiled
|
|
1969
2636
|
.map((_, i) => {
|
|
1970
|
-
if (!reachable.has(i)) return '';
|
|
2637
|
+
if (!reachable.has(i)) return '';
|
|
1971
2638
|
if (infos[i].isMiddleware) {
|
|
1972
|
-
// pages/_middleware.rose: server-only, imported as a namespace so a missing
|
|
1973
|
-
// `handle` export is simply "no middleware" (null), never a build error
|
|
1974
2639
|
return `import * as middlewareMod from './comp-${i}.ssr.js';`;
|
|
1975
2640
|
}
|
|
1976
2641
|
if (infos[i].isApi) {
|
|
1977
|
-
// api route: import its HTTP-method handlers (aliased per component)
|
|
1978
2642
|
const names = compiled[i].apiMethods ?? [];
|
|
1979
2643
|
const handlerImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
|
|
1980
2644
|
return handlerImports
|
|
1981
2645
|
? `import { ${handlerImports} } from './comp-${i}.ssr.js';`
|
|
1982
2646
|
: `import './comp-${i}.ssr.js';`;
|
|
1983
2647
|
}
|
|
1984
|
-
// a page's server actions are imported alongside its render; layouts
|
|
1985
|
-
// and the 404 page never receive POSTs, so they never need one
|
|
1986
2648
|
const isPage = !infos[i].isLayout && !infos[i].isNotFound;
|
|
1987
2649
|
const names = isPage ? compiled[i].actionNames : [];
|
|
1988
2650
|
const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
|
|
1989
|
-
// The action guard rides the same import, server-only like the actions it fronts
|
|
1990
2651
|
const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : '';
|
|
1991
2652
|
const named = [actionImports, guardImport].filter(Boolean).join(', ');
|
|
1992
2653
|
return named
|
|
@@ -1995,51 +2656,58 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1995
2656
|
})
|
|
1996
2657
|
.join('\n');
|
|
1997
2658
|
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2659
|
+
const notFoundEntries = infos
|
|
2660
|
+
.map((info, i) => ({ info, i }))
|
|
2661
|
+
.filter(({ info }) => info.isNotFound)
|
|
2662
|
+
.map(({ info, i }) => {
|
|
2663
|
+
const rel = path.relative(path.join(root, 'src', 'pages'), info.filePath).replace(/\\/g, '/');
|
|
2664
|
+
const dir = path.posix.dirname(rel);
|
|
2665
|
+
const prefix = dir === '.' ? '/' : '/' + dir;
|
|
2666
|
+
const flags = routeShellOff(infos, compiled, i) ? ', { shell: false }' : '';
|
|
2667
|
+
return { prefix, render: split ? loaderOf(i) : compose(i), flags };
|
|
2668
|
+
})
|
|
2669
|
+
.sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2670
|
+
const notFoundTable = `[\n${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join('\n')}\n]`;
|
|
2002
2671
|
|
|
2003
|
-
// pages/500.rose renders for routes whose render throws (a dead $data source, a bad
|
|
2004
|
-
// expression): the page degrades instead of crashing the response …
|
|
2005
2672
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
2006
2673
|
const errorRender = errIdx >= 0 ? (split ? loaderOf(errIdx) : compose(errIdx)) : 'null';
|
|
2007
2674
|
|
|
2008
|
-
// pages/_middleware.rose: the request interceptor (absent -> null).
|
|
2009
2675
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
2010
2676
|
|
|
2011
2677
|
const serverRoutes = pages
|
|
2012
2678
|
.map(({ info, i }) => {
|
|
2013
|
-
// actions: name -> imported fn, so a POST's __action field …
|
|
2014
2679
|
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(', ');
|
|
2015
|
-
// csr: false rides on the route so renderPage/renderPageStream can drop the state
|
|
2016
|
-
// script + bundle from the document (; the decision is the compiler's since #29).
|
|
2017
2680
|
if (compiled[i].csr === false && compiled[i].needsClient) {
|
|
2018
|
-
throw new
|
|
2681
|
+
throw new RoseError(
|
|
2682
|
+
'E-EXPORT',
|
|
2019
2683
|
`${info.filePath}: csr = false but this route needs the client bundle ` +
|
|
2020
|
-
`(${(compiled[i].clientReasons ?? ['needs the client']).join(' + ')})
|
|
2684
|
+
`(${(compiled[i].clientReasons ?? ['needs the client']).join(' + ')}).`,
|
|
2685
|
+
{ file: info.filePath, hint: 'remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above' },
|
|
2021
2686
|
);
|
|
2022
2687
|
}
|
|
2023
2688
|
if (compiled[i].csr === false) {
|
|
2024
2689
|
const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
|
|
2025
2690
|
if (needy !== undefined) {
|
|
2026
|
-
throw new
|
|
2691
|
+
throw new RoseError(
|
|
2692
|
+
'E-EXPORT',
|
|
2027
2693
|
`${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle ` +
|
|
2028
|
-
`(event wiring, onMount/onCleanup, refresh() or a server action)
|
|
2694
|
+
`(event wiring, onMount/onCleanup, refresh() or a server action).`,
|
|
2695
|
+
{ file: info.filePath, hint: 'a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only' },
|
|
2029
2696
|
);
|
|
2030
2697
|
}
|
|
2031
2698
|
}
|
|
2032
2699
|
const csrFlag = routeNoJs(i) ? ', csr: false' : '';
|
|
2033
|
-
|
|
2034
|
-
|
|
2700
|
+
const shellFlag = routeShellOff(infos, compiled, i) ? ', shell: false' : '';
|
|
2701
|
+
const bufferFlag = compiled[i].buffer ? ', buffer: true' : '';
|
|
2702
|
+
const signalFlag = compiled[i].controlSignal ? ', signal: true' : '';
|
|
2035
2703
|
const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : '';
|
|
2036
|
-
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag} }`;
|
|
2704
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
|
|
2037
2705
|
})
|
|
2038
2706
|
.join(',\n ');
|
|
2039
2707
|
|
|
2040
2708
|
const serverEntry = `
|
|
2041
2709
|
${serverImports}
|
|
2042
|
-
import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
|
|
2710
|
+
import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
|
|
2043
2711
|
${runtimePlugins.length > 0
|
|
2044
2712
|
? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
|
|
2045
2713
|
: `// no plugin declares a runtime hook, so there is no plugins
|
|
@@ -2049,12 +2717,7 @@ const __pluginHooks = [];
|
|
|
2049
2717
|
const __hasRequestHooks = false;
|
|
2050
2718
|
const __hasResponseHooks = false;`}
|
|
2051
2719
|
|
|
2052
|
-
|
|
2053
|
-
// middleware and may short-circuit the request with its own Response; onResponse
|
|
2054
|
-
// runs once the response exists and may replace it. Both are no-ops when the
|
|
2055
|
-
// project declares no runtime hooks. A throwing hook is logged and skipped -
|
|
2056
|
-
// the request continues - so a broken logging plugin can never take a site
|
|
2057
|
-
// down (a build-time transform, by contrast, fails loudly).
|
|
2720
|
+
|
|
2058
2721
|
export async function runRequestHooks(ctx) {
|
|
2059
2722
|
for (const p of __pluginHooks) {
|
|
2060
2723
|
if (!p.onRequest) continue;
|
|
@@ -2082,22 +2745,20 @@ export async function runResponseHooks(ctx, res) {
|
|
|
2082
2745
|
return out;
|
|
2083
2746
|
}
|
|
2084
2747
|
|
|
2085
|
-
|
|
2086
|
-
|
|
2748
|
+
|
|
2749
|
+
|
|
2087
2750
|
export const hasRequestHooks = __hasRequestHooks;
|
|
2088
2751
|
export const hasResponseHooks = __hasResponseHooks;
|
|
2089
2752
|
|
|
2090
|
-
//
|
|
2091
|
-
|
|
2092
|
-
|
|
2753
|
+
// P0-1: the query of the request being rendered, for $query().
|
|
2754
|
+
export function setQuery(query) {
|
|
2755
|
+
setRequestQuery(query || {});
|
|
2756
|
+
}
|
|
2757
|
+
|
|
2758
|
+
|
|
2093
2759
|
setLocales(${localesJson}, '${defaultLocale}');
|
|
2094
2760
|
|
|
2095
|
-
|
|
2096
|
-
// own process with its own dist/server.js module, so a $store write must
|
|
2097
|
-
// travel: this worker -> primary -> every other worker. process.send exists
|
|
2098
|
-
// only inside cluster workers, so a single-process runner (dev, preview,
|
|
2099
|
-
// the edge adapter) keeps the transport null and $store stays plain
|
|
2100
|
-
// per-process state - the documented boundary, not a bug.
|
|
2761
|
+
|
|
2101
2762
|
if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
2102
2763
|
setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
|
|
2103
2764
|
process.on('message', (msg) => {
|
|
@@ -2105,74 +2766,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
|
2105
2766
|
});
|
|
2106
2767
|
}
|
|
2107
2768
|
|
|
2769
|
+
// (the cross-machine seam): the cluster relay above covers ONE machine.
|
|
2770
|
+
export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
|
|
2771
|
+
setStoreTransport(send);
|
|
2772
|
+
}
|
|
2773
|
+
export function __deliverStorePatch(name: string, value: unknown): void {
|
|
2774
|
+
applyStorePatch(name, value);
|
|
2775
|
+
}
|
|
2776
|
+
|
|
2108
2777
|
export { localeList };
|
|
2109
2778
|
export const defaultLocale = '${defaultLocale}';
|
|
2110
2779
|
|
|
2111
|
-
// Route params maps, re-exported for the build's prerender step: routePath
|
|
2112
|
-
// -> the component's exported params (a static map or a function). Reading
|
|
2113
|
-
// them through the server bundle keeps the deploy dir free of component
|
|
2114
|
-
// modules - both bundles are self-contained, nothing else may ship. Only
|
|
2115
|
-
// components that actually export params appear here (a missing export
|
|
2116
|
-
// means the dynamic route renders on demand).
|
|
2780
|
+
// Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
|
|
2117
2781
|
${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join('\n')}
|
|
2118
2782
|
|
|
2119
2783
|
export const routeParams = {
|
|
2120
2784
|
${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(',\n ')}
|
|
2121
2785
|
};
|
|
2122
2786
|
|
|
2123
|
-
// Routes whose component reads the request context (getContext()), mutates a
|
|
2124
|
-
// shared store ($store), or opted into nonce-based CSP: the bag is
|
|
2125
|
-
// per-request, the store is per-process, and a nonce is per-response, so
|
|
2126
|
-
// these are dynamic - the build never bakes them and the servers never
|
|
2127
|
-
// answer them from a prerendered file. Public routes keep the static fast
|
|
2128
|
-
// path (file cache, ETag/304, streaming) untouched.
|
|
2787
|
+
// Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
|
|
2129
2788
|
export const dynamicRoutes = [
|
|
2130
|
-
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
2789
|
+
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
2131
2790
|
];
|
|
2132
2791
|
|
|
2133
|
-
// Which api routes opt into build-time baking (export const prerender = true):
|
|
2134
|
-
// routePath -> boolean. The build calls the GET handler once and writes the
|
|
2135
|
-
// body to dist/, so the Go single binary serves read-only APIs without Node.
|
|
2792
|
+
// Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
|
|
2136
2793
|
${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join('\n')}
|
|
2137
2794
|
|
|
2138
2795
|
export const apiPrerender = {
|
|
2139
2796
|
${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : 'false'}`).join(',\n ')}
|
|
2140
2797
|
};
|
|
2141
2798
|
|
|
2142
|
-
|
|
2143
|
-
// bakes these routes like any other, and the preview server serves the
|
|
2144
|
-
// baked file for up to N seconds - after which the next request is answered
|
|
2145
|
-
// STALE (instant, from disk) while a background pass re-renders and swaps
|
|
2146
|
-
// the file (ISR). Routes that read the request context are
|
|
2147
|
-
// excluded: they render per request and have no baked file to revalidate.
|
|
2148
|
-
// The dev server ignores the window (it rebuilds on change), the edge
|
|
2149
|
-
// adapter renders live (always fresh), and the Go binary serves the baked
|
|
2150
|
-
// file forever - the same static-half boundary as page POSTs.
|
|
2799
|
+
|
|
2151
2800
|
export const revalidate = [
|
|
2152
2801
|
${pages.filter(({ i }) => compiled[i].revalidate !== undefined && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(',\n ')}
|
|
2153
2802
|
];
|
|
2154
2803
|
|
|
2155
|
-
//
|
|
2156
|
-
// every render on the server (pages, POSTs, api calls alike). Returning a
|
|
2157
|
-
// Response short-circuits the whole request - a redirect, an auth wall, a
|
|
2158
|
-
// rewrite; returning nothing continues, and getContext() hands the
|
|
2159
|
-
// per-request bag to $data, server actions and api handlers. Absent -> null,
|
|
2160
|
-
// and the servers keep their static fast paths.
|
|
2804
|
+
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
2161
2805
|
export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
|
|
2162
2806
|
|
|
2163
|
-
// Routes whose DOCUMENTS ship without the client bundle (
|
|
2164
|
-
// decided by the compiler since #29): HTML + CSS only - no runtime, no
|
|
2165
|
-
// state script, zero JavaScript for whoever lands on them. The compiler
|
|
2166
|
-
// picks these automatically: a route whose whole chain needs nothing from
|
|
2167
|
-
// the client (no event wiring, no lifecycle, no action, no form) is a
|
|
2168
|
-
// content route. An exported "csr = true" forces the bundle back in; an
|
|
2169
|
-
// exported "csr = false" is the same decision, asserted. The route's render
|
|
2170
|
-
// function still rides in the client bundle, so a client-side navigation
|
|
2171
|
-
// from an interactive page paints it normally and a static deploy's SPA
|
|
2172
|
-
// fallback can render it too; only the document is JS-free.
|
|
2173
|
-
// isNoJs() lets the servers keep these routes on the buffered path: a
|
|
2174
|
-
// streamed no-JS document would carry the shell's default <title> (the
|
|
2175
|
-
// route head is applied client-side at boot, and there is no client).
|
|
2807
|
+
// Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
|
|
2176
2808
|
export const noJsRoutes = [
|
|
2177
2809
|
${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(',\n ')}
|
|
2178
2810
|
];
|
|
@@ -2181,11 +2813,12 @@ export function isNoJs(pathname) {
|
|
|
2181
2813
|
return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
2182
2814
|
}
|
|
2183
2815
|
|
|
2184
|
-
//
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2816
|
+
// P0-2 (bug report): routes that exported "buffer = true".
|
|
2817
|
+
export function isBuffered(pathname) {
|
|
2818
|
+
return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
|
|
2189
2822
|
export const routeHeaders = [
|
|
2190
2823
|
${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(',\n ')}
|
|
2191
2824
|
];
|
|
@@ -2195,14 +2828,7 @@ export function headersFor(pathname) {
|
|
|
2195
2828
|
return hit ? hit.headers : null;
|
|
2196
2829
|
}
|
|
2197
2830
|
|
|
2198
|
-
|
|
2199
|
-
// ). The servers ask this BEFORE writing a document: when it is true they
|
|
2200
|
-
// mint one random nonce per response, put it in the CSP header ('nonce-...'
|
|
2201
|
-
// plus 'strict-dynamic', so the document's own code may load more code) and
|
|
2202
|
-
// stamp the same value on the script tag. The default policy stays a hash -
|
|
2203
|
-
// cspNonceRoutes is empty for an app that never asks, so the fast path is
|
|
2204
|
-
// unchanged. The Go binary never sees this: these routes are dynamic, so it
|
|
2205
|
-
// has no baked file for them to serve.
|
|
2831
|
+
|
|
2206
2832
|
export const cspNonceRoutes = [
|
|
2207
2833
|
${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
2208
2834
|
];
|
|
@@ -2211,9 +2837,7 @@ export function cspNonce(pathname) {
|
|
|
2211
2837
|
return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
2212
2838
|
}
|
|
2213
2839
|
|
|
2214
|
-
// A Web-standard Request from whatever the host provides: the edge adapter
|
|
2215
|
-
// passes one already; the Node server passes its IncomingMessage (plus the
|
|
2216
|
-
// already-parsed FormData for POSTs, so middleware can read form fields).
|
|
2840
|
+
// A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
|
|
2217
2841
|
function toWebRequest(raw, form) {
|
|
2218
2842
|
if (raw instanceof Request) return raw;
|
|
2219
2843
|
const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
|
|
@@ -2221,13 +2845,7 @@ function toWebRequest(raw, form) {
|
|
|
2221
2845
|
return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
|
|
2222
2846
|
}
|
|
2223
2847
|
|
|
2224
|
-
|
|
2225
|
-
// its short-circuit Response, or null to continue. The servers call this
|
|
2226
|
-
// EXACTLY ONCE per request, before anything else: it resets the per-request
|
|
2227
|
-
// context bag and the middleware fills it via getContext(), which $data,
|
|
2228
|
-
// server actions and api handlers then read while rendering. rawReq: the
|
|
2229
|
-
// host's request (Node IncomingMessage or a Web-standard Request); form:
|
|
2230
|
-
// the already-parsed FormData of a POST.
|
|
2848
|
+
|
|
2231
2849
|
export async function runMiddleware(rawReq, form) {
|
|
2232
2850
|
resetRequestContext();
|
|
2233
2851
|
if (!middleware || !rawReq) return null;
|
|
@@ -2239,10 +2857,7 @@ const routes = [
|
|
|
2239
2857
|
${serverRoutes}
|
|
2240
2858
|
];
|
|
2241
2859
|
|
|
2242
|
-
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
|
|
2243
|
-
// render HTML and never reach the client bundle. The middleware ran before
|
|
2244
|
-
// this (the servers call runMiddleware() first), so handlers can read
|
|
2245
|
-
// getContext() for auth without re-running anything.
|
|
2860
|
+
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
|
|
2246
2861
|
const apiRoutes = [
|
|
2247
2862
|
${apiRoutes.map(({ info, i }) => {
|
|
2248
2863
|
const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(', ');
|
|
@@ -2250,19 +2865,40 @@ const apiRoutes = [
|
|
|
2250
2865
|
}).join(',\n ')}
|
|
2251
2866
|
];
|
|
2252
2867
|
|
|
2253
|
-
// pages
|
|
2254
|
-
|
|
2868
|
+
// Not-found pages, deepest segment first: the root 404.rose ('/') and any
|
|
2869
|
+
// pages/<seg>/_notfound.rose, each already composed with its layout chain.
|
|
2870
|
+
// notFoundFor picks the nearest one up the path - an /admin miss answers
|
|
2871
|
+
// the admin 404, a public miss the site's - and notFoundPage is the whole
|
|
2872
|
+
// answer (real 404 status, or the built-in plain 404 when the app has none).
|
|
2873
|
+
const notFoundRoutes = ${notFoundTable};
|
|
2874
|
+
const notFoundFor = (pathname) => {
|
|
2875
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
2876
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
2877
|
+
}
|
|
2878
|
+
return null;
|
|
2879
|
+
};
|
|
2880
|
+
|
|
2881
|
+
const notFoundFlags = (pathname) => {
|
|
2882
|
+
for (const [prefix, render, flags] of notFoundRoutes) {
|
|
2883
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
|
|
2884
|
+
}
|
|
2885
|
+
return null;
|
|
2886
|
+
};
|
|
2887
|
+
const notFoundPage = async (pathname) => {
|
|
2888
|
+
const nf = notFoundFor(pathname);
|
|
2889
|
+
if (nf) {
|
|
2890
|
+
const page = await renderFallback(pathname, nf);
|
|
2891
|
+
// __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
|
|
2892
|
+
return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
|
|
2893
|
+
}
|
|
2894
|
+
return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
|
|
2895
|
+
};
|
|
2896
|
+
|
|
2255
2897
|
|
|
2256
|
-
// pages/500.rose (with its layouts) or null -> built-in plain 500: a route
|
|
2257
2898
|
// whose render throws degrades to this instead of failing the response.
|
|
2258
2899
|
const errorPage = ${errorRender};
|
|
2259
2900
|
|
|
2260
|
-
|
|
2261
|
-
// of its [lang] segment (the default when there is none, or when the segment
|
|
2262
|
-
// names no dictionary: that request 404s in the default language) and the
|
|
2263
|
-
// reading direction that locale implies. The buffered render returns the same
|
|
2264
|
-
// pair; the streaming path needs it BEFORE the shell flushes, which is why
|
|
2265
|
-
// the servers ask for it by pathname.
|
|
2901
|
+
|
|
2266
2902
|
export function docAttrs(pathname) {
|
|
2267
2903
|
for (const route of routes) {
|
|
2268
2904
|
if (!matchRoute(route.pattern, pathname)) continue;
|
|
@@ -2272,7 +2908,7 @@ export function docAttrs(pathname) {
|
|
|
2272
2908
|
const lang = pathname.split('/')[langIdx];
|
|
2273
2909
|
if (isLocale(lang)) return { lang, dir: localeDir(lang) };
|
|
2274
2910
|
}
|
|
2275
|
-
break;
|
|
2911
|
+
break;
|
|
2276
2912
|
}
|
|
2277
2913
|
return { lang: defaultLocale, dir: localeDir(defaultLocale) };
|
|
2278
2914
|
}
|
|
@@ -2285,8 +2921,22 @@ async function renderFallback(pathname, render) {
|
|
|
2285
2921
|
}
|
|
2286
2922
|
|
|
2287
2923
|
export function matchRoute(pattern, pathname) {
|
|
2924
|
+
// Q0 (bug report): one canonical URL per route.
|
|
2925
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
2288
2926
|
const patternParts = pattern.split('/');
|
|
2289
2927
|
const pathParts = pathname.split('/');
|
|
2928
|
+
|
|
2929
|
+
const last = patternParts[patternParts.length - 1];
|
|
2930
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
2931
|
+
const fixed = patternParts.slice(0, -1);
|
|
2932
|
+
if (pathParts.length < fixed.length) return false;
|
|
2933
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
2934
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
2935
|
+
if (fixed[i].startsWith(':')) continue;
|
|
2936
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
2937
|
+
}
|
|
2938
|
+
return true;
|
|
2939
|
+
}
|
|
2290
2940
|
if (patternParts.length !== pathParts.length) return false;
|
|
2291
2941
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2292
2942
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -2295,13 +2945,7 @@ export function matchRoute(pattern, pathname) {
|
|
|
2295
2945
|
return true;
|
|
2296
2946
|
}
|
|
2297
2947
|
|
|
2298
|
-
// Head blocks (one per component in the route chain) are pulled out of the
|
|
2299
|
-
// page html: the shell injects them into <head>, and the client re-applies
|
|
2300
|
-
// them on navigation. Document order is page-first, so the shell's keyed
|
|
2301
|
-
// merge lets a page override its layouts. The EMPTY marker pair stays in the
|
|
2302
|
-
// body so the client's wire() still finds the block: at boot it adopts the
|
|
2303
|
-
// shell-injected elements in place (marked with the same keys, so no
|
|
2304
|
-
// duplicates) and keeps the head reactive.
|
|
2948
|
+
// Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
|
|
2305
2949
|
function extractHead(rendered) {
|
|
2306
2950
|
const head = [];
|
|
2307
2951
|
const html = rendered.replace(/<!--\u27e6h:(\\d+)\u27e7-->([\\s\\S]*?)<!--\u27e6\\/h:\\1\u27e7-->/g, (_, id, content) => {
|
|
@@ -2311,18 +2955,7 @@ function extractHead(rendered) {
|
|
|
2311
2955
|
return { html, head };
|
|
2312
2956
|
}
|
|
2313
2957
|
|
|
2314
|
-
//
|
|
2315
|
-
// selected server action runs first and returns a state patch (e.g.
|
|
2316
|
-
// { guests: [...] }); seeding those keys BEFORE the render makes state()
|
|
2317
|
-
// adopt them, so the response is the page as it looks AFTER the action -
|
|
2318
|
-
// with or without JS. A __action field picks the action by name (default
|
|
2319
|
-
// 'action', the conventional <form method="POST"> target); a click handler
|
|
2320
|
-
// bound to an action ($action('like')) sends the same field.
|
|
2321
|
-
// A route whose render throws degrades to pages/500.rose (status 500) - or
|
|
2322
|
-
// the built-in plain 500 - instead of failing the whole response.
|
|
2323
|
-
// The middleware does NOT run here: the servers run it once per request via
|
|
2324
|
-
// runMiddleware() (which also seeds the request context), so a page render
|
|
2325
|
-
// never re-runs it.
|
|
2958
|
+
// Form: the submitted FormData of a progressive-enhancement POST.
|
|
2326
2959
|
export async function renderPage(pathname, form) {
|
|
2327
2960
|
clearRequestState();
|
|
2328
2961
|
for (const route of routes) {
|
|
@@ -2330,31 +2963,21 @@ export async function renderPage(pathname, form) {
|
|
|
2330
2963
|
const patternParts = route.pattern.split('/');
|
|
2331
2964
|
const pathParts = pathname.split('/');
|
|
2332
2965
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2966
|
+
const seg = patternParts[i];
|
|
2967
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
2968
|
+
|
|
2969
|
+
|
|
2970
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2336
2971
|
}
|
|
2337
|
-
//
|
|
2338
|
-
// 404 - the URL is the contract, and rendering the page with fallback
|
|
2339
|
-
// strings would serve duplicate content under a bogus language
|
|
2972
|
+
// I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
|
|
2340
2973
|
const langIdx = patternParts.indexOf(':lang');
|
|
2341
2974
|
if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
|
|
2342
|
-
|
|
2343
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
2975
|
+
return await notFoundPage(pathname);
|
|
2344
2976
|
}
|
|
2345
|
-
|
|
2346
|
-
|
|
2977
|
+
|
|
2978
|
+
|
|
2347
2979
|
const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
|
|
2348
|
-
// The action dispatch. The page's guard (exported
|
|
2349
|
-
// beforeAction) runs FIRST and vetoes with an ActionError - the
|
|
2350
|
-
// action-level permission check. Then the selected action runs and its
|
|
2351
|
-
// return value seeds this render's state, per key, so an incremental
|
|
2352
|
-
// patch ($append and friends) grows a large list by one row instead of
|
|
2353
|
-
// re-sending the whole thing. An ActionError from either half is a
|
|
2354
|
-
// BUSINESS failure: it is seeded as the 'actionError' state, the
|
|
2355
|
-
// response carries its status, and the page renders with the failure
|
|
2356
|
-
// visible (a {#boundary} around the action's widget contains it).
|
|
2357
|
-
// Anything else is a bug and keeps going to the 500 page.
|
|
2980
|
+
// The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
|
|
2358
2981
|
let actionStatus = 0;
|
|
2359
2982
|
if (form && route.actions) {
|
|
2360
2983
|
const actionName = form.get('__action') || 'action';
|
|
@@ -2366,9 +2989,7 @@ export async function renderPage(pathname, form) {
|
|
|
2366
2989
|
if (patch && typeof patch === 'object') {
|
|
2367
2990
|
for (const key of Object.keys(patch)) {
|
|
2368
2991
|
const v = patch[key];
|
|
2369
|
-
// An incremental patch is RECORDED, not applied: the render's
|
|
2370
|
-
// own state declarations apply it, so the delta is relative to
|
|
2371
|
-
// the value the page was going to render anyway.
|
|
2992
|
+
// An incremental patch is RECORDED, not applied: the render's own state declarations apply.
|
|
2372
2993
|
if (v instanceof StateDelta) setStateDelta(key, v);
|
|
2373
2994
|
else setState(key, v);
|
|
2374
2995
|
}
|
|
@@ -2377,6 +2998,11 @@ export async function renderPage(pathname, form) {
|
|
|
2377
2998
|
if (err instanceof ActionError) {
|
|
2378
2999
|
setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
|
|
2379
3000
|
actionStatus = err.code;
|
|
3001
|
+
} else if (err && err.__rosetack === 'redirect') {
|
|
3002
|
+
|
|
3003
|
+
return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
|
|
3004
|
+
} else if (err && err.__rosetack === 'notFound') {
|
|
3005
|
+
return await notFoundPage(pathname);
|
|
2380
3006
|
} else {
|
|
2381
3007
|
throw err;
|
|
2382
3008
|
}
|
|
@@ -2387,32 +3013,27 @@ export async function renderPage(pathname, form) {
|
|
|
2387
3013
|
try {
|
|
2388
3014
|
rendered = extractHead(await route.render([], ''));
|
|
2389
3015
|
} catch (err) {
|
|
3016
|
+
// The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
|
|
3017
|
+
const signal = err && err.__rosetack;
|
|
3018
|
+
if (signal === 'redirect') {
|
|
3019
|
+
return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
|
|
3020
|
+
}
|
|
3021
|
+
if (signal === 'notFound') {
|
|
3022
|
+
return await notFoundPage(pathname);
|
|
3023
|
+
}
|
|
2390
3024
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2391
3025
|
if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
|
|
2392
3026
|
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
2393
3027
|
}
|
|
2394
3028
|
// __route tells the bootstrap which route this document was rendered for.
|
|
2395
|
-
// A static-file server may serve another route's document (SPA fallback);
|
|
2396
|
-
// the bootstrap then client-renders instead of adopting mismatched DOM.
|
|
2397
3029
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2398
|
-
//
|
|
2399
|
-
|
|
2400
|
-
// asserted csr = false) - the document ships no runtime, no state
|
|
2401
|
-
// script, zero JavaScript. Every other route keeps the bundle. The
|
|
2402
|
-
// caller passes this straight to the shell as js.
|
|
2403
|
-
// Status is the failed action's code when one failed - the page
|
|
2404
|
-
// rendered fine, so the body is the page with the failure visible, and
|
|
2405
|
-
// the status says what happened (a 403 from the guard, a 422 from a
|
|
2406
|
-
// validation action). 200 otherwise.
|
|
2407
|
-
// Lang/dir are the document's <html> attributes - the locale
|
|
2408
|
-
// this route rendered in, and its reading direction.
|
|
2409
|
-
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
|
|
3030
|
+
// Csr ( auto since #29): false when the compiler found nothing in the route's chain that needs the client (or the route asserted csr = false) .
|
|
3031
|
+
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
|
|
2410
3032
|
}
|
|
2411
3033
|
}
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
3034
|
+
|
|
3035
|
+
|
|
3036
|
+
return await notFoundPage(pathname);
|
|
2416
3037
|
}
|
|
2417
3038
|
|
|
2418
3039
|
// Would renderPageStream handle this path? (matched route = stream, anything
|
|
@@ -2420,21 +3041,20 @@ export async function renderPage(pathname, form) {
|
|
|
2420
3041
|
export function canStream(pathname) {
|
|
2421
3042
|
return routes.some((route) => {
|
|
2422
3043
|
if (!matchRoute(route.pattern, pathname)) return false;
|
|
2423
|
-
//
|
|
2424
|
-
// streamed response cannot change its status - so it takes the buffered
|
|
2425
|
-
// path (renderPage returns the real 404), never the streaming one
|
|
3044
|
+
// I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
|
|
2426
3045
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
2427
3046
|
return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
|
|
2428
3047
|
});
|
|
2429
3048
|
}
|
|
2430
3049
|
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
3050
|
+
|
|
3051
|
+
export function shellOff(pathname) {
|
|
3052
|
+
return routes.some(
|
|
3053
|
+
(route) => route.shell === false && matchRoute(route.pattern, pathname),
|
|
3054
|
+
);
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
// === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
|
|
2438
3058
|
export function isApi(pathname) {
|
|
2439
3059
|
return pathname === '/api' || pathname.startsWith('/api/');
|
|
2440
3060
|
}
|
|
@@ -2458,7 +3078,25 @@ export async function handleApi(method, pathname, request) {
|
|
|
2458
3078
|
headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
|
|
2459
3079
|
});
|
|
2460
3080
|
}
|
|
2461
|
-
|
|
3081
|
+
try {
|
|
3082
|
+
return toResponse(await fn(request));
|
|
3083
|
+
} catch (err) {
|
|
3084
|
+
|
|
3085
|
+
const signal = err && err.__rosetack;
|
|
3086
|
+
if (signal === 'redirect') {
|
|
3087
|
+
return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
|
|
3088
|
+
status: err.status ?? 307,
|
|
3089
|
+
headers: { 'content-type': 'application/json', location: err.path },
|
|
3090
|
+
});
|
|
3091
|
+
}
|
|
3092
|
+
if (signal === 'notFound') {
|
|
3093
|
+
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
3094
|
+
status: 404,
|
|
3095
|
+
headers: { 'content-type': 'application/json' },
|
|
3096
|
+
});
|
|
3097
|
+
}
|
|
3098
|
+
throw err;
|
|
3099
|
+
}
|
|
2462
3100
|
}
|
|
2463
3101
|
}
|
|
2464
3102
|
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
@@ -2467,18 +3105,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
2467
3105
|
});
|
|
2468
3106
|
}
|
|
2469
3107
|
|
|
2470
|
-
// === Streaming SSR ===
|
|
2471
|
-
// The static shell (doctype, <head>, body + container open) flushes BEFORE
|
|
2472
|
-
// the - possibly slow - render completes: the first byte leaves in
|
|
2473
|
-
// microseconds instead of after every $data resolves. The route HTML, the
|
|
2474
|
-
// state script, and the inlined bundle follow as later chunks of one chunked
|
|
2475
|
-
// response - still exactly one request.
|
|
2476
|
-
// The route's <head> tags are NOT in the streamed document: the client
|
|
2477
|
-
// applies them at boot from the body's head markers, so JS users see the
|
|
2478
|
-
// correct head immediately; no-JS consumers of streamed responses get the
|
|
2479
|
-
// static shell head (prerendered files stay complete documents).
|
|
2480
|
-
// Returns 200 (matched; a render throw degrades to the error-page body) or
|
|
2481
|
-
// 404 (unmatched - nothing written, so the caller can still buffer).
|
|
3108
|
+
// === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
|
|
2482
3109
|
export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
2483
3110
|
clearRequestState();
|
|
2484
3111
|
for (const route of routes) {
|
|
@@ -2486,9 +3113,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2486
3113
|
const patternParts = route.pattern.split('/');
|
|
2487
3114
|
const pathParts = pathname.split('/');
|
|
2488
3115
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
3116
|
+
const seg = patternParts[i];
|
|
3117
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
3118
|
+
|
|
3119
|
+
|
|
3120
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2492
3121
|
}
|
|
2493
3122
|
// i18n: an unknown locale must 404 BEFORE the shell flushes - a
|
|
2494
3123
|
// streamed response cannot change its status afterwards
|
|
@@ -2499,23 +3128,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2499
3128
|
try {
|
|
2500
3129
|
html = extractHead(await route.render([], '')).html;
|
|
2501
3130
|
} catch (err) {
|
|
2502
|
-
|
|
2503
|
-
// (the status stays 200 - a real 500 needs the buffered path, which
|
|
2504
|
-
// the server picks for routes known-broken at build time)
|
|
3131
|
+
|
|
2505
3132
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2506
3133
|
html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
|
|
2507
3134
|
}
|
|
2508
3135
|
write(html);
|
|
2509
|
-
//
|
|
2510
|
-
// ends here - no state script, no inlined bundle. (The servers keep
|
|
2511
|
-
// these routes off the streaming path so their <head> is complete;
|
|
2512
|
-
// this is the correctness floor if one streams anyway.)
|
|
3136
|
+
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
2513
3137
|
if (route.csr === false) {
|
|
2514
3138
|
write('</div>\\n</body>\\n</html>');
|
|
2515
3139
|
return 200;
|
|
2516
3140
|
}
|
|
2517
3141
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2518
|
-
|
|
3142
|
+
// P1-6 (bug report): the JSON data block is embedded in the document.
|
|
3143
|
+
const stateSafe = state.replace(/</g, '\\\\u003c');
|
|
3144
|
+
write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
|
|
2519
3145
|
return 200;
|
|
2520
3146
|
}
|
|
2521
3147
|
}
|
|
@@ -2533,8 +3159,6 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2533
3159
|
...TS_LOADER,
|
|
2534
3160
|
});
|
|
2535
3161
|
|
|
2536
|
-
// api routes and the middleware have no client module: they are server-only handlers /
|
|
2537
|
-
// interceptors.
|
|
2538
3162
|
const clientImports = split ? '' : compiled
|
|
2539
3163
|
.map((_, i) => ({ i }))
|
|
2540
3164
|
.filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i))
|
|
@@ -2547,12 +3171,12 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2547
3171
|
: `{ pattern: '${info.pattern}', render: ${compose(i)} }`))
|
|
2548
3172
|
.join(',\n ');
|
|
2549
3173
|
|
|
2550
|
-
// P1: the app-global prefetch strategy, declared once (the root layout) as `export const
|
|
2551
|
-
// prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
|
|
2552
3174
|
const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? 'all';
|
|
3175
|
+
const vitalsOn = compiled.some((c) => c.vitals === true);
|
|
3176
|
+
const vitalsBlock = vitalsOn
|
|
3177
|
+
? `\n// the app asked for web-vitals - measure once, at boot, and let the\n// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).\nreportVitals();\n`
|
|
3178
|
+
: '';
|
|
2553
3179
|
|
|
2554
|
-
// The <html lang dir> tracker only exists when the app actually has a [lang] route - an
|
|
2555
|
-
// app without i18n pays nothing for it …
|
|
2556
3180
|
const hasLang = infos.some((i) => i.pattern.includes(':lang'));
|
|
2557
3181
|
const langDirBlock = hasLang
|
|
2558
3182
|
? ` // <html lang dir> follows the route - the one part of the document
|
|
@@ -2560,51 +3184,41 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2560
3184
|
// logical properties both read it). A route with no [lang] segment
|
|
2561
3185
|
// returns to the default locale, and a bogus segment falls back to it
|
|
2562
3186
|
// too, exactly like the server's docAttrs.
|
|
3187
|
+
// Only when this container IS the document's app root. A mount
|
|
3188
|
+
// (dist/mount.js) renders into a foreign page, whose language and
|
|
3189
|
+
// direction belong to the host, not to the mounted route.
|
|
2563
3190
|
const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
|
|
2564
3191
|
const known = !seg || isLocale(seg);
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
3192
|
+
if (container === document.getElementById('app')) {
|
|
3193
|
+
const docLang = known && seg ? seg : __defLocale;
|
|
3194
|
+
document.documentElement.lang = docLang;
|
|
3195
|
+
const docDir = localeDir(docLang);
|
|
3196
|
+
if (docDir) document.documentElement.setAttribute('dir', docDir);
|
|
3197
|
+
else document.documentElement.removeAttribute('dir');
|
|
3198
|
+
}
|
|
2570
3199
|
if (!known) {`
|
|
2571
3200
|
: ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
2572
3201
|
|
|
2573
3202
|
const clientEntry = `
|
|
2574
3203
|
${clientImports}
|
|
2575
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
|
|
2576
|
-
|
|
2577
|
-
//
|
|
2578
|
-
// renders any PRELOADED locale from the bundle, so switching language costs
|
|
2579
|
-
// zero requests (the same bet as the inlined route table). a locale
|
|
2580
|
-
// the app left out of the preload (i18n.preload in rosetack.config.js) is a
|
|
2581
|
-
// pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
|
|
2582
|
-
// on first use - one request per language per session, then it renders from
|
|
2583
|
-
// memory like any other. The default build preloads everything and ships no
|
|
2584
|
-
// packs at all.
|
|
3204
|
+
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
|
|
3205
|
+
|
|
3206
|
+
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
2585
3207
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
2586
3208
|
setLocalePacks(${JSON.stringify(packed)});
|
|
2587
3209
|
${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
|
|
2588
3210
|
// follow a route that carries no [lang] segment (a non-i18n page)
|
|
2589
3211
|
const __defLocale = '${defaultLocale}';` : ''}
|
|
2590
|
-
|
|
2591
|
-
// before its visitor asks for it (ensureLocale) or to feed a dictionary
|
|
2592
|
-
// fetched itself (loadLocale). Both are already in the bundle - ensureLocale
|
|
2593
|
-
// is what applyParams calls - so the re-export costs the statement alone.
|
|
3212
|
+
${vitalsOn ? `// the app asked for web-vitals. The import is what keeps\n// reportVitals alive through minification and tree-shaking; the call is one\n// statement at boot, before the first render.\nimport { reportVitals } from './runtime.js';`: ''}
|
|
3213
|
+
// The two pack doors, re-exported for an app that wants to warm a language before its visitor asks for it (ensureLocale) or to feed a dictionary.
|
|
2594
3214
|
export { ensureLocale, loadLocale } from './runtime.js';
|
|
3215
|
+
${vitalsBlock}
|
|
2595
3216
|
|
|
2596
3217
|
const routes = [
|
|
2597
3218
|
${clientRoutes}
|
|
2598
3219
|
];
|
|
2599
3220
|
|
|
2600
|
-
// === Mode B: lazy route chunks ===
|
|
2601
|
-
// Split mode's registry entries arrive without a render function: loadChain
|
|
2602
|
-
// loads the route's module graph (the page plus its layouts, one chunk per
|
|
2603
|
-
// module, the shared runtime in its own vendor chunk) in parallel and
|
|
2604
|
-
// composes it at runtime - the exact nesting compose() built at compile
|
|
2605
|
-
// time for inline mode. getRender memoizes the composed function on the
|
|
2606
|
-
// entry, so a chunk loads once per session; inline mode's entries are the
|
|
2607
|
-
// render functions themselves, so the helper is a pass-through there.
|
|
3221
|
+
// === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
|
|
2608
3222
|
const loadChain = async (loaders) => {
|
|
2609
3223
|
const mods = await Promise.all(loaders.map((load) => load()));
|
|
2610
3224
|
let expr = (closes, children) => mods[0].render(closes, children);
|
|
@@ -2620,36 +3234,62 @@ const getRender = async (route) => {
|
|
|
2620
3234
|
return (route.render ??= (await route.load()).render);
|
|
2621
3235
|
};
|
|
2622
3236
|
|
|
2623
|
-
// pages
|
|
2624
|
-
const
|
|
3237
|
+
// Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
|
|
3238
|
+
const notFoundRoutes = ${notFoundTable};
|
|
3239
|
+
const notFoundFor = (pathname) => {
|
|
3240
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
3241
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
3242
|
+
}
|
|
3243
|
+
return null;
|
|
3244
|
+
};
|
|
2625
3245
|
|
|
2626
|
-
//
|
|
2627
|
-
// whose render throws on the client degrades to this instead of breaking
|
|
2628
|
-
// navigation.
|
|
3246
|
+
// Pages/500.rose (with its layouts) or null -> built-in plain 500: a route whose render throws on the client degrades to this instead of breaking.
|
|
2629
3247
|
const errorPage = ${errorRender};
|
|
2630
3248
|
|
|
2631
3249
|
// Paint a fallback page (404/500) into the container, wired like any render.
|
|
2632
|
-
async function paintFallback(container, page, builtin) {
|
|
2633
|
-
|
|
2634
|
-
clearRequestState();
|
|
3250
|
+
async function paintFallback(container, page, builtin, keepState = false) {
|
|
3251
|
+
if (!keepState) __navReset(container);
|
|
2635
3252
|
clearMounts(); // a failed render leaves stale mounts behind
|
|
2636
3253
|
// inline mode passes the render itself; split mode passes a loader
|
|
2637
3254
|
const render = page ? await getRender(page) : null;
|
|
2638
3255
|
if (render) {
|
|
2639
3256
|
const closes = [];
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
3257
|
+
await __withOwner(container, async () => {
|
|
3258
|
+
const html = await render(closes, '');
|
|
3259
|
+
container.innerHTML = html;
|
|
3260
|
+
wire(container, closes);
|
|
3261
|
+
bindEvents(container);
|
|
3262
|
+
flushMounts();
|
|
3263
|
+
});
|
|
2645
3264
|
return;
|
|
2646
3265
|
}
|
|
2647
3266
|
container.innerHTML = builtin;
|
|
2648
3267
|
}
|
|
2649
3268
|
|
|
3269
|
+
|
|
3270
|
+
export async function startNotFound(container, pathname) {
|
|
3271
|
+
const el = document.getElementById('__rosetack_state');
|
|
3272
|
+
if (el) resumeState(el.textContent);
|
|
3273
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
|
|
3274
|
+
}
|
|
3275
|
+
|
|
2650
3276
|
export function matchRoute(pattern, pathname) {
|
|
3277
|
+
// Q0 (bug report): one canonical URL per route.
|
|
3278
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
2651
3279
|
const patternParts = pattern.split('/');
|
|
2652
3280
|
const pathParts = pathname.split('/');
|
|
3281
|
+
|
|
3282
|
+
const last = patternParts[patternParts.length - 1];
|
|
3283
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
3284
|
+
const fixed = patternParts.slice(0, -1);
|
|
3285
|
+
if (pathParts.length < fixed.length) return false;
|
|
3286
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
3287
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
3288
|
+
if (fixed[i].startsWith(':')) continue;
|
|
3289
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
3290
|
+
}
|
|
3291
|
+
return true;
|
|
3292
|
+
}
|
|
2653
3293
|
if (patternParts.length !== pathParts.length) return false;
|
|
2654
3294
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2655
3295
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -2658,78 +3298,64 @@ export function matchRoute(pattern, pathname) {
|
|
|
2658
3298
|
return true;
|
|
2659
3299
|
}
|
|
2660
3300
|
|
|
2661
|
-
// === Link prefetch ===
|
|
2662
|
-
// Hover / focus / touch an internal link and the target route renders NOW -
|
|
2663
|
-
// $data included - against a throwaway signal map. The click that follows
|
|
2664
|
-
// paints from the cached HTML: no await, no request, no spinner. Other
|
|
2665
|
-
// frameworks prefetch data only; rosetack prefetches the whole render because
|
|
2666
|
-
// the inlined bundle already contains every route.
|
|
2667
|
-
// Trade-off: the cache holds either a result or the in-flight promise (dedupes
|
|
2668
|
-
// hover storms); one isolated render runs at a time so signal-map swapping
|
|
2669
|
-
// stays correct without any merging logic. Entries are single-use: a consumed
|
|
2670
|
-
// entry disappears from the cache, which is also how tests observe a hit.
|
|
2671
|
-
// P1, three guards for link-heavy pages:
|
|
2672
|
-
// 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
|
|
2673
|
-
// 'viewport' | 'all'" (root layout); 'all' is the original behavior.
|
|
2674
|
-
// Trade-off: app-global, not per-route - per-route would carry the mode
|
|
2675
|
-
// in each document's shell.
|
|
2676
|
-
// 2. budget - renders are serialized by the queue, so "concurrency" is 1;
|
|
2677
|
-
// the budget caps the QUEUE: a hover storm past it drops the excess
|
|
2678
|
-
// instead of rendering fifty routes nobody clicks.
|
|
2679
|
-
// 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
|
|
2680
|
-
// is evicted first (Map iteration order; entries are single-use, so
|
|
2681
|
-
// insertion order IS the recency order).
|
|
3301
|
+
// === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
|
|
2682
3302
|
let prefetchMode = ${JSON.stringify(prefetchMode)};
|
|
2683
3303
|
export function setPrefetchMode(mode) { prefetchMode = mode; }
|
|
2684
3304
|
const PREFETCH_BUDGET = 8;
|
|
2685
3305
|
const PREFETCH_MAX_CACHED = 4;
|
|
2686
|
-
const prefetchCache = new Map();
|
|
3306
|
+
const prefetchCache = new Map();
|
|
2687
3307
|
let prefetchQueue = Promise.resolve();
|
|
2688
3308
|
let prefetchPending = 0;
|
|
2689
3309
|
|
|
2690
|
-
|
|
2691
|
-
// a runtime pack (i18n.preload) is awaited HERE - the one place every client
|
|
2692
|
-
// render path goes through (navigation, prefetch, action adopt) - so a packed
|
|
2693
|
-
// locale costs one request per session and then renders from memory. A
|
|
2694
|
-
// preloaded locale (the default: every dictionary inline) resolves without
|
|
2695
|
-
// touching the network, so the common path stays synchronous in spirit.
|
|
3310
|
+
|
|
2696
3311
|
async function applyParams(route, pathname) {
|
|
2697
3312
|
const patternParts = route.pattern.split('/');
|
|
2698
3313
|
const pathParts = pathname.split('/');
|
|
2699
3314
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2700
|
-
|
|
3315
|
+
const seg = patternParts[i];
|
|
3316
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
3317
|
+
|
|
3318
|
+
|
|
3319
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2701
3320
|
}
|
|
2702
3321
|
const langIdx = patternParts.indexOf(':lang');
|
|
2703
3322
|
if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
|
|
2704
3323
|
}
|
|
2705
3324
|
|
|
3325
|
+
|
|
3326
|
+
function __netOk() {
|
|
3327
|
+
const c = navigator.connection;
|
|
3328
|
+
if (!c) return true;
|
|
3329
|
+
if (c.saveData) return false;
|
|
3330
|
+
const t = c.effectiveType;
|
|
3331
|
+
return t !== 'slow-2g' && t !== '2g';
|
|
3332
|
+
}
|
|
3333
|
+
|
|
2706
3334
|
export function prefetch(pathname, source = 'hover') {
|
|
2707
3335
|
if (prefetchMode === 'off') return;
|
|
2708
3336
|
if (prefetchMode === 'hover' && source !== 'hover') return;
|
|
2709
3337
|
if (prefetchMode === 'viewport' && source !== 'viewport') return;
|
|
3338
|
+
if (!__netOk()) return; // save-data / 2g: no bytes before the click
|
|
2710
3339
|
if (prefetchCache.has(pathname)) return;
|
|
2711
|
-
if (pathname === location.pathname) return;
|
|
3340
|
+
if (pathname === location.pathname) return;
|
|
2712
3341
|
const route = routes.find((r) => matchRoute(r.pattern, pathname));
|
|
2713
3342
|
if (!route) return;
|
|
2714
|
-
if (prefetchPending >= PREFETCH_BUDGET) return; //
|
|
3343
|
+
if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
|
|
3344
|
+
const qi = pathname.indexOf('?');
|
|
3345
|
+
const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
|
|
2715
3346
|
const p = prefetchQueue.then(async () => {
|
|
2716
3347
|
try {
|
|
2717
|
-
|
|
2718
|
-
// queued and the onCleanup disposers it registered: the paint that
|
|
2719
|
-
// consumes this entry replays the mounts after wiring and adopts the
|
|
2720
|
-
// cleanups, so the prefetched route's timers are disposed on the next
|
|
2721
|
-
// navigation like any live route's
|
|
3348
|
+
setPrefetchOverride(qOverride);
|
|
3349
|
+
// The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
|
|
2722
3350
|
const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
|
|
2723
3351
|
await applyParams(route, pathname); // a packed locale's dictionary lands before the render
|
|
2724
3352
|
const closes = [];
|
|
2725
|
-
const render = await getRender(route);
|
|
3353
|
+
const render = await getRender(route);
|
|
2726
3354
|
const html = await render(closes, '');
|
|
2727
3355
|
return { html, closes };
|
|
2728
3356
|
});
|
|
2729
3357
|
const entry = { ...result, state, mounts, cleanups };
|
|
2730
|
-
prefetchCache.set(pathname, entry); //
|
|
2731
|
-
// evict oldest-first; in-flight promises are never evicted (evicting
|
|
2732
|
-
// one would only force a duplicate render)
|
|
3358
|
+
prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
|
|
2733
3359
|
while (prefetchCache.size > PREFETCH_MAX_CACHED) {
|
|
2734
3360
|
const oldest = prefetchCache.keys().next().value;
|
|
2735
3361
|
if (prefetchCache.get(oldest) instanceof Promise) break;
|
|
@@ -2737,9 +3363,10 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
2737
3363
|
}
|
|
2738
3364
|
return entry;
|
|
2739
3365
|
} catch {
|
|
2740
|
-
prefetchCache.delete(pathname);
|
|
3366
|
+
prefetchCache.delete(pathname);
|
|
2741
3367
|
return null;
|
|
2742
3368
|
} finally {
|
|
3369
|
+
setPrefetchOverride(null);
|
|
2743
3370
|
prefetchPending--;
|
|
2744
3371
|
}
|
|
2745
3372
|
});
|
|
@@ -2749,13 +3376,10 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
2749
3376
|
}
|
|
2750
3377
|
|
|
2751
3378
|
export function prefetchStats() {
|
|
2752
|
-
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
|
|
3379
|
+
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
|
|
2753
3380
|
}
|
|
2754
3381
|
|
|
2755
|
-
// One delegated listener per event type on the app container: survives DOM
|
|
2756
|
-
// swaps and cloned blocks, so handlers never need re-binding. A handler
|
|
2757
|
-
// compiled from a server action (data-on-*="$action:name") dispatches to
|
|
2758
|
-
// $action instead of the local handler registry.
|
|
3382
|
+
// One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
|
|
2759
3383
|
const DELEGATED = ['click', 'input', 'change', 'submit'];
|
|
2760
3384
|
function bindEvents(container) {
|
|
2761
3385
|
if (container.__rosetack_bound) return;
|
|
@@ -2772,41 +3396,64 @@ function bindEvents(container) {
|
|
|
2772
3396
|
}
|
|
2773
3397
|
}
|
|
2774
3398
|
|
|
2775
|
-
// === Server actions from any event ===
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
async function postForm(body) {
|
|
2782
|
-
const res = await fetch(location.pathname, { method: 'POST', body });
|
|
3399
|
+
// === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
|
|
3400
|
+
async function postForm(body, container, pathname) {
|
|
3401
|
+
|
|
3402
|
+
const box = container || document.getElementById('app');
|
|
3403
|
+
const route = pathname || location.pathname;
|
|
3404
|
+
const res = await fetch(route, { method: 'POST', body });
|
|
2783
3405
|
const html = await res.text();
|
|
2784
3406
|
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
2785
3407
|
const next = doc.getElementById('app');
|
|
2786
3408
|
const st = doc.getElementById('__rosetack_state');
|
|
2787
3409
|
const paint = () => {
|
|
2788
|
-
|
|
2789
|
-
adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
|
|
3410
|
+
adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
|
|
2790
3411
|
};
|
|
2791
3412
|
if (document.startViewTransition) document.startViewTransition(paint);
|
|
2792
3413
|
else paint();
|
|
2793
3414
|
}
|
|
2794
3415
|
|
|
2795
|
-
// Call a page's server action by name from any event handler:
|
|
2796
|
-
// <button on:click={like}> compiles to $action('like'). Without JS the
|
|
2797
|
-
// binding is inert - the progressive-enhancement story stays with forms.
|
|
3416
|
+
// Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
|
|
2798
3417
|
export async function $action(name, e) {
|
|
2799
3418
|
if (e && e.preventDefault) e.preventDefault();
|
|
2800
3419
|
const body = new FormData();
|
|
2801
3420
|
body.append('__action', name);
|
|
2802
|
-
|
|
3421
|
+
// An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
|
|
3422
|
+
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
3423
|
+
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
2803
3424
|
}
|
|
2804
3425
|
|
|
2805
3426
|
export { postForm };
|
|
2806
3427
|
|
|
2807
|
-
//
|
|
2808
|
-
|
|
2809
|
-
|
|
3428
|
+
// The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
|
|
3429
|
+
export { serializeState };
|
|
3430
|
+
|
|
3431
|
+
// Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
|
|
3432
|
+
|
|
3433
|
+
|
|
3434
|
+
function __ownsDoc(container) {
|
|
3435
|
+
return container === document.getElementById('app');
|
|
3436
|
+
}
|
|
3437
|
+
function __navReset(container) {
|
|
3438
|
+
if (__ownsDoc(container)) {
|
|
3439
|
+
resetEffects();
|
|
3440
|
+
clearRequestState();
|
|
3441
|
+
} else {
|
|
3442
|
+
resetContainerFx(container);
|
|
3443
|
+
}
|
|
3444
|
+
}
|
|
3445
|
+
// Attribute everything a render creates (state keys, effects, onCleanups) to
|
|
3446
|
+
// its container. The document path sets no owner and keeps the global sets.
|
|
3447
|
+
async function __withOwner(container, fn) {
|
|
3448
|
+
if (__ownsDoc(container)) return fn();
|
|
3449
|
+
setFxOwner(container);
|
|
3450
|
+
try {
|
|
3451
|
+
return await fn();
|
|
3452
|
+
} finally {
|
|
3453
|
+
setFxOwner(null);
|
|
3454
|
+
}
|
|
3455
|
+
}
|
|
3456
|
+
|
|
2810
3457
|
export async function start(container, pathname, initial) {
|
|
2811
3458
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2812
3459
|
if (initial) {
|
|
@@ -2815,104 +3462,110 @@ export async function start(container, pathname, initial) {
|
|
|
2815
3462
|
}
|
|
2816
3463
|
for (const route of routes) {
|
|
2817
3464
|
if (matchRoute(route.pattern, pathname)) {
|
|
2818
|
-
//
|
|
2819
|
-
// (before the prefetch check: a cached entry for a bogus locale is
|
|
2820
|
-
// discarded, never painted)
|
|
3465
|
+
// I18n: an unknown locale paints the 404 page, same as the server (before the prefetch check: a cached entry for a bogus locale is discarded).
|
|
2821
3466
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
2822
3467
|
${langDirBlock}
|
|
2823
|
-
await paintFallback(container,
|
|
3468
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2824
3469
|
return;
|
|
2825
3470
|
}
|
|
2826
|
-
// Prefetched on hover/focus/touch: the render already ran, so paint its
|
|
2827
|
-
// HTML and adopt its signal entries - events then patch the very nodes
|
|
2828
|
-
// we wire, and no $data re-runs on click.
|
|
3471
|
+
// Prefetched on hover/focus/touch: the render already ran, so paint its HTML and adopt its signal entries - events then patch the very nodes we.
|
|
2829
3472
|
let hit = initial ? undefined : prefetchCache.get(pathname);
|
|
2830
3473
|
if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
|
|
2831
3474
|
if (hit) {
|
|
2832
|
-
prefetchCache.delete(pathname);
|
|
2833
|
-
|
|
3475
|
+
prefetchCache.delete(pathname);
|
|
3476
|
+
__navReset(container);
|
|
2834
3477
|
restoreState(hit.state);
|
|
2835
3478
|
container.innerHTML = hit.html;
|
|
2836
|
-
|
|
3479
|
+
await __withOwner(container, () => {
|
|
3480
|
+
wire(container, hit.closes);
|
|
3481
|
+
bindEvents(container);
|
|
3482
|
+
hit.mounts.forEach((fn) => fn());
|
|
3483
|
+
adoptCleanups(hit.cleanups);
|
|
3484
|
+
});
|
|
3485
|
+
return;
|
|
3486
|
+
}
|
|
3487
|
+
if (!initial) __navReset(container);
|
|
3488
|
+
let broken = false;
|
|
3489
|
+
let signal = null;
|
|
3490
|
+
await __withOwner(container, async () => {
|
|
3491
|
+
await applyParams(route, pathname);
|
|
3492
|
+
const closes = [];
|
|
3493
|
+
let html;
|
|
3494
|
+
try {
|
|
3495
|
+
const render = await getRender(route);
|
|
3496
|
+
html = await render(closes, '');
|
|
3497
|
+
} catch (err) {
|
|
3498
|
+
|
|
3499
|
+
if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
|
|
3500
|
+
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
3501
|
+
|
|
3502
|
+
|
|
3503
|
+
broken = true;
|
|
3504
|
+
return;
|
|
3505
|
+
}
|
|
3506
|
+
if (!initial) container.innerHTML = html;
|
|
3507
|
+
wire(container, closes);
|
|
2837
3508
|
bindEvents(container);
|
|
2838
|
-
|
|
2839
|
-
|
|
3509
|
+
flushMounts();
|
|
3510
|
+
});
|
|
3511
|
+
if (signal === 'notFound') {
|
|
3512
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2840
3513
|
return;
|
|
2841
3514
|
}
|
|
2842
|
-
if (
|
|
2843
|
-
|
|
2844
|
-
|
|
3515
|
+
if (signal) {
|
|
3516
|
+
location.href = signal;
|
|
3517
|
+
return;
|
|
2845
3518
|
}
|
|
2846
|
-
|
|
2847
|
-
const closes = [];
|
|
2848
|
-
let html;
|
|
2849
|
-
try {
|
|
2850
|
-
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
2851
|
-
html = await render(closes, '');
|
|
2852
|
-
} catch {
|
|
2853
|
-
// the route itself is broken: degrade to pages/500.rose (or the
|
|
2854
|
-
// built-in plain 500) instead of leaving the container empty
|
|
3519
|
+
if (broken) {
|
|
2855
3520
|
await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
2856
|
-
return;
|
|
2857
3521
|
}
|
|
2858
|
-
if (!initial) container.innerHTML = html;
|
|
2859
|
-
wire(container, closes);
|
|
2860
|
-
bindEvents(container);
|
|
2861
|
-
flushMounts();
|
|
2862
3522
|
return;
|
|
2863
3523
|
}
|
|
2864
3524
|
}
|
|
2865
|
-
//
|
|
2866
|
-
|
|
2867
|
-
//
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
}
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
//
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
clearRequestState();
|
|
3525
|
+
// Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
|
|
3526
|
+
${hasLang ? ` // the same app-root gate as above - a mount never touches the
|
|
3527
|
+
// host document's language or direction.
|
|
3528
|
+
if (container === document.getElementById('app')) {
|
|
3529
|
+
document.documentElement.lang = __defLocale;
|
|
3530
|
+
document.documentElement.removeAttribute('dir');
|
|
3531
|
+
}` : ''}
|
|
3532
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
3533
|
+
}
|
|
3534
|
+
|
|
3535
|
+
// Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
|
|
3536
|
+
export async function adopt(container, html, stateJson, pathname) {
|
|
3537
|
+
|
|
3538
|
+
|
|
3539
|
+
const route0 = pathname || location.pathname;
|
|
3540
|
+
__navReset(container);
|
|
2882
3541
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2883
3542
|
resumeState(stateJson);
|
|
2884
3543
|
container.innerHTML = html;
|
|
2885
|
-
|
|
3544
|
+
|
|
2886
3545
|
const st = document.getElementById('__rosetack_state');
|
|
2887
3546
|
if (st) st.textContent = stateJson;
|
|
2888
3547
|
for (const route of routes) {
|
|
2889
|
-
if (matchRoute(route.pattern,
|
|
2890
|
-
await
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
3548
|
+
if (matchRoute(route.pattern, route0)) {
|
|
3549
|
+
await __withOwner(container, async () => {
|
|
3550
|
+
await applyParams(route, route0);
|
|
3551
|
+
const closes = [];
|
|
3552
|
+
try {
|
|
3553
|
+
const render = await getRender(route);
|
|
3554
|
+
await render(closes, '');
|
|
3555
|
+
} catch {
|
|
3556
|
+
|
|
3557
|
+
|
|
3558
|
+
return;
|
|
3559
|
+
}
|
|
3560
|
+
wire(container, closes);
|
|
3561
|
+
bindEvents(container);
|
|
3562
|
+
flushMounts();
|
|
3563
|
+
});
|
|
2903
3564
|
return;
|
|
2904
3565
|
}
|
|
2905
3566
|
}
|
|
2906
3567
|
}
|
|
2907
|
-
// === refresh() implementation ===
|
|
2908
|
-
// Re-render the current route in place: the client half of router.refresh()
|
|
2909
|
-
// (a router refresh) / (a full invalidation). Same machinery as a client-side
|
|
2910
|
-
// navigation to the current path - $data re-runs, state re-seeds from the
|
|
2911
|
-
// fresh render, wire() patches the marked nodes - but a refresh never lands
|
|
2912
|
-
// a prefetch entry: a hover from a minute ago is exactly what it exists to
|
|
2913
|
-
// bypass. Zero requests: the render (and its $data) runs in the page.
|
|
2914
|
-
// Trade-off: state resets like navigation (no per-key retention); add
|
|
2915
|
-
// retention when an app needs refresh-without-losing-input.
|
|
3568
|
+
// === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
|
|
2916
3569
|
setRefreshHook(async () => {
|
|
2917
3570
|
prefetchCache.delete(location.pathname);
|
|
2918
3571
|
await start(document.getElementById('app'), location.pathname, false);
|
|
@@ -2920,8 +3573,6 @@ setRefreshHook(async () => {
|
|
|
2920
3573
|
`;
|
|
2921
3574
|
await fs.promises.writeFile(path.join(buildDir, 'client-entry.js'), clientEntry);
|
|
2922
3575
|
if (split) {
|
|
2923
|
-
// Mode B: esbuild code splitting. One chunk per route module, the shared runtime in its
|
|
2924
|
-
// own vendor chunk …
|
|
2925
3576
|
await fs.promises.rm(path.join(outDir, 'chunks'), { recursive: true, force: true });
|
|
2926
3577
|
await esbuild.build({
|
|
2927
3578
|
entryPoints: [path.join(buildDir, 'client-entry.js')],
|
|
@@ -2949,31 +3600,51 @@ setRefreshHook(async () => {
|
|
|
2949
3600
|
});
|
|
2950
3601
|
}
|
|
2951
3602
|
|
|
2952
|
-
|
|
3603
|
+
await fs.promises.writeFile(path.join(outDir, 'mount.js'), MOUNT_ENTRY);
|
|
3604
|
+
|
|
2953
3605
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
2954
3606
|
|
|
2955
3607
|
const publicDir = path.join(root, 'public');
|
|
2956
3608
|
if (fs.existsSync(publicDir)) {
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
);
|
|
3609
|
+
await fs.promises.cp(publicDir, path.join(outDir, 'public'), { recursive: true });
|
|
3610
|
+
// Browsers ask for /favicon.ico without being told to: an app that ships one in public/
|
|
3611
|
+
// gets it at the root of the build too, so every server …
|
|
3612
|
+
const favicon = path.join(publicDir, 'favicon.ico');
|
|
3613
|
+
if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, 'favicon.ico'));
|
|
2963
3614
|
}
|
|
2964
3615
|
|
|
2965
|
-
// The build's zero-JS lint report - every route, its verdict, and the reason. Printed on
|
|
2966
|
-
// every build (dev rebuilds included) so the decision is auditable instead of silent.
|
|
2967
3616
|
console.log('rosetack zero-JS report:');
|
|
2968
3617
|
for (const line of buildReport(infos, compiled)) console.log(' ' + line);
|
|
3618
|
+
const warnGroups = new Map<string, { why: string; files: Map<string, Set<string>> }>();
|
|
2969
3619
|
for (const { info, i } of pages) {
|
|
2970
3620
|
if (!routeShipsNoJs(infos, compiled, i)) continue;
|
|
2971
3621
|
for (const ci of [i, ...layoutsOf(infos, i)]) {
|
|
2972
3622
|
for (const w of compiled[ci].jsWarnings ?? []) {
|
|
2973
|
-
|
|
3623
|
+
let g = warnGroups.get(w);
|
|
3624
|
+
if (!g) {
|
|
3625
|
+
g = { why: w, files: new Map() };
|
|
3626
|
+
warnGroups.set(w, g);
|
|
3627
|
+
}
|
|
3628
|
+
const file = path.relative(root, infos[ci].filePath).replace(/\\/g, '/');
|
|
3629
|
+
let routes = g.files.get(file);
|
|
3630
|
+
if (!routes) {
|
|
3631
|
+
routes = new Set();
|
|
3632
|
+
g.files.set(file, routes);
|
|
3633
|
+
}
|
|
3634
|
+
routes.add(info.routePath);
|
|
2974
3635
|
}
|
|
2975
3636
|
}
|
|
2976
3637
|
}
|
|
3638
|
+
for (const g of warnGroups.values()) {
|
|
3639
|
+
const allRoutes = new Set<string>();
|
|
3640
|
+
for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
|
|
3641
|
+
const parts = [...g.files.entries()]
|
|
3642
|
+
.sort((a, b) => b[1].size - a[1].size)
|
|
3643
|
+
.map(([file, routes]) => `${file} (${routes.size === 1 ? [...routes][0] : `${routes.size} routes`})`);
|
|
3644
|
+
const shown = parts.slice(0, 4).join(', ');
|
|
3645
|
+
const more = parts.length > 4 ? `, +${parts.length - 4} more files` : '';
|
|
3646
|
+
console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
|
|
3647
|
+
}
|
|
2977
3648
|
|
|
2978
3649
|
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
2979
3650
|
}
|
|
@@ -3029,26 +3700,24 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
|
|
|
3029
3700
|
const relative = path.relative(pagesDir, filePath).replace(/\\/g, '/');
|
|
3030
3701
|
const withoutExt = relative.replace(/\.rose$/, '');
|
|
3031
3702
|
const base = path.posix.basename(withoutExt);
|
|
3032
|
-
// A component (src/components/**) is not a route at all - it is imported by one.
|
|
3033
|
-
// Everything below still runs so a broken file reports a sane routePath in build errors …
|
|
3034
3703
|
const isComponent = filePath.replace(/\\/g, '/').includes('/src/components/');
|
|
3035
3704
|
const isLayout = !isComponent && base === '_layout';
|
|
3036
|
-
const isNotFound = !isComponent && base === '404';
|
|
3705
|
+
const isNotFound = !isComponent && (base === '404' || base === '_notfound');
|
|
3037
3706
|
const isError = !isComponent && base === '500';
|
|
3038
|
-
// pages/api/*.rose: Web-standard handler routes (JSON in, JSON out), never
|
|
3039
|
-
// HTML pages - they dispatch by method and never reach the client bundle.
|
|
3040
3707
|
const isApi = !isComponent && (withoutExt === 'api' || withoutExt.startsWith('api/'));
|
|
3041
|
-
// pages/_middleware.rose: the request interceptor. It runs before every render and is not
|
|
3042
|
-
// a route: it matches nothing and never reaches the client bundle.
|
|
3043
3708
|
const isMiddleware = !isComponent && withoutExt === '_middleware';
|
|
3044
3709
|
|
|
3045
|
-
let parts = withoutExt.split('/').filter((p) => p !== '_layout');
|
|
3046
|
-
// a trailing `index` segment names its directory (blog/index -> /blog,
|
|
3047
|
-
// api/index -> /api); only the root index collapses to '/'
|
|
3710
|
+
let parts = withoutExt.split('/').filter((p) => p !== '_layout' && p !== '_notfound');
|
|
3048
3711
|
if (parts.length > 1 && parts[parts.length - 1] === 'index') parts = parts.slice(0, -1);
|
|
3049
|
-
const
|
|
3050
|
-
|
|
3051
|
-
)
|
|
3712
|
+
const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
|
|
3713
|
+
const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
|
|
3714
|
+
const routeParts = parts.map((part) => {
|
|
3715
|
+
const optional = OPTIONAL_CATCH_ALL.exec(part);
|
|
3716
|
+
if (optional) return `**${optional[1]}`;
|
|
3717
|
+
const catchAll = CATCH_ALL.exec(part);
|
|
3718
|
+
if (catchAll) return `*${catchAll[1]}`;
|
|
3719
|
+
return part.startsWith('[') && part.endsWith(']') ? `:${part.slice(1, -1)}` : part;
|
|
3720
|
+
});
|
|
3052
3721
|
|
|
3053
3722
|
let routePath: string;
|
|
3054
3723
|
if (routeParts.length === 0 || (routeParts.length === 1 && routeParts[0] === 'index')) {
|
|
@@ -3061,7 +3730,13 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
|
|
|
3061
3730
|
filePath,
|
|
3062
3731
|
routePath,
|
|
3063
3732
|
pattern: routePath,
|
|
3064
|
-
paramNames: parts.
|
|
3733
|
+
paramNames: parts.flatMap((p) => {
|
|
3734
|
+
const optional = OPTIONAL_CATCH_ALL.exec(p);
|
|
3735
|
+
if (optional) return [optional[1]];
|
|
3736
|
+
const catchAll = CATCH_ALL.exec(p);
|
|
3737
|
+
if (catchAll) return [catchAll[1]];
|
|
3738
|
+
return p.startsWith('[') && p.endsWith(']') ? [p.slice(1, -1)] : [];
|
|
3739
|
+
}),
|
|
3065
3740
|
isLayout,
|
|
3066
3741
|
isNotFound,
|
|
3067
3742
|
isError,
|