rosetack 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist-cli/test.mjs CHANGED
@@ -9,6 +9,43 @@ import * as fs from "fs";
9
9
  import * as path from "path";
10
10
  import { pathToFileURL, fileURLToPath } from "url";
11
11
  import * as esbuild from "esbuild";
12
+
13
+ // src/compiler/errors.ts
14
+ var RoseError = class extends Error {
15
+ code;
16
+ file;
17
+ line;
18
+ hint;
19
+ constructor(code, message, opts = {}) {
20
+ super(message);
21
+ this.name = "RoseError";
22
+ this.code = code;
23
+ this.file = opts.file;
24
+ this.line = opts.line;
25
+ this.hint = opts.hint;
26
+ }
27
+ info() {
28
+ const info = { code: this.code };
29
+ if (this.file !== void 0) info.file = this.file;
30
+ if (this.line !== void 0) info.line = this.line;
31
+ info.message = this.message;
32
+ if (this.hint !== void 0) info.hint = this.hint;
33
+ return info;
34
+ }
35
+ };
36
+ function lineOf(src, index) {
37
+ let line = 1;
38
+ const end = Math.min(index, src.length);
39
+ for (let i = 0; i < end; i++) {
40
+ if (src[i] === "\n") line++;
41
+ }
42
+ return line;
43
+ }
44
+ function lineAt(src, match) {
45
+ return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
46
+ }
47
+
48
+ // src/compiler/index.ts
12
49
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
13
50
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
14
51
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
@@ -16,12 +53,11 @@ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
16
53
  var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
17
54
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
18
55
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
19
- var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
20
56
  var SLOT_RE = /<slot\s*\/?>/g;
21
57
  var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
22
58
  function encodeSlotCall(attrs) {
23
59
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
24
- if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
60
+ if (!name) throw new RoseError("E-TEMPLATE", '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
25
61
  const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
26
62
  return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
27
63
  }
@@ -108,7 +144,116 @@ function callifyStateReads(script, names) {
108
144
  }
109
145
  function callifyTemplateExprs(template, names) {
110
146
  if (names.length === 0) return template;
111
- return template.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${callifyStateReads(expr, names)}}`);
147
+ let out = "";
148
+ let last = 0;
149
+ for (const s of templateExprSpans(template)) {
150
+ out += template.slice(last, s.start) + "{" + callifyStateReads(s.expr, names) + "}";
151
+ last = s.end + 1;
152
+ }
153
+ return out + template.slice(last);
154
+ }
155
+ function templateExprSpans(src) {
156
+ const spans = [];
157
+ let i = 0;
158
+ while (i < src.length) {
159
+ if (src[i] === "{") {
160
+ const end = scanExprEnd(src, i);
161
+ if (end > i + 1) {
162
+ spans.push({ start: i, end, expr: src.slice(i + 1, end) });
163
+ i = end + 1;
164
+ continue;
165
+ }
166
+ }
167
+ i++;
168
+ }
169
+ return spans;
170
+ }
171
+ function scanExprEnd(src, open) {
172
+ let depth = 0;
173
+ let i = open;
174
+ while (i < src.length) {
175
+ const ch = src[i];
176
+ if (ch === "'" || ch === '"') {
177
+ i = skipQuoted(src, i);
178
+ continue;
179
+ }
180
+ if (ch === "`") {
181
+ i = skipTemplate(src, i);
182
+ continue;
183
+ }
184
+ if (ch === "{") depth++;
185
+ else if (ch === "}" && --depth === 0) return i;
186
+ i++;
187
+ }
188
+ return -1;
189
+ }
190
+ function skipQuoted(src, i) {
191
+ const q = src[i];
192
+ let j = i + 1;
193
+ while (j < src.length) {
194
+ if (src[j] === "\\") {
195
+ j += 2;
196
+ continue;
197
+ }
198
+ if (src[j] === q) return j + 1;
199
+ j++;
200
+ }
201
+ return j;
202
+ }
203
+ function skipTemplate(src, i) {
204
+ let j = i + 1;
205
+ while (j < src.length) {
206
+ const ch = src[j];
207
+ if (ch === "\\") {
208
+ j += 2;
209
+ continue;
210
+ }
211
+ if (ch === "`") return j + 1;
212
+ if (ch === "$" && src[j + 1] === "{") {
213
+ const end = scanExprEnd(src, j + 1);
214
+ j = end < 0 ? src.length : end + 1;
215
+ continue;
216
+ }
217
+ j++;
218
+ }
219
+ return j;
220
+ }
221
+ function stripComments(src) {
222
+ let out = "";
223
+ let i = 0;
224
+ while (i < src.length) {
225
+ const q = src[i];
226
+ if (q === '"' || q === "'") {
227
+ const end = skipQuoted(src, i);
228
+ out += src.slice(i, end);
229
+ i = end;
230
+ continue;
231
+ }
232
+ if (q === "`") {
233
+ const end = skipTemplate(src, i);
234
+ out += src.slice(i, end);
235
+ i = end;
236
+ continue;
237
+ }
238
+ if (src.startsWith("//", i)) {
239
+ while (i < src.length && src[i] !== "\n") i++;
240
+ continue;
241
+ }
242
+ if (src.startsWith("/*", i)) {
243
+ i += 2;
244
+ while (i < src.length && !src.startsWith("*/", i)) i++;
245
+ i = Math.min(i + 2, src.length);
246
+ continue;
247
+ }
248
+ if (src.startsWith("<!--", i)) {
249
+ i += 4;
250
+ while (i < src.length && !src.startsWith("-->", i)) i++;
251
+ i = Math.min(i + 3, src.length);
252
+ continue;
253
+ }
254
+ out += src[i++];
255
+ }
256
+ return out;
112
257
  }
113
258
  async function loadConfig(root) {
114
259
  const file = path.join(root, "rosetack.config.js");
@@ -121,21 +266,29 @@ async function loadConfig(root) {
121
266
  }
122
267
  function resolveRoseImports(script, fromFile, registry) {
123
268
  const imports = [];
124
- const resolve3 = (spec) => {
269
+ const resolve3 = (spec, at) => {
125
270
  const abs = path.resolve(path.dirname(fromFile), spec);
126
271
  const hit = registry.get(abs);
127
272
  if (!hit) {
128
- 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.`);
273
+ throw new RoseError(
274
+ "E-IMPORT",
275
+ `${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.`,
276
+ {
277
+ file: fromFile,
278
+ line: lineOf(script, at),
279
+ hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`
280
+ }
281
+ );
129
282
  }
130
283
  return hit;
131
284
  };
132
- let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
133
- const hit = resolve3(spec);
285
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at) => {
286
+ const hit = resolve3(spec, at);
134
287
  imports.push({ name, specifier: spec, index: hit.index });
135
288
  return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
136
289
  });
137
- rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
138
- const hit = resolve3(spec);
290
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at) => {
291
+ const hit = resolve3(spec, at);
139
292
  const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
140
293
  imports.push({ name: alias, specifier: spec, index: hit.index });
141
294
  return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
@@ -145,6 +298,60 @@ function resolveRoseImports(script, fromFile, registry) {
145
298
  function rewriteRoseImports(script, kind) {
146
299
  return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
147
300
  }
301
+ var NODE_ONLY_SPEC = /^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream|child_process|worker_threads|dns|cluster|better-sqlite3|sqlite3|pg|mysql2|mongodb|redis|ioredis)$)/;
302
+ function nodeOnlyImports(importStmts) {
303
+ const out = [];
304
+ for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
305
+ if (m[1]) continue;
306
+ if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
307
+ }
308
+ return out;
309
+ }
310
+ function wireEventBindings(template, actionNames) {
311
+ const bindings = [];
312
+ let out = "";
313
+ let rest = template;
314
+ for (; ; ) {
315
+ const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
316
+ if (!m) {
317
+ out += rest;
318
+ break;
319
+ }
320
+ out += rest.slice(0, m.index);
321
+ let i = m.index + m[0].length;
322
+ let depth = 1;
323
+ while (i < rest.length) {
324
+ const ch = rest[i];
325
+ if (ch === '"' || ch === "'") {
326
+ i = skipQuoted(rest, i);
327
+ continue;
328
+ }
329
+ if (ch === "`") {
330
+ i = skipTemplate(rest, i);
331
+ continue;
332
+ }
333
+ if (ch === "{") depth++;
334
+ else if (ch === "}") {
335
+ depth--;
336
+ if (depth === 0) break;
337
+ }
338
+ i++;
339
+ }
340
+ const expr = rest.slice(m.index + m[0].length, i).trim();
341
+ if (actionNames.has(expr)) {
342
+ out += `data-on-${m[1]}="$action:${expr}"`;
343
+ } else if (/^\w+$/.test(expr)) {
344
+ out += `data-on-${m[1]}="${expr}"`;
345
+ bindings.push({ event: m[1], fn: expr });
346
+ } else {
347
+ const name = `__h${bindings.length}`;
348
+ out += `data-on-${m[1]}="${name}"`;
349
+ bindings.push({ event: m[1], fn: `${name}: ${expr}` });
350
+ }
351
+ rest = rest.slice(i + 1);
352
+ }
353
+ return { template: out, bindings };
354
+ }
148
355
  function scanSlotDecls(filePath) {
149
356
  let src;
150
357
  try {
@@ -207,7 +414,11 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
207
414
  try {
208
415
  source = await p.transform(source, filePath);
209
416
  } catch (err) {
210
- throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
417
+ throw new RoseError(
418
+ "E-PLUGIN",
419
+ `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
420
+ { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
421
+ );
211
422
  }
212
423
  }
213
424
  if (isApi) {
@@ -225,7 +436,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
225
436
  guardName: null,
226
437
  style: "",
227
438
  hasParams: false,
228
- api: `import { getContext } from './runtime.js';
439
+ api: `import { getContext, $query } from './runtime.js';
229
440
  ${rewriteRoseImports(`${hoisted.imports}
230
441
  ${hoisted.rest}`, "ssr").trim()}`,
231
442
  apiMethods,
@@ -233,41 +444,84 @@ ${hoisted.rest}`, "ssr").trim()}`,
233
444
  usesContext: usesContext2
234
445
  };
235
446
  }
236
- const styleMatch = source.match(STYLE_RE);
447
+ const sourceNoHead = source.replace(HEAD_RE, "");
448
+ const styleMatch = sourceNoHead.match(STYLE_RE);
237
449
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
238
- const sourceNoBlocks = source.replace(STYLE_RE, "");
450
+ const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
239
451
  const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
240
452
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
241
453
  const rawScript = roseResolved.script;
242
454
  const roseImports = roseResolved.imports;
243
455
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
456
+ if (path.basename(filePath) !== "_middleware.rose") {
457
+ for (const spec of nodeOnlyImports(importStmts)) {
458
+ const at = importStmts.indexOf(spec);
459
+ throw new RoseError(
460
+ "E-NODE-ONLY",
461
+ `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
462
+ {
463
+ file: filePath,
464
+ line: at >= 0 ? lineOf(importStmts, at) : void 0,
465
+ hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`
466
+ }
467
+ );
468
+ }
469
+ }
244
470
  const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
245
471
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
246
- throw new Error(
247
- `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`
472
+ throw new RoseError(
473
+ "E-EXPORT",
474
+ `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
475
+ { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
248
476
  );
249
477
  }
250
- const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
478
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
251
479
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
252
480
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
253
481
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
254
482
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
255
483
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
256
484
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
257
- throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
485
+ throw new RoseError(
486
+ "E-EXPORT",
487
+ `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
488
+ { file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
489
+ );
490
+ }
491
+ const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
492
+ const vitals = vitalsMatch ? vitalsMatch[1].trim() === "true" : void 0;
493
+ if (vitalsMatch && !vitals) {
494
+ throw new RoseError(
495
+ "E-EXPORT",
496
+ `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
497
+ { file: filePath, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
498
+ );
258
499
  }
259
500
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
260
501
  const bundle = bundleMatch ? bundleMatch[1] : void 0;
261
502
  if (bundle && !["inline", "split"].includes(bundle)) {
262
- throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
503
+ throw new RoseError(
504
+ "E-EXPORT",
505
+ `${filePath}: export const bundle must be 'inline' or 'split'`,
506
+ { file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
507
+ );
263
508
  }
264
509
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
265
510
  const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
511
+ const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
512
+ const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
266
513
  if (csr === false) {
267
514
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
268
515
  if (dead) {
269
- throw new Error(
270
- `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`
516
+ const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
517
+ throw new RoseError(
518
+ "E-EXPORT",
519
+ `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
520
+ {
521
+ file: filePath,
522
+ line: lineAt(deadSrc, dead),
523
+ hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'
524
+ }
271
525
  );
272
526
  }
273
527
  }
@@ -278,10 +532,18 @@ ${hoisted.rest}`, "ssr").trim()}`,
278
532
  try {
279
533
  value = new Function(`return ${headersLiteral}`)();
280
534
  } catch {
281
- throw new Error(`${filePath}: export const headers must be an object literal`);
535
+ throw new RoseError(
536
+ "E-EXPORT",
537
+ `${filePath}: export const headers must be an object literal`,
538
+ { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
539
+ );
282
540
  }
283
541
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
284
- throw new Error(`${filePath}: export const headers must be a flat map of string -> string`);
542
+ throw new RoseError(
543
+ "E-EXPORT",
544
+ `${filePath}: export const headers must be a flat map of string -> string`,
545
+ { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
546
+ );
285
547
  }
286
548
  headers = value;
287
549
  }
@@ -292,11 +554,19 @@ ${hoisted.rest}`, "ssr").trim()}`,
292
554
  try {
293
555
  value = new Function(`return ${cspLiteral}`)();
294
556
  } catch {
295
- throw new Error(`${filePath}: export const csp must be an object literal`);
557
+ throw new RoseError(
558
+ "E-EXPORT",
559
+ `${filePath}: export const csp must be an object literal`,
560
+ { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
561
+ );
296
562
  }
297
563
  const nonce = value?.nonce;
298
564
  if (nonce !== void 0 && typeof nonce !== "boolean") {
299
- throw new Error(`${filePath}: csp.nonce must be a boolean`);
565
+ throw new RoseError(
566
+ "E-EXPORT",
567
+ `${filePath}: csp.nonce must be a boolean`,
568
+ { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
569
+ );
300
570
  }
301
571
  cspNonce = nonce === true;
302
572
  }
@@ -305,54 +575,38 @@ ${hoisted.rest}`, "ssr").trim()}`,
305
575
  const actionNames = new Set(actions.map((a) => a.name));
306
576
  const clientReasons = [];
307
577
  if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
308
- if (/<form[\s>]/.test(source)) clientReasons.push("a <form> (its in-place adopt is the enhancement)");
578
+ if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
579
+ clientReasons.push("a form bound to a client dispatch ($action)");
580
+ }
309
581
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
310
582
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
311
- if (actionNames.size > 0) {
312
- clientReasons.push(`server action${actionNames.size > 1 ? "s" : ""} (${[...actionNames].join(", ")})`);
313
- }
314
583
  const needsClient = clientReasons.length > 0;
315
584
  const jsWarnings = [];
316
585
  if (!needsClient) {
317
- if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
586
+ const codeOnly = stripComments(source);
587
+ const scriptCodeOnly = stripComments(rawScript);
588
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
318
589
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
319
590
  }
320
- if (/javascript:/i.test(source)) {
591
+ if (/javascript:/i.test(codeOnly)) {
321
592
  jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
322
593
  }
323
- if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
594
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
324
595
  jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
325
596
  }
326
- if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(rawScript)) {
597
+ if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(scriptCodeOnly)) {
327
598
  jsWarnings.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true");
328
599
  }
329
600
  }
330
601
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
331
- const headMatch = sourceNoBlocks.match(HEAD_RE);
332
- const headContent = headMatch?.[1] ?? "";
333
- const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, "");
334
- const rawTemplate = templateMatch ? templateMatch[1] : sourceNoHead.replace(COMPONENT_RE, "").trim();
602
+ const headContent = source.match(HEAD_RE)?.[1] ?? "";
603
+ const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
335
604
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
336
605
  const decls = extractDecls(script);
337
606
  const stateDecls = decls.filter((d) => d.kind === "state");
338
607
  const setterNames = /* @__PURE__ */ new Map();
339
608
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
340
- const eventBindings = [];
341
- let em;
342
- EVENT_RE.lastIndex = 0;
343
- while (em = EVENT_RE.exec(template)) {
344
- if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
345
- }
346
- let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end]));
347
- cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
348
- const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
349
- const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
350
- return `${setter}(${val})`;
351
- });
352
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
353
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
354
- const ssrTemplate = templateCalled.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}").replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) => actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
355
- const stateDeclsCode = decls.map((d) => {
609
+ const declCode = (d) => {
356
610
  const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
357
611
  if (d.kind === "state") {
358
612
  return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
@@ -362,7 +616,30 @@ ${hoisted.rest}`, "ssr").trim()}`,
362
616
  return `const __had_${d.name} = hasState(${JSON.stringify(key)});
363
617
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
364
618
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
365
- }).join("\n");
619
+ };
620
+ const nestedDecls = [];
621
+ let spliced = "";
622
+ let pos = 0;
623
+ decls.forEach((d, i) => {
624
+ const top = braceDepthAt(script, d.start) === 0;
625
+ if (!top) nestedDecls.push(d);
626
+ spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
627
+ pos = d.end;
628
+ });
629
+ spliced += script.slice(pos);
630
+ let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
631
+ const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
632
+ const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
633
+ return `${setter}(${val})`;
634
+ });
635
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
636
+ cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
637
+ const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
638
+ const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
639
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
640
+ const wired = wireEventBindings(templateCalled, actionNames);
641
+ const eventBindings = wired.bindings;
642
+ const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
366
643
  const stateKeys = decls.map((d) => d.name);
367
644
  const comps = new Map(roseImports.map((r) => {
368
645
  const abs = path.resolve(path.dirname(filePath), r.specifier);
@@ -370,7 +647,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
370
647
  return [r.name, { index: hit.index, slots: hit.slots }];
371
648
  }));
372
649
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
373
- const compiledHead = headContent.trim() ? compileTemplate(headContent, "__hd", "__hc", null, 0, false) : "";
650
+ const compiledHead = headContent.trim() ? compileHead(headContent) : "";
374
651
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
375
652
  const ssrExports = actions.length > 0 ? `${exportStmts}
376
653
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
@@ -385,8 +662,8 @@ ${ssrExports}
385
662
  ${ssrGuard}
386
663
 
387
664
  ${cleanScript}
388
- ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
389
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
665
+ ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
666
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
390
667
  return {
391
668
  ssr: rewriteRoseImports(ssr, "ssr"),
392
669
  client: rewriteRoseImports(client, "client"),
@@ -398,7 +675,9 @@ ${cleanScript}
398
675
  usesContext,
399
676
  revalidate,
400
677
  csr,
678
+ buffer,
401
679
  prefetch,
680
+ vitals,
402
681
  bundle,
403
682
  needsClient,
404
683
  clientReasons,
@@ -633,31 +912,134 @@ function extractDecls(script) {
633
912
  }
634
913
  return decls;
635
914
  }
636
- function removeRanges(text, ranges) {
637
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
638
- let out = "";
639
- let pos = 0;
640
- for (const [start, end] of sorted) {
641
- out += text.slice(pos, start);
642
- pos = end;
915
+ function braceDepthAt(src, index) {
916
+ let depth = 0;
917
+ let i = 0;
918
+ while (i < index) {
919
+ const ch = src[i];
920
+ if (ch === "'" || ch === '"' || ch === "`") {
921
+ const quote = ch;
922
+ i++;
923
+ while (i < index) {
924
+ if (src[i] === "\\") {
925
+ i += 2;
926
+ continue;
927
+ }
928
+ if (src[i] === quote) {
929
+ i++;
930
+ break;
931
+ }
932
+ if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
933
+ let d = 1;
934
+ i += 2;
935
+ while (i < index && d > 0) {
936
+ if (src[i] === "{") d++;
937
+ else if (src[i] === "}") d--;
938
+ i++;
939
+ }
940
+ continue;
941
+ }
942
+ i++;
943
+ }
944
+ continue;
945
+ }
946
+ if (ch === "/" && src[i + 1] === "/") {
947
+ const nl = src.indexOf("\n", i);
948
+ i = nl === -1 ? src.length : nl;
949
+ continue;
950
+ }
951
+ if (ch === "/" && src[i + 1] === "*") {
952
+ const close = src.indexOf("*/", i + 2);
953
+ i = close === -1 ? src.length : close + 2;
954
+ continue;
955
+ }
956
+ if (ch === "{") depth++;
957
+ else if (ch === "}") depth--;
958
+ i++;
643
959
  }
644
- out += text.slice(pos);
645
- return out;
960
+ return depth;
646
961
  }
647
962
  function autoCall(expr) {
648
963
  const e = expr.trim();
649
964
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
650
965
  }
966
+ function findBlock(src, kind) {
967
+ const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
968
+ const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
969
+ let open;
970
+ while (open = head.exec(src)) {
971
+ const start = open.index;
972
+ const afterOpen = start + open[0].length;
973
+ let depth = 1;
974
+ let i = afterOpen;
975
+ for (; ; ) {
976
+ head.lastIndex = i;
977
+ closeRe.lastIndex = i;
978
+ const nextOpen = head.exec(src);
979
+ const nextClose = closeRe.exec(src);
980
+ if (!nextClose) break;
981
+ if (nextOpen && nextOpen.index < nextClose.index) {
982
+ depth++;
983
+ i = nextOpen.index + nextOpen[0].length;
984
+ continue;
985
+ }
986
+ i = nextClose.index + nextClose[0].length;
987
+ if (--depth === 0) {
988
+ const content = src.slice(afterOpen, nextClose.index);
989
+ const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
990
+ const arr = [src.slice(start, i), ...groups];
991
+ arr.index = start;
992
+ return arr;
993
+ }
994
+ }
995
+ head.lastIndex = afterOpen;
996
+ }
997
+ return null;
998
+ }
999
+ function compileHead(head) {
1000
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
1001
+ let out = "";
1002
+ let buf = "";
1003
+ let seg = 0;
1004
+ let i = 0;
1005
+ const flush = () => {
1006
+ if (buf.trim()) out += compileTemplate(buf, "__hd", "__hc", null, seg++, false);
1007
+ buf = "";
1008
+ };
1009
+ while (i < head.length) {
1010
+ if (head.startsWith("<!--", i)) {
1011
+ const end = head.indexOf("-->", i + 4);
1012
+ i = end < 0 ? head.length : end + 3;
1013
+ continue;
1014
+ }
1015
+ RAW_OPEN.lastIndex = i;
1016
+ const open = RAW_OPEN.exec(head);
1017
+ if (open) {
1018
+ const tag = open[1].toLowerCase();
1019
+ const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
1020
+ const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
1021
+ const end = gt < 0 ? head.length : gt + 1;
1022
+ flush();
1023
+ out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
1024
+ i = end;
1025
+ continue;
1026
+ }
1027
+ buf += head[i++];
1028
+ }
1029
+ flush();
1030
+ return out;
1031
+ }
651
1032
  function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
652
1033
  let result = "";
653
1034
  let remaining = template;
654
1035
  let blockId = 0;
655
1036
  const nextId = () => `${depth}_${blockId++}`;
656
1037
  while (remaining.length > 0) {
657
- const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/);
658
- const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/);
659
- const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/);
660
- const exprMatch = remaining.match(/\{([^{}]+)\}/);
1038
+ const ifMatch = findBlock(remaining, "if");
1039
+ const eachMatch = findBlock(remaining, "each");
1040
+ const boundaryMatch = findBlock(remaining, "boundary");
1041
+ const firstExpr = templateExprSpans(remaining)[0];
1042
+ const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
661
1043
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
662
1044
  const candidates = [];
663
1045
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
@@ -695,7 +1077,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
695
1077
  const call = autoCall(items);
696
1078
  const id = nextId();
697
1079
  const itemRe = new RegExp(`\\b${item}\\b`, "g");
698
- const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(itemRe, "__s")}}`);
1080
+ let scoped = "";
1081
+ let lastSpan = 0;
1082
+ for (const s of templateExprSpans(content.trim())) {
1083
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
1084
+ lastSpan = s.end + 1;
1085
+ }
1086
+ scoped += content.trim().slice(lastSpan);
699
1087
  const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
700
1088
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
701
1089
  `;
@@ -735,7 +1123,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
735
1123
  rest = remaining.substring(tag.end);
736
1124
  } else {
737
1125
  const closeIdx = findClose(remaining, tag.end, tag.name);
738
- if (closeIdx < 0) throw new Error(`unclosed <${tag.name}> - every component tag needs its matching close tag`);
1126
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${tag.name}> - every component tag needs its matching close tag`, { hint: `add the matching </${tag.name}> (or close the tag with /> when it takes no children)` });
739
1127
  childrenSrc = remaining.substring(tag.end, closeIdx);
740
1128
  rest = remaining.substring(closeIdx + tag.name.length + 3);
741
1129
  }
@@ -749,7 +1137,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
749
1137
  const decl = entry.slots.find((s) => s.name === nm);
750
1138
  let content = src;
751
1139
  for (const p of decl?.props ?? []) {
752
- content = content.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(new RegExp(`\\b${p}\\b`, "g"), `__s.${p}`)}}`);
1140
+ const pRe = new RegExp(`\\b${p}\\b`, "g");
1141
+ let out = "";
1142
+ let lastSpan = 0;
1143
+ for (const s of templateExprSpans(content)) {
1144
+ out += content.slice(lastSpan, s.start) + "{" + s.expr.replace(pRe, `__s.${p}`) + "}";
1145
+ lastSpan = s.end + 1;
1146
+ }
1147
+ content = out + content.slice(lastSpan);
753
1148
  }
754
1149
  return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
755
1150
  });
@@ -780,6 +1175,21 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
780
1175
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
781
1176
  continue;
782
1177
  }
1178
+ const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
1179
+ if (rawMatch) {
1180
+ if (before) result += emitChunk(before, acc, closes, scope);
1181
+ const expr2 = rawMatch[1].trim();
1182
+ if (!markers) {
1183
+ result += `${acc} += String(${expr2} ?? '');
1184
+ `;
1185
+ } else {
1186
+ const fn = scope ? `(${scope}) => (${expr2})` : `() => (${expr2})`;
1187
+ result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ""});
1188
+ `;
1189
+ }
1190
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1191
+ continue;
1192
+ }
783
1193
  const attrMatch = before.match(/([\w-]+)=\s*$/);
784
1194
  if (attrMatch) {
785
1195
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -891,7 +1301,7 @@ function rejectNestedSlot(src, outer) {
891
1301
  if (end < 0) return;
892
1302
  const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
893
1303
  if (hit && nm[1] !== "/") {
894
- throw new Error(`slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`);
1304
+ throw new RoseError("E-TEMPLATE", `slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`, { hint: "move the inner <slot> out of the outer one - a slot is a direct child of the component tag, never nested in another slot" });
895
1305
  }
896
1306
  i = end;
897
1307
  }
@@ -945,7 +1355,7 @@ function splitSlots(src) {
945
1355
  if (!selfClosing && !isVoid) elemDepth++;
946
1356
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
947
1357
  if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
948
- 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`);
1358
+ throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
949
1359
  }
950
1360
  if (slotName) {
951
1361
  const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
@@ -953,7 +1363,7 @@ function splitSlots(src) {
953
1363
  named.set(slotName, (named.get(slotName) ?? "") + stripped);
954
1364
  } else {
955
1365
  const closeIdx = findClose(src, end, nm[2]);
956
- if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
1366
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
957
1367
  const tail = `</${nm[2]}>`;
958
1368
  const inner = src.slice(end, closeIdx);
959
1369
  rejectNestedSlot(inner, slotName);
@@ -1029,7 +1439,7 @@ function compileSlot(acc) {
1029
1439
  return `${acc} += String(children);
1030
1440
  `;
1031
1441
  }
1032
- var 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';`;
1442
+ var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark } from './runtime.js';`;
1033
1443
  function propsCode(props) {
1034
1444
  if (props.length === 0) return "";
1035
1445
  return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
@@ -1051,10 +1461,12 @@ const __slotBlock = (closes, sl, name, pairs) => {
1051
1461
  });
1052
1462
  return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1053
1463
  };`;
1054
- function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "") {
1464
+ function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1055
1465
  const headCode = headFn ? `
1056
1466
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1057
1467
  __html += headMark(closes, __head);` : "";
1468
+ const actionState = hasActions ? `
1469
+ const $setState = (key, value) => setState(key, value);` : "";
1058
1470
  return `
1059
1471
  ${RUNTIME_IMPORTS}
1060
1472
 
@@ -1062,6 +1474,7 @@ ${imports}
1062
1474
 
1063
1475
  ${exports}
1064
1476
  ${guard}
1477
+ ${actionState}
1065
1478
 
1066
1479
  ${namedSlots ? SLOT_HELPER : ""}
1067
1480
 
@@ -1069,19 +1482,20 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1069
1482
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1070
1483
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1071
1484
  ${propsCode(props)}
1485
+ ${script}
1072
1486
  ${stateDeclsCode}
1487
+ ${dataDeclsCode}
1073
1488
  // The incremental patches of the action that produced THIS response,
1074
1489
  // applied to the state the declarations above just established (a no-op on
1075
1490
  // every path that is not a server action's re-render - see the runtime).
1076
1491
  ${isComponent ? "" : "applyStateDeltas();"}
1077
- ${script}
1078
1492
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1079
1493
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1080
1494
  return __html;
1081
1495
  }
1082
1496
  `;
1083
1497
  }
1084
- function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
1498
+ function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1085
1499
  const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1086
1500
  const headCode = headFn ? `
1087
1501
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -1099,8 +1513,9 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1099
1513
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1100
1514
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1101
1515
  ${propsCode(props)}
1102
- ${stateDeclsCode}
1103
1516
  ${script}
1517
+ ${stateDeclsCode}
1518
+ ${dataDeclsCode}
1104
1519
  ${handlerRegistry}
1105
1520
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1106
1521
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
@@ -1132,7 +1547,11 @@ async function buildProject(root, outDir) {
1132
1547
  const compFiles = await scanComponentFiles(root);
1133
1548
  const files = [...pageFiles, ...compFiles];
1134
1549
  if (pageFiles.length === 0) {
1135
- 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>`);
1550
+ throw new RoseError(
1551
+ "E-ROUTE",
1552
+ `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1553
+ { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1554
+ );
1136
1555
  }
1137
1556
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1138
1557
  const config = await loadConfig(root);
@@ -1236,7 +1655,7 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1236
1655
  `);
1237
1656
  }
1238
1657
  const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
1239
- if (!runtimeEntry) throw new Error("rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler");
1658
+ if (!runtimeEntry) throw new RoseError("E-INTERNAL", "rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler", { hint: "the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout" });
1240
1659
  await esbuild.build({
1241
1660
  entryPoints: [runtimeEntry],
1242
1661
  bundle: true,
@@ -1292,25 +1711,30 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1292
1711
  const serverRoutes = pages.map(({ info, i }) => {
1293
1712
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
1294
1713
  if (compiled[i].csr === false && compiled[i].needsClient) {
1295
- throw new Error(
1296
- `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`
1714
+ throw new RoseError(
1715
+ "E-EXPORT",
1716
+ `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`,
1717
+ { file: info.filePath, hint: "remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above" }
1297
1718
  );
1298
1719
  }
1299
1720
  if (compiled[i].csr === false) {
1300
1721
  const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1301
1722
  if (needy !== void 0) {
1302
- throw new Error(
1303
- `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`
1723
+ throw new RoseError(
1724
+ "E-EXPORT",
1725
+ `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`,
1726
+ { file: info.filePath, hint: "a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only" }
1304
1727
  );
1305
1728
  }
1306
1729
  }
1307
1730
  const csrFlag = routeNoJs(i) ? ", csr: false" : "";
1731
+ const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
1308
1732
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1309
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag} }`;
1733
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
1310
1734
  }).join(",\n ");
1311
1735
  const serverEntry = `
1312
1736
  ${serverImports}
1313
- import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1737
+ import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1314
1738
  ${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
1315
1739
  // module to import - the runners below stay no-ops and the servers call them
1316
1740
  // unconditionally (one code path, no flags to keep in sync).
@@ -1356,6 +1780,16 @@ export async function runResponseHooks(ctx, res) {
1356
1780
  export const hasRequestHooks = __hasRequestHooks;
1357
1781
  export const hasResponseHooks = __hasResponseHooks;
1358
1782
 
1783
+ // P0-1: the query of the request being rendered, for $query(). The servers
1784
+ // call this before every render (stream, buffered, POST, api) with the parsed
1785
+ // query string; routing itself matches the pathname, which is what fixed the
1786
+ // query-404. A render with no query (the build's prerender, the ISR
1787
+ // background pass) passes {} explicitly - the bag is per request, so a stale
1788
+ // one must never leak into the next.
1789
+ export function setQuery(query) {
1790
+ setRequestQuery(query || {});
1791
+ }
1792
+
1359
1793
  // i18n: the dictionaries baked at build time from
1360
1794
  // src/locales/*.json. A route segment named [lang] is the locale: the value
1361
1795
  // must name one of these dictionaries, and $t resolves keys against it.
@@ -1390,13 +1824,15 @@ export const routeParams = {
1390
1824
  };
1391
1825
 
1392
1826
  // Routes whose component reads the request context (getContext()), mutates a
1393
- // shared store ($store), or opted into nonce-based CSP: the bag is
1394
- // per-request, the store is per-process, and a nonce is per-response, so
1395
- // these are dynamic - the build never bakes them and the servers never
1396
- // answer them from a prerendered file. Public routes keep the static fast
1397
- // path (file cache, ETag/304, streaming) untouched.
1827
+ // shared store ($store()), reads the query ($query(), P0-1), opted into
1828
+ // nonce-based CSP or into the buffered path (buffer = true, P0-2):
1829
+ // the bag is per-request, the store is per-process, a nonce is per-response,
1830
+ // and a buffered route's hooks must run per request - so these are dynamic.
1831
+ // The build never bakes them and the servers never answer them from a
1832
+ // prerendered file. Public routes keep the static fast path (file cache,
1833
+ // ETag/304, streaming) untouched.
1398
1834
  export const dynamicRoutes = [
1399
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1835
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1400
1836
  ];
1401
1837
 
1402
1838
  // Which api routes opt into build-time baking (export const prerender = true):
@@ -1450,6 +1886,16 @@ export function isNoJs(pathname) {
1450
1886
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1451
1887
  }
1452
1888
 
1889
+ // P0-2 (bug report): routes that exported "buffer = true". The servers ask
1890
+ // this BEFORE choosing a path: a streamed response commits its status and
1891
+ // headers before the body exists, so its onResponse hooks cannot see the
1892
+ // document and a render that throws mid-flight still answers 200. A buffered
1893
+ // route keeps every capability and gives up the early flush - the trade is
1894
+ // the route's to make, per route, not the framework's.
1895
+ export function isBuffered(pathname) {
1896
+ return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
1897
+ }
1898
+
1453
1899
  // Per-route response headers: a route exporting a headers
1454
1900
  // map carries them into every response the servers write for it, merged
1455
1901
  // OVER the framework defaults (the strict CSP) - so an app can tighten or
@@ -1804,6 +2250,12 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1804
2250
  const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
1805
2251
  const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
1806
2252
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
2253
+ const vitalsOn = compiled.some((c) => c.vitals === true);
2254
+ const vitalsBlock = vitalsOn ? `
2255
+ // the app asked for web-vitals - measure once, at boot, and let the
2256
+ // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2257
+ reportVitals;
2258
+ ` : "";
1807
2259
  const hasLang = infos.some((i) => i.pattern.includes(":lang"));
1808
2260
  const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
1809
2261
  // client-side navigation cannot leave stale (screen readers and CSS
@@ -1820,7 +2272,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1820
2272
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
1821
2273
  const clientEntry = `
1822
2274
  ${clientImports}
1823
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
2275
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
1824
2276
 
1825
2277
  // i18n: the dictionaries baked at build time - the client
1826
2278
  // renders any PRELOADED locale from the bundle, so switching language costs
@@ -1835,11 +2287,16 @@ setLocalePacks(${JSON.stringify(packed)});
1835
2287
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
1836
2288
  // follow a route that carries no [lang] segment (a non-i18n page)
1837
2289
  const __defLocale = '${defaultLocale}';` : ""}
2290
+ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2291
+ // reportVitals alive through minification and tree-shaking; the call is one
2292
+ // statement at boot, before the first render.
2293
+ import { reportVitals } from './runtime.js';` : ""}
1838
2294
  // The two pack doors, re-exported for an app that wants to warm a language
1839
2295
  // before its visitor asks for it (ensureLocale) or to feed a dictionary it
1840
2296
  // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
1841
2297
  // is what applyParams calls - so the re-export costs the statement alone.
1842
2298
  export { ensureLocale, loadLocale } from './runtime.js';
2299
+ ${vitalsBlock}
1843
2300
 
1844
2301
  const routes = [
1845
2302
  ${clientRoutes}
@@ -1960,8 +2417,15 @@ export function prefetch(pathname, source = 'hover') {
1960
2417
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
1961
2418
  if (!route) return;
1962
2419
  if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
2420
+ // P0-1: the link may carry a query (/search?q=cats). $query() reads the
2421
+ // browser's own URL, which is the page being LEFT - so the prefetched
2422
+ // render would see the wrong one. Override it for the duration and clear
2423
+ // it after; the queue below serializes renders, so one slot is enough.
2424
+ const qi = pathname.indexOf('?');
2425
+ const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
1963
2426
  const p = prefetchQueue.then(async () => {
1964
2427
  try {
2428
+ setPrefetchOverride(qOverride);
1965
2429
  // the isolated render also captures the onMount callbacks the route
1966
2430
  // queued and the onCleanup disposers it registered: the paint that
1967
2431
  // consumes this entry replays the mounts after wiring and adopts the
@@ -1988,6 +2452,7 @@ export function prefetch(pathname, source = 'hover') {
1988
2452
  prefetchCache.delete(pathname); // failed: the next hover retries
1989
2453
  return null;
1990
2454
  } finally {
2455
+ setPrefetchOverride(null);
1991
2456
  prefetchPending--;
1992
2457
  }
1993
2458
  });
@@ -2052,6 +2517,13 @@ export async function $action(name, e) {
2052
2517
 
2053
2518
  export { postForm };
2054
2519
 
2520
+ // The live signal graph as JSON - the same serializeState the zero-hydration
2521
+ // resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
2522
+ // can hand it to the dev server's reload bridge and to a devtools extension.
2523
+ // A local re-export on purpose: it keeps the binding alive through minification
2524
+ // for the bootstrap text appended after the bundle.
2525
+ export { serializeState };
2526
+
2055
2527
  // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2056
2528
  // the existing nodes and bind events. initial=false: client-side navigation -
2057
2529
  // re-render the route chain from scratch and wire the fresh DOM.
@@ -2372,13 +2844,34 @@ document.addEventListener('submit', (e) => {
2372
2844
  e.preventDefault();
2373
2845
  postForm(new FormData(f));
2374
2846
  });
2847
+ // Dev seam: the live signal graph, readable as JSON. Two callers, one
2848
+ // implementation: the dev server's reload bridge snapshots it before a
2849
+ // rebuild-triggered reload so the edit lands on the state the developer had,
2850
+ // and a devtools extension reads it the same way. It is the same
2851
+ // serializeState the zero-hydration resume already ships, so the only new
2852
+ // bytes are the assignment.
2853
+ window.__rosetack = { state: () => serializeState() };
2375
2854
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
2376
2855
  // If the document was rendered for a DIFFERENT route (a static-file server's
2377
2856
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
2378
2857
  // client router render the requested route from scratch.
2379
2858
  const __st = document.getElementById('__rosetack_state');
2380
- const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
2381
- if (__state.__route === window.location.pathname) {
2859
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
2860
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
2861
+ // the next document (window.__rosetack_resume). The resumed values win over the
2862
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
2863
+ // the route renders client-side from the bundle rather than adopting the SSR
2864
+ // DOM, because a resumed list can be longer than the document's rows and
2865
+ // adoption could not add them. Absent in every non-dev document.
2866
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
2867
+ if (__resumed) {
2868
+ const __route = __state.__route;
2869
+ __state = Object.assign(__state, __resumed);
2870
+ __state.__route = __route;
2871
+ }
2872
+ if (__resumed) {
2873
+ start(__app, window.location.pathname);
2874
+ } else if (__state.__route === window.location.pathname) {
2382
2875
  start(__app, window.location.pathname, true);
2383
2876
  } else {
2384
2877
  start(__app, window.location.pathname);
@@ -2418,6 +2911,7 @@ var STYLES_MIN = STYLES.replace(
2418
2911
  function mergeHeadBlocks(blocks) {
2419
2912
  const byKey = /* @__PURE__ */ new Map();
2420
2913
  const order = [];
2914
+ const positional = /* @__PURE__ */ new Map();
2421
2915
  const put = (key, html) => {
2422
2916
  if (!byKey.has(key)) {
2423
2917
  byKey.set(key, html);
@@ -2426,11 +2920,20 @@ function mergeHeadBlocks(blocks) {
2426
2920
  };
2427
2921
  for (const block of blocks) {
2428
2922
  for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
2429
- for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
2923
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
2430
2924
  const tag = m[1].toLowerCase();
2431
- const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
2432
- const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
2433
- const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
2925
+ if (tag === "title") continue;
2926
+ const attrs = m[2];
2927
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
2928
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
2929
+ let key;
2930
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
2931
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
2932
+ else {
2933
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
2934
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
2935
+ }
2936
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
2434
2937
  put(key, marked);
2435
2938
  }
2436
2939
  }
@@ -2454,16 +2957,19 @@ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(),
2454
2957
  const jsTail = js ? `
2455
2958
  <script type="application/json" id="__rosetack_state">${stateJson}</script>
2456
2959
  ${clientTag}` : "";
2960
+ const open = js ? '<div id="app">' : "";
2961
+ const close = js ? "</div>" : "";
2962
+ const shellStyles = js ? `
2963
+ <style>${STYLES_MIN}</style>` : "";
2457
2964
  return `<!DOCTYPE html>
2458
2965
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
2459
2966
  <head>
2460
2967
  <meta charset="UTF-8">
2461
2968
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
2462
- ${titleTag}
2463
- <style>${STYLES_MIN}</style>${styleTag}
2969
+ ${titleTag}${shellStyles}${styleTag}
2464
2970
  </head>
2465
2971
  <body>
2466
- <div id="app">${ssrHtml}</div>${jsTail}
2972
+ ${open}${ssrHtml}${close}${jsTail}
2467
2973
  </body>
2468
2974
  </html>`;
2469
2975
  }