rosetack 0.1.0 → 0.1.1

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.
Files changed (49) hide show
  1. package/dist-cli/compiler.mjs +2302 -0
  2. package/dist-cli/edge.mjs +297 -0
  3. package/dist-cli/rosetack.mjs +3411 -0
  4. package/dist-cli/runtime.mjs +619 -0
  5. package/dist-cli/test.mjs +2696 -0
  6. package/pack.mjs +49 -0
  7. package/package.json +25 -7
  8. package/src/FRAMEWORK_VERSION +1 -1
  9. package/src/cli/edge.ts +58 -23
  10. package/src/cli/index.ts +521 -65
  11. package/src/cli/shell.ts +75 -22
  12. package/src/cli/test.ts +400 -0
  13. package/src/compiler/index.ts +1277 -191
  14. package/src/runtime/index.ts +356 -65
  15. package/src/types/rosetack.d.ts +142 -0
  16. package/.github/workflows/ci.yml +0 -72
  17. package/.github/workflows/release.yml +0 -122
  18. package/benchmark.ts +0 -227
  19. package/example/public/favicon.ico +0 -0
  20. package/example/public/logo.svg +0 -148
  21. package/example/public/rose-mark-black.png +0 -0
  22. package/example/public/rose-mark.png +0 -0
  23. package/example/public/rose-mono.png +0 -0
  24. package/example/rosetack.config.js +0 -10
  25. package/example/src/locales/en.json +0 -8
  26. package/example/src/locales/zh.json +0 -8
  27. package/example/src/pages/404.rose +0 -15
  28. package/example/src/pages/500.rose +0 -10
  29. package/example/src/pages/[lang]/about.rose +0 -40
  30. package/example/src/pages/_layout.rose +0 -33
  31. package/example/src/pages/_middleware.rose +0 -37
  32. package/example/src/pages/about.rose +0 -67
  33. package/example/src/pages/admin.rose +0 -27
  34. package/example/src/pages/api/hello.rose +0 -19
  35. package/example/src/pages/api/login.rose +0 -55
  36. package/example/src/pages/api/posts.rose +0 -80
  37. package/example/src/pages/api/secret.rose +0 -14
  38. package/example/src/pages/blog/[id].rose +0 -25
  39. package/example/src/pages/broken.rose +0 -16
  40. package/example/src/pages/fresh.rose +0 -22
  41. package/example/src/pages/garden.rose +0 -27
  42. package/example/src/pages/index.rose +0 -84
  43. package/example/src/pages/sign.rose +0 -45
  44. package/example/src/pages/thorn.rose +0 -23
  45. package/example/src/pages/vault.rose +0 -14
  46. package/go.mod +0 -3
  47. package/main.go +0 -470
  48. package/tools/release-notes.mjs +0 -113
  49. package/tsconfig.json +0 -17
@@ -18,21 +18,46 @@ const HEAD_RE = /<head>([\s\S]*?)<\/head>/;
18
18
  // <style> block: component CSS, scoped by a build-time attribute on the component's
19
19
  // top-level elements and inlined into the document …
20
20
  const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
21
- const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\s*\(/g;
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
+ const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
24
+ const DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
22
25
  const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
23
26
  const EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
24
27
  const SLOT_RE = /<slot\s*\/?>/g;
28
+ /** A named slot: `<slot name="row" item={post} />` . The lookahead
29
+ * keeps the plain `<slot />` out of it - that one is the default slot. */
30
+ const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
31
+
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
+ */
37
+ function encodeSlotCall(attrs: string): string {
38
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
39
+ if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
40
+ const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)]
41
+ .filter((m) => m[1] !== 'name')
42
+ .map((m) => `['${m[1]}', (${m[2].trim()})]`);
43
+ return `${JSON.stringify(name)}, [${pairs.join(', ')}]`;
44
+ }
25
45
  // {#boundary}...{/boundary}: an error boundary - its content renders into its own string; a
26
- // throw anywhere inside swaps in this fallback instead of failing the whole page.
46
+ // throw anywhere inside swaps in a fallback instead of failing the whole page.
27
47
  const BOUNDARY_FALLBACK = '<p>This section failed to render.</p>';
28
48
  // API route handlers are exported functions named by HTTP method (pages/api/*.rose).
29
49
  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
+ const TS_LOADER = { loader: { '.js': 'ts' as const } };
30
53
 
31
54
  export interface CompileResult {
32
55
  ssr: string;
33
56
  client: string;
34
57
  stateKeys: string[];
35
58
  actionNames: string[];
59
+ /** The page exports `beforeAction` (the action guard), or null */
60
+ guardName: string | null;
36
61
  /** scoped CSS from the component's <style> block ('' when it has none) */
37
62
  style: string;
38
63
  /** the component exports `params` (dynamic-route prerender enumeration) */
@@ -51,14 +76,14 @@ export interface CompileResult {
51
76
  csr?: boolean;
52
77
  /** the component exports `prefetch = 'off' | 'hover' | 'viewport' | 'all'` (app-global link-prefetch strategy) */
53
78
  prefetch?: string;
54
- /** the component exports `bundle = 'inline' | 'split'` (app-global client bundle mode, P0 §1) */
79
+ /** the component exports `bundle = 'inline' | 'split'` (app-global client bundle mode) */
55
80
  bundle?: string;
56
- /** innovation #29: the static analysis says this component needs the client bundle */
81
+ /** The static analysis says this component needs the client bundle */
57
82
  needsClient?: boolean;
58
- /** innovation #31: WHY it needs the client - the rules that fired, for the build report */
83
+ /** WHY it needs the client - the rules that fired, for the build report */
59
84
  clientReasons?: string[];
60
85
  /**
61
- * innovation #31: shapes that MIGHT need JavaScript but the syntactic
86
+ * Shapes that MIGHT need JavaScript but the syntactic
62
87
  * predicate cannot prove, on a component that otherwise ships none (an
63
88
  * inline on* attribute, a javascript: URL, eval/new Function). Warnings,
64
89
  * never errors: the document still ships, but the build says it out loud.
@@ -66,6 +91,27 @@ export interface CompileResult {
66
91
  jsWarnings?: string[];
67
92
  /** the component exports `headers = { ... }` (per-route response headers) */
68
93
  headers?: Record<string, string>;
94
+ /**
95
+ * The component exports `csp = { nonce: true }` - its documents get a
96
+ * per-request nonce policy instead of the hashed one. Never prerendered: a
97
+ * baked file cannot carry a fresh nonce.
98
+ */
99
+ cspNonce?: boolean;
100
+ /**
101
+ * The component's props - `export let title = 'x'` in its script.
102
+ * A prop is a plain value the caller passes per invocation (never a
103
+ * signal: the parent re-renders the child when a prop changes), so it is
104
+ * read straight from the props object with its default as the fallback.
105
+ */
106
+ props?: Array<{ name: string; def: string | null }>;
107
+ /**
108
+ * `.rose` imports this component makes, resolved to module indices.
109
+ * The specifiers are rewritten per bundle (ssr/client) by the generators,
110
+ * so one source resolves against both module sets.
111
+ */
112
+ roseImports?: Array<{ name: string; specifier: string; index: number }>;
113
+ /** This file lives in src/components/ (a reusable component, not a route) */
114
+ isComponent?: boolean;
69
115
  }
70
116
 
71
117
  export interface RouteInfo {
@@ -82,6 +128,8 @@ export interface RouteInfo {
82
128
  isApi: boolean;
83
129
  /** pages/_middleware.rose: the request interceptor, not a route */
84
130
  isMiddleware: boolean;
131
+ /** src/components/*.rose: a reusable component, never a route */
132
+ isComponent?: boolean;
85
133
  }
86
134
 
87
135
  interface Decl {
@@ -186,34 +234,261 @@ function callifyStateReads(script: string, names: string[]): string {
186
234
  return scan(script);
187
235
  }
188
236
 
189
- /** A plugin transforms a component's raw source before compilation sees it. */
237
+ /**
238
+ * The template-side twin of callifyStateReads: every `{...}` expression gets
239
+ * the same bare-read rewrite, and nothing else does. A whole-template scan
240
+ * would also rewrite the word in prose - `<p>likes {likes()}</p>` would print
241
+ * "likes()" - so the pass walks expressions only. Block syntax ({#if …},
242
+ * {#each …}) rides along: callifying `rows` in `{#each rows as row}` is
243
+ * exactly what the each branch already expects (`rows()`).
244
+ */
245
+ function callifyTemplateExprs(template: string, names: string[]): string {
246
+ if (names.length === 0) return template;
247
+ return template.replace(/\{([^{}]*)\}/g, (whole, expr) =>
248
+ `{${callifyStateReads(expr, names)}}`);
249
+ }
250
+
251
+ /**
252
+ * The <script> block of a .rose source, verbatim. `rosetack check` must
253
+ * type-check exactly what the compiler will embed, so the extraction lives
254
+ * here and both consumers share it - one regex, one truth.
255
+ */
256
+ export function scriptOf(source: string): string | null {
257
+ return source.match(COMPONENT_RE)?.[1] ?? null;
258
+ }
259
+
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
+ */
267
+ export interface RequestHookContext {
268
+ request: Request;
269
+ url: URL;
270
+ method: string;
271
+ pathname: string;
272
+ state: Record<string, unknown>;
273
+ }
274
+
275
+ /**
276
+ * A plugin, in two halves. `transform` runs at BUILD time over each
277
+ * component's raw source. The rest run at RUNTIME: `onRequest`/`onResponse`
278
+ * once per request (Node server, dev/preview and edge adapter alike),
279
+ * `onServe`/`onShutdown` once per worker process under `rosetack serve`
280
+ * (Node only - an edge runtime owns the lifecycle, there is no worker start
281
+ * to hook).
282
+ *
283
+ * A runtime hook is bundled into dist/server.js together with the config
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
+ */
190
287
  export interface Plugin {
191
288
  name: string;
192
- transform(code: string, filePath: string): string | Promise<string>;
289
+ transform?(code: string, filePath: string): string | Promise<string>;
290
+ /** Before routing and middleware. Return a Response to short-circuit (auth wall, rate limit, maintenance page). */
291
+ onRequest?(ctx: RequestHookContext): Response | void | Promise<Response | void>;
292
+ /** After the response exists, before it is sent. Return a Response to replace it. */
293
+ 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>;
296
+ /** Worker drain, before exit: close the pool. */
297
+ onShutdown?(): void | Promise<void>;
298
+ }
299
+
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
+ */
314
+ export interface I18nConfig {
315
+ preload?: string[];
316
+ }
317
+
318
+ export interface rosetackConfig {
319
+ plugins: Plugin[];
320
+ i18n: I18nConfig;
193
321
  }
194
322
 
195
323
  /**
196
324
  * Plugins live in `<root>/rosetack.config.js` as the default export: an array
197
- * of `{ name, transform }`, run over each component's raw source (template +
198
- * script + style, before any parsing). ponytail: ONE hook - it covers macros,
199
- * custom syntax, includes and auto-imports; add bundler/build hooks when a
200
- * real plugin needs one. The import is cache-busted per build so a config
201
- * edit takes effect on the dev server's next rebuild, and a missing file is
202
- * simply "no plugins" (existence is checked first, so a config with a syntax
203
- * error still fails loudly).
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.
204
336
  */
205
- export async function loadPlugins(root: string): Promise<Plugin[]> {
337
+ export async function loadConfig(root: string): Promise<rosetackConfig> {
206
338
  const file = path.join(root, 'rosetack.config.js');
207
- if (!fs.existsSync(file)) return [];
339
+ if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
208
340
  const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
209
- return (mod.default as Plugin[] | undefined) ?? [];
341
+ return {
342
+ plugins: (mod.default as Plugin[] | undefined) ?? [],
343
+ i18n: (mod.i18n as I18nConfig | undefined) ?? {},
344
+ };
210
345
  }
211
346
 
212
- export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = []): Promise<CompileResult> {
347
+ /** The plugins alone (the serve command's lifecycle hooks). */
348
+ export async function loadPlugins(root: string): Promise<Plugin[]> {
349
+ return (await loadConfig(root)).plugins;
350
+ }
351
+
352
+ /**
353
+ * The module registry the build hands every compileComponent call.
354
+ * Maps a resolved .rose file to its module index and scope key, so an
355
+ * `import Card from '../components/Card.rose'` can be rewritten to the
356
+ * compiled module in BOTH bundles (the specifier differs per bundle, the
357
+ * index does not). One map, built once per build from the full file list -
358
+ * a component may import a component, so the graph is resolved before any
359
+ * compilation starts.
360
+ *
361
+ * `slots` is the child's slot declaration (`<slot name="row" item={post}>`),
362
+ * pre-scanned from its template: the parent needs the names the child passes
363
+ * INTO a slot to resolve them in the slot content it writes, and compilation
364
+ * order cannot guarantee the child is compiled first.
365
+ */
366
+ export type RoseRegistry = Map<string, { index: number; scopeKey: string; slots: Array<{ name: string; props: string[] }> }>;
367
+
368
+ /**
369
+ * Resolve every `.rose` import in a script against the registry. Returns the
370
+ * rewritten script plus the (local name, specifier, index) triples, so the
371
+ * generators can emit the right module path per bundle. An unresolvable
372
+ * specifier fails the build naming the file and the import - a typo'd
373
+ * component path must not silently ship a broken bundle.
374
+ */
375
+ function resolveRoseImports(script: string, fromFile: string, registry: RoseRegistry): { script: string; imports: Array<{ name: string; specifier: string; index: number }> } {
376
+ const imports: Array<{ name: string; specifier: string; index: number }> = [];
377
+ const resolve = (spec: string): { index: number; scopeKey: string } => {
378
+ const abs = path.resolve(path.dirname(fromFile), spec);
379
+ const hit = registry.get(abs);
380
+ if (!hit) {
381
+ throw new Error(`${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.`);
382
+ }
383
+ return hit;
384
+ };
385
+ // A default import becomes a named one: the compiled module exports
386
+ // `render`, and the parent's `<Card>` tag calls exactly that.
387
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
388
+ const hit = resolve(spec);
389
+ imports.push({ name, specifier: spec, index: hit.index });
390
+ return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
391
+ });
392
+ // A named import (`import { render as Card }`) keeps its clause; only the
393
+ // specifier becomes the placeholder.
394
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
395
+ const hit = resolve(spec);
396
+ const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? 'render';
397
+ imports.push({ name: alias, specifier: spec, index: hit.index });
398
+ return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
399
+ });
400
+ return { script: rewritten, imports };
401
+ }
402
+
403
+ /**
404
+ * Rewrite the `__rose_N__` placeholders to this bundle's module paths. Both
405
+ * bundles are generated from the same resolved script, so one placeholder
406
+ * resolves to two different files - the only per-bundle difference in the
407
+ * whole component pipeline.
408
+ */
409
+ function rewriteRoseImports(script: string, kind: 'ssr' | 'client'): string {
410
+ return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
411
+ }
412
+
413
+ /**
414
+ * Pre-scan a file's template for its slot declarations -
415
+ * `<slot name="row" item={post}>` -> { name: 'row', props: ['item'] }.
416
+ * Cheap regex on purpose: the parent's compiler needs the names the child
417
+ * passes INTO a slot, before (and independently of) compiling the child.
418
+ */
419
+ function scanSlotDecls(filePath: string): Array<{ name: string; props: string[] }> {
420
+ let src: string;
421
+ try {
422
+ src = fs.readFileSync(filePath, 'utf-8');
423
+ } catch {
424
+ return [];
425
+ }
426
+ // Same template extraction compileComponent does: a <template> block when
427
+ // the file has one, otherwise everything that is not script/style/head.
428
+ const noBlocks = src.replace(STYLE_RE, '');
429
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, '').replace(COMPONENT_RE, '').trim();
430
+ const out: Array<{ name: string; props: string[] }> = [];
431
+ for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
432
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
433
+ if (!name) continue;
434
+ const props = [...m[1].matchAll(/\b(\w+)\s*=\s*\{/g)].map((x) => x[1]).filter((n) => n !== 'name');
435
+ out.push({ name: name[1], props });
436
+ }
437
+ return out;
438
+ }
439
+
440
+ /**
441
+ * Lift `import` statements out of a script block to module scope. The
442
+ * script body is embedded inside render(), where an import declaration is a
443
+ * syntax error - and a component import is exactly what a page/component
444
+ * script now carries. Line-based on purpose: multi-line imports are tracked
445
+ * by brace/paren depth and end at their `from '...'` clause.
446
+ */
447
+ function hoistImports(script: string): { imports: string; rest: string } {
448
+ const imports: string[] = [];
449
+ const rest: string[] = [];
450
+ let buf: string[] | null = null;
451
+ let depth = 0;
452
+ const done = (line: string) => depth <= 0 && /from\s*['"][^'"]+['"]\s*;?\s*$/.test(line);
453
+ for (const line of script.split('\n')) {
454
+ if (buf) {
455
+ buf.push(line);
456
+ for (const ch of line) {
457
+ if (ch === '{' || ch === '(') depth++;
458
+ else if (ch === '}' || ch === ')') depth--;
459
+ }
460
+ if (done(line)) {
461
+ imports.push(buf.join('\n'));
462
+ buf = null;
463
+ }
464
+ continue;
465
+ }
466
+ if (/^\s*import\b/.test(line)) {
467
+ buf = [line];
468
+ depth = 0;
469
+ for (const ch of line) {
470
+ if (ch === '{' || ch === '(') depth++;
471
+ else if (ch === '}' || ch === ')') depth--;
472
+ }
473
+ if (done(line)) {
474
+ imports.push(line);
475
+ buf = null;
476
+ }
477
+ continue;
478
+ }
479
+ rest.push(line);
480
+ }
481
+ if (buf) imports.push(buf.join('\n')); // unterminated import: keep it whole
482
+ return { imports: imports.join('\n'), rest: rest.join('\n') };
483
+ }
484
+
485
+ export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = [], registry: RoseRegistry = new Map()): Promise<CompileResult> {
213
486
  let source = await fs.promises.readFile(filePath, 'utf-8');
214
- // Plugins (innovation #30) see the raw source first: whatever they return is what the
215
- // compiler parses.
487
+ // Plugins see the raw source first: whatever they return is what the compiler parses.
216
488
  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
+ if (!p.transform) continue;
217
492
  try {
218
493
  source = await p.transform(source, filePath);
219
494
  } catch (err) {
@@ -233,14 +508,16 @@ export async function compileComponent(filePath: string, publicDir: string, scop
233
508
  // per-request, a baked body would freeze one request's answer
234
509
  const usesContext = /getContext\s*\(/.test(rawScript);
235
510
  const hasPrerender = !usesContext && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript);
511
+ const hoisted = hoistImports(resolveRoseImports(rawScript, filePath, registry).script);
236
512
  return {
237
513
  ssr: '',
238
514
  client: '',
239
515
  stateKeys: [],
240
516
  actionNames: [],
517
+ guardName: null,
241
518
  style: '',
242
519
  hasParams: false,
243
- api: `import { getContext } from './runtime.js';\n${rawScript.trim()}`,
520
+ api: `import { getContext } from './runtime.js';\n${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
244
521
  apiMethods,
245
522
  hasPrerender,
246
523
  usesContext,
@@ -254,7 +531,25 @@ export async function compileComponent(filePath: string, publicDir: string, scop
254
531
  const sourceNoBlocks = source.replace(STYLE_RE, '');
255
532
 
256
533
  const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
257
- const rawScript = scriptMatch?.[1] ?? '';
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) …
536
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? '', filePath, registry);
537
+ const rawScript = roseResolved.script;
538
+ 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
+ const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
542
+ // A component (src/components/*.rose) is not a route: the build marks it in the registry
543
+ // with a `components/...` scope key …
544
+ 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
+ if (isComponent && /\$data\s*\(/.test(rawScript)) {
548
+ throw new Error(
549
+ `${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()}>.`
551
+ );
552
+ }
258
553
  // getContext() in the script makes the route dynamic: the request bag is per-request, so
259
554
  // the build must not bake it and the servers must not answer it from a prerendered file.
260
555
  const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
@@ -264,22 +559,22 @@ export async function compileComponent(filePath: string, publicDir: string, scop
264
559
  // is served for up to N seconds …
265
560
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
266
561
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
267
- // P1 (consultant report): an exported `prefetch = '...'` sets the app-global
268
- // link-prefetch strategy - 'off', 'hover' …
562
+ // P1: an exported `prefetch = '...'` sets the app-global link-prefetch strategy - 'off',
563
+ // 'hover' …
269
564
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
270
565
  const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
271
566
  if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
272
567
  throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
273
568
  }
274
- // P0 §1 (consultant report): the bundle mode - the fix for the large-app architecture
275
- // gap.
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 …
276
571
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
277
572
  const bundle = bundleMatch ? bundleMatch[1] : undefined;
278
573
  if (bundle && !['inline', 'split'].includes(bundle)) {
279
574
  throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
280
575
  }
281
- // Innovation #29: the compiler decides zero-JS, not the developer. This is the same "does
282
- // anything here need the client bundle" predicate that innovation #25 used to REFUSE …
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 …
283
578
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
284
579
  const csr: boolean | undefined = csrMatch ? csrMatch[1] !== 'false' : undefined;
285
580
  if (csr === false) {
@@ -292,8 +587,7 @@ export async function compileComponent(filePath: string, publicDir: string, scop
292
587
  }
293
588
  }
294
589
 
295
- // An exported `headers = { ... }` sets this route's response headers (innovation #26) -
296
- // the servers merge them OVER the framework defaults (the strict CSP) …
590
+ // An exported `headers = { ... }` sets this route's response headers
297
591
  let headers: Record<string, string> | undefined;
298
592
  const headersLiteral = extractObjectLiteral(rawScript, 'headers');
299
593
  if (headersLiteral) {
@@ -309,13 +603,31 @@ export async function compileComponent(filePath: string, publicDir: string, scop
309
603
  headers = value as Record<string, string>;
310
604
  }
311
605
 
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
+ let cspNonce: boolean | undefined;
609
+ const cspLiteral = extractObjectLiteral(rawScript, 'csp');
610
+ if (cspLiteral) {
611
+ let value: unknown;
612
+ try {
613
+ value = new Function(`return ${cspLiteral}`)();
614
+ } catch {
615
+ throw new Error(`${filePath}: export const csp must be an object literal`);
616
+ }
617
+ const nonce = (value as { nonce?: unknown } | null)?.nonce;
618
+ if (nonce !== undefined && typeof nonce !== 'boolean') {
619
+ throw new Error(`${filePath}: csp.nonce must be a boolean`);
620
+ }
621
+ cspNonce = nonce === true;
622
+ }
623
+
312
624
  // Top-level `export` statements (e.g. `export const params = {...}` for dynamic-route
313
625
  // prerendering) are hoisted to module scope: the script body itself is embedded inside …
314
- const { clean: scriptNoExports, exports: exportStmts, actions } = extractExports(rawScript);
626
+ const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
315
627
  const script = scriptNoExports;
316
628
  const actionNames = new Set(actions.map((a) => a.name));
317
629
 
318
- // Innovation #29: does anything in this component need the client bundle?
630
+ // Does anything in this component need the client bundle?
319
631
  const clientReasons: string[] = [];
320
632
  if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)'); // event wiring in the template
321
633
  if (/<form[\s>]/.test(source)) clientReasons.push('a <form> (its in-place adopt is the enhancement)'); // a POST form
@@ -326,8 +638,8 @@ export async function compileComponent(filePath: string, publicDir: string, scop
326
638
  }
327
639
  const needsClient = clientReasons.length > 0;
328
640
 
329
- // Innovation #31: the predicate is SYNTACTIC, so a component that ships no runtime is
330
- // scanned for the shapes that would silently need one …
641
+ // The predicate is SYNTACTIC, so a component that ships no runtime is scanned for the
642
+ // shapes that would silently need one …
331
643
  const jsWarnings: string[] = [];
332
644
  if (!needsClient) {
333
645
  if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
@@ -384,52 +696,113 @@ export async function compileComponent(filePath: string, publicDir: string, scop
384
696
  return `${setter}(${val})`;
385
697
  });
386
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
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
702
+
703
+ // The template gets the same treatment: the script auto-calls a bare state read, so
704
+ // `{liked}` must not silently render the getter's source text.
705
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
706
+
387
707
  // on:event={fn} -> data-on-event="fn"; a handler that names a server action becomes
388
- // data-on-event="$action:fn" (dispatched by $action); <slot /> -> block marker
389
- const ssrTemplate = template
708
+ // data-on-event="$action:fn" (dispatched by $action) …
709
+ const ssrTemplate = templateCalled
710
+ .replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
390
711
  .replace(SLOT_RE, '{__slot__}')
391
712
  .replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) =>
392
713
  actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
393
714
 
394
- // Replace bare state reads with getter calls (after decl removal). A plain regex would
395
- // also rewrite state names inside string literals …
396
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
397
-
398
715
  const stateDeclsCode = decls
399
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;
400
720
  if (d.kind === 'state') {
401
- return `const [${d.name}, ${setterNames.get(d.name)!}] = state("${d.name}", ${d.expr});`;
721
+ return `const [${d.name}, ${setterNames.get(d.name)!}] = state(${JSON.stringify(key)}, ${d.expr});`;
402
722
  }
403
723
  // $data: fetch only when this key has no value yet (server: always after
404
724
  // clearRequestState; client: only on first visit or client-side nav)
405
725
  const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
406
726
  const fn = isFn ? d.expr : `() => (${d.expr})`;
407
- return `const __had_${d.name} = hasState("${d.name}");
408
- const [${d.name}, set${capitalize(d.name)}] = state("${d.name}", null);
727
+ return `const __had_${d.name} = hasState(${JSON.stringify(key)});
728
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
409
729
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
410
730
  })
411
731
  .join('\n');
412
732
 
413
733
  const stateKeys = decls.map((d) => d.name);
414
734
 
415
- const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0);
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
+ const comps = new Map(roseImports.map((r) => {
738
+ const abs = path.resolve(path.dirname(filePath), r.specifier);
739
+ const hit = registry.get(abs)!;
740
+ return [r.name, { index: hit.index, slots: hit.slots }] as const;
741
+ }));
742
+ const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0, true, comps);
416
743
  // head block: no markers (esc() inline) - the whole block re-renders per
417
744
  // call, so one reactive closure drives document title/meta on navigation.
418
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.
747
+ const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
419
748
 
420
749
  // Actions ship in the SSR module only; the client bundle gets every other
421
750
  // export (params, sync helpers) but never an action body.
422
751
  const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
423
- const ssr = generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead);
424
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead);
752
+ // The guard is emitted at the SSR module's scope, beside the actions it fronts …
753
+ const ssrGuard = guard ? `\n${guard}` : '';
754
+ // pages/_middleware.rose is a hook module, not a route: no template, no state, no head.
755
+ const isMiddleware = path.basename(filePath) === '_middleware.rose';
756
+ const ssr = isMiddleware
757
+ ? `${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);
760
+
761
+ // One rewrite for both bundles and every branch above: the `__rose_N__` placeholder
762
+ // resolves to this bundle's own module path …
763
+ return {
764
+ ssr: rewriteRoseImports(ssr, 'ssr'),
765
+ client: rewriteRoseImports(client, 'client'),
766
+ stateKeys,
767
+ actionNames: [...actionNames],
768
+ guardName: guard ? 'beforeAction' : null,
769
+ style: scopedStyle,
770
+ hasParams,
771
+ usesContext,
772
+ revalidate,
773
+ csr,
774
+ prefetch,
775
+ bundle,
776
+ needsClient,
777
+ clientReasons,
778
+ jsWarnings,
779
+ headers,
780
+ cspNonce,
781
+ props,
782
+ roseImports,
783
+ isComponent,
784
+ };
785
+ }
425
786
 
426
- return { ssr, client, stateKeys, actionNames: [...actionNames], style: scopedStyle, hasParams, usesContext, revalidate, csr, prefetch, bundle, needsClient, clientReasons, jsWarnings, headers };
787
+ /**
788
+ * Collapse a declaration block's whitespace outside strings. Every byte of
789
+ * component CSS ships inside every document, so the source's formatting is a
790
+ * tax paid on every route; collapsing it is free - declarations are not
791
+ * whitespace-sensitive, and quoted strings (content: "a b") are left
792
+ * untouched by the alternation.
793
+ */
794
+ function minifyDecls(block: string): string {
795
+ return block
796
+ .replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g, (m) =>
797
+ m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, ' ').replace(/\s*([:;{},])\s*/g, '$1').trim()
798
+ )
799
+ .trim();
427
800
  }
428
801
 
429
802
  /**
430
803
  * Scope a component's CSS to its own subtree: every selector is prefixed
431
804
  * with the component's scope attribute, recursing into @media/@supports.
432
- * ponytail: no full CSS parser - comma lists only, and @keyframes blocks
805
+ * Trade-off: no full CSS parser - comma lists only, and @keyframes blocks
433
806
  * pass through unscoped (their from/to/to selectors are not selectors).
434
807
  * Global element rules (:root/html/body) belong in the shell's STYLES.
435
808
  */
@@ -454,10 +827,10 @@ function scopeCss(css: string, key: string): string {
454
827
  if (sel.startsWith('@')) {
455
828
  // at-rule: keep the prelude, scope the inner rules (keyframes pass
456
829
  // through: their 0%/from/to "selectors" are not selectors)
457
- out += `${sel} { ${/^@(?:-[\w]+-)?keyframes/.test(sel) ? block : scopeCss(block, key)} }`;
830
+ out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
458
831
  } else if (sel) {
459
- const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(', ');
460
- out += `${scoped} { ${block} }`;
832
+ const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(',');
833
+ out += `${scoped}{${minifyDecls(block)}}`;
461
834
  }
462
835
  prelude = '';
463
836
  i = j;
@@ -518,7 +891,7 @@ function injectScopeAttr(template: string, key: string): string {
518
891
 
519
892
  const VOID_TAGS = new Set(['img', 'br', 'hr', 'input', 'meta', 'link', 'source', 'wbr']);
520
893
 
521
- // ponytail: tolerate leading indentation - .rose script blocks are indented
894
+ // Trade-off: tolerate leading indentation - .rose script blocks are indented
522
895
  const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
523
896
 
524
897
  /**
@@ -526,7 +899,7 @@ const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(
526
899
  * body. They must be self-contained (no references to state or template
527
900
  * scope) - they exist for build-time consumers like dynamic-route `params`.
528
901
  *
529
- * Every exported ASYNC function is a SERVER-ONLY action (Next.js semantics:
902
+ * Every exported ASYNC function is a SERVER-ONLY action (server-action semantics:
530
903
  * `export const params` and sync helpers stay shared, async exports are
531
904
  * server code). `action` is the conventional name a <form method="POST">
532
905
  * posts to; any other name is reachable from an event handler
@@ -559,9 +932,17 @@ function extractObjectLiteral(script: string, name: string): string | null {
559
932
  return script.slice(start, i);
560
933
  }
561
934
 
562
- function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }> } {
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
+ export function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }>; props: Array<{ name: string; def: string | null }>; guard: string } {
563
938
  const stmts: string[] = [];
564
939
  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
+ 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
+ const guards: string[] = [];
565
946
  let out = '';
566
947
  let pos = 0;
567
948
  let m: RegExpExecArray | null;
@@ -616,15 +997,24 @@ function extractExports(script: string): { clean: string; exports: string; actio
616
997
  out += script.slice(pos, start);
617
998
  const stmt = script.slice(start, i).trim();
618
999
  const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
619
- if (asyncFn) {
1000
+ const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
1001
+ if (anyFn?.[1] === 'beforeAction') {
1002
+ guards.push(stmt); // the guard: server-only, never an action target
1003
+ } else if (asyncFn) {
620
1004
  actions.push({ name: asyncFn[1], stmt }); // server-only: kept out of the client bundle
1005
+ } 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
+ const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
1009
+ if (pm) props.push({ name: pm[1], def: pm[2]?.trim() ?? null });
1010
+ else stmts.push(stmt); // a destructuring pattern: not a prop, keep it shared
621
1011
  } else {
622
1012
  stmts.push(stmt);
623
1013
  }
624
1014
  pos = i;
625
1015
  }
626
1016
  out += script.slice(pos);
627
- return { clean: out, exports: stmts.join('\n'), actions };
1017
+ return { clean: out, exports: stmts.join('\n'), actions, props, guard: guards.join('\n') };
628
1018
  }
629
1019
 
630
1020
  function extractDecls(script: string): Decl[] {
@@ -632,7 +1022,26 @@ function extractDecls(script: string): Decl[] {
632
1022
  DECL_RE.lastIndex = 0;
633
1023
  let m: RegExpExecArray | null;
634
1024
  while ((m = DECL_RE.exec(script))) {
635
- const open = m.index + m[0].length;
1025
+ // The regex matched up to `$state`/`$data`; what follows is an optional type-argument
1026
+ // list and then the call.
1027
+ let j = m.index + m[0].length;
1028
+ const skipSpace = () => { while (j < script.length && /\s/.test(script[j])) j++; };
1029
+ skipSpace();
1030
+ if (script[j] === '<') {
1031
+ let depth = 0;
1032
+ while (j < script.length) {
1033
+ const ch = script[j];
1034
+ if (ch === '<') depth++;
1035
+ else if (ch === '>' && script[j - 1] !== '=') {
1036
+ depth--;
1037
+ if (depth === 0) { j++; break; }
1038
+ } else if (ch === '=' && script[j + 1] === '>') j++; // `=>`: both chars are one token
1039
+ j++;
1040
+ }
1041
+ skipSpace();
1042
+ }
1043
+ if (script[j] !== '(') continue; // `$state` used as a value, not a call
1044
+ const open = j + 1;
636
1045
  let depth = 1;
637
1046
  let i = open;
638
1047
  while (i < script.length && depth > 0) {
@@ -642,6 +1051,8 @@ function extractDecls(script: string): Decl[] {
642
1051
  i++;
643
1052
  }
644
1053
  let end = i;
1054
+ const cast = DECL_CAST_RE.exec(script.slice(i));
1055
+ if (cast) end = i + cast[0].length;
645
1056
  if (script[end] === ';') end++;
646
1057
  decls.push({
647
1058
  name: m[1],
@@ -679,14 +1090,35 @@ function removeRanges(text: string, ranges: Array<[number, number]>): string {
679
1090
  *
680
1091
  * Text/attr values are HTML-escaped on the server; wire() writes raw values
681
1092
  * because DOM text nodes and attributes are not HTML-parsed.
1093
+ *
1094
+ * `comps` maps an imported component's local name to its module index
1095
+ * and slot declarations. A `<Card title={x}>` tag compiles to a call of that
1096
+ * module's render() - the child pushes its markers into the SAME closes array
1097
+ * the parent is using, so one wire() pass covers the whole tree (the same
1098
+ * trick the layout chain already uses with children html).
682
1099
  */
1100
+
1101
+ /**
1102
+ * Auto-call a BARE state read and nothing else. The callify pass has already
1103
+ * rewritten a bare name to `name()`, so what reaches here is that - or an
1104
+ * expression the developer wrote (a comparison, a member read, a call with
1105
+ * arguments). Appending () to THOSE is a crash the developer reads as a
1106
+ * framework bug: `{#if flash().name}` must not become `flash().name()`, and
1107
+ * `{#each rows.filter(ok) as row}` must not become `rows.filter(ok)()`.
1108
+ */
1109
+ function autoCall(expr: string): string {
1110
+ const e = expr.trim();
1111
+ return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1112
+ }
1113
+
683
1114
  function compileTemplate(
684
1115
  template: string,
685
1116
  acc: string,
686
1117
  closes: string,
687
1118
  scope: string | null,
688
1119
  depth: number,
689
- markers = true
1120
+ markers = true,
1121
+ comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map()
690
1122
  ): string {
691
1123
  let result = '';
692
1124
  let remaining = template;
@@ -699,12 +1131,14 @@ function compileTemplate(
699
1131
  const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/) as RegExpExecArray | null;
700
1132
  const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/) as RegExpExecArray | null;
701
1133
  const exprMatch = remaining.match(/\{([^{}]+)\}/) as RegExpExecArray | null;
1134
+ const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
702
1135
 
703
- const candidates: Array<{ type: string; match: RegExpExecArray; index: number }> = [];
1136
+ const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
704
1137
  if (ifMatch?.index !== undefined) candidates.push({ type: 'if', match: ifMatch, index: ifMatch.index });
705
1138
  if (eachMatch?.index !== undefined) candidates.push({ type: 'each', match: eachMatch, index: eachMatch.index });
706
1139
  if (boundaryMatch?.index !== undefined) candidates.push({ type: 'boundary', match: boundaryMatch, index: boundaryMatch.index });
707
1140
  if (exprMatch?.index !== undefined) candidates.push({ type: 'expr', match: exprMatch, index: exprMatch.index });
1141
+ if (compTag) candidates.push({ type: 'comp', match: exprMatch!, index: compTag.start, tag: compTag });
708
1142
  const earliest = candidates.length > 0
709
1143
  ? candidates.reduce((a, b) => (a.index <= b.index ? a : b))
710
1144
  : null;
@@ -718,21 +1152,18 @@ function compileTemplate(
718
1152
  const [, cond, content] = earliest.match;
719
1153
  const before = remaining.substring(0, earliest.index);
720
1154
  if (before) result += emitChunk(before, acc, closes, scope);
721
- const call = cond.trim().endsWith('()') ? cond.trim() : `${cond.trim()}()`;
1155
+ const call = autoCall(cond);
722
1156
  const id = nextId();
723
1157
  const innerScope = scope ?? '__s';
724
1158
  // Inner markers live in the block's OWN closes array, so wiring an
725
1159
  // adopted/cloned block never re-touches the parent's markers.
726
- const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers);
1160
+ const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers, comps);
727
1161
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
728
1162
  if (markers) {
729
- result += `const __c${id} = [];\n`;
730
- result += `const __bh${id} = __b${id}(${scope ?? 'undefined'}, __c${id});\n`;
731
- result += `const __i${id} = ${closes}.length;\n`;
732
- result += `${closes}.push(() => (${call}) ? { html: __bh${id}, closes: __c${id} } : null);\n`;
733
- result += `${acc} += "<!--\u27e6i:" + __i${id} + "\u27e7-->";\n`;
734
- result += `{ const __r = ${closes}[__i${id}](); if (__r) ${acc} += __r.html; }\n`;
735
- result += `${acc} += "<!--\u27e6/i:" + __i${id} + "\u27e7-->";\n`;
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
+ result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ''});\n`;
736
1167
  } else {
737
1168
  result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
738
1169
  }
@@ -741,18 +1172,16 @@ function compileTemplate(
741
1172
  const [, items, item, content] = earliest.match;
742
1173
  const before = remaining.substring(0, earliest.index);
743
1174
  if (before) result += emitChunk(before, acc, closes, scope);
744
- const call = items.trim().endsWith('()') ? items.trim() : `${items.trim()}()`;
1175
+ const call = autoCall(items);
745
1176
  const id = nextId();
746
- // Rename the item variable to the block's scope parameter
747
- const scoped = content.trim().replace(new RegExp(`\\b${item}\\b`, 'g'), '__s');
748
- const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, markers);
1177
+ // Rename the item variable to the block's scope parameter - INSIDE EXPRESSIONS ONLY.
1178
+ const itemRe = new RegExp(`\\b${item}\\b`, 'g');
1179
+ const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) =>
1180
+ `{${expr.replace(itemRe, '__s')}}`);
1181
+ const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, markers, comps);
749
1182
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
750
1183
  if (markers) {
751
- result += `const __i${id} = ${closes}.length;\n`;
752
- result += `${closes}.push(() => (${call}).map((${item}) => { const __c = []; return { html: __b${id}(${item}, __c), closes: __c, scope: ${item} }; }));\n`;
753
- result += `${acc} += "<!--\u27e6l:" + __i${id} + "\u27e7-->";\n`;
754
- result += `${closes}[__i${id}]().forEach((__r) => { ${acc} += __r.html; });\n`;
755
- result += `${acc} += "<!--\u27e6/l:" + __i${id} + "\u27e7-->";\n`;
1184
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});\n`;
756
1185
  } else {
757
1186
  result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');\n`;
758
1187
  }
@@ -764,12 +1193,64 @@ function compileTemplate(
764
1193
  const id = nextId();
765
1194
  // Error boundary: the content renders into its OWN string and is only appended on
766
1195
  // success - a throw anywhere inside swaps in the fallback …
767
- const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers);
1196
+ const catchesAction = /\$action:|<form[\s>]/.test(content);
1197
+ const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers, comps);
768
1198
  result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
769
1199
  result += `let __bd${id} = '';\n`;
770
- result += `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
1200
+ result += catchesAction
1201
+ ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }\n`
1202
+ : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
771
1203
  result += `${acc} += __bd${id};\n`;
772
1204
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1205
+ } else if (earliest.type === 'comp') {
1206
+ // <Card prop={x}>...</Card> -> Card(closes, children, props, slots).
1207
+ const tag = earliest.tag!;
1208
+ if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
1209
+ const entry = comps.get(tag.name)!;
1210
+ const id = nextId();
1211
+ let childrenSrc = '';
1212
+ let rest: string;
1213
+ if (tag.selfClosing) {
1214
+ rest = remaining.substring(tag.end);
1215
+ } else {
1216
+ const closeIdx = findClose(remaining, tag.end, tag.name);
1217
+ if (closeIdx < 0) throw new Error(`unclosed <${tag.name}> - every component tag needs its matching close tag`);
1218
+ childrenSrc = remaining.substring(tag.end, closeIdx);
1219
+ rest = remaining.substring(closeIdx + tag.name.length + 3);
1220
+ }
1221
+ 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
+ const hasChildren = def.trim().length > 0;
1225
+ if (hasChildren) {
1226
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1, markers, comps)} return h; };\n`;
1227
+ }
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
+ const slotFns = named.map(([nm, src]) => {
1231
+ const decl = entry.slots.find((s) => s.name === nm);
1232
+ let content = src;
1233
+ for (const p of decl?.props ?? []) {
1234
+ content = content.replace(/\{([^{}]*)\}/g, (whole, expr) =>
1235
+ `{${expr.replace(new RegExp(`\\b${p}\\b`, 'g'), `__s.${p}`)}}`);
1236
+ }
1237
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1, markers, comps)} return h; }`;
1238
+ });
1239
+ const propsObj = parseCompAttrs(tag.attrs)
1240
+ .filter((a) => a.name !== 'slot')
1241
+ .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
+ const key = a.name.startsWith('on:') ? `on${capitalize(a.name.slice(3))}` : a.name;
1245
+ const val = a.kind === 'expr' ? `(${a.value})` : a.kind === 'str' ? JSON.stringify(a.value) : 'true';
1246
+ return `${JSON.stringify(key)}: ${val}`;
1247
+ })
1248
+ .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
+ const childrenArg = hasChildren ? `__ch${id}(${scope ?? 'undefined'}, ${closes})` : `''`;
1252
+ result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(', ')} });\n`;
1253
+ remaining = rest;
773
1254
  } else {
774
1255
  const [, expr] = earliest.match;
775
1256
  const trimmed = expr.trim();
@@ -780,6 +1261,17 @@ function compileTemplate(
780
1261
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
781
1262
  continue;
782
1263
  }
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
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
1267
+ if (slotCall) {
1268
+ 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
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);\n`;
1272
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1273
+ continue;
1274
+ }
783
1275
  // attr={expr} -> reactive attribute; otherwise a text marker
784
1276
  const attrMatch = before.match(/([\w-]+)=\s*$/);
785
1277
  if (attrMatch) {
@@ -788,7 +1280,11 @@ function compileTemplate(
788
1280
  result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
789
1281
  } else {
790
1282
  if (before) result += emitChunk(before, acc, closes, scope);
791
- result += emitText(trimmed, acc, closes, scope, markers);
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
+ const after = remaining.substring(earliest.index + earliest.match[0].length);
1286
+ const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith('{');
1287
+ result += emitText(trimmed, acc, closes, scope, markers, pair);
792
1288
  }
793
1289
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
794
1290
  }
@@ -797,6 +1293,221 @@ function compileTemplate(
797
1293
  return result;
798
1294
  }
799
1295
 
1296
+ /** One component tag found in a template . */
1297
+ interface CompTag {
1298
+ /** index of `<` in the searched string */
1299
+ start: number;
1300
+ /** index just past `>` */
1301
+ end: number;
1302
+ name: string;
1303
+ /** the raw attribute text between the tag name and `>` */
1304
+ attrs: string;
1305
+ selfClosing: boolean;
1306
+ }
1307
+
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
+ */
1313
+ function scanTagEnd(src: string, start: number): number {
1314
+ let j = start + 1;
1315
+ let quote = '';
1316
+ let brace = 0;
1317
+ while (j < src.length) {
1318
+ const c = src[j];
1319
+ if (quote) {
1320
+ if (c === quote) quote = '';
1321
+ } else if (c === '"' || c === "'") quote = c;
1322
+ else if (c === '{') brace++;
1323
+ else if (c === '}') brace = Math.max(0, brace - 1);
1324
+ else if (c === '>' && brace === 0) return j + 1;
1325
+ j++;
1326
+ }
1327
+ return -1;
1328
+ }
1329
+
1330
+ /** The earliest open tag whose name is an imported component . */
1331
+ function findCompTag(src: string, comps: Map<string, unknown>): CompTag | null {
1332
+ let i = 0;
1333
+ while (i < src.length) {
1334
+ const lt = src.indexOf('<', i);
1335
+ if (lt < 0) return null;
1336
+ const nm = /^<([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
1337
+ if (nm && comps.has(nm[1])) {
1338
+ const end = scanTagEnd(src, lt);
1339
+ if (end > 0) {
1340
+ const raw = src.slice(lt, end);
1341
+ const selfClosing = /\/>$/.test(raw);
1342
+ return { start: lt, end, name: nm[1], attrs: raw.slice(1 + nm[1].length, selfClosing ? -2 : -1), selfClosing };
1343
+ }
1344
+ }
1345
+ i = lt + 1;
1346
+ }
1347
+ return null;
1348
+ }
1349
+
1350
+ /** Index of the `</name>` that closes the tag opened before `from` (-1: none). */
1351
+ function findClose(src: string, from: number, name: string): number {
1352
+ const re = new RegExp(`<(/?)${name}(?=[\\s/>])`, 'g');
1353
+ re.lastIndex = from;
1354
+ let depth = 1;
1355
+ let m: RegExpExecArray | null;
1356
+ while ((m = re.exec(src))) {
1357
+ const end = scanTagEnd(src, m.index);
1358
+ if (end < 0) return -1;
1359
+ if (m[1] === '/') {
1360
+ depth--;
1361
+ if (depth === 0) return m.index;
1362
+ } else if (!/\/>$/.test(src.slice(m.index, end))) depth++;
1363
+ }
1364
+ return -1;
1365
+ }
1366
+
1367
+ interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool'; value: string }
1368
+
1369
+ /** Parse a component tag's attributes into prop={expr} / prop="lit" / bool. */
1370
+ function parseCompAttrs(attrs: string): CompAttr[] {
1371
+ const out: CompAttr[] = [];
1372
+ let i = 0;
1373
+ while (i < attrs.length) {
1374
+ const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
1375
+ if (!nm) break;
1376
+ i += nm[0].length;
1377
+ const eq = /^\s*=\s*/.exec(attrs.slice(i));
1378
+ if (!eq) {
1379
+ out.push({ name: nm[1], kind: 'bool', value: '' });
1380
+ continue;
1381
+ }
1382
+ i += eq[0].length;
1383
+ const ch = attrs[i];
1384
+ if (ch === '{') {
1385
+ let depth = 1;
1386
+ let j = i + 1;
1387
+ while (j < attrs.length && depth > 0) {
1388
+ if (attrs[j] === '{') depth++;
1389
+ else if (attrs[j] === '}') depth--;
1390
+ j++;
1391
+ }
1392
+ out.push({ name: nm[1], kind: 'expr', value: attrs.slice(i + 1, j - 1).trim() });
1393
+ i = j;
1394
+ } else if (ch === '"' || ch === "'") {
1395
+ const j = attrs.indexOf(ch, i + 1);
1396
+ out.push({ name: nm[1], kind: 'str', value: attrs.slice(i + 1, j < 0 ? attrs.length : j) });
1397
+ i = j < 0 ? attrs.length : j + 1;
1398
+ } else break;
1399
+ }
1400
+ return out;
1401
+ }
1402
+
1403
+ /**
1404
+ * Reject a slot= that hides inside a named slot's content. The child only
1405
+ * ever looks at its DIRECT named children, so `<span slot="a"><b slot="a">`
1406
+ * would silently drop the inner one - say it at build time instead. The walk
1407
+ * is quote-aware (scanTagEnd), so an attribute value containing '>' cannot
1408
+ * fake a tag.
1409
+ */
1410
+ function rejectNestedSlot(src: string, outer: string): void {
1411
+ let i = 0;
1412
+ while (i < src.length) {
1413
+ const lt = src.indexOf('<', i);
1414
+ if (lt < 0) return;
1415
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
1416
+ if (!nm) { i = lt + 1; continue; }
1417
+ const end = scanTagEnd(src, lt);
1418
+ if (end < 0) return;
1419
+ const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
1420
+ if (hit && nm[1] !== '/') {
1421
+ throw new Error(`slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`);
1422
+ }
1423
+ i = end;
1424
+ }
1425
+ }
1426
+
1427
+ /**
1428
+ * Split a component's children into the default slot and the named slots
1429
+ * (`<li slot="row">`). Only DIRECT children may be slot content: lifting an
1430
+ * element out of another element, or out of an {#if}/{#each} block, would
1431
+ * break the template around it - so that is a build error, not a silent
1432
+ * mis-render.
1433
+ */
1434
+ function splitSlots(src: string): { def: string; named: Array<[string, string]> } {
1435
+ let def = '';
1436
+ const named = new Map<string, string>();
1437
+ let i = 0;
1438
+ let elemDepth = 0;
1439
+ let blockDepth = 0;
1440
+ while (i < src.length) {
1441
+ const lt = src.indexOf('<', i);
1442
+ const ob = src.indexOf('{#', i);
1443
+ const cb = src.indexOf('{/', i);
1444
+ const cands = [lt, ob, cb].filter((x) => x >= 0);
1445
+ if (cands.length === 0) {
1446
+ def += src.slice(i);
1447
+ break;
1448
+ }
1449
+ const next = Math.min(...cands);
1450
+ if (next > i) def += src.slice(i, next);
1451
+ if (next === ob || next === cb) {
1452
+ const close = src.indexOf('}', next);
1453
+ const token = src.slice(next, close < 0 ? src.length : close + 1);
1454
+ if (next === ob) blockDepth++;
1455
+ else blockDepth = Math.max(0, blockDepth - 1);
1456
+ def += token;
1457
+ i = next + token.length;
1458
+ continue;
1459
+ }
1460
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(next, next + 64));
1461
+ if (!nm) {
1462
+ def += '<';
1463
+ i = next + 1;
1464
+ continue;
1465
+ }
1466
+ const end = scanTagEnd(src, next);
1467
+ if (end < 0) {
1468
+ def += src.slice(next);
1469
+ break;
1470
+ }
1471
+ const tagText = src.slice(next, end);
1472
+ const selfClosing = /\/>$/.test(tagText);
1473
+ const isVoid = VOID_TAGS.has(nm[2].toLowerCase());
1474
+ if (nm[1] === '/') {
1475
+ elemDepth = Math.max(0, elemDepth - 1);
1476
+ def += tagText;
1477
+ i = end;
1478
+ continue;
1479
+ }
1480
+ if (!selfClosing && !isVoid) elemDepth++;
1481
+ const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
1482
+ if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
1483
+ throw new Error(`slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`);
1484
+ }
1485
+ if (slotName) {
1486
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '');
1487
+ if (selfClosing || isVoid) {
1488
+ named.set(slotName, (named.get(slotName) ?? '') + stripped);
1489
+ } else {
1490
+ const closeIdx = findClose(src, end, nm[2]);
1491
+ if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
1492
+ const tail = `</${nm[2]}>`;
1493
+ 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
+ rejectNestedSlot(inner, slotName);
1497
+ named.set(slotName, (named.get(slotName) ?? '') + stripped + inner + tail);
1498
+ elemDepth = Math.max(0, elemDepth - 1);
1499
+ i = closeIdx + tail.length;
1500
+ continue;
1501
+ }
1502
+ i = end;
1503
+ continue;
1504
+ }
1505
+ def += tagText;
1506
+ i = end;
1507
+ }
1508
+ return { def, named: [...named.entries()] };
1509
+ }
1510
+
800
1511
  /** Emit a static chunk (attributes are handled by the expr branch). */
801
1512
  function emitChunk(text: string, acc: string, closes: string, scope: string | null): string {
802
1513
  if (!text) return '';
@@ -816,7 +1527,7 @@ const IMG_MIME: Record<string, string> = {
816
1527
  '.svg': 'image/svg+xml',
817
1528
  '.ico': 'image/x-icon',
818
1529
  };
819
- // ponytail: fixed 4 KB cap; make it configurable when a real app cares
1530
+ // Trade-off: fixed 4 KB cap; make it configurable when a real app cares
820
1531
  const INLINE_IMG_MAX = 4096;
821
1532
 
822
1533
  function inlineImages(template: string, publicDir: string): string {
@@ -841,23 +1552,31 @@ function inlineImages(template: string, publicDir: string): string {
841
1552
  });
842
1553
  }
843
1554
 
844
- /** Emit a reactive text marker: <!--⟦m:K⟧-->escaped value. */
845
- function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
846
- const arg = scope ? `${scope}` : '';
1555
+ /**
1556
+ * Emit a reactive text marker through the runtime's textMark(): the helper
1557
+ * pushes the closure and returns the marker pair around the escaped value.
1558
+ * A marker whose value is followed by literal text passes pair, so the wire
1559
+ * can bound exactly the value and leave the prose alone.
1560
+ */
1561
+ function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true, pair = false): string {
847
1562
  if (!markers) {
848
1563
  // head block: inline escaped value, no marker comment (clean SSR html)
849
1564
  return `${acc} += esc(${expr});\n`;
850
1565
  }
851
- return `${acc} += "<!--\u27e6m:" + (${closes}.push(${scope ? `(${scope})` : '()'} => (${expr})) - 1) + "\u27e7-->" + esc(${closes}[${closes}.length - 1](${arg}));\n`;
1566
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1567
+ let extra = pair ? ', 1' : scope ? ', 0' : '';
1568
+ if (scope) extra += `, ${scope}`;
1569
+ return `${acc} += textMark(${closes}, ${fn}${extra});\n`;
852
1570
  }
853
1571
 
854
- /** Emit a reactive attribute: name="value" data-b="K:name". */
1572
+ /** Emit a reactive attribute through the runtime's attrMark(). */
855
1573
  function emitAttr(attr: string, expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
856
1574
  if (!markers) {
857
1575
  return `${acc} += '${attr}="' + esc(${expr}) + '"';\n`;
858
1576
  }
859
- const arg = scope ? `${scope}` : '';
860
- return `${acc} += '${attr}="' + esc(${closes}[${closes}.push(${scope ? `(${scope})` : '()'} => (${expr})) - 1](${arg})) + '" data-b="' + (${closes}.length - 1) + ':${attr}"';\n`;
1577
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1578
+ const arg = scope ? `, ${scope}` : '';
1579
+ return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
861
1580
  }
862
1581
 
863
1582
  /**
@@ -868,26 +1587,75 @@ function compileSlot(acc: string): string {
868
1587
  return `${acc} += String(children);\n`;
869
1588
  }
870
1589
 
871
- function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = ''): string {
1590
+ // The runtime's public surface, as one import line. Three generators emit it (page SSR,
1591
+ // page client, the middleware module) …
1592
+ const RUNTIME_IMPORTS = `import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark } from './runtime.js';`;
1593
+
1594
+ /**
1595
+ * `export let title = 'x'` -> a per-invocation const read from the
1596
+ * caller's props object, defaulting to the declared value. Emitted at the top
1597
+ * of render(), BEFORE the state declarations: a prop may seed one
1598
+ * (`let open = $state(collapsed)`).
1599
+ */
1600
+ function propsCode(props: Array<{ name: string; def: string | null }>): string {
1601
+ if (props.length === 0) return '';
1602
+ return props
1603
+ .map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ''};`)
1604
+ .join('\n');
1605
+ }
1606
+
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
+ const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1610
+ const fn = sl[name];
1611
+ if (typeof fn !== 'function') return null;
1612
+ const o = {};
1613
+ for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1614
+ return { o, fn };
1615
+ };
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
+ };`;
1626
+
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 {
872
1628
  // The head block renders to a clean html string (no markers) and is wrapped in an h
873
1629
  // marker pair: renderPage extracts it for <head> injection …
874
1630
  const headCode = headFn
875
1631
  ? `
876
1632
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
877
- const __hi = closes.length;
878
- closes.push(__head);
879
- __html += "<!--\u27e6h:" + __hi + "\u27e7-->" + __head() + "<!--\u27e6/h:" + __hi + "\u27e7-->";`
1633
+ __html += headMark(closes, __head);`
880
1634
  : '';
1635
+ // A page's render is async ($data awaits); a component's is not - its parent calls it
1636
+ // inside a string concatenation (`h += Card(...)`) …
881
1637
  return `
882
- import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, $cookies, $sessionCookie, $store } from './runtime.js';
1638
+ ${RUNTIME_IMPORTS}
1639
+
1640
+ ${imports}
883
1641
 
884
1642
  ${exports}
1643
+ ${guard}
1644
+
1645
+ ${namedSlots ? SLOT_HELPER : ''}
885
1646
 
886
- export async function render(closes, children) {
1647
+ export ${isComponent ? 'function' : 'async function'} render(closes, children, __props, __slots) {
1648
+ ${props.length > 0 ? 'const __p = __props || {};' : ''}
1649
+ ${namedSlots ? 'const __sl = __slots || {};' : ''}
1650
+ ${propsCode(props)}
887
1651
  ${stateDeclsCode}
1652
+ // The incremental patches of the action that produced THIS response,
1653
+ // applied to the state the declarations above just established (a no-op on
1654
+ // every path that is not a server action's re-render - see the runtime).
1655
+ ${isComponent ? '' : 'applyStateDeltas();'}
888
1656
  ${script}
889
1657
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
890
- let __html = await __root(closes, children);${headCode}
1658
+ let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
891
1659
  return __html;
892
1660
  }
893
1661
  `;
@@ -899,34 +1667,41 @@ function generateClient(
899
1667
  stateDeclsCode: string,
900
1668
  eventBindings: Array<{ event: string; fn: string }>,
901
1669
  exports = '',
902
- headFn = ''
1670
+ headFn = '',
1671
+ props: Array<{ name: string; def: string | null }> = [],
1672
+ namedSlots = false,
1673
+ imports = '',
1674
+ isComponent = false
903
1675
  ): string {
904
- // Handlers live on a shared global so one delegated listener per event
905
- // type can dispatch for any component, including freshly cloned nodes.
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.
906
1678
  const handlerRegistry = eventBindings.length > 0
907
- ? `Object.assign(__handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
1679
+ ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
908
1680
  : '';
909
1681
  const headCode = headFn
910
1682
  ? `
911
1683
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
912
- const __hi = closes.length;
913
- closes.push(__head);
914
- __html += "<!--\u27e6h:" + __hi + "\u27e7-->" + __head() + "<!--\u27e6/h:" + __hi + "\u27e7-->";`
1684
+ __html += headMark(closes, __head);`
915
1685
  : '';
916
1686
 
917
1687
  return `
918
- import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, $cookies, $sessionCookie, $store } from './runtime.js';
1688
+ ${RUNTIME_IMPORTS}
1689
+
1690
+ ${imports}
919
1691
 
920
1692
  ${exports}
921
1693
 
922
- const __handlers = globalThis.__rosetack_handlers ?? (globalThis.__rosetack_handlers = {});
1694
+ ${namedSlots ? SLOT_HELPER : ''}
923
1695
 
924
- export async function render(closes, children) {
1696
+ export ${isComponent ? 'function' : 'async function'} render(closes, children, __props, __slots) {
1697
+ ${props.length > 0 ? 'const __p = __props || {};' : ''}
1698
+ ${namedSlots ? 'const __sl = __slots || {};' : ''}
1699
+ ${propsCode(props)}
925
1700
  ${stateDeclsCode}
926
1701
  ${script}
927
1702
  ${handlerRegistry}
928
1703
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
929
- let __html = await __root(closes, children);${headCode}
1704
+ let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
930
1705
  return __html;
931
1706
  }
932
1707
  `;
@@ -943,7 +1718,7 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
943
1718
  .map(({ i }) => i);
944
1719
 
945
1720
  /**
946
- * Innovation #29's decision as a pure function: does this route's document
1721
+ * 's decision as a pure function: does this route's document
947
1722
  * ship without the client bundle? Shared by the route table (csr: false) and
948
1723
  * the build report (#31), so the report can never disagree with the build.
949
1724
  */
@@ -956,7 +1731,7 @@ const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number
956
1731
  };
957
1732
 
958
1733
  /**
959
- * The build's zero-JS lint report (innovation #31): one line per route with
1734
+ * The build's zero-JS lint report: one line per route with
960
1735
  * its verdict and the exact reason - which component in the chain needs the
961
1736
  * client bundle and why, or that nothing does. Pure: the same inputs the
962
1737
  * route table is built from.
@@ -964,8 +1739,8 @@ const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number
964
1739
  export function buildReport(infos: RouteInfo[], compiled: CompileResult[]): string[] {
965
1740
  return infos
966
1741
  .map((info, i) => ({ info, i }))
967
- .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware)
968
- .map(({ info, i }) => {
1742
+ .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
1743
+ .map(({ info, i }) => {
969
1744
  if (routeShipsNoJs(infos, compiled, i)) {
970
1745
  return `${info.routePath} zero-JS nothing in the chain needs the client`;
971
1746
  }
@@ -987,31 +1762,92 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
987
1762
  /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
988
1763
  await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
989
1764
 
990
- const files = await scanRoseFiles(root);
991
- // Phase 0: a build that silently produces nothing is the worst possible failure mode (an
992
- // empty dist/ deploys as a blank site).
993
- if (files.length === 0) {
1765
+ const pageFiles = await scanRoseFiles(root);
1766
+ const compFiles = await scanComponentFiles(root);
1767
+ 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
+ if (pageFiles.length === 0) {
994
1771
  throw new Error(`no .rose pages found under ${path.join(root, 'src', 'pages')} - run rosetack from a project root, or pass one: rosetack build <dir>`);
995
1772
  }
996
1773
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
997
- // Plugins (innovation #30): rosetack.config.js at the project root, loaded
998
- // fresh per build so the dev server's hot rebuild picks up config edits.
999
- const plugins = await loadPlugins(root);
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
+ const config = await loadConfig(root);
1777
+ const plugins = config.plugins;
1000
1778
  // scope key: the component's path under pages/ (index, _layout, blog/[id])
1001
- const scopeKeys = files.map((f) =>
1002
- path.relative(path.join(root, 'src', 'pages'), f).replace(/\\/g, '/').replace(/\.rose$/, ''));
1779
+ const scopeKeys = files.map((f, i) => {
1780
+ const base = infos[i].isComponent ? path.join(root, 'src') : path.join(root, 'src', 'pages');
1781
+ return path.relative(base, f).replace(/\\/g, '/').replace(/\.rose$/, '');
1782
+ });
1783
+ // The build-wide import registry: absolute path -> module index, scope key, and the named
1784
+ // slots the component declares.
1785
+ const registry: RoseRegistry = new Map(
1786
+ files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1787
+ );
1003
1788
  const compiled = await Promise.all(
1004
- files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins))
1789
+ files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
1005
1790
  );
1006
1791
 
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
+ const importsOf = new Map<number, number[]>();
1795
+ files.forEach((_, i) => {
1796
+ const list: number[] = [];
1797
+ for (const r of compiled[i].roseImports ?? []) {
1798
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1799
+ const hit = registry.get(abs);
1800
+ if (hit) list.push(hit.index);
1801
+ }
1802
+ importsOf.set(i, list);
1803
+ });
1804
+ // The walk reports WHICH dependency needs the client, so the build's lint
1805
+ // line names the component instead of the page.
1806
+ const needyDep = (i: number, seen = new Set<number>()): string | null => {
1807
+ if (compiled[i].needsClient) return path.basename(files[i]);
1808
+ if (seen.has(i)) return null;
1809
+ seen.add(i);
1810
+ for (const dep of importsOf.get(i) ?? []) {
1811
+ const hit = needyDep(dep, seen);
1812
+ if (hit) return hit;
1813
+ }
1814
+ return null;
1815
+ };
1816
+ compiled.forEach((c, i) => {
1817
+ if (c.needsClient) return;
1818
+ const who = needyDep(i);
1819
+ if (who) {
1820
+ c.needsClient = true;
1821
+ c.clientReasons = [...(c.clientReasons ?? []), `imported component ${who} needs the client`];
1822
+ }
1823
+ });
1824
+
1825
+ // Reachability: a component no page (transitively) imports ships in neither
1826
+ // bundle - not the server's, not the client's.
1827
+ const reachable = new Set<number>();
1828
+ const visit = (i: number) => {
1829
+ if (reachable.has(i)) return;
1830
+ reachable.add(i);
1831
+ for (const r of compiled[i].roseImports ?? []) {
1832
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1833
+ const hit = registry.get(abs);
1834
+ if (hit) visit(hit.index);
1835
+ }
1836
+ };
1837
+ files.forEach((_, i) => {
1838
+ if (!infos[i].isComponent) visit(i);
1839
+ });
1840
+
1007
1841
  // Every component's scoped CSS in one stylesheet, inlined into the shell:
1008
1842
  // styles ship inside the document like the JS bundle - zero requests.
1009
- const styles = compiled.map((c) => c.style).filter(Boolean).join('\n');
1843
+ const styles = compiled
1844
+ .map((c, i) => (reachable.has(i) ? c.style : ''))
1845
+ .filter(Boolean).join('\n');
1010
1846
  if (styles) await fs.promises.writeFile(path.join(outDir, 'styles.css'), styles);
1011
1847
  else await fs.promises.rm(path.join(outDir, 'styles.css'), { force: true });
1012
1848
 
1013
- // i18n (innovation #27): every JSON file in src/locales/ is a language. The dictionaries
1014
- // are baked into BOTH bundles at build time …
1849
+ // i18n: every JSON file in src/locales/ is a language. The dictionaries are baked into
1850
+ // BOTH bundles at build time …
1015
1851
  let locales: Record<string, Record<string, string>> = {};
1016
1852
  try {
1017
1853
  for (const f of await fs.promises.readdir(path.join(root, 'src', 'locales'))) {
@@ -1024,15 +1860,56 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1024
1860
  const defaultLocale = locales.en ? 'en' : Object.keys(locales).sort()[0] ?? 'en';
1025
1861
  const localesJson = JSON.stringify(locales).replace(/</g, '\\u003c');
1026
1862
 
1863
+ // Which dictionaries ride in the CLIENT bundle. Default: all of them, so a locale switch
1864
+ // stays a zero-request navigation.
1865
+ const preload: string[] = config.i18n.preload ?? Object.keys(locales);
1866
+ const packed = Object.keys(locales).filter((l) => !preload.includes(l));
1867
+ for (const l of preload) {
1868
+ if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
1869
+ }
1870
+ await fs.promises.rm(path.join(outDir, 'locales'), { recursive: true, force: true });
1871
+ if (packed.length > 0) {
1872
+ const packDir = path.join(outDir, 'locales');
1873
+ await fs.promises.mkdir(packDir, { recursive: true });
1874
+ for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
1875
+ }
1876
+ const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
1877
+ const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, '\\u003c');
1878
+
1027
1879
  // Intermediates (component modules, shared runtime, bundle entries) live in a build dir
1028
1880
  // that is removed before returning: both bundles are fully self-contained …
1029
1881
  const buildDir = path.join(outDir, '.build');
1030
1882
  await fs.promises.rm(buildDir, { recursive: true, force: true });
1031
1883
  await fs.promises.mkdir(buildDir, { recursive: true });
1032
1884
 
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
+ const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1888
+ if (runtimePlugins.length > 0) {
1889
+ // Relative from .build/, so the build works from any cwd (`rosetack build <dir>` from
1890
+ // elsewhere).
1891
+ const configRel = path.relative(buildDir, path.join(root, 'rosetack.config.js')).replace(/\\/g, '/');
1892
+ await fs.promises.writeFile(path.join(buildDir, 'plugins.js'), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
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.
1895
+ import config from ${JSON.stringify(configRel)};
1896
+
1897
+ const list = Array.isArray(config) ? config : [];
1898
+ export const hooks = list
1899
+ .filter((p) => p && (p.onRequest || p.onResponse))
1900
+ .map((p) => ({ name: p.name, onRequest: p.onRequest ? p.onRequest.bind(p) : null, onResponse: p.onResponse ? p.onResponse.bind(p) : null }));
1901
+
1902
+ export const hasRequestHooks = hooks.some((p) => p.onRequest);
1903
+ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1904
+ `);
1905
+ }
1906
+
1033
1907
  // Shared runtime module, bundled once into client and server output. The runtime ships
1034
1908
  // WITH THE COMPILER …
1035
- const runtimeEntry = fileURLToPath(new URL('../runtime/index.ts', import.meta.url));
1909
+ const runtimeEntry = ['../runtime/index.ts', '../src/runtime/index.ts']
1910
+ .map((rel) => fileURLToPath(new URL(rel, import.meta.url)))
1911
+ .find((p) => fs.existsSync(p));
1912
+ if (!runtimeEntry) throw new Error('rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler');
1036
1913
  await esbuild.build({
1037
1914
  entryPoints: [runtimeEntry],
1038
1915
  bundle: true,
@@ -1054,7 +1931,7 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1054
1931
 
1055
1932
  const pages = infos
1056
1933
  .map((info, i) => ({ info, i }))
1057
- .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware);
1934
+ .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1058
1935
 
1059
1936
  // API routes (pages/api/*.rose) dispatch handlers, never render HTML: they live in the
1060
1937
  // server bundle only and are excluded from the client route table entirely.
@@ -1071,7 +1948,8 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1071
1948
  return expr;
1072
1949
  };
1073
1950
 
1074
- // P0 §1 (consultant report): mode B. `export const bundle = 'split'` …
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 …
1075
1953
  const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? 'inline';
1076
1954
  const split = bundleMode === 'split';
1077
1955
  // The chain a route's chunk graph must load: the page first, then its layouts
@@ -1083,12 +1961,13 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1083
1961
  `load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(', ')}])`;
1084
1962
  const loaderOf = (idx: number): string => `{ ${loaderInner(idx)} }`;
1085
1963
 
1086
- // Innovation #29: the compiler decides zero-JS, not the developer. A route ships no
1087
- // client bundle - no runtime, no state script, zero JavaScript …
1964
+ // The compiler decides zero-JS, not the developer. A route ships no client bundle - no
1965
+ // runtime, no state script, zero JavaScript …
1088
1966
  const routeNoJs = (i: number): boolean => routeShipsNoJs(infos, compiled, i);
1089
1967
 
1090
1968
  const serverImports = compiled
1091
1969
  .map((_, i) => {
1970
+ if (!reachable.has(i)) return ''; // an unimported component ships nowhere
1092
1971
  if (infos[i].isMiddleware) {
1093
1972
  // pages/_middleware.rose: server-only, imported as a namespace so a missing
1094
1973
  // `handle` export is simply "no middleware" (null), never a build error
@@ -1107,8 +1986,11 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1107
1986
  const isPage = !infos[i].isLayout && !infos[i].isNotFound;
1108
1987
  const names = isPage ? compiled[i].actionNames : [];
1109
1988
  const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
1110
- return names.length > 0
1111
- ? `import { render as render_${i}, ${actionImports} } from './comp-${i}.ssr.js';`
1989
+ // The action guard rides the same import, server-only like the actions it fronts
1990
+ const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : '';
1991
+ const named = [actionImports, guardImport].filter(Boolean).join(', ');
1992
+ return named
1993
+ ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';`
1112
1994
  : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1113
1995
  })
1114
1996
  .join('\n');
@@ -1131,7 +2013,13 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1131
2013
  // actions: name -> imported fn, so a POST's __action field …
1132
2014
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(', ');
1133
2015
  // csr: false rides on the route so renderPage/renderPageStream can drop the state
1134
- // script + bundle from the document …
2016
+ // script + bundle from the document (; the decision is the compiler's since #29).
2017
+ if (compiled[i].csr === false && compiled[i].needsClient) {
2018
+ throw new Error(
2019
+ `${info.filePath}: csr = false but this route needs the client bundle ` +
2020
+ `(${(compiled[i].clientReasons ?? ['needs the client']).join(' + ')}).`
2021
+ );
2022
+ }
1135
2023
  if (compiled[i].csr === false) {
1136
2024
  const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1137
2025
  if (needy !== undefined) {
@@ -1142,20 +2030,69 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1142
2030
  }
1143
2031
  }
1144
2032
  const csrFlag = routeNoJs(i) ? ', csr: false' : '';
1145
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${csrFlag} }`;
2033
+ // Guard - runs before every action of this route (null when the
2034
+ // page exports no beforeAction)
2035
+ 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} }`;
1146
2037
  })
1147
2038
  .join(',\n ');
1148
2039
 
1149
2040
  const serverEntry = `
1150
2041
  ${serverImports}
1151
- import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, setStoreTransport, applyStorePatch } from './runtime.js';
2042
+ import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
2043
+ ${runtimePlugins.length > 0
2044
+ ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
2045
+ : `// no plugin declares a runtime hook, so there is no plugins
2046
+ // module to import - the runners below stay no-ops and the servers call them
2047
+ // unconditionally (one code path, no flags to keep in sync).
2048
+ const __pluginHooks = [];
2049
+ const __hasRequestHooks = false;
2050
+ const __hasResponseHooks = false;`}
2051
+
2052
+ // The runtime plugin hooks. onRequest runs before routing and
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).
2058
+ export async function runRequestHooks(ctx) {
2059
+ for (const p of __pluginHooks) {
2060
+ if (!p.onRequest) continue;
2061
+ try {
2062
+ const r = await p.onRequest(ctx);
2063
+ if (r instanceof Response) return r;
2064
+ } catch (err) {
2065
+ console.error('rosetack: plugin', p.name, 'onRequest failed:', err instanceof Error ? err.message : err);
2066
+ }
2067
+ }
2068
+ return null;
2069
+ }
1152
2070
 
1153
- // i18n (innovation #27): the dictionaries baked at build time from
2071
+ export async function runResponseHooks(ctx, res) {
2072
+ let out = res;
2073
+ for (const p of __pluginHooks) {
2074
+ if (!p.onResponse) continue;
2075
+ try {
2076
+ const r = await p.onResponse(ctx, out);
2077
+ if (r instanceof Response) out = r;
2078
+ } catch (err) {
2079
+ console.error('rosetack: plugin', p.name, 'onResponse failed:', err instanceof Error ? err.message : err);
2080
+ }
2081
+ }
2082
+ return out;
2083
+ }
2084
+
2085
+ // The servers read these to skip building the hook context entirely when no
2086
+ // hook exists - the hot path pays nothing for the feature.
2087
+ export const hasRequestHooks = __hasRequestHooks;
2088
+ export const hasResponseHooks = __hasResponseHooks;
2089
+
2090
+ // i18n: the dictionaries baked at build time from
1154
2091
  // src/locales/*.json. A route segment named [lang] is the locale: the value
1155
2092
  // must name one of these dictionaries, and $t resolves keys against it.
1156
2093
  setLocales(${localesJson}, '${defaultLocale}');
1157
2094
 
1158
- // Phase 2: the store transport. Under "rosetack serve" every worker is its
2095
+ // The store transport. Under "rosetack serve" every worker is its
1159
2096
  // own process with its own dist/server.js module, so a $store write must
1160
2097
  // travel: this worker -> primary -> every other worker. process.send exists
1161
2098
  // only inside cluster workers, so a single-process runner (dev, preview,
@@ -1183,12 +2120,14 @@ export const routeParams = {
1183
2120
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(',\n ')}
1184
2121
  };
1185
2122
 
1186
- // Routes whose component reads the request context (getContext()): the bag
1187
- // is per-request, so these are dynamic - the build never bakes them and the
1188
- // servers never answer them from a prerendered file. Public routes keep the
1189
- // static fast path (file cache, ETag/304, streaming) untouched.
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.
1190
2129
  export const dynamicRoutes = [
1191
- ${pages.filter(({ i }) => compiled[i].usesContext).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2130
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
1192
2131
  ];
1193
2132
 
1194
2133
  // Which api routes opt into build-time baking (export const prerender = true):
@@ -1204,7 +2143,7 @@ export const apiPrerender = {
1204
2143
  // bakes these routes like any other, and the preview server serves the
1205
2144
  // baked file for up to N seconds - after which the next request is answered
1206
2145
  // STALE (instant, from disk) while a background pass re-renders and swaps
1207
- // the file (ISR, innovation #24). Routes that read the request context are
2146
+ // the file (ISR). Routes that read the request context are
1208
2147
  // excluded: they render per request and have no baked file to revalidate.
1209
2148
  // The dev server ignores the window (it rebuilds on change), the edge
1210
2149
  // adapter renders live (always fresh), and the Go binary serves the baked
@@ -1221,7 +2160,7 @@ export const revalidate = [
1221
2160
  // and the servers keep their static fast paths.
1222
2161
  export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
1223
2162
 
1224
- // Routes whose DOCUMENTS ship without the client bundle (innovation #25,
2163
+ // Routes whose DOCUMENTS ship without the client bundle (
1225
2164
  // decided by the compiler since #29): HTML + CSS only - no runtime, no
1226
2165
  // state script, zero JavaScript for whoever lands on them. The compiler
1227
2166
  // picks these automatically: a route whose whole chain needs nothing from
@@ -1242,7 +2181,7 @@ export function isNoJs(pathname) {
1242
2181
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1243
2182
  }
1244
2183
 
1245
- // Per-route response headers (innovation #26): a route exporting a headers
2184
+ // Per-route response headers: a route exporting a headers
1246
2185
  // map carries them into every response the servers write for it, merged
1247
2186
  // OVER the framework defaults (the strict CSP) - so an app can tighten or
1248
2187
  // relax the policy per route. Absent -> null, and the servers keep sending
@@ -1256,6 +2195,22 @@ export function headersFor(pathname) {
1256
2195
  return hit ? hit.headers : null;
1257
2196
  }
1258
2197
 
2198
+ // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
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.
2206
+ export const cspNonceRoutes = [
2207
+ ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2208
+ ];
2209
+
2210
+ export function cspNonce(pathname) {
2211
+ return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
2212
+ }
2213
+
1259
2214
  // A Web-standard Request from whatever the host provides: the edge adapter
1260
2215
  // passes one already; the Node server passes its IncomingMessage (plus the
1261
2216
  // already-parsed FormData for POSTs, so middleware can read form fields).
@@ -1302,11 +2257,31 @@ const notFound = ${notFoundRender};
1302
2257
  // whose render throws degrades to this instead of failing the response.
1303
2258
  const errorPage = ${errorRender};
1304
2259
 
2260
+ // The <html> attributes of the document for a pathname - the locale
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.
2266
+ export function docAttrs(pathname) {
2267
+ for (const route of routes) {
2268
+ if (!matchRoute(route.pattern, pathname)) continue;
2269
+ const parts = route.pattern.split('/');
2270
+ const langIdx = parts.indexOf(':lang');
2271
+ if (langIdx >= 0) {
2272
+ const lang = pathname.split('/')[langIdx];
2273
+ if (isLocale(lang)) return { lang, dir: localeDir(lang) };
2274
+ }
2275
+ break; // matched, but not a localized route (or a bogus locale): the default
2276
+ }
2277
+ return { lang: defaultLocale, dir: localeDir(defaultLocale) };
2278
+ }
2279
+
1305
2280
  // Paint a fallback page (404/500) and serialize its state.
1306
2281
  async function renderFallback(pathname, render) {
1307
2282
  const { html, head } = extractHead(await render([], ''));
1308
2283
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1309
- return { html, state, head };
2284
+ return { html, state, head, ...docAttrs(pathname) };
1310
2285
  }
1311
2286
 
1312
2287
  export function matchRoute(pattern, pathname) {
@@ -1359,20 +2334,52 @@ export async function renderPage(pathname, form) {
1359
2334
  setState(patternParts[i].slice(1), pathParts[i]);
1360
2335
  }
1361
2336
  }
1362
- // i18n (innovation #27): a [lang] segment naming no dictionary is a
2337
+ // i18n: a [lang] segment naming no dictionary is a
1363
2338
  // 404 - the URL is the contract, and rendering the page with fallback
1364
2339
  // strings would serve duplicate content under a bogus language
1365
2340
  const langIdx = patternParts.indexOf(':lang');
1366
2341
  if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
1367
2342
  if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
1368
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404 };
2343
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1369
2344
  }
2345
+ // The document's <html lang>/<dir> follow this route's locale
2346
+ // (the default's when the route is not localized)
2347
+ 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.
2358
+ let actionStatus = 0;
1370
2359
  if (form && route.actions) {
1371
- const fn = route.actions[form.get('__action') || 'action'];
2360
+ const actionName = form.get('__action') || 'action';
2361
+ const fn = route.actions[actionName];
1372
2362
  if (fn) {
1373
- const patch = await fn(form);
1374
- if (patch && typeof patch === 'object') {
1375
- for (const key of Object.keys(patch)) setState(key, patch[key]);
2363
+ try {
2364
+ if (route.guard) await route.guard(actionName, form);
2365
+ const patch = await fn(form);
2366
+ if (patch && typeof patch === 'object') {
2367
+ for (const key of Object.keys(patch)) {
2368
+ 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.
2372
+ if (v instanceof StateDelta) setStateDelta(key, v);
2373
+ else setState(key, v);
2374
+ }
2375
+ }
2376
+ } catch (err) {
2377
+ if (err instanceof ActionError) {
2378
+ setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
2379
+ actionStatus = err.code;
2380
+ } else {
2381
+ throw err;
2382
+ }
1376
2383
  }
1377
2384
  }
1378
2385
  }
@@ -1382,24 +2389,30 @@ export async function renderPage(pathname, form) {
1382
2389
  } catch (err) {
1383
2390
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1384
2391
  if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
1385
- return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500 };
2392
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
1386
2393
  }
1387
2394
  // __route tells the bootstrap which route this document was rendered for.
1388
2395
  // A static-file server may serve another route's document (SPA fallback);
1389
2396
  // the bootstrap then client-renders instead of adopting mismatched DOM.
1390
2397
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1391
- // csr (innovation #25, auto since #29): false when the compiler found
2398
+ // csr ( auto since #29): false when the compiler found
1392
2399
  // nothing in the route's chain that needs the client (or the route
1393
2400
  // asserted csr = false) - the document ships no runtime, no state
1394
2401
  // script, zero JavaScript. Every other route keeps the bundle. The
1395
2402
  // caller passes this straight to the shell as js.
1396
- return { html: rendered.html, state, head: rendered.head, status: 200, csr: route.csr !== false };
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) };
1397
2410
  }
1398
2411
  }
1399
2412
  if (notFound) {
1400
2413
  return { ...(await renderFallback(pathname, notFound)), status: 404 };
1401
2414
  }
1402
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404 };
2415
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1403
2416
  }
1404
2417
 
1405
2418
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -1407,7 +2420,7 @@ export async function renderPage(pathname, form) {
1407
2420
  export function canStream(pathname) {
1408
2421
  return routes.some((route) => {
1409
2422
  if (!matchRoute(route.pattern, pathname)) return false;
1410
- // i18n (innovation #27): an unknown locale must answer 404, and a
2423
+ // i18n: an unknown locale must answer 404, and a
1411
2424
  // streamed response cannot change its status - so it takes the buffered
1412
2425
  // path (renderPage returns the real 404), never the streaming one
1413
2426
  const langIdx = route.pattern.split('/').indexOf(':lang');
@@ -1493,7 +2506,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1493
2506
  html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
1494
2507
  }
1495
2508
  write(html);
1496
- // csr: false (innovation #25, auto since #29): a no-JS route's document
2509
+ // csr: false ( auto since #29): a no-JS route's document
1497
2510
  // ends here - no state script, no inlined bundle. (The servers keep
1498
2511
  // these routes off the streaming path so their <head> is complete;
1499
2512
  // this is the correctness floor if one streams anyway.)
@@ -1517,13 +2530,14 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1517
2530
  format: 'esm',
1518
2531
  platform: 'node',
1519
2532
  write: true,
2533
+ ...TS_LOADER,
1520
2534
  });
1521
2535
 
1522
2536
  // api routes and the middleware have no client module: they are server-only handlers /
1523
2537
  // interceptors.
1524
2538
  const clientImports = split ? '' : compiled
1525
2539
  .map((_, i) => ({ i }))
1526
- .filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware)
2540
+ .filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i))
1527
2541
  .map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`)
1528
2542
  .join('\n');
1529
2543
 
@@ -1533,24 +2547,57 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1533
2547
  : `{ pattern: '${info.pattern}', render: ${compose(i)} }`))
1534
2548
  .join(',\n ');
1535
2549
 
1536
- // P1 (consultant report): the app-global prefetch strategy, declared once (the root
1537
- // layout) as `export const prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
2550
+ // P1: the app-global prefetch strategy, declared once (the root layout) as `export const
2551
+ // prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
1538
2552
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? 'all';
1539
2553
 
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
+ const hasLang = infos.some((i) => i.pattern.includes(':lang'));
2557
+ const langDirBlock = hasLang
2558
+ ? ` // <html lang dir> follows the route - the one part of the document
2559
+ // client-side navigation cannot leave stale (screen readers and CSS
2560
+ // logical properties both read it). A route with no [lang] segment
2561
+ // returns to the default locale, and a bogus segment falls back to it
2562
+ // too, exactly like the server's docAttrs.
2563
+ const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
2564
+ const known = !seg || isLocale(seg);
2565
+ const docLang = known && seg ? seg : __defLocale;
2566
+ document.documentElement.lang = docLang;
2567
+ const docDir = localeDir(docLang);
2568
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
2569
+ else document.documentElement.removeAttribute('dir');
2570
+ if (!known) {`
2571
+ : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2572
+
1540
2573
  const clientEntry = `
1541
2574
  ${clientImports}
1542
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, setLocales, isLocale } from './runtime.js';
1543
-
1544
- // i18n (innovation #27): the dictionaries baked at build time - the client
1545
- // renders any locale from the bundle, so switching language costs zero
1546
- // requests (the same bet as the inlined route table).
1547
- setLocales(${localesJson}, '${defaultLocale}');
2575
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
2576
+
2577
+ // i18n: the dictionaries baked at build time - the client
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.
2585
+ setLocales(${clientLocalesJson}, '${defaultLocale}');
2586
+ setLocalePacks(${JSON.stringify(packed)});
2587
+ ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
2588
+ // follow a route that carries no [lang] segment (a non-i18n page)
2589
+ const __defLocale = '${defaultLocale}';` : ''}
2590
+ // The two pack doors, re-exported for an app that wants to warm a language
2591
+ // before its visitor asks for it (ensureLocale) or to feed a dictionary it
2592
+ // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
2593
+ // is what applyParams calls - so the re-export costs the statement alone.
2594
+ export { ensureLocale, loadLocale } from './runtime.js';
1548
2595
 
1549
2596
  const routes = [
1550
2597
  ${clientRoutes}
1551
2598
  ];
1552
2599
 
1553
- // === Mode B (P0 §1): lazy route chunks ===
2600
+ // === Mode B: lazy route chunks ===
1554
2601
  // Split mode's registry entries arrive without a render function: loadChain
1555
2602
  // loads the route's module graph (the page plus its layouts, one chunk per
1556
2603
  // module, the shared runtime in its own vendor chunk) in parallel and
@@ -1614,17 +2661,17 @@ export function matchRoute(pattern, pathname) {
1614
2661
  // === Link prefetch ===
1615
2662
  // Hover / focus / touch an internal link and the target route renders NOW -
1616
2663
  // $data included - against a throwaway signal map. The click that follows
1617
- // paints from the cached HTML: no await, no request, no spinner. SvelteKit
1618
- // and Qwik prefetch data only; rosetack prefetches the whole render because
2664
+ // paints from the cached HTML: no await, no request, no spinner. Other
2665
+ // frameworks prefetch data only; rosetack prefetches the whole render because
1619
2666
  // the inlined bundle already contains every route.
1620
- // ponytail: the cache holds either a result or the in-flight promise (dedupes
2667
+ // Trade-off: the cache holds either a result or the in-flight promise (dedupes
1621
2668
  // hover storms); one isolated render runs at a time so signal-map swapping
1622
2669
  // stays correct without any merging logic. Entries are single-use: a consumed
1623
2670
  // entry disappears from the cache, which is also how tests observe a hit.
1624
- // P1 (consultant report), three guards for link-heavy pages:
2671
+ // P1, three guards for link-heavy pages:
1625
2672
  // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
1626
2673
  // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
1627
- // ponytail: app-global, not per-route - per-route would carry the mode
2674
+ // Trade-off: app-global, not per-route - per-route would carry the mode
1628
2675
  // in each document's shell.
1629
2676
  // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
1630
2677
  // the budget caps the QUEUE: a hover storm past it drops the excess
@@ -1640,12 +2687,20 @@ const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promis
1640
2687
  let prefetchQueue = Promise.resolve();
1641
2688
  let prefetchPending = 0;
1642
2689
 
1643
- function applyParams(route, pathname) {
2690
+ // Applies the route's params to state. A [lang] segment whose dictionary is
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.
2696
+ async function applyParams(route, pathname) {
1644
2697
  const patternParts = route.pattern.split('/');
1645
2698
  const pathParts = pathname.split('/');
1646
2699
  for (let i = 0; i < patternParts.length; i++) {
1647
2700
  if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
1648
2701
  }
2702
+ const langIdx = patternParts.indexOf(':lang');
2703
+ if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
1649
2704
  }
1650
2705
 
1651
2706
  export function prefetch(pathname, source = 'hover') {
@@ -1665,7 +2720,7 @@ export function prefetch(pathname, source = 'hover') {
1665
2720
  // cleanups, so the prefetched route's timers are disposed on the next
1666
2721
  // navigation like any live route's
1667
2722
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
1668
- applyParams(route, pathname);
2723
+ await applyParams(route, pathname); // a packed locale's dictionary lands before the render
1669
2724
  const closes = [];
1670
2725
  const render = await getRender(route); // split mode: loads the route's chunk here
1671
2726
  const html = await render(closes, '');
@@ -1711,7 +2766,7 @@ function bindEvents(container) {
1711
2766
  if (!el || !container.contains(el)) return;
1712
2767
  const fn = el.getAttribute('data-on-' + ev);
1713
2768
  if (fn.startsWith('$action:')) return $action(fn.slice(8), e);
1714
- const h = globalThis.__rosetack_handlers[fn];
2769
+ const h = handlers[fn];
1715
2770
  if (h) h(e);
1716
2771
  });
1717
2772
  }
@@ -1764,7 +2819,7 @@ export async function start(container, pathname, initial) {
1764
2819
  // (before the prefetch check: a cached entry for a bogus locale is
1765
2820
  // discarded, never painted)
1766
2821
  const langIdx = route.pattern.split('/').indexOf(':lang');
1767
- if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {
2822
+ ${langDirBlock}
1768
2823
  await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
1769
2824
  return;
1770
2825
  }
@@ -1788,7 +2843,7 @@ export async function start(container, pathname, initial) {
1788
2843
  resetEffects();
1789
2844
  clearRequestState();
1790
2845
  }
1791
- applyParams(route, pathname);
2846
+ await applyParams(route, pathname);
1792
2847
  const closes = [];
1793
2848
  let html;
1794
2849
  try {
@@ -1808,7 +2863,10 @@ export async function start(container, pathname, initial) {
1808
2863
  }
1809
2864
  }
1810
2865
  // unmatched route: pages/404.rose renders (with its head + interactivity),
1811
- // else the built-in plain 404
2866
+ // else the built-in plain 404 - and an i18n app's document returns to the
2867
+ // default locale, the same one the server stamps on its 404
2868
+ ${hasLang ? ` document.documentElement.lang = __defLocale;
2869
+ document.documentElement.removeAttribute('dir');` : ''}
1812
2870
  await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
1813
2871
  }
1814
2872
 
@@ -1829,7 +2887,7 @@ export async function adopt(container, html, stateJson) {
1829
2887
  if (st) st.textContent = stateJson;
1830
2888
  for (const route of routes) {
1831
2889
  if (matchRoute(route.pattern, location.pathname)) {
1832
- applyParams(route, location.pathname);
2890
+ await applyParams(route, location.pathname);
1833
2891
  const closes = [];
1834
2892
  try {
1835
2893
  const render = await getRender(route); // split mode: loads the route's chunk here
@@ -1848,12 +2906,12 @@ export async function adopt(container, html, stateJson) {
1848
2906
  }
1849
2907
  // === refresh() implementation ===
1850
2908
  // Re-render the current route in place: the client half of router.refresh()
1851
- // (Next.js) / invalidateAll() (SvelteKit). Same machinery as a client-side
2909
+ // (a router refresh) / (a full invalidation). Same machinery as a client-side
1852
2910
  // navigation to the current path - $data re-runs, state re-seeds from the
1853
2911
  // fresh render, wire() patches the marked nodes - but a refresh never lands
1854
2912
  // a prefetch entry: a hover from a minute ago is exactly what it exists to
1855
2913
  // bypass. Zero requests: the render (and its $data) runs in the page.
1856
- // ponytail: state resets like navigation (no per-key retention); add
2914
+ // Trade-off: state resets like navigation (no per-key retention); add
1857
2915
  // retention when an app needs refresh-without-losing-input.
1858
2916
  setRefreshHook(async () => {
1859
2917
  prefetchCache.delete(location.pathname);
@@ -1862,8 +2920,8 @@ setRefreshHook(async () => {
1862
2920
  `;
1863
2921
  await fs.promises.writeFile(path.join(buildDir, 'client-entry.js'), clientEntry);
1864
2922
  if (split) {
1865
- // Mode B (P0 §1): esbuild code splitting. One chunk per route module, the shared
1866
- // runtime in its own vendor chunk …
2923
+ // Mode B: esbuild code splitting. One chunk per route module, the shared runtime in its
2924
+ // own vendor chunk …
1867
2925
  await fs.promises.rm(path.join(outDir, 'chunks'), { recursive: true, force: true });
1868
2926
  await esbuild.build({
1869
2927
  entryPoints: [path.join(buildDir, 'client-entry.js')],
@@ -1876,6 +2934,7 @@ setRefreshHook(async () => {
1876
2934
  entryNames: 'client',
1877
2935
  chunkNames: 'chunks/[name]-[hash]',
1878
2936
  write: true,
2937
+ ...TS_LOADER,
1879
2938
  });
1880
2939
  } else {
1881
2940
  await esbuild.build({
@@ -1886,6 +2945,7 @@ setRefreshHook(async () => {
1886
2945
  platform: 'browser',
1887
2946
  minify: true,
1888
2947
  write: true,
2948
+ ...TS_LOADER,
1889
2949
  });
1890
2950
  }
1891
2951
 
@@ -1902,8 +2962,8 @@ setRefreshHook(async () => {
1902
2962
  );
1903
2963
  }
1904
2964
 
1905
- // Innovation #31: the build's zero-JS lint report - every route, its verdict, and the
1906
- // reason.
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.
1907
2967
  console.log('rosetack zero-JS report:');
1908
2968
  for (const line of buildReport(infos, compiled)) console.log(' ' + line);
1909
2969
  for (const { info, i } of pages) {
@@ -1918,7 +2978,8 @@ setRefreshHook(async () => {
1918
2978
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
1919
2979
  }
1920
2980
 
1921
- async function scanRoseFiles(root: string): Promise<string[]> {
2981
+ /** Every .rose file under <root>/src/pages, recursively (layouts and api included). */
2982
+ export async function scanRoseFiles(root: string): Promise<string[]> {
1922
2983
  const pagesDir = path.join(root, 'src', 'pages');
1923
2984
  if (!fs.existsSync(pagesDir)) return [];
1924
2985
 
@@ -1936,6 +2997,27 @@ async function scanRoseFiles(root: string): Promise<string[]> {
1936
2997
  return scan(pagesDir);
1937
2998
  }
1938
2999
 
3000
+ /** Every .rose file under <root>/src/components, recursively . These
3001
+ * are not routes: they are compiled into the same module index space as the
3002
+ * pages so a page can `import Card from '../components/Card.rose'`. */
3003
+ export async function scanComponentFiles(root: string): Promise<string[]> {
3004
+ const compDir = path.join(root, 'src', 'components');
3005
+ if (!fs.existsSync(compDir)) return [];
3006
+
3007
+ async function scan(dir: string): Promise<string[]> {
3008
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
3009
+ const files: string[] = [];
3010
+ for (const entry of entries) {
3011
+ const full = path.join(dir, entry.name);
3012
+ if (entry.isDirectory()) files.push(...(await scan(full)));
3013
+ else if (entry.name.endsWith('.rose')) files.push(full);
3014
+ }
3015
+ return files;
3016
+ }
3017
+
3018
+ return scan(compDir);
3019
+ }
3020
+
1939
3021
  function isAncestorDir(layoutPath: string, pagePath: string): boolean {
1940
3022
  const layoutDir = path.dirname(layoutPath);
1941
3023
  const pageDir = path.dirname(pagePath);
@@ -1947,15 +3029,18 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
1947
3029
  const relative = path.relative(pagesDir, filePath).replace(/\\/g, '/');
1948
3030
  const withoutExt = relative.replace(/\.rose$/, '');
1949
3031
  const base = path.posix.basename(withoutExt);
1950
- const isLayout = base === '_layout';
1951
- const isNotFound = base === '404';
1952
- const isError = base === '500';
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
+ const isComponent = filePath.replace(/\\/g, '/').includes('/src/components/');
3035
+ const isLayout = !isComponent && base === '_layout';
3036
+ const isNotFound = !isComponent && base === '404';
3037
+ const isError = !isComponent && base === '500';
1953
3038
  // pages/api/*.rose: Web-standard handler routes (JSON in, JSON out), never
1954
3039
  // HTML pages - they dispatch by method and never reach the client bundle.
1955
- const isApi = withoutExt === 'api' || withoutExt.startsWith('api/');
3040
+ const isApi = !isComponent && (withoutExt === 'api' || withoutExt.startsWith('api/'));
1956
3041
  // pages/_middleware.rose: the request interceptor. It runs before every render and is not
1957
3042
  // a route: it matches nothing and never reaches the client bundle.
1958
- const isMiddleware = withoutExt === '_middleware';
3043
+ const isMiddleware = !isComponent && withoutExt === '_middleware';
1959
3044
 
1960
3045
  let parts = withoutExt.split('/').filter((p) => p !== '_layout');
1961
3046
  // a trailing `index` segment names its directory (blog/index -> /blog,
@@ -1982,6 +3067,7 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
1982
3067
  isError,
1983
3068
  isApi,
1984
3069
  isMiddleware,
3070
+ isComponent,
1985
3071
  };
1986
3072
  }
1987
3073