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/deploy/k8s/rosetack.yaml +107 -0
- package/dist-cli/compiler.mjs +577 -96
- package/dist-cli/edge.mjs +46 -11
- package/dist-cli/rosetack.mjs +963 -144
- package/dist-cli/runtime.mjs +94 -10
- package/dist-cli/test.mjs +610 -104
- package/package.json +1 -1
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/edge.ts +9 -2
- package/src/cli/index.ts +349 -41
- package/src/cli/prompt.ts +127 -0
- package/src/cli/shell.ts +59 -9
- package/src/compiler/errors.ts +74 -0
- package/src/compiler/index.ts +729 -124
- package/src/runtime/index.ts +122 -14
- package/src/types/rosetack.d.ts +9 -0
package/dist-cli/rosetack.mjs
CHANGED
|
@@ -12,6 +12,47 @@ import * as fs from "fs";
|
|
|
12
12
|
import * as path from "path";
|
|
13
13
|
import { pathToFileURL, fileURLToPath } from "url";
|
|
14
14
|
import * as esbuild from "esbuild";
|
|
15
|
+
|
|
16
|
+
// src/compiler/errors.ts
|
|
17
|
+
var RoseError = class extends Error {
|
|
18
|
+
code;
|
|
19
|
+
file;
|
|
20
|
+
line;
|
|
21
|
+
hint;
|
|
22
|
+
constructor(code, message, opts = {}) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "RoseError";
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.file = opts.file;
|
|
27
|
+
this.line = opts.line;
|
|
28
|
+
this.hint = opts.hint;
|
|
29
|
+
}
|
|
30
|
+
info() {
|
|
31
|
+
const info = { code: this.code };
|
|
32
|
+
if (this.file !== void 0) info.file = this.file;
|
|
33
|
+
if (this.line !== void 0) info.line = this.line;
|
|
34
|
+
info.message = this.message;
|
|
35
|
+
if (this.hint !== void 0) info.hint = this.hint;
|
|
36
|
+
return info;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
function lineOf(src, index) {
|
|
40
|
+
let line = 1;
|
|
41
|
+
const end = Math.min(index, src.length);
|
|
42
|
+
for (let i = 0; i < end; i++) {
|
|
43
|
+
if (src[i] === "\n") line++;
|
|
44
|
+
}
|
|
45
|
+
return line;
|
|
46
|
+
}
|
|
47
|
+
function lineAt(src, match) {
|
|
48
|
+
return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
|
|
49
|
+
}
|
|
50
|
+
function errorInfo(err) {
|
|
51
|
+
if (err instanceof RoseError) return err.info();
|
|
52
|
+
return { code: "E-UNKNOWN", message: err instanceof Error ? err.message : String(err) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/compiler/index.ts
|
|
15
56
|
var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
16
57
|
var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
17
58
|
var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
@@ -19,12 +60,11 @@ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
|
19
60
|
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
20
61
|
var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
21
62
|
var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
22
|
-
var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
|
|
23
63
|
var SLOT_RE = /<slot\s*\/?>/g;
|
|
24
64
|
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
|
|
25
65
|
function encodeSlotCall(attrs) {
|
|
26
66
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
|
|
27
|
-
if (!name) throw new
|
|
67
|
+
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} />' });
|
|
28
68
|
const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
|
|
29
69
|
return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
|
|
30
70
|
}
|
|
@@ -111,7 +151,116 @@ function callifyStateReads(script, names) {
|
|
|
111
151
|
}
|
|
112
152
|
function callifyTemplateExprs(template, names) {
|
|
113
153
|
if (names.length === 0) return template;
|
|
114
|
-
|
|
154
|
+
let out = "";
|
|
155
|
+
let last = 0;
|
|
156
|
+
for (const s of templateExprSpans(template)) {
|
|
157
|
+
out += template.slice(last, s.start) + "{" + callifyStateReads(s.expr, names) + "}";
|
|
158
|
+
last = s.end + 1;
|
|
159
|
+
}
|
|
160
|
+
return out + template.slice(last);
|
|
161
|
+
}
|
|
162
|
+
function templateExprSpans(src) {
|
|
163
|
+
const spans = [];
|
|
164
|
+
let i = 0;
|
|
165
|
+
while (i < src.length) {
|
|
166
|
+
if (src[i] === "{") {
|
|
167
|
+
const end = scanExprEnd(src, i);
|
|
168
|
+
if (end > i + 1) {
|
|
169
|
+
spans.push({ start: i, end, expr: src.slice(i + 1, end) });
|
|
170
|
+
i = end + 1;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
i++;
|
|
175
|
+
}
|
|
176
|
+
return spans;
|
|
177
|
+
}
|
|
178
|
+
function scanExprEnd(src, open) {
|
|
179
|
+
let depth = 0;
|
|
180
|
+
let i = open;
|
|
181
|
+
while (i < src.length) {
|
|
182
|
+
const ch = src[i];
|
|
183
|
+
if (ch === "'" || ch === '"') {
|
|
184
|
+
i = skipQuoted(src, i);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (ch === "`") {
|
|
188
|
+
i = skipTemplate(src, i);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (ch === "{") depth++;
|
|
192
|
+
else if (ch === "}" && --depth === 0) return i;
|
|
193
|
+
i++;
|
|
194
|
+
}
|
|
195
|
+
return -1;
|
|
196
|
+
}
|
|
197
|
+
function skipQuoted(src, i) {
|
|
198
|
+
const q = src[i];
|
|
199
|
+
let j = i + 1;
|
|
200
|
+
while (j < src.length) {
|
|
201
|
+
if (src[j] === "\\") {
|
|
202
|
+
j += 2;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (src[j] === q) return j + 1;
|
|
206
|
+
j++;
|
|
207
|
+
}
|
|
208
|
+
return j;
|
|
209
|
+
}
|
|
210
|
+
function skipTemplate(src, i) {
|
|
211
|
+
let j = i + 1;
|
|
212
|
+
while (j < src.length) {
|
|
213
|
+
const ch = src[j];
|
|
214
|
+
if (ch === "\\") {
|
|
215
|
+
j += 2;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (ch === "`") return j + 1;
|
|
219
|
+
if (ch === "$" && src[j + 1] === "{") {
|
|
220
|
+
const end = scanExprEnd(src, j + 1);
|
|
221
|
+
j = end < 0 ? src.length : end + 1;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
j++;
|
|
225
|
+
}
|
|
226
|
+
return j;
|
|
227
|
+
}
|
|
228
|
+
function stripComments(src) {
|
|
229
|
+
let out = "";
|
|
230
|
+
let i = 0;
|
|
231
|
+
while (i < src.length) {
|
|
232
|
+
const q = src[i];
|
|
233
|
+
if (q === '"' || q === "'") {
|
|
234
|
+
const end = skipQuoted(src, i);
|
|
235
|
+
out += src.slice(i, end);
|
|
236
|
+
i = end;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (q === "`") {
|
|
240
|
+
const end = skipTemplate(src, i);
|
|
241
|
+
out += src.slice(i, end);
|
|
242
|
+
i = end;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (src.startsWith("//", i)) {
|
|
246
|
+
while (i < src.length && src[i] !== "\n") i++;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
if (src.startsWith("/*", i)) {
|
|
250
|
+
i += 2;
|
|
251
|
+
while (i < src.length && !src.startsWith("*/", i)) i++;
|
|
252
|
+
i = Math.min(i + 2, src.length);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (src.startsWith("<!--", i)) {
|
|
256
|
+
i += 4;
|
|
257
|
+
while (i < src.length && !src.startsWith("-->", i)) i++;
|
|
258
|
+
i = Math.min(i + 3, src.length);
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
out += src[i++];
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
115
264
|
}
|
|
116
265
|
function scriptOf(source) {
|
|
117
266
|
return source.match(COMPONENT_RE)?.[1] ?? null;
|
|
@@ -130,21 +279,29 @@ async function loadPlugins(root) {
|
|
|
130
279
|
}
|
|
131
280
|
function resolveRoseImports(script, fromFile, registry) {
|
|
132
281
|
const imports = [];
|
|
133
|
-
const resolve3 = (spec) => {
|
|
282
|
+
const resolve3 = (spec, at) => {
|
|
134
283
|
const abs = path.resolve(path.dirname(fromFile), spec);
|
|
135
284
|
const hit = registry.get(abs);
|
|
136
285
|
if (!hit) {
|
|
137
|
-
throw new
|
|
286
|
+
throw new RoseError(
|
|
287
|
+
"E-IMPORT",
|
|
288
|
+
`${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.`,
|
|
289
|
+
{
|
|
290
|
+
file: fromFile,
|
|
291
|
+
line: lineOf(script, at),
|
|
292
|
+
hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`
|
|
293
|
+
}
|
|
294
|
+
);
|
|
138
295
|
}
|
|
139
296
|
return hit;
|
|
140
297
|
};
|
|
141
|
-
let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
|
|
142
|
-
const hit = resolve3(spec);
|
|
298
|
+
let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at) => {
|
|
299
|
+
const hit = resolve3(spec, at);
|
|
143
300
|
imports.push({ name, specifier: spec, index: hit.index });
|
|
144
301
|
return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
|
|
145
302
|
});
|
|
146
|
-
rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s
|
|
147
|
-
const hit = resolve3(spec);
|
|
303
|
+
rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at) => {
|
|
304
|
+
const hit = resolve3(spec, at);
|
|
148
305
|
const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
|
|
149
306
|
imports.push({ name: alias, specifier: spec, index: hit.index });
|
|
150
307
|
return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
|
|
@@ -154,6 +311,60 @@ function resolveRoseImports(script, fromFile, registry) {
|
|
|
154
311
|
function rewriteRoseImports(script, kind) {
|
|
155
312
|
return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
|
|
156
313
|
}
|
|
314
|
+
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)$)/;
|
|
315
|
+
function nodeOnlyImports(importStmts) {
|
|
316
|
+
const out = [];
|
|
317
|
+
for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
|
|
318
|
+
if (m[1]) continue;
|
|
319
|
+
if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
function wireEventBindings(template, actionNames) {
|
|
324
|
+
const bindings = [];
|
|
325
|
+
let out = "";
|
|
326
|
+
let rest = template;
|
|
327
|
+
for (; ; ) {
|
|
328
|
+
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
329
|
+
if (!m) {
|
|
330
|
+
out += rest;
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
out += rest.slice(0, m.index);
|
|
334
|
+
let i = m.index + m[0].length;
|
|
335
|
+
let depth = 1;
|
|
336
|
+
while (i < rest.length) {
|
|
337
|
+
const ch = rest[i];
|
|
338
|
+
if (ch === '"' || ch === "'") {
|
|
339
|
+
i = skipQuoted(rest, i);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
if (ch === "`") {
|
|
343
|
+
i = skipTemplate(rest, i);
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (ch === "{") depth++;
|
|
347
|
+
else if (ch === "}") {
|
|
348
|
+
depth--;
|
|
349
|
+
if (depth === 0) break;
|
|
350
|
+
}
|
|
351
|
+
i++;
|
|
352
|
+
}
|
|
353
|
+
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
354
|
+
if (actionNames.has(expr)) {
|
|
355
|
+
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
356
|
+
} else if (/^\w+$/.test(expr)) {
|
|
357
|
+
out += `data-on-${m[1]}="${expr}"`;
|
|
358
|
+
bindings.push({ event: m[1], fn: expr });
|
|
359
|
+
} else {
|
|
360
|
+
const name = `__h${bindings.length}`;
|
|
361
|
+
out += `data-on-${m[1]}="${name}"`;
|
|
362
|
+
bindings.push({ event: m[1], fn: `${name}: ${expr}` });
|
|
363
|
+
}
|
|
364
|
+
rest = rest.slice(i + 1);
|
|
365
|
+
}
|
|
366
|
+
return { template: out, bindings };
|
|
367
|
+
}
|
|
157
368
|
function scanSlotDecls(filePath) {
|
|
158
369
|
let src;
|
|
159
370
|
try {
|
|
@@ -216,7 +427,11 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
216
427
|
try {
|
|
217
428
|
source = await p.transform(source, filePath);
|
|
218
429
|
} catch (err) {
|
|
219
|
-
throw new
|
|
430
|
+
throw new RoseError(
|
|
431
|
+
"E-PLUGIN",
|
|
432
|
+
`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
433
|
+
{ file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
|
|
434
|
+
);
|
|
220
435
|
}
|
|
221
436
|
}
|
|
222
437
|
if (isApi) {
|
|
@@ -234,7 +449,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
234
449
|
guardName: null,
|
|
235
450
|
style: "",
|
|
236
451
|
hasParams: false,
|
|
237
|
-
api: `import { getContext } from './runtime.js';
|
|
452
|
+
api: `import { getContext, $query } from './runtime.js';
|
|
238
453
|
${rewriteRoseImports(`${hoisted.imports}
|
|
239
454
|
${hoisted.rest}`, "ssr").trim()}`,
|
|
240
455
|
apiMethods,
|
|
@@ -242,41 +457,84 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
242
457
|
usesContext: usesContext2
|
|
243
458
|
};
|
|
244
459
|
}
|
|
245
|
-
const
|
|
460
|
+
const sourceNoHead = source.replace(HEAD_RE, "");
|
|
461
|
+
const styleMatch = sourceNoHead.match(STYLE_RE);
|
|
246
462
|
const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
|
|
247
|
-
const sourceNoBlocks =
|
|
463
|
+
const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
|
|
248
464
|
const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
|
|
249
465
|
const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
|
|
250
466
|
const rawScript = roseResolved.script;
|
|
251
467
|
const roseImports = roseResolved.imports;
|
|
252
468
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
469
|
+
if (path.basename(filePath) !== "_middleware.rose") {
|
|
470
|
+
for (const spec of nodeOnlyImports(importStmts)) {
|
|
471
|
+
const at = importStmts.indexOf(spec);
|
|
472
|
+
throw new RoseError(
|
|
473
|
+
"E-NODE-ONLY",
|
|
474
|
+
`${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.`,
|
|
475
|
+
{
|
|
476
|
+
file: filePath,
|
|
477
|
+
line: at >= 0 ? lineOf(importStmts, at) : void 0,
|
|
478
|
+
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`
|
|
479
|
+
}
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
253
483
|
const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
|
|
254
484
|
if (isComponent && /\$data\s*\(/.test(rawScript)) {
|
|
255
|
-
throw new
|
|
256
|
-
|
|
485
|
+
throw new RoseError(
|
|
486
|
+
"E-EXPORT",
|
|
487
|
+
`${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()}>.`,
|
|
488
|
+
{ file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
|
|
257
489
|
);
|
|
258
490
|
}
|
|
259
|
-
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
|
|
491
|
+
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
|
|
260
492
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
261
493
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
262
494
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
|
|
263
495
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
264
496
|
const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
|
|
265
497
|
if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
|
|
266
|
-
throw new
|
|
498
|
+
throw new RoseError(
|
|
499
|
+
"E-EXPORT",
|
|
500
|
+
`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
|
|
501
|
+
{ 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'" }
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
|
|
505
|
+
const vitals = vitalsMatch ? vitalsMatch[1].trim() === "true" : void 0;
|
|
506
|
+
if (vitalsMatch && !vitals) {
|
|
507
|
+
throw new RoseError(
|
|
508
|
+
"E-EXPORT",
|
|
509
|
+
`${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
|
|
510
|
+
{ 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" }
|
|
511
|
+
);
|
|
267
512
|
}
|
|
268
513
|
const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
269
514
|
const bundle = bundleMatch ? bundleMatch[1] : void 0;
|
|
270
515
|
if (bundle && !["inline", "split"].includes(bundle)) {
|
|
271
|
-
throw new
|
|
516
|
+
throw new RoseError(
|
|
517
|
+
"E-EXPORT",
|
|
518
|
+
`${filePath}: export const bundle must be 'inline' or 'split'`,
|
|
519
|
+
{ 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" }
|
|
520
|
+
);
|
|
272
521
|
}
|
|
273
522
|
const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
|
|
274
523
|
const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
|
|
524
|
+
const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
|
|
525
|
+
const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
|
|
275
526
|
if (csr === false) {
|
|
276
527
|
const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
|
|
277
528
|
if (dead) {
|
|
278
|
-
|
|
279
|
-
|
|
529
|
+
const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
|
|
530
|
+
throw new RoseError(
|
|
531
|
+
"E-EXPORT",
|
|
532
|
+
`${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.)`,
|
|
533
|
+
{
|
|
534
|
+
file: filePath,
|
|
535
|
+
line: lineAt(deadSrc, dead),
|
|
536
|
+
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'
|
|
537
|
+
}
|
|
280
538
|
);
|
|
281
539
|
}
|
|
282
540
|
}
|
|
@@ -287,10 +545,18 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
287
545
|
try {
|
|
288
546
|
value = new Function(`return ${headersLiteral}`)();
|
|
289
547
|
} catch {
|
|
290
|
-
throw new
|
|
548
|
+
throw new RoseError(
|
|
549
|
+
"E-EXPORT",
|
|
550
|
+
`${filePath}: export const headers must be an object literal`,
|
|
551
|
+
{ file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
|
|
552
|
+
);
|
|
291
553
|
}
|
|
292
554
|
if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
|
|
293
|
-
throw new
|
|
555
|
+
throw new RoseError(
|
|
556
|
+
"E-EXPORT",
|
|
557
|
+
`${filePath}: export const headers must be a flat map of string -> string`,
|
|
558
|
+
{ file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
|
|
559
|
+
);
|
|
294
560
|
}
|
|
295
561
|
headers = value;
|
|
296
562
|
}
|
|
@@ -301,11 +567,19 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
301
567
|
try {
|
|
302
568
|
value = new Function(`return ${cspLiteral}`)();
|
|
303
569
|
} catch {
|
|
304
|
-
throw new
|
|
570
|
+
throw new RoseError(
|
|
571
|
+
"E-EXPORT",
|
|
572
|
+
`${filePath}: export const csp must be an object literal`,
|
|
573
|
+
{ file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
|
|
574
|
+
);
|
|
305
575
|
}
|
|
306
576
|
const nonce = value?.nonce;
|
|
307
577
|
if (nonce !== void 0 && typeof nonce !== "boolean") {
|
|
308
|
-
throw new
|
|
578
|
+
throw new RoseError(
|
|
579
|
+
"E-EXPORT",
|
|
580
|
+
`${filePath}: csp.nonce must be a boolean`,
|
|
581
|
+
{ file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
|
|
582
|
+
);
|
|
309
583
|
}
|
|
310
584
|
cspNonce = nonce === true;
|
|
311
585
|
}
|
|
@@ -314,54 +588,38 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
314
588
|
const actionNames = new Set(actions.map((a) => a.name));
|
|
315
589
|
const clientReasons = [];
|
|
316
590
|
if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
|
|
317
|
-
if (/<form[
|
|
591
|
+
if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
|
|
592
|
+
clientReasons.push("a form bound to a client dispatch ($action)");
|
|
593
|
+
}
|
|
318
594
|
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
319
595
|
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
|
|
320
|
-
if (actionNames.size > 0) {
|
|
321
|
-
clientReasons.push(`server action${actionNames.size > 1 ? "s" : ""} (${[...actionNames].join(", ")})`);
|
|
322
|
-
}
|
|
323
596
|
const needsClient = clientReasons.length > 0;
|
|
324
597
|
const jsWarnings = [];
|
|
325
598
|
if (!needsClient) {
|
|
326
|
-
|
|
599
|
+
const codeOnly = stripComments(source);
|
|
600
|
+
const scriptCodeOnly = stripComments(rawScript);
|
|
601
|
+
if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
|
|
327
602
|
jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
|
|
328
603
|
}
|
|
329
|
-
if (/javascript:/i.test(
|
|
604
|
+
if (/javascript:/i.test(codeOnly)) {
|
|
330
605
|
jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
|
|
331
606
|
}
|
|
332
|
-
if (/\b(?:eval|new Function)\s*\(/.test(
|
|
607
|
+
if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
|
|
333
608
|
jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
|
|
334
609
|
}
|
|
335
|
-
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(
|
|
610
|
+
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)) {
|
|
336
611
|
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");
|
|
337
612
|
}
|
|
338
613
|
}
|
|
339
614
|
const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, "");
|
|
343
|
-
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoHead.replace(COMPONENT_RE, "").trim();
|
|
615
|
+
const headContent = source.match(HEAD_RE)?.[1] ?? "";
|
|
616
|
+
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
|
|
344
617
|
const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
|
|
345
618
|
const decls = extractDecls(script);
|
|
346
619
|
const stateDecls = decls.filter((d) => d.kind === "state");
|
|
347
620
|
const setterNames = /* @__PURE__ */ new Map();
|
|
348
621
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
349
|
-
const
|
|
350
|
-
let em;
|
|
351
|
-
EVENT_RE.lastIndex = 0;
|
|
352
|
-
while (em = EVENT_RE.exec(template)) {
|
|
353
|
-
if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
|
|
354
|
-
}
|
|
355
|
-
let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end]));
|
|
356
|
-
cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
|
|
357
|
-
const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
|
|
358
|
-
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
359
|
-
return `${setter}(${val})`;
|
|
360
|
-
});
|
|
361
|
-
cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
|
|
362
|
-
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
363
|
-
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}"`);
|
|
364
|
-
const stateDeclsCode = decls.map((d) => {
|
|
622
|
+
const declCode = (d) => {
|
|
365
623
|
const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
|
|
366
624
|
if (d.kind === "state") {
|
|
367
625
|
return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
|
|
@@ -371,7 +629,30 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
371
629
|
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
372
630
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
373
631
|
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
374
|
-
}
|
|
632
|
+
};
|
|
633
|
+
const nestedDecls = [];
|
|
634
|
+
let spliced = "";
|
|
635
|
+
let pos = 0;
|
|
636
|
+
decls.forEach((d, i) => {
|
|
637
|
+
const top = braceDepthAt(script, d.start) === 0;
|
|
638
|
+
if (!top) nestedDecls.push(d);
|
|
639
|
+
spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
|
|
640
|
+
pos = d.end;
|
|
641
|
+
});
|
|
642
|
+
spliced += script.slice(pos);
|
|
643
|
+
let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
|
|
644
|
+
const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
|
|
645
|
+
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
646
|
+
return `${setter}(${val})`;
|
|
647
|
+
});
|
|
648
|
+
cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
|
|
649
|
+
cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
|
|
650
|
+
const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
|
|
651
|
+
const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
|
|
652
|
+
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
653
|
+
const wired = wireEventBindings(templateCalled, actionNames);
|
|
654
|
+
const eventBindings = wired.bindings;
|
|
655
|
+
const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
|
|
375
656
|
const stateKeys = decls.map((d) => d.name);
|
|
376
657
|
const comps = new Map(roseImports.map((r) => {
|
|
377
658
|
const abs = path.resolve(path.dirname(filePath), r.specifier);
|
|
@@ -379,7 +660,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
379
660
|
return [r.name, { index: hit.index, slots: hit.slots }];
|
|
380
661
|
}));
|
|
381
662
|
const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
|
|
382
|
-
const compiledHead = headContent.trim() ?
|
|
663
|
+
const compiledHead = headContent.trim() ? compileHead(headContent) : "";
|
|
383
664
|
const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
|
|
384
665
|
const ssrExports = actions.length > 0 ? `${exportStmts}
|
|
385
666
|
${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
|
|
@@ -394,8 +675,8 @@ ${ssrExports}
|
|
|
394
675
|
${ssrGuard}
|
|
395
676
|
|
|
396
677
|
${cleanScript}
|
|
397
|
-
` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
|
|
398
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
|
|
678
|
+
` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
679
|
+
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
399
680
|
return {
|
|
400
681
|
ssr: rewriteRoseImports(ssr, "ssr"),
|
|
401
682
|
client: rewriteRoseImports(client, "client"),
|
|
@@ -407,7 +688,9 @@ ${cleanScript}
|
|
|
407
688
|
usesContext,
|
|
408
689
|
revalidate,
|
|
409
690
|
csr,
|
|
691
|
+
buffer,
|
|
410
692
|
prefetch,
|
|
693
|
+
vitals,
|
|
411
694
|
bundle,
|
|
412
695
|
needsClient,
|
|
413
696
|
clientReasons,
|
|
@@ -642,31 +925,134 @@ function extractDecls(script) {
|
|
|
642
925
|
}
|
|
643
926
|
return decls;
|
|
644
927
|
}
|
|
645
|
-
function
|
|
646
|
-
|
|
647
|
-
let
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
928
|
+
function braceDepthAt(src, index) {
|
|
929
|
+
let depth = 0;
|
|
930
|
+
let i = 0;
|
|
931
|
+
while (i < index) {
|
|
932
|
+
const ch = src[i];
|
|
933
|
+
if (ch === "'" || ch === '"' || ch === "`") {
|
|
934
|
+
const quote = ch;
|
|
935
|
+
i++;
|
|
936
|
+
while (i < index) {
|
|
937
|
+
if (src[i] === "\\") {
|
|
938
|
+
i += 2;
|
|
939
|
+
continue;
|
|
940
|
+
}
|
|
941
|
+
if (src[i] === quote) {
|
|
942
|
+
i++;
|
|
943
|
+
break;
|
|
944
|
+
}
|
|
945
|
+
if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
|
|
946
|
+
let d = 1;
|
|
947
|
+
i += 2;
|
|
948
|
+
while (i < index && d > 0) {
|
|
949
|
+
if (src[i] === "{") d++;
|
|
950
|
+
else if (src[i] === "}") d--;
|
|
951
|
+
i++;
|
|
952
|
+
}
|
|
953
|
+
continue;
|
|
954
|
+
}
|
|
955
|
+
i++;
|
|
956
|
+
}
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
if (ch === "/" && src[i + 1] === "/") {
|
|
960
|
+
const nl = src.indexOf("\n", i);
|
|
961
|
+
i = nl === -1 ? src.length : nl;
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
if (ch === "/" && src[i + 1] === "*") {
|
|
965
|
+
const close = src.indexOf("*/", i + 2);
|
|
966
|
+
i = close === -1 ? src.length : close + 2;
|
|
967
|
+
continue;
|
|
968
|
+
}
|
|
969
|
+
if (ch === "{") depth++;
|
|
970
|
+
else if (ch === "}") depth--;
|
|
971
|
+
i++;
|
|
652
972
|
}
|
|
653
|
-
|
|
654
|
-
return out;
|
|
973
|
+
return depth;
|
|
655
974
|
}
|
|
656
975
|
function autoCall(expr) {
|
|
657
976
|
const e = expr.trim();
|
|
658
977
|
return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
|
|
659
978
|
}
|
|
979
|
+
function findBlock(src, kind) {
|
|
980
|
+
const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
|
|
981
|
+
const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
|
|
982
|
+
let open;
|
|
983
|
+
while (open = head.exec(src)) {
|
|
984
|
+
const start = open.index;
|
|
985
|
+
const afterOpen = start + open[0].length;
|
|
986
|
+
let depth = 1;
|
|
987
|
+
let i = afterOpen;
|
|
988
|
+
for (; ; ) {
|
|
989
|
+
head.lastIndex = i;
|
|
990
|
+
closeRe.lastIndex = i;
|
|
991
|
+
const nextOpen = head.exec(src);
|
|
992
|
+
const nextClose = closeRe.exec(src);
|
|
993
|
+
if (!nextClose) break;
|
|
994
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
995
|
+
depth++;
|
|
996
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
i = nextClose.index + nextClose[0].length;
|
|
1000
|
+
if (--depth === 0) {
|
|
1001
|
+
const content = src.slice(afterOpen, nextClose.index);
|
|
1002
|
+
const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
|
|
1003
|
+
const arr = [src.slice(start, i), ...groups];
|
|
1004
|
+
arr.index = start;
|
|
1005
|
+
return arr;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
head.lastIndex = afterOpen;
|
|
1009
|
+
}
|
|
1010
|
+
return null;
|
|
1011
|
+
}
|
|
1012
|
+
function compileHead(head) {
|
|
1013
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
|
|
1014
|
+
let out = "";
|
|
1015
|
+
let buf = "";
|
|
1016
|
+
let seg = 0;
|
|
1017
|
+
let i = 0;
|
|
1018
|
+
const flush = () => {
|
|
1019
|
+
if (buf.trim()) out += compileTemplate(buf, "__hd", "__hc", null, seg++, false);
|
|
1020
|
+
buf = "";
|
|
1021
|
+
};
|
|
1022
|
+
while (i < head.length) {
|
|
1023
|
+
if (head.startsWith("<!--", i)) {
|
|
1024
|
+
const end = head.indexOf("-->", i + 4);
|
|
1025
|
+
i = end < 0 ? head.length : end + 3;
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
RAW_OPEN.lastIndex = i;
|
|
1029
|
+
const open = RAW_OPEN.exec(head);
|
|
1030
|
+
if (open) {
|
|
1031
|
+
const tag = open[1].toLowerCase();
|
|
1032
|
+
const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
|
|
1033
|
+
const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
|
|
1034
|
+
const end = gt < 0 ? head.length : gt + 1;
|
|
1035
|
+
flush();
|
|
1036
|
+
out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
|
|
1037
|
+
i = end;
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
buf += head[i++];
|
|
1041
|
+
}
|
|
1042
|
+
flush();
|
|
1043
|
+
return out;
|
|
1044
|
+
}
|
|
660
1045
|
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
|
|
661
1046
|
let result = "";
|
|
662
1047
|
let remaining = template;
|
|
663
1048
|
let blockId = 0;
|
|
664
1049
|
const nextId = () => `${depth}_${blockId++}`;
|
|
665
1050
|
while (remaining.length > 0) {
|
|
666
|
-
const ifMatch = remaining
|
|
667
|
-
const eachMatch = remaining
|
|
668
|
-
const boundaryMatch = remaining
|
|
669
|
-
const
|
|
1051
|
+
const ifMatch = findBlock(remaining, "if");
|
|
1052
|
+
const eachMatch = findBlock(remaining, "each");
|
|
1053
|
+
const boundaryMatch = findBlock(remaining, "boundary");
|
|
1054
|
+
const firstExpr = templateExprSpans(remaining)[0];
|
|
1055
|
+
const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
|
|
670
1056
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
671
1057
|
const candidates = [];
|
|
672
1058
|
if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
|
|
@@ -704,7 +1090,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
704
1090
|
const call = autoCall(items);
|
|
705
1091
|
const id = nextId();
|
|
706
1092
|
const itemRe = new RegExp(`\\b${item}\\b`, "g");
|
|
707
|
-
|
|
1093
|
+
let scoped = "";
|
|
1094
|
+
let lastSpan = 0;
|
|
1095
|
+
for (const s of templateExprSpans(content.trim())) {
|
|
1096
|
+
scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
|
|
1097
|
+
lastSpan = s.end + 1;
|
|
1098
|
+
}
|
|
1099
|
+
scoped += content.trim().slice(lastSpan);
|
|
708
1100
|
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
|
|
709
1101
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
|
|
710
1102
|
`;
|
|
@@ -744,7 +1136,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
744
1136
|
rest = remaining.substring(tag.end);
|
|
745
1137
|
} else {
|
|
746
1138
|
const closeIdx = findClose(remaining, tag.end, tag.name);
|
|
747
|
-
if (closeIdx < 0) throw new
|
|
1139
|
+
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)` });
|
|
748
1140
|
childrenSrc = remaining.substring(tag.end, closeIdx);
|
|
749
1141
|
rest = remaining.substring(closeIdx + tag.name.length + 3);
|
|
750
1142
|
}
|
|
@@ -758,7 +1150,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
758
1150
|
const decl = entry.slots.find((s) => s.name === nm);
|
|
759
1151
|
let content = src;
|
|
760
1152
|
for (const p of decl?.props ?? []) {
|
|
761
|
-
|
|
1153
|
+
const pRe = new RegExp(`\\b${p}\\b`, "g");
|
|
1154
|
+
let out = "";
|
|
1155
|
+
let lastSpan = 0;
|
|
1156
|
+
for (const s of templateExprSpans(content)) {
|
|
1157
|
+
out += content.slice(lastSpan, s.start) + "{" + s.expr.replace(pRe, `__s.${p}`) + "}";
|
|
1158
|
+
lastSpan = s.end + 1;
|
|
1159
|
+
}
|
|
1160
|
+
content = out + content.slice(lastSpan);
|
|
762
1161
|
}
|
|
763
1162
|
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
|
|
764
1163
|
});
|
|
@@ -789,6 +1188,21 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
789
1188
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
790
1189
|
continue;
|
|
791
1190
|
}
|
|
1191
|
+
const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
|
|
1192
|
+
if (rawMatch) {
|
|
1193
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1194
|
+
const expr2 = rawMatch[1].trim();
|
|
1195
|
+
if (!markers) {
|
|
1196
|
+
result += `${acc} += String(${expr2} ?? '');
|
|
1197
|
+
`;
|
|
1198
|
+
} else {
|
|
1199
|
+
const fn = scope ? `(${scope}) => (${expr2})` : `() => (${expr2})`;
|
|
1200
|
+
result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ""});
|
|
1201
|
+
`;
|
|
1202
|
+
}
|
|
1203
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
792
1206
|
const attrMatch = before.match(/([\w-]+)=\s*$/);
|
|
793
1207
|
if (attrMatch) {
|
|
794
1208
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
@@ -900,7 +1314,7 @@ function rejectNestedSlot(src, outer) {
|
|
|
900
1314
|
if (end < 0) return;
|
|
901
1315
|
const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
|
|
902
1316
|
if (hit && nm[1] !== "/") {
|
|
903
|
-
throw new
|
|
1317
|
+
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" });
|
|
904
1318
|
}
|
|
905
1319
|
i = end;
|
|
906
1320
|
}
|
|
@@ -954,7 +1368,7 @@ function splitSlots(src) {
|
|
|
954
1368
|
if (!selfClosing && !isVoid) elemDepth++;
|
|
955
1369
|
const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
|
|
956
1370
|
if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
|
|
957
|
-
throw new
|
|
1371
|
+
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' });
|
|
958
1372
|
}
|
|
959
1373
|
if (slotName) {
|
|
960
1374
|
const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
|
|
@@ -962,7 +1376,7 @@ function splitSlots(src) {
|
|
|
962
1376
|
named.set(slotName, (named.get(slotName) ?? "") + stripped);
|
|
963
1377
|
} else {
|
|
964
1378
|
const closeIdx = findClose(src, end, nm[2]);
|
|
965
|
-
if (closeIdx < 0) throw new
|
|
1379
|
+
if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
|
|
966
1380
|
const tail = `</${nm[2]}>`;
|
|
967
1381
|
const inner = src.slice(end, closeIdx);
|
|
968
1382
|
rejectNestedSlot(inner, slotName);
|
|
@@ -1038,7 +1452,7 @@ function compileSlot(acc) {
|
|
|
1038
1452
|
return `${acc} += String(children);
|
|
1039
1453
|
`;
|
|
1040
1454
|
}
|
|
1041
|
-
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';`;
|
|
1455
|
+
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';`;
|
|
1042
1456
|
function propsCode(props) {
|
|
1043
1457
|
if (props.length === 0) return "";
|
|
1044
1458
|
return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
|
|
@@ -1060,10 +1474,12 @@ const __slotBlock = (closes, sl, name, pairs) => {
|
|
|
1060
1474
|
});
|
|
1061
1475
|
return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
|
|
1062
1476
|
};`;
|
|
1063
|
-
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "") {
|
|
1477
|
+
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
|
|
1064
1478
|
const headCode = headFn ? `
|
|
1065
1479
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
1066
1480
|
__html += headMark(closes, __head);` : "";
|
|
1481
|
+
const actionState = hasActions ? `
|
|
1482
|
+
const $setState = (key, value) => setState(key, value);` : "";
|
|
1067
1483
|
return `
|
|
1068
1484
|
${RUNTIME_IMPORTS}
|
|
1069
1485
|
|
|
@@ -1071,6 +1487,7 @@ ${imports}
|
|
|
1071
1487
|
|
|
1072
1488
|
${exports}
|
|
1073
1489
|
${guard}
|
|
1490
|
+
${actionState}
|
|
1074
1491
|
|
|
1075
1492
|
${namedSlots ? SLOT_HELPER : ""}
|
|
1076
1493
|
|
|
@@ -1078,19 +1495,20 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
|
|
|
1078
1495
|
${props.length > 0 ? "const __p = __props || {};" : ""}
|
|
1079
1496
|
${namedSlots ? "const __sl = __slots || {};" : ""}
|
|
1080
1497
|
${propsCode(props)}
|
|
1498
|
+
${script}
|
|
1081
1499
|
${stateDeclsCode}
|
|
1500
|
+
${dataDeclsCode}
|
|
1082
1501
|
// The incremental patches of the action that produced THIS response,
|
|
1083
1502
|
// applied to the state the declarations above just established (a no-op on
|
|
1084
1503
|
// every path that is not a server action's re-render - see the runtime).
|
|
1085
1504
|
${isComponent ? "" : "applyStateDeltas();"}
|
|
1086
|
-
${script}
|
|
1087
1505
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1088
1506
|
let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
|
|
1089
1507
|
return __html;
|
|
1090
1508
|
}
|
|
1091
1509
|
`;
|
|
1092
1510
|
}
|
|
1093
|
-
function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
|
|
1511
|
+
function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
|
|
1094
1512
|
const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
|
|
1095
1513
|
const headCode = headFn ? `
|
|
1096
1514
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
@@ -1108,8 +1526,9 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
|
|
|
1108
1526
|
${props.length > 0 ? "const __p = __props || {};" : ""}
|
|
1109
1527
|
${namedSlots ? "const __sl = __slots || {};" : ""}
|
|
1110
1528
|
${propsCode(props)}
|
|
1111
|
-
${stateDeclsCode}
|
|
1112
1529
|
${script}
|
|
1530
|
+
${stateDeclsCode}
|
|
1531
|
+
${dataDeclsCode}
|
|
1113
1532
|
${handlerRegistry}
|
|
1114
1533
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1115
1534
|
let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
|
|
@@ -1141,7 +1560,11 @@ async function buildProject(root, outDir) {
|
|
|
1141
1560
|
const compFiles = await scanComponentFiles(root);
|
|
1142
1561
|
const files = [...pageFiles, ...compFiles];
|
|
1143
1562
|
if (pageFiles.length === 0) {
|
|
1144
|
-
throw new
|
|
1563
|
+
throw new RoseError(
|
|
1564
|
+
"E-ROUTE",
|
|
1565
|
+
`no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
|
|
1566
|
+
{ file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
|
|
1567
|
+
);
|
|
1145
1568
|
}
|
|
1146
1569
|
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
1147
1570
|
const config = await loadConfig(root);
|
|
@@ -1245,7 +1668,7 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1245
1668
|
`);
|
|
1246
1669
|
}
|
|
1247
1670
|
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
|
|
1248
|
-
if (!runtimeEntry) throw new
|
|
1671
|
+
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" });
|
|
1249
1672
|
await esbuild.build({
|
|
1250
1673
|
entryPoints: [runtimeEntry],
|
|
1251
1674
|
bundle: true,
|
|
@@ -1301,25 +1724,30 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1301
1724
|
const serverRoutes = pages.map(({ info, i }) => {
|
|
1302
1725
|
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
1303
1726
|
if (compiled[i].csr === false && compiled[i].needsClient) {
|
|
1304
|
-
throw new
|
|
1305
|
-
|
|
1727
|
+
throw new RoseError(
|
|
1728
|
+
"E-EXPORT",
|
|
1729
|
+
`${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`,
|
|
1730
|
+
{ file: info.filePath, hint: "remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above" }
|
|
1306
1731
|
);
|
|
1307
1732
|
}
|
|
1308
1733
|
if (compiled[i].csr === false) {
|
|
1309
1734
|
const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
|
|
1310
1735
|
if (needy !== void 0) {
|
|
1311
|
-
throw new
|
|
1312
|
-
|
|
1736
|
+
throw new RoseError(
|
|
1737
|
+
"E-EXPORT",
|
|
1738
|
+
`${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).`,
|
|
1739
|
+
{ file: info.filePath, hint: "a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only" }
|
|
1313
1740
|
);
|
|
1314
1741
|
}
|
|
1315
1742
|
}
|
|
1316
1743
|
const csrFlag = routeNoJs(i) ? ", csr: false" : "";
|
|
1744
|
+
const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
|
|
1317
1745
|
const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
|
|
1318
|
-
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag} }`;
|
|
1746
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
|
|
1319
1747
|
}).join(",\n ");
|
|
1320
1748
|
const serverEntry = `
|
|
1321
1749
|
${serverImports}
|
|
1322
|
-
import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
|
|
1750
|
+
import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
|
|
1323
1751
|
${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
|
|
1324
1752
|
// module to import - the runners below stay no-ops and the servers call them
|
|
1325
1753
|
// unconditionally (one code path, no flags to keep in sync).
|
|
@@ -1365,6 +1793,16 @@ export async function runResponseHooks(ctx, res) {
|
|
|
1365
1793
|
export const hasRequestHooks = __hasRequestHooks;
|
|
1366
1794
|
export const hasResponseHooks = __hasResponseHooks;
|
|
1367
1795
|
|
|
1796
|
+
// P0-1: the query of the request being rendered, for $query(). The servers
|
|
1797
|
+
// call this before every render (stream, buffered, POST, api) with the parsed
|
|
1798
|
+
// query string; routing itself matches the pathname, which is what fixed the
|
|
1799
|
+
// query-404. A render with no query (the build's prerender, the ISR
|
|
1800
|
+
// background pass) passes {} explicitly - the bag is per request, so a stale
|
|
1801
|
+
// one must never leak into the next.
|
|
1802
|
+
export function setQuery(query) {
|
|
1803
|
+
setRequestQuery(query || {});
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1368
1806
|
// i18n: the dictionaries baked at build time from
|
|
1369
1807
|
// src/locales/*.json. A route segment named [lang] is the locale: the value
|
|
1370
1808
|
// must name one of these dictionaries, and $t resolves keys against it.
|
|
@@ -1399,13 +1837,15 @@ export const routeParams = {
|
|
|
1399
1837
|
};
|
|
1400
1838
|
|
|
1401
1839
|
// Routes whose component reads the request context (getContext()), mutates a
|
|
1402
|
-
// shared store ($store),
|
|
1403
|
-
//
|
|
1404
|
-
//
|
|
1405
|
-
//
|
|
1406
|
-
//
|
|
1840
|
+
// shared store ($store()), reads the query ($query(), P0-1), opted into
|
|
1841
|
+
// nonce-based CSP or into the buffered path (buffer = true, P0-2):
|
|
1842
|
+
// the bag is per-request, the store is per-process, a nonce is per-response,
|
|
1843
|
+
// and a buffered route's hooks must run per request - so these are dynamic.
|
|
1844
|
+
// The build never bakes them and the servers never answer them from a
|
|
1845
|
+
// prerendered file. Public routes keep the static fast path (file cache,
|
|
1846
|
+
// ETag/304, streaming) untouched.
|
|
1407
1847
|
export const dynamicRoutes = [
|
|
1408
|
-
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1848
|
+
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1409
1849
|
];
|
|
1410
1850
|
|
|
1411
1851
|
// Which api routes opt into build-time baking (export const prerender = true):
|
|
@@ -1459,6 +1899,16 @@ export function isNoJs(pathname) {
|
|
|
1459
1899
|
return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1460
1900
|
}
|
|
1461
1901
|
|
|
1902
|
+
// P0-2 (bug report): routes that exported "buffer = true". The servers ask
|
|
1903
|
+
// this BEFORE choosing a path: a streamed response commits its status and
|
|
1904
|
+
// headers before the body exists, so its onResponse hooks cannot see the
|
|
1905
|
+
// document and a render that throws mid-flight still answers 200. A buffered
|
|
1906
|
+
// route keeps every capability and gives up the early flush - the trade is
|
|
1907
|
+
// the route's to make, per route, not the framework's.
|
|
1908
|
+
export function isBuffered(pathname) {
|
|
1909
|
+
return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1462
1912
|
// Per-route response headers: a route exporting a headers
|
|
1463
1913
|
// map carries them into every response the servers write for it, merged
|
|
1464
1914
|
// OVER the framework defaults (the strict CSP) - so an app can tighten or
|
|
@@ -1813,6 +2263,12 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
1813
2263
|
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");
|
|
1814
2264
|
const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
|
|
1815
2265
|
const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
|
|
2266
|
+
const vitalsOn = compiled.some((c) => c.vitals === true);
|
|
2267
|
+
const vitalsBlock = vitalsOn ? `
|
|
2268
|
+
// the app asked for web-vitals - measure once, at boot, and let the
|
|
2269
|
+
// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
|
|
2270
|
+
reportVitals;
|
|
2271
|
+
` : "";
|
|
1816
2272
|
const hasLang = infos.some((i) => i.pattern.includes(":lang"));
|
|
1817
2273
|
const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
|
|
1818
2274
|
// client-side navigation cannot leave stale (screen readers and CSS
|
|
@@ -1829,7 +2285,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
1829
2285
|
if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
1830
2286
|
const clientEntry = `
|
|
1831
2287
|
${clientImports}
|
|
1832
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
|
|
2288
|
+
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
|
|
1833
2289
|
|
|
1834
2290
|
// i18n: the dictionaries baked at build time - the client
|
|
1835
2291
|
// renders any PRELOADED locale from the bundle, so switching language costs
|
|
@@ -1844,11 +2300,16 @@ setLocalePacks(${JSON.stringify(packed)});
|
|
|
1844
2300
|
${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
|
|
1845
2301
|
// follow a route that carries no [lang] segment (a non-i18n page)
|
|
1846
2302
|
const __defLocale = '${defaultLocale}';` : ""}
|
|
2303
|
+
${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
|
|
2304
|
+
// reportVitals alive through minification and tree-shaking; the call is one
|
|
2305
|
+
// statement at boot, before the first render.
|
|
2306
|
+
import { reportVitals } from './runtime.js';` : ""}
|
|
1847
2307
|
// The two pack doors, re-exported for an app that wants to warm a language
|
|
1848
2308
|
// before its visitor asks for it (ensureLocale) or to feed a dictionary it
|
|
1849
2309
|
// fetched itself (loadLocale). Both are already in the bundle - ensureLocale
|
|
1850
2310
|
// is what applyParams calls - so the re-export costs the statement alone.
|
|
1851
2311
|
export { ensureLocale, loadLocale } from './runtime.js';
|
|
2312
|
+
${vitalsBlock}
|
|
1852
2313
|
|
|
1853
2314
|
const routes = [
|
|
1854
2315
|
${clientRoutes}
|
|
@@ -1969,8 +2430,15 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
1969
2430
|
const route = routes.find((r) => matchRoute(r.pattern, pathname));
|
|
1970
2431
|
if (!route) return;
|
|
1971
2432
|
if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
|
|
2433
|
+
// P0-1: the link may carry a query (/search?q=cats). $query() reads the
|
|
2434
|
+
// browser's own URL, which is the page being LEFT - so the prefetched
|
|
2435
|
+
// render would see the wrong one. Override it for the duration and clear
|
|
2436
|
+
// it after; the queue below serializes renders, so one slot is enough.
|
|
2437
|
+
const qi = pathname.indexOf('?');
|
|
2438
|
+
const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
|
|
1972
2439
|
const p = prefetchQueue.then(async () => {
|
|
1973
2440
|
try {
|
|
2441
|
+
setPrefetchOverride(qOverride);
|
|
1974
2442
|
// the isolated render also captures the onMount callbacks the route
|
|
1975
2443
|
// queued and the onCleanup disposers it registered: the paint that
|
|
1976
2444
|
// consumes this entry replays the mounts after wiring and adopts the
|
|
@@ -1997,6 +2465,7 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
1997
2465
|
prefetchCache.delete(pathname); // failed: the next hover retries
|
|
1998
2466
|
return null;
|
|
1999
2467
|
} finally {
|
|
2468
|
+
setPrefetchOverride(null);
|
|
2000
2469
|
prefetchPending--;
|
|
2001
2470
|
}
|
|
2002
2471
|
});
|
|
@@ -2061,6 +2530,13 @@ export async function $action(name, e) {
|
|
|
2061
2530
|
|
|
2062
2531
|
export { postForm };
|
|
2063
2532
|
|
|
2533
|
+
// The live signal graph as JSON - the same serializeState the zero-hydration
|
|
2534
|
+
// resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
|
|
2535
|
+
// can hand it to the dev server's reload bridge and to a devtools extension.
|
|
2536
|
+
// A local re-export on purpose: it keeps the binding alive through minification
|
|
2537
|
+
// for the bootstrap text appended after the bundle.
|
|
2538
|
+
export { serializeState };
|
|
2539
|
+
|
|
2064
2540
|
// initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
|
|
2065
2541
|
// the existing nodes and bind events. initial=false: client-side navigation -
|
|
2066
2542
|
// re-render the route chain from scratch and wire the fresh DOM.
|
|
@@ -2400,13 +2876,34 @@ document.addEventListener('submit', (e) => {
|
|
|
2400
2876
|
e.preventDefault();
|
|
2401
2877
|
postForm(new FormData(f));
|
|
2402
2878
|
});
|
|
2879
|
+
// Dev seam: the live signal graph, readable as JSON. Two callers, one
|
|
2880
|
+
// implementation: the dev server's reload bridge snapshots it before a
|
|
2881
|
+
// rebuild-triggered reload so the edit lands on the state the developer had,
|
|
2882
|
+
// and a devtools extension reads it the same way. It is the same
|
|
2883
|
+
// serializeState the zero-hydration resume already ships, so the only new
|
|
2884
|
+
// bytes are the assignment.
|
|
2885
|
+
window.__rosetack = { state: () => serializeState() };
|
|
2403
2886
|
// initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
|
|
2404
2887
|
// If the document was rendered for a DIFFERENT route (a static-file server's
|
|
2405
2888
|
// SPA fallback serves index.html for unknown paths), adopt nothing - let the
|
|
2406
2889
|
// client router render the requested route from scratch.
|
|
2407
2890
|
const __st = document.getElementById('__rosetack_state');
|
|
2408
|
-
|
|
2409
|
-
|
|
2891
|
+
let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
|
|
2892
|
+
// The dev server's reload bridge hands the pre-reload signal graph back inside
|
|
2893
|
+
// the next document (window.__rosetack_resume). The resumed values win over the
|
|
2894
|
+
// fresh render's, but the ROUTE stays the one the server just rendered - and
|
|
2895
|
+
// the route renders client-side from the bundle rather than adopting the SSR
|
|
2896
|
+
// DOM, because a resumed list can be longer than the document's rows and
|
|
2897
|
+
// adoption could not add them. Absent in every non-dev document.
|
|
2898
|
+
const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
|
|
2899
|
+
if (__resumed) {
|
|
2900
|
+
const __route = __state.__route;
|
|
2901
|
+
__state = Object.assign(__state, __resumed);
|
|
2902
|
+
__state.__route = __route;
|
|
2903
|
+
}
|
|
2904
|
+
if (__resumed) {
|
|
2905
|
+
start(__app, window.location.pathname);
|
|
2906
|
+
} else if (__state.__route === window.location.pathname) {
|
|
2410
2907
|
start(__app, window.location.pathname, true);
|
|
2411
2908
|
} else {
|
|
2412
2909
|
start(__app, window.location.pathname);
|
|
@@ -2466,6 +2963,7 @@ var STYLES_MIN = STYLES.replace(
|
|
|
2466
2963
|
function mergeHeadBlocks(blocks) {
|
|
2467
2964
|
const byKey = /* @__PURE__ */ new Map();
|
|
2468
2965
|
const order = [];
|
|
2966
|
+
const positional = /* @__PURE__ */ new Map();
|
|
2469
2967
|
const put = (key, html) => {
|
|
2470
2968
|
if (!byKey.has(key)) {
|
|
2471
2969
|
byKey.set(key, html);
|
|
@@ -2474,11 +2972,20 @@ function mergeHeadBlocks(blocks) {
|
|
|
2474
2972
|
};
|
|
2475
2973
|
for (const block of blocks) {
|
|
2476
2974
|
for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
|
|
2477
|
-
for (const m of block.matchAll(/<(
|
|
2975
|
+
for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
|
|
2478
2976
|
const tag = m[1].toLowerCase();
|
|
2479
|
-
|
|
2480
|
-
const
|
|
2481
|
-
const
|
|
2977
|
+
if (tag === "title") continue;
|
|
2978
|
+
const attrs = m[2];
|
|
2979
|
+
const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
|
|
2980
|
+
const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
|
|
2981
|
+
let key;
|
|
2982
|
+
if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
|
|
2983
|
+
else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
|
|
2984
|
+
else {
|
|
2985
|
+
key = `${tag}:#${positional.get(tag) ?? 0}`;
|
|
2986
|
+
positional.set(tag, (positional.get(tag) ?? 0) + 1);
|
|
2987
|
+
}
|
|
2988
|
+
const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
|
|
2482
2989
|
put(key, marked);
|
|
2483
2990
|
}
|
|
2484
2991
|
}
|
|
@@ -2517,16 +3024,19 @@ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(),
|
|
|
2517
3024
|
const jsTail = js ? `
|
|
2518
3025
|
<script type="application/json" id="__rosetack_state">${stateJson}</script>
|
|
2519
3026
|
${clientTag}` : "";
|
|
3027
|
+
const open = js ? '<div id="app">' : "";
|
|
3028
|
+
const close = js ? "</div>" : "";
|
|
3029
|
+
const shellStyles = js ? `
|
|
3030
|
+
<style>${STYLES_MIN}</style>` : "";
|
|
2520
3031
|
return `<!DOCTYPE html>
|
|
2521
3032
|
<html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
|
|
2522
3033
|
<head>
|
|
2523
3034
|
<meta charset="UTF-8">
|
|
2524
3035
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
|
|
2525
|
-
${titleTag}
|
|
2526
|
-
<style>${STYLES_MIN}</style>${styleTag}
|
|
3036
|
+
${titleTag}${shellStyles}${styleTag}
|
|
2527
3037
|
</head>
|
|
2528
3038
|
<body>
|
|
2529
|
-
|
|
3039
|
+
${open}${ssrHtml}${close}${jsTail}
|
|
2530
3040
|
</body>
|
|
2531
3041
|
</html>`;
|
|
2532
3042
|
}
|
|
@@ -2534,6 +3044,121 @@ function getHtmlShell(ssrHtml, stateJson, head = [], js = true, lang = "en", dir
|
|
|
2534
3044
|
return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce);
|
|
2535
3045
|
}
|
|
2536
3046
|
|
|
3047
|
+
// src/cli/prompt.ts
|
|
3048
|
+
var AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
|
|
3049
|
+
|
|
3050
|
+
rosetack is a zero-hydration web framework: a .rose file compiles to a server
|
|
3051
|
+
render plus a client resume bundle, one request per page, no hydration. Write
|
|
3052
|
+
the smallest thing that works - the compiler decides what ships.
|
|
3053
|
+
|
|
3054
|
+
## File layout (all paths relative to the project root)
|
|
3055
|
+
|
|
3056
|
+
- src/pages/index.rose -> route /
|
|
3057
|
+
- src/pages/about.rose -> route /about
|
|
3058
|
+
- src/pages/blog/[id].rose -> route /blog/:id (the param is readable as state \`id()\`)
|
|
3059
|
+
- src/pages/[lang]/about.rose -> localized route (see i18n below)
|
|
3060
|
+
- src/pages/_layout.rose -> root layout wrapping every route (app-global exports live here)
|
|
3061
|
+
- src/pages/_middleware.rose -> server-only request middleware (handle(request), getContext())
|
|
3062
|
+
- src/pages/404.rose, 500.rose -> error pages
|
|
3063
|
+
- src/pages/api/posts.rose -> JSON API route (export async function GET/POST/...)
|
|
3064
|
+
- src/components/Card.rose -> reusable component, imported by relative path
|
|
3065
|
+
- src/locales/en.json -> i18n dictionaries (one file per language)
|
|
3066
|
+
|
|
3067
|
+
## A page
|
|
3068
|
+
|
|
3069
|
+
\`\`\`rose
|
|
3070
|
+
<script>
|
|
3071
|
+
let count = $state(0); // reactive state: read it as count()
|
|
3072
|
+
let posts = $data(async () => db.query()); // server data: awaited on the server,
|
|
3073
|
+
// resumed on the client - never re-fetched
|
|
3074
|
+
const total = count() + 1; // a top-level read AFTER the declaration is fine
|
|
3075
|
+
async function like() { // a server action (progressive enhancement)
|
|
3076
|
+
return $merge({ likes: 1 });
|
|
3077
|
+
}
|
|
3078
|
+
</script>
|
|
3079
|
+
|
|
3080
|
+
<h1>Posts</h1>
|
|
3081
|
+
<p>Total: {total}</p>
|
|
3082
|
+
<button on:click={() => $setState('count', count() + 1)}>+1</button>
|
|
3083
|
+
<form method="POST"><button formaction="?__action=like">Like</button></form>
|
|
3084
|
+
\`\`\`
|
|
3085
|
+
|
|
3086
|
+
Rules the compiler enforces (breaking one fails the build):
|
|
3087
|
+
|
|
3088
|
+
- The script block is TypeScript. Types, interfaces, \`import type\`, \`as\` casts and
|
|
3089
|
+
type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
|
|
3090
|
+
- $state / $data declarations are top-level statements. The declared name IS the
|
|
3091
|
+
getter: write count() in the template and the script, never bare count.
|
|
3092
|
+
- A route param (pages/blog/[id].rose) is read as state too: declare it
|
|
3093
|
+
(\`let id = $state('1')\`) and read id() - the server overwrites the default
|
|
3094
|
+
with the URL's value, and export const params = { id: [...] } bakes those
|
|
3095
|
+
values at build time.
|
|
3096
|
+
- $data() is banned in components (src/components/**) - a component renders
|
|
3097
|
+
synchronously inside its parent. Fetch in the page or the middleware and pass
|
|
3098
|
+
the value down as a prop.
|
|
3099
|
+
- Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
|
|
3100
|
+
trusted-HTML escape hatch - use it only for content you control.
|
|
3101
|
+
- Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
|
|
3102
|
+
{#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
|
|
3103
|
+
- A <slot> with attributes is a named slot and must declare its name:
|
|
3104
|
+
<slot name="row" item={post} />. A named slot must be a DIRECT child of the
|
|
3105
|
+
component tag - never inside another element or an {#if}/{#each} block.
|
|
3106
|
+
- Every component tag needs its matching close tag (or self-closes with />).
|
|
3107
|
+
- In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
|
|
3108
|
+
through. A <style> inside <head> is document CSS; a <style> in the body is
|
|
3109
|
+
the component's scoped stylesheet.
|
|
3110
|
+
- Node-only modules (node:fs, better-sqlite3, pg, redis, ...) are REFUSED in
|
|
3111
|
+
pages and components: their script ships to the browser. Import them in
|
|
3112
|
+
src/pages/_middleware.rose or a pages/api/*.rose handler instead, and pass
|
|
3113
|
+
the rows to the page through getContext().
|
|
3114
|
+
|
|
3115
|
+
## Events and server actions
|
|
3116
|
+
|
|
3117
|
+
- on:click={handler} wires a client event. The handler is a named function from
|
|
3118
|
+
the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
|
|
3119
|
+
- A server action is an exported async function. Call it from a native form
|
|
3120
|
+
(method="POST", no JS needed - progressive enhancement) or from any event
|
|
3121
|
+
(on:click={like} - one POST, in-place adopt). Its return value is an
|
|
3122
|
+
incremental patch: $append(row) / $prepend(row) / $merge({...}).
|
|
3123
|
+
- Business failures: throw new ActionError('message', 422, 'field'). It lands
|
|
3124
|
+
in ordinary state - $actionError() reads it back, a {#boundary} contains it.
|
|
3125
|
+
- beforeAction(name, form) is the per-page guard that vetoes an action.
|
|
3126
|
+
|
|
3127
|
+
## Route exports (in the script block, validated at build time)
|
|
3128
|
+
|
|
3129
|
+
- export const csr = false | true force/assert zero-JS (absent = the compiler decides)
|
|
3130
|
+
- export const buffer = true keep this route off the streaming path
|
|
3131
|
+
- export const headers = { ... } flat string map, merged over the strict CSP default
|
|
3132
|
+
- export const csp = { nonce: true } per-response nonce instead of the hash (route becomes dynamic)
|
|
3133
|
+
- export const prefetch = 'off' | 'hover' | 'viewport' | 'all' app-global, root layout only
|
|
3134
|
+
- export const bundle = 'inline' | 'split' app-global; 'split' = mode B for large apps
|
|
3135
|
+
- export const vitals = true opt into the web-vitals hook
|
|
3136
|
+
- export const revalidate = N stale-while-revalidate ISR window, seconds
|
|
3137
|
+
- export const params = { id: ['1'] } prerender these param values at build time
|
|
3138
|
+
- export const prerender = true (api routes) bake the GET body for static deploys
|
|
3139
|
+
|
|
3140
|
+
## i18n
|
|
3141
|
+
|
|
3142
|
+
src/locales/<lang>.json is a dictionary; a [lang] route segment selects one;
|
|
3143
|
+
$t('key', { name }) translates reactively; unknown locales answer 404.
|
|
3144
|
+
|
|
3145
|
+
## When a build fails
|
|
3146
|
+
|
|
3147
|
+
Every compiler failure is structured: { code, file, line, message, hint }.
|
|
3148
|
+
Run \`rosetack build --json\` to read it as JSON, fix the named file at the named
|
|
3149
|
+
line, and build again. Codes: E-IMPORT (unresolvable .rose import), E-PLUGIN
|
|
3150
|
+
(transform threw), E-NODE-ONLY (server-only import in a page/component),
|
|
3151
|
+
E-EXPORT (invalid export const value), E-TEMPLATE (unclosed tag / slot
|
|
3152
|
+
placement), E-ROUTE (no pages found), E-INTERNAL (installation problem).
|
|
3153
|
+
|
|
3154
|
+
## The one invariant worth protecting
|
|
3155
|
+
|
|
3156
|
+
A route ships ONE request with ZERO hydration: the whole client bundle is
|
|
3157
|
+
inlined in the document. Keep it that way - browser-only code (document.,
|
|
3158
|
+
window., timers) belongs in onMount, and anything the predicate cannot see
|
|
3159
|
+
(inline on* attributes, javascript: URLs, eval) is reported by the build.
|
|
3160
|
+
`;
|
|
3161
|
+
|
|
2537
3162
|
// src/cli/index.ts
|
|
2538
3163
|
function pickEncoding(req) {
|
|
2539
3164
|
const ae = req.headers["accept-encoding"] || "";
|
|
@@ -2570,7 +3195,7 @@ function sendHtml(req, res, status, html, extraHeaders) {
|
|
|
2570
3195
|
return;
|
|
2571
3196
|
}
|
|
2572
3197
|
res.setHeader("ETag", etag);
|
|
2573
|
-
const enc = pickEncoding(req);
|
|
3198
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
2574
3199
|
if (enc) {
|
|
2575
3200
|
res.setHeader("Content-Encoding", enc);
|
|
2576
3201
|
res.end(compress(enc, html));
|
|
@@ -2597,15 +3222,23 @@ async function sendPage(req, res, ssrModule, hookCtx, page, routePath) {
|
|
|
2597
3222
|
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
|
|
2598
3223
|
let headers = pageHeaders(ssrModule, routePath, nonce);
|
|
2599
3224
|
if (hookCtx) {
|
|
2600
|
-
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
3225
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
3226
|
+
status,
|
|
3227
|
+
headers: { "content-type": "text/html; charset=utf-8", ...headers }
|
|
3228
|
+
}));
|
|
2601
3229
|
status = out.status;
|
|
2602
3230
|
headers = webHeadersToNode(out);
|
|
2603
|
-
html = await out.text();
|
|
3231
|
+
html = out.bodyUsed ? html : await out.text();
|
|
2604
3232
|
}
|
|
2605
3233
|
sendHtml(req, res, status, html, headers);
|
|
2606
3234
|
}
|
|
2607
3235
|
var fileCache = /* @__PURE__ */ new Map();
|
|
2608
|
-
var
|
|
3236
|
+
var __portArg = process.argv.find((a) => a === "--port" || a.startsWith("--port="));
|
|
3237
|
+
if (__portArg) {
|
|
3238
|
+
const __v = __portArg.includes("=") ? __portArg.slice("--port=".length) : process.argv[process.argv.indexOf(__portArg) + 1];
|
|
3239
|
+
if (__v && Number(__v) > 0) process.env.PORT = __v;
|
|
3240
|
+
}
|
|
3241
|
+
var SRC_DIR = process.argv[3] && !process.argv[3].startsWith("-") ? path3.resolve(process.argv[3]) : process.cwd();
|
|
2609
3242
|
var OUT_DIR2 = path3.join(process.cwd(), "dist");
|
|
2610
3243
|
var PORT = Number(process.env.PORT) || 3e3;
|
|
2611
3244
|
var serverModule = null;
|
|
@@ -2617,7 +3250,13 @@ async function loadServer() {
|
|
|
2617
3250
|
if (!serverModule || mtimeMs !== serverMtime) {
|
|
2618
3251
|
serverMtime = mtimeMs;
|
|
2619
3252
|
serverVersion++;
|
|
2620
|
-
|
|
3253
|
+
let target = file;
|
|
3254
|
+
if (devMode) {
|
|
3255
|
+
target = path3.join(OUT_DIR2, ".build", `server-${serverVersion}.mjs`);
|
|
3256
|
+
await fs3.promises.mkdir(path3.dirname(target), { recursive: true });
|
|
3257
|
+
await fs3.promises.copyFile(file, target);
|
|
3258
|
+
}
|
|
3259
|
+
serverModule = await import(pathToFileURL2(target).href);
|
|
2621
3260
|
}
|
|
2622
3261
|
return serverModule;
|
|
2623
3262
|
}
|
|
@@ -2633,6 +3272,7 @@ async function build2() {
|
|
|
2633
3272
|
routes: ssrModule.routeHeaders ?? []
|
|
2634
3273
|
}));
|
|
2635
3274
|
await writeBrotli(OUT_DIR2);
|
|
3275
|
+
await analyze(OUT_DIR2, ssrModule.dynamicRoutes ?? []);
|
|
2636
3276
|
}
|
|
2637
3277
|
var BROTLI_EXT = /* @__PURE__ */ new Set([".html", ".js", ".css", ".json", ".svg", ".txt"]);
|
|
2638
3278
|
async function writeBrotli(dir) {
|
|
@@ -2646,6 +3286,43 @@ async function writeBrotli(dir) {
|
|
|
2646
3286
|
await fs3.promises.writeFile(p + ".br", zlib.brotliCompressSync(await fs3.promises.readFile(p)));
|
|
2647
3287
|
}
|
|
2648
3288
|
}
|
|
3289
|
+
async function analyze(outDir, dynamic) {
|
|
3290
|
+
const rows = [];
|
|
3291
|
+
const walk = async (dir, prefix) => {
|
|
3292
|
+
for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
|
|
3293
|
+
if (e.isDirectory()) {
|
|
3294
|
+
await walk(path3.join(dir, e.name), `${prefix}/${e.name}`);
|
|
3295
|
+
continue;
|
|
3296
|
+
}
|
|
3297
|
+
if (!e.name.endsWith(".html")) continue;
|
|
3298
|
+
const file = path3.join(dir, e.name);
|
|
3299
|
+
const raw = await fs3.promises.readFile(file);
|
|
3300
|
+
const brFile = `${file}.br`;
|
|
3301
|
+
rows.push({
|
|
3302
|
+
route: prefix || "/",
|
|
3303
|
+
raw: raw.length,
|
|
3304
|
+
gzip: zlib.gzipSync(raw, { level: 9 }).length,
|
|
3305
|
+
br: fs3.existsSync(brFile) ? (await fs3.promises.stat(brFile)).size : 0,
|
|
3306
|
+
js: /<script type="module"/.test(raw.toString("utf8"))
|
|
3307
|
+
});
|
|
3308
|
+
}
|
|
3309
|
+
};
|
|
3310
|
+
await walk(outDir, "");
|
|
3311
|
+
const kb = (n) => `${(n / 1024).toFixed(1)} KB`;
|
|
3312
|
+
const lines = ["rosetack build analysis (measured from dist/; br = the precompressed bytes the Go binary serves):"];
|
|
3313
|
+
for (const r of rows.sort((a, b) => a.route < b.route ? -1 : 1)) {
|
|
3314
|
+
lines.push(` ${r.route.padEnd(16)}${kb(r.raw).padStart(9)} raw ${kb(r.gzip).padStart(8)} gzip ${kb(r.br).padStart(8)} br ${r.js ? "bundle inlined" : "zero-JS"}`);
|
|
3315
|
+
}
|
|
3316
|
+
const client = path3.join(outDir, "client.js");
|
|
3317
|
+
if (fs3.existsSync(client)) {
|
|
3318
|
+
const raw = await fs3.promises.readFile(client);
|
|
3319
|
+
lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs3.existsSync(`${client}.br`) ? (await fs3.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
|
|
3320
|
+
}
|
|
3321
|
+
if (dynamic.length > 0) {
|
|
3322
|
+
lines.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${dynamic.join(" ")}`);
|
|
3323
|
+
}
|
|
3324
|
+
for (const l of lines) console.log(l);
|
|
3325
|
+
}
|
|
2649
3326
|
async function clearPrerendered(dir, depth = 0) {
|
|
2650
3327
|
for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
|
|
2651
3328
|
if (depth === 0 && e.name === "locales" && e.isDirectory()) continue;
|
|
@@ -2676,6 +3353,7 @@ async function prerender(routes) {
|
|
|
2676
3353
|
skipped.push(routePath);
|
|
2677
3354
|
return;
|
|
2678
3355
|
}
|
|
3356
|
+
ssrModule.setQuery?.({});
|
|
2679
3357
|
const page = await ssrModule.renderPage(routePath);
|
|
2680
3358
|
if (page.status === 500) {
|
|
2681
3359
|
console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
|
|
@@ -2761,6 +3439,7 @@ function revalidateInBackground(routePath, filePath) {
|
|
|
2761
3439
|
void (async () => {
|
|
2762
3440
|
try {
|
|
2763
3441
|
const ssrModule = await loadServer();
|
|
3442
|
+
ssrModule.setQuery?.({});
|
|
2764
3443
|
const page = await ssrModule.renderPage(routePath);
|
|
2765
3444
|
if (page.status === 200) {
|
|
2766
3445
|
await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
@@ -2860,7 +3539,75 @@ function webHeadersToNode(web) {
|
|
|
2860
3539
|
if (cookies.length) out["set-cookie"] = cookies;
|
|
2861
3540
|
return out;
|
|
2862
3541
|
}
|
|
2863
|
-
|
|
3542
|
+
var DEV_BRIDGE = `<script>(function(){var es=new EventSource('/__rosetack_reload');es.onmessage=function(m){if(m.data!=='rebuild')return;es.close();var s=window.__rosetack?window.__rosetack.state():null;if(s)fetch('/__rosetack_state',{method:'POST',body:s,headers:{'content-type':'application/json'}}).catch(function(){});setTimeout(function(){location.reload()},40)}})()</script>`;
|
|
3543
|
+
var devResume = null;
|
|
3544
|
+
var devClients = /* @__PURE__ */ new Set();
|
|
3545
|
+
var devMode = false;
|
|
3546
|
+
function devReload(req, res) {
|
|
3547
|
+
res.writeHead(200, {
|
|
3548
|
+
"Content-Type": "text/event-stream",
|
|
3549
|
+
"Cache-Control": "no-cache, no-transform",
|
|
3550
|
+
Connection: "keep-alive"
|
|
3551
|
+
});
|
|
3552
|
+
res.write(": ok\n\n");
|
|
3553
|
+
devClients.add(res);
|
|
3554
|
+
req.on("close", () => devClients.delete(res));
|
|
3555
|
+
}
|
|
3556
|
+
function devSaveState(req, res) {
|
|
3557
|
+
let body = "";
|
|
3558
|
+
req.on("data", (c) => {
|
|
3559
|
+
body += c;
|
|
3560
|
+
if (body.length > 1e6) req.destroy();
|
|
3561
|
+
});
|
|
3562
|
+
req.on("end", () => {
|
|
3563
|
+
try {
|
|
3564
|
+
JSON.parse(body);
|
|
3565
|
+
devResume = body;
|
|
3566
|
+
} catch {
|
|
3567
|
+
}
|
|
3568
|
+
res.writeHead(204).end();
|
|
3569
|
+
});
|
|
3570
|
+
}
|
|
3571
|
+
function devNotify() {
|
|
3572
|
+
for (const res of devClients) {
|
|
3573
|
+
try {
|
|
3574
|
+
res.write("data: rebuild\n\n");
|
|
3575
|
+
} catch {
|
|
3576
|
+
devClients.delete(res);
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
}
|
|
3580
|
+
function devWrap(inner) {
|
|
3581
|
+
devMode = true;
|
|
3582
|
+
return (req, res) => {
|
|
3583
|
+
const url = req.url || "/";
|
|
3584
|
+
if (url.startsWith("/__rosetack_reload")) return devReload(req, res);
|
|
3585
|
+
if (url.startsWith("/__rosetack_state") && req.method === "POST") return devSaveState(req, res);
|
|
3586
|
+
let injected = false;
|
|
3587
|
+
const seed = devResume;
|
|
3588
|
+
devResume = null;
|
|
3589
|
+
const isHtml = () => String(res.getHeader("content-type") || "").includes("text/html");
|
|
3590
|
+
const inject = (chunk) => {
|
|
3591
|
+
if (injected || !isHtml()) return chunk;
|
|
3592
|
+
const s = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
|
3593
|
+
const at = s.indexOf("<head>");
|
|
3594
|
+
if (at < 0) return chunk;
|
|
3595
|
+
injected = true;
|
|
3596
|
+
const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\//g, "<\\/")}</script>` : "";
|
|
3597
|
+
const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
|
|
3598
|
+
return Buffer.isBuffer(chunk) ? Buffer.from(out, "utf8") : out;
|
|
3599
|
+
};
|
|
3600
|
+
const write = res.write.bind(res);
|
|
3601
|
+
res.write = (chunk, ...rest) => write(inject(chunk), ...rest);
|
|
3602
|
+
const end = res.end.bind(res);
|
|
3603
|
+
res.end = (chunk, ...rest) => {
|
|
3604
|
+
if (!res.headersSent && isHtml()) res.removeHeader("Content-Security-Policy");
|
|
3605
|
+
end(chunk === void 0 || chunk === null ? chunk : inject(chunk), ...rest);
|
|
3606
|
+
};
|
|
3607
|
+
inner(req, res);
|
|
3608
|
+
};
|
|
3609
|
+
}
|
|
3610
|
+
function serveStatic(dir, isr = false, dev2 = false) {
|
|
2864
3611
|
return (req, res) => {
|
|
2865
3612
|
const blocked = crossSiteWrite(req);
|
|
2866
3613
|
if (blocked) {
|
|
@@ -2900,6 +3647,7 @@ function serveStatic(dir, isr = false) {
|
|
|
2900
3647
|
headers,
|
|
2901
3648
|
body: body.length > 0 ? body : void 0
|
|
2902
3649
|
});
|
|
3650
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
2903
3651
|
let apiRes = await ssrModule.handleApi(req.method || "GET", apiPath, request);
|
|
2904
3652
|
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
2905
3653
|
writeWebHeaders(apiRes, res);
|
|
@@ -2926,16 +3674,20 @@ function serveStatic(dir, isr = false) {
|
|
|
2926
3674
|
return;
|
|
2927
3675
|
}
|
|
2928
3676
|
}
|
|
2929
|
-
|
|
3677
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
3678
|
+
const page2 = await ssrModule.renderPage(pathnameOf(req.url || "/"), form);
|
|
2930
3679
|
await sendPage(req, res, ssrModule, hookCtx, page2, pathnameOf(req.url || "/"));
|
|
2931
|
-
} catch {
|
|
2932
|
-
|
|
2933
|
-
res.
|
|
3680
|
+
} catch (err) {
|
|
3681
|
+
console.error(`rosetack: POST ${pathnameOf(req.url || "/")} failed:`, err instanceof Error ? err.stack : err);
|
|
3682
|
+
if (!res.headersSent) {
|
|
3683
|
+
res.statusCode = 400;
|
|
3684
|
+
res.end("Bad request");
|
|
3685
|
+
}
|
|
2934
3686
|
}
|
|
2935
3687
|
});
|
|
2936
3688
|
return;
|
|
2937
3689
|
}
|
|
2938
|
-
let safe = path3.normalize(req.url || "/").replace(/^(\.\.(\/)?)+/, "");
|
|
3690
|
+
let safe = path3.normalize(pathnameOf(req.url || "/")).replace(/^(\.\.(\/)?)+/, "");
|
|
2939
3691
|
if (safe === "\\" || safe === "/") safe = "/";
|
|
2940
3692
|
let filePath = path3.join(dir, safe);
|
|
2941
3693
|
if (!fs3.existsSync(filePath) && ASSET_EXT.has(path3.extname(safe).toLowerCase())) {
|
|
@@ -3004,7 +3756,7 @@ function serveStatic(dir, isr = false) {
|
|
|
3004
3756
|
res.end();
|
|
3005
3757
|
return;
|
|
3006
3758
|
}
|
|
3007
|
-
const enc = pickEncoding(req);
|
|
3759
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
3008
3760
|
res.statusCode = status;
|
|
3009
3761
|
if (enc) {
|
|
3010
3762
|
res.setHeader("Content-Encoding", enc);
|
|
@@ -3019,12 +3771,13 @@ function serveStatic(dir, isr = false) {
|
|
|
3019
3771
|
broken = new Set(JSON.parse(fs3.readFileSync(path3.join(dir, "broken.json"), "utf-8")));
|
|
3020
3772
|
} catch {
|
|
3021
3773
|
}
|
|
3022
|
-
const safe2 = req.url || "/";
|
|
3023
|
-
|
|
3774
|
+
const safe2 = pathnameOf(req.url || "/");
|
|
3775
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
3776
|
+
if (!dev2 && !broken.has(safe2) && !ssrModule.isBuffered?.(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
3024
3777
|
const enc = pickEncoding(req);
|
|
3025
3778
|
let status = 200;
|
|
3026
|
-
const nonce = nonceFor(ssrModule,
|
|
3027
|
-
let headers = pageHeaders(ssrModule,
|
|
3779
|
+
const nonce = nonceFor(ssrModule, safe2);
|
|
3780
|
+
let headers = pageHeaders(ssrModule, safe2, nonce);
|
|
3028
3781
|
if (hookCtx) {
|
|
3029
3782
|
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers }));
|
|
3030
3783
|
status = out.status;
|
|
@@ -3060,10 +3813,16 @@ function serveStatic(dir, isr = false) {
|
|
|
3060
3813
|
return;
|
|
3061
3814
|
}
|
|
3062
3815
|
const page = await ssrModule.renderPage(safe2);
|
|
3063
|
-
await sendPage(req, res, ssrModule, hookCtx, page,
|
|
3064
|
-
}).catch(() => {
|
|
3065
|
-
|
|
3066
|
-
res.
|
|
3816
|
+
await sendPage(req, res, ssrModule, hookCtx, page, safe2);
|
|
3817
|
+
}).catch((err) => {
|
|
3818
|
+
console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
|
|
3819
|
+
if (res.headersSent) {
|
|
3820
|
+
res.destroy();
|
|
3821
|
+
return;
|
|
3822
|
+
}
|
|
3823
|
+
res.statusCode = 500;
|
|
3824
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
3825
|
+
res.end("<h1>500</h1><p>Something went wrong rendering this page.</p>");
|
|
3067
3826
|
});
|
|
3068
3827
|
};
|
|
3069
3828
|
}
|
|
@@ -3074,6 +3833,48 @@ function pathnameOf(url) {
|
|
|
3074
3833
|
return (url || "/").split("?")[0];
|
|
3075
3834
|
}
|
|
3076
3835
|
}
|
|
3836
|
+
function queryOf(url) {
|
|
3837
|
+
const q = {};
|
|
3838
|
+
try {
|
|
3839
|
+
new URL(url || "/", "http://localhost").searchParams.forEach((v, k) => {
|
|
3840
|
+
if (!(k in q)) q[k] = v;
|
|
3841
|
+
});
|
|
3842
|
+
} catch {
|
|
3843
|
+
}
|
|
3844
|
+
return q;
|
|
3845
|
+
}
|
|
3846
|
+
function listenFree(server, port, onReady) {
|
|
3847
|
+
const attempt = (p) => {
|
|
3848
|
+
const onError = (err) => {
|
|
3849
|
+
server.removeListener("error", onError);
|
|
3850
|
+
if (err && err.code === "EADDRINUSE" && p - port < 20) {
|
|
3851
|
+
console.log(`\u{1F339} port ${p} is in use - trying ${p + 1}`);
|
|
3852
|
+
attempt(p + 1);
|
|
3853
|
+
return;
|
|
3854
|
+
}
|
|
3855
|
+
console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
|
|
3856
|
+
process.exit(1);
|
|
3857
|
+
};
|
|
3858
|
+
server.once("error", onError);
|
|
3859
|
+
server.listen(p, () => {
|
|
3860
|
+
server.removeListener("error", onError);
|
|
3861
|
+
onReady(p);
|
|
3862
|
+
});
|
|
3863
|
+
};
|
|
3864
|
+
attempt(port);
|
|
3865
|
+
}
|
|
3866
|
+
async function freePort(from) {
|
|
3867
|
+
const net = await import("node:net");
|
|
3868
|
+
for (let p = from; p < from + 20; p++) {
|
|
3869
|
+
const free = await new Promise((resolve3) => {
|
|
3870
|
+
const probe = net.createServer();
|
|
3871
|
+
probe.once("error", () => resolve3(false));
|
|
3872
|
+
probe.listen(p, () => probe.close(() => resolve3(true)));
|
|
3873
|
+
});
|
|
3874
|
+
if (free) return p;
|
|
3875
|
+
}
|
|
3876
|
+
return from;
|
|
3877
|
+
}
|
|
3077
3878
|
function version() {
|
|
3078
3879
|
for (const rel of ["../../package.json", "../package.json"]) {
|
|
3079
3880
|
try {
|
|
@@ -3098,23 +3899,24 @@ async function dev() {
|
|
|
3098
3899
|
try {
|
|
3099
3900
|
console.log("Rebuilding...");
|
|
3100
3901
|
await build2();
|
|
3902
|
+
devNotify();
|
|
3101
3903
|
} catch (err) {
|
|
3102
|
-
console.error("Build failed (server still running):", err instanceof Error ? err.message : err);
|
|
3904
|
+
console.error("Build failed (server still running):", err instanceof Error ? err.message : String(err));
|
|
3103
3905
|
}
|
|
3104
3906
|
}, 200);
|
|
3105
3907
|
});
|
|
3106
3908
|
const http = await import("http");
|
|
3107
|
-
const server = http.createServer(serveStatic(OUT_DIR2));
|
|
3108
|
-
server
|
|
3109
|
-
console.log("\u{1F339} http://localhost:" +
|
|
3909
|
+
const server = http.createServer(devWrap(serveStatic(OUT_DIR2, false, true)));
|
|
3910
|
+
listenFree(server, PORT, (port) => {
|
|
3911
|
+
console.log("\u{1F339} http://localhost:" + port);
|
|
3110
3912
|
});
|
|
3111
3913
|
}
|
|
3112
3914
|
async function preview() {
|
|
3113
3915
|
await build2();
|
|
3114
3916
|
const http = await import("http");
|
|
3115
3917
|
const server = http.createServer(serveStatic(OUT_DIR2, true));
|
|
3116
|
-
server
|
|
3117
|
-
console.log(`\u{1F339} RoseTack v${version()} preview at http://localhost:` +
|
|
3918
|
+
listenFree(server, PORT, (port) => {
|
|
3919
|
+
console.log(`\u{1F339} RoseTack v${version()} preview at http://localhost:` + port);
|
|
3118
3920
|
});
|
|
3119
3921
|
}
|
|
3120
3922
|
async function serve() {
|
|
@@ -3126,9 +3928,9 @@ async function serve() {
|
|
|
3126
3928
|
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
3127
3929
|
const os = await import("node:os");
|
|
3128
3930
|
const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
|
|
3129
|
-
const PORT2 = Number(process.env.PORT) || 3e3;
|
|
3130
3931
|
if (cluster.isPrimary) {
|
|
3131
|
-
|
|
3932
|
+
const port = await freePort(Number(process.env.PORT) || 3e3);
|
|
3933
|
+
for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
|
|
3132
3934
|
cluster.on("message", (worker, msg) => {
|
|
3133
3935
|
if (!msg || msg.type !== "rosetack:store") return;
|
|
3134
3936
|
for (const w of Object.values(cluster.workers ?? {})) {
|
|
@@ -3145,7 +3947,7 @@ async function serve() {
|
|
|
3145
3947
|
cluster.on("exit", () => {
|
|
3146
3948
|
if (--live <= 0) process.exit(0);
|
|
3147
3949
|
});
|
|
3148
|
-
console.log(`\u{1F339} RoseTack v${version()} serve: ${workers} worker${workers > 1 ? "s" : ""} on http://localhost:${
|
|
3950
|
+
console.log(`\u{1F339} RoseTack v${version()} serve: ${workers} worker${workers > 1 ? "s" : ""} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
3149
3951
|
return;
|
|
3150
3952
|
}
|
|
3151
3953
|
process.on("disconnect", () => process.exit(0));
|
|
@@ -3160,11 +3962,11 @@ async function serve() {
|
|
|
3160
3962
|
server.requestTimeout = 3e4;
|
|
3161
3963
|
server.headersTimeout = 65e3;
|
|
3162
3964
|
server.keepAliveTimeout = 5e3;
|
|
3163
|
-
server
|
|
3164
|
-
console.log(`\u{1F339} RoseTack worker ${process.pid} listening on http://localhost:${
|
|
3965
|
+
listenFree(server, PORT, async (port) => {
|
|
3966
|
+
console.log(`\u{1F339} RoseTack worker ${process.pid} listening on http://localhost:${port}`);
|
|
3165
3967
|
for (const p of servicePlugins) {
|
|
3166
3968
|
try {
|
|
3167
|
-
await p.onServe({ port
|
|
3969
|
+
await p.onServe({ port, workers });
|
|
3168
3970
|
} catch (err) {
|
|
3169
3971
|
console.error("rosetack: plugin", p.name, "onServe failed:", err instanceof Error ? err.message : err);
|
|
3170
3972
|
}
|
|
@@ -3401,11 +4203,28 @@ async function check() {
|
|
|
3401
4203
|
console.error(`rosetack: ${errors} type error${errors === 1 ? "" : "s"} in ${checked} script${checked === 1 ? "" : "s"}`);
|
|
3402
4204
|
process.exit(1);
|
|
3403
4205
|
}
|
|
3404
|
-
var
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
else
|
|
4206
|
+
var argv = process.argv.slice(2);
|
|
4207
|
+
var cmd = argv[0];
|
|
4208
|
+
var asJson = argv.includes("--json");
|
|
4209
|
+
function reportFailure(err) {
|
|
4210
|
+
if (asJson) {
|
|
4211
|
+
process.stdout.write(`${JSON.stringify({ ok: false, errors: [errorInfo(err)] })}
|
|
4212
|
+
`);
|
|
4213
|
+
} else if (err instanceof RoseError) {
|
|
4214
|
+
console.error(`rosetack: ${err.message}`);
|
|
4215
|
+
if (err.hint) console.error(` hint: ${err.hint}`);
|
|
4216
|
+
const at = err.file ? `${err.file}${err.line ? `:${err.line}` : ""}` : null;
|
|
4217
|
+
if (at) console.error(` at ${at}`);
|
|
4218
|
+
} else {
|
|
4219
|
+
console.error(err instanceof Error ? err.stack ?? err.message : String(err));
|
|
4220
|
+
}
|
|
4221
|
+
process.exit(1);
|
|
4222
|
+
}
|
|
4223
|
+
if (cmd === "dev") void dev().catch(reportFailure);
|
|
4224
|
+
else if (cmd === "build") void build2().catch(reportFailure);
|
|
4225
|
+
else if (cmd === "preview") void preview().catch(reportFailure);
|
|
4226
|
+
else if (cmd === "serve") void serve().catch(reportFailure);
|
|
4227
|
+
else if (cmd === "new") void scaffold().catch(reportFailure);
|
|
4228
|
+
else if (cmd === "check") void check().catch(reportFailure);
|
|
4229
|
+
else if (cmd === "prompt") console.log(AI_PROMPT);
|
|
4230
|
+
else console.log("Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON)");
|