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/package.json
CHANGED
package/src/FRAMEWORK_VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.1.
|
|
1
|
+
0.1.2
|
package/src/cli/edge.ts
CHANGED
|
@@ -26,6 +26,8 @@ type ServerModule = {
|
|
|
26
26
|
renderPageStream(pathname: string, write: (chunk: string) => void, shellOpen: string, clientTag: string): Promise<number>;
|
|
27
27
|
canStream(pathname: string): boolean;
|
|
28
28
|
isNoJs(pathname: string): boolean;
|
|
29
|
+
/** P0-2: routes that exported `buffer = true` - buffered, never streamed */
|
|
30
|
+
isBuffered(pathname: string): boolean;
|
|
29
31
|
isApi(pathname: string): boolean;
|
|
30
32
|
handleApi(method: string, pathname: string, request: Request): Promise<Response>;
|
|
31
33
|
/** The document's <html lang>/<dir> for a pathname (streaming needs them before the render) */
|
|
@@ -51,6 +53,8 @@ type ServerModule = {
|
|
|
51
53
|
headersFor(pathname: string): Record<string, string> | null;
|
|
52
54
|
/** Routes that exported `csp = { nonce: true }` - nonce policy, never baked */
|
|
53
55
|
cspNonce(pathname: string): boolean;
|
|
56
|
+
/** P0-1: the query of the request being rendered, for $query() */
|
|
57
|
+
setQuery(query: Record<string, string>): void;
|
|
54
58
|
};
|
|
55
59
|
|
|
56
60
|
/**
|
|
@@ -89,7 +93,10 @@ export async function createEdgeHandler(outDir: string): Promise<(request: Reque
|
|
|
89
93
|
};
|
|
90
94
|
|
|
91
95
|
return async function handle(request: Request): Promise<Response> {
|
|
92
|
-
const { pathname } = new URL(request.url);
|
|
96
|
+
const { pathname, searchParams } = new URL(request.url);
|
|
97
|
+
// P0-1: the query reaches the render through $query() - routing itself
|
|
98
|
+
// matches the pathname, exactly as the Node server does.
|
|
99
|
+
mod.setQuery?.(Object.fromEntries(searchParams));
|
|
93
100
|
// Runtime hooks: onRequest runs before middleware and routing and may short-circuit with
|
|
94
101
|
// its own Response - an auth wall, a rate limit.
|
|
95
102
|
const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks
|
|
@@ -115,7 +122,7 @@ export async function createEdgeHandler(outDir: string): Promise<(request: Reque
|
|
|
115
122
|
const form = request.method === 'POST' ? await request.formData() : undefined;
|
|
116
123
|
// csr = false routes buffer too: a streamed no-JS document would carry the shell's default
|
|
117
124
|
// <title> - the route head is applied client-side at boot, and there is no client.
|
|
118
|
-
if (!form && !broken.has(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
|
|
125
|
+
if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
|
|
119
126
|
// The nonce is minted before the Response exists, because its headers are fixed from then
|
|
120
127
|
// on - and the document's script tag is written into that same stream …
|
|
121
128
|
const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
|
package/src/cli/index.ts
CHANGED
|
@@ -7,8 +7,9 @@ import * as path from 'path';
|
|
|
7
7
|
import * as zlib from 'zlib';
|
|
8
8
|
import { createRequire } from 'module';
|
|
9
9
|
import { pathToFileURL, fileURLToPath } from 'url';
|
|
10
|
-
import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, type RouteInfo } from '../compiler/index.js';
|
|
10
|
+
import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, RoseError, errorInfo, type RouteInfo } from '../compiler/index.js';
|
|
11
11
|
import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
|
|
12
|
+
import { AI_PROMPT } from './prompt.js';
|
|
12
13
|
// Type-only: erased by esbuild/tsx, so the published CLI stays a ~100 KB bundle with no
|
|
13
14
|
// TypeScript dependency.
|
|
14
15
|
import type * as ts from 'typescript';
|
|
@@ -63,7 +64,7 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
|
|
|
63
64
|
return;
|
|
64
65
|
}
|
|
65
66
|
res.setHeader('ETag', etag);
|
|
66
|
-
const enc = pickEncoding(req);
|
|
67
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
67
68
|
if (enc) {
|
|
68
69
|
res.setHeader('Content-Encoding', enc);
|
|
69
70
|
res.end(compress(enc, html));
|
|
@@ -108,10 +109,17 @@ async function sendPage(req: any, res: any, ssrModule: any, hookCtx: any, page:
|
|
|
108
109
|
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
|
|
109
110
|
let headers: Record<string, any> = pageHeaders(ssrModule, routePath, nonce);
|
|
110
111
|
if (hookCtx) {
|
|
111
|
-
|
|
112
|
+
// P0-3: the document's content-type travels WITH the Response. The WHATWG constructor
|
|
113
|
+
// fills in text/plain when it is missing …
|
|
114
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
115
|
+
status,
|
|
116
|
+
headers: { 'content-type': 'text/html; charset=utf-8', ...headers },
|
|
117
|
+
}));
|
|
112
118
|
status = out.status;
|
|
113
119
|
headers = webHeadersToNode(out);
|
|
114
|
-
|
|
120
|
+
// P0-4: a hook that READ the body and returned the same Response cannot have it read
|
|
121
|
+
// again (TypeError: body already used) …
|
|
122
|
+
html = out.bodyUsed ? html : await out.text();
|
|
115
123
|
}
|
|
116
124
|
sendHtml(req, res, status, html, headers);
|
|
117
125
|
}
|
|
@@ -120,9 +128,17 @@ async function sendPage(req: any, res: any, ssrModule: any, hookCtx: any, page:
|
|
|
120
128
|
// preview never does).
|
|
121
129
|
const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
|
|
122
130
|
|
|
131
|
+
// P0-0 (bug report): `--port N` (or `--port=N`), the same override the PORT env gives, as
|
|
132
|
+
// an argument …
|
|
133
|
+
const __portArg = process.argv.find((a) => a === '--port' || a.startsWith('--port='));
|
|
134
|
+
if (__portArg) {
|
|
135
|
+
const __v = __portArg.includes('=') ? __portArg.slice('--port='.length) : process.argv[process.argv.indexOf(__portArg) + 1];
|
|
136
|
+
if (__v && Number(__v) > 0) process.env.PORT = __v;
|
|
137
|
+
}
|
|
138
|
+
|
|
123
139
|
// (the "the framework is real" gate): the CLI builds ANY project, not just this repo's
|
|
124
140
|
// demo.
|
|
125
|
-
const SRC_DIR = process.argv[3] ? path.resolve(process.argv[3]) : process.cwd();
|
|
141
|
+
const SRC_DIR = process.argv[3] && !process.argv[3].startsWith('-') ? path.resolve(process.argv[3]) : process.cwd();
|
|
126
142
|
// The deploy dir is ./dist of the directory the command ran from - a documented contract
|
|
127
143
|
// (test-cli.mjs asserts it): building a project that is not the cwd still drops its output …
|
|
128
144
|
const OUT_DIR = path.join(process.cwd(), 'dist');
|
|
@@ -138,6 +154,15 @@ const PORT = Number(process.env.PORT) || 3000;
|
|
|
138
154
|
* import must NOT be per-request: server state (stores mutated by server
|
|
139
155
|
* actions) lives in that module, and a fresh import per request would
|
|
140
156
|
* reset it on every hit, so an action's effect would vanish immediately.
|
|
157
|
+
*
|
|
158
|
+
* The dev re-import needs a NEW PATH, not a new `?v=` query: tsx's ESM
|
|
159
|
+
* loader (which `npm run dev` runs the CLI through) caches by resolved
|
|
160
|
+
* path and ignores the search string, so the query trick silently handed
|
|
161
|
+
* back the previous module - a rebuild that served the OLD code until the
|
|
162
|
+
* NEXT rebuild landed, which is exactly the "hot reload" a developer
|
|
163
|
+
* cannot trust. A copied file under dist/.build/ (which every build
|
|
164
|
+
* deletes, and which never ships) is a new module under any loader.
|
|
165
|
+
* Preview and serve never rebuild, so they import dist/server.js itself.
|
|
141
166
|
*/
|
|
142
167
|
let serverModule: any = null;
|
|
143
168
|
let serverMtime = -1;
|
|
@@ -149,7 +174,13 @@ async function loadServer(): Promise<any> {
|
|
|
149
174
|
if (!serverModule || mtimeMs !== serverMtime) {
|
|
150
175
|
serverMtime = mtimeMs;
|
|
151
176
|
serverVersion++;
|
|
152
|
-
|
|
177
|
+
let target = file;
|
|
178
|
+
if (devMode) {
|
|
179
|
+
target = path.join(OUT_DIR, '.build', `server-${serverVersion}.mjs`);
|
|
180
|
+
await fs.promises.mkdir(path.dirname(target), { recursive: true });
|
|
181
|
+
await fs.promises.copyFile(file, target);
|
|
182
|
+
}
|
|
183
|
+
serverModule = await import(pathToFileURL(target).href);
|
|
153
184
|
}
|
|
154
185
|
return serverModule;
|
|
155
186
|
}
|
|
@@ -178,6 +209,9 @@ async function build(): Promise<void> {
|
|
|
178
209
|
// Precompressed brotli siblings (dist/<file>.br) for the Go single binary. The binary
|
|
179
210
|
// embeds dist/ verbatim …
|
|
180
211
|
await writeBrotli(OUT_DIR);
|
|
212
|
+
// What this build actually costs on the wire, per route. Runs
|
|
213
|
+
// after writeBrotli so the br column is the file the Go binary serves.
|
|
214
|
+
await analyze(OUT_DIR, (ssrModule.dynamicRoutes as string[] | undefined) ?? []);
|
|
181
215
|
}
|
|
182
216
|
|
|
183
217
|
/**
|
|
@@ -198,6 +232,55 @@ async function writeBrotli(dir: string): Promise<void> {
|
|
|
198
232
|
}
|
|
199
233
|
}
|
|
200
234
|
|
|
235
|
+
/**
|
|
236
|
+
* The build analysis. The zero-JS report says
|
|
237
|
+
* WHICH routes ship no runtime; this says what every route costs on the
|
|
238
|
+
* wire, measured from the files this build just wrote - never from a number
|
|
239
|
+
* quoted from memory. Brotli is the `.br` sibling the build already wrote
|
|
240
|
+
* (the exact bytes the Go binary serves); gzip is computed here because the
|
|
241
|
+
* Node server compresses per request and gzip is the fallback every proxy
|
|
242
|
+
* eventually falls back to. Dynamic routes are not baked, so they are
|
|
243
|
+
* LISTED, not measured: their numbers come from `npm run benchmark`, which
|
|
244
|
+
* renders them live against `rosetack serve`.
|
|
245
|
+
*/
|
|
246
|
+
async function analyze(outDir: string, dynamic: string[]): Promise<void> {
|
|
247
|
+
const rows: Array<{ route: string; raw: number; gzip: number; br: number; js: boolean }> = [];
|
|
248
|
+
const walk = async (dir: string, prefix: string): Promise<void> => {
|
|
249
|
+
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
250
|
+
if (e.isDirectory()) {
|
|
251
|
+
await walk(path.join(dir, e.name), `${prefix}/${e.name}`);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (!e.name.endsWith('.html')) continue;
|
|
255
|
+
const file = path.join(dir, e.name);
|
|
256
|
+
const raw = await fs.promises.readFile(file);
|
|
257
|
+
const brFile = `${file}.br`;
|
|
258
|
+
rows.push({
|
|
259
|
+
route: prefix || '/',
|
|
260
|
+
raw: raw.length,
|
|
261
|
+
gzip: zlib.gzipSync(raw, { level: 9 }).length,
|
|
262
|
+
br: fs.existsSync(brFile) ? (await fs.promises.stat(brFile)).size : 0,
|
|
263
|
+
js: /<script type="module"/.test(raw.toString('utf8')),
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
await walk(outDir, '');
|
|
268
|
+
const kb = (n: number) => `${(n / 1024).toFixed(1)} KB`;
|
|
269
|
+
const lines = ['rosetack build analysis (measured from dist/; br = the precompressed bytes the Go binary serves):'];
|
|
270
|
+
for (const r of rows.sort((a, b) => (a.route < b.route ? -1 : 1))) {
|
|
271
|
+
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'}`);
|
|
272
|
+
}
|
|
273
|
+
const client = path.join(outDir, 'client.js');
|
|
274
|
+
if (fs.existsSync(client)) {
|
|
275
|
+
const raw = await fs.promises.readFile(client);
|
|
276
|
+
lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs.existsSync(`${client}.br`) ? (await fs.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
|
|
277
|
+
}
|
|
278
|
+
if (dynamic.length > 0) {
|
|
279
|
+
lines.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${dynamic.join(' ')}`);
|
|
280
|
+
}
|
|
281
|
+
for (const l of lines) console.log(l);
|
|
282
|
+
}
|
|
283
|
+
|
|
201
284
|
/**
|
|
202
285
|
* Delete the prerendered output of a previous build: HTML documents and
|
|
203
286
|
* baked API bodies, with their brotli siblings. Everything else in dist/
|
|
@@ -252,6 +335,9 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
252
335
|
skipped.push(routePath);
|
|
253
336
|
return;
|
|
254
337
|
}
|
|
338
|
+
// P0-1: a baked document has no request and therefore no query - say so
|
|
339
|
+
// explicitly, so a query from the previous render can never leak in.
|
|
340
|
+
ssrModule.setQuery?.({});
|
|
255
341
|
const page = await ssrModule.renderPage(routePath);
|
|
256
342
|
if (page.status === 500) {
|
|
257
343
|
// The route's render failed and the error page rendered instead. Do NOT bake that
|
|
@@ -372,6 +458,9 @@ function revalidateInBackground(routePath: string, filePath: string): void {
|
|
|
372
458
|
void (async () => {
|
|
373
459
|
try {
|
|
374
460
|
const ssrModule = await loadServer();
|
|
461
|
+
// P0-1: the background pass has no request either - an empty query, so
|
|
462
|
+
// the swapped file never carries another visitor's search terms.
|
|
463
|
+
ssrModule.setQuery?.({});
|
|
375
464
|
const page = await ssrModule.renderPage(routePath);
|
|
376
465
|
if (page.status === 200) {
|
|
377
466
|
// the swap must honor the route's csr decision: a zero-JS route revalidated here stays
|
|
@@ -515,7 +604,95 @@ function webHeadersToNode(web: any): Record<string, any> {
|
|
|
515
604
|
return out;
|
|
516
605
|
}
|
|
517
606
|
|
|
518
|
-
|
|
607
|
+
// --- dev-only live reload + state bridge --- The dev server rebuilds on change …
|
|
608
|
+
const 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>`;
|
|
609
|
+
// One slot: the next document a dev client asks for carries it back. trade-off: a single
|
|
610
|
+
// browser tab is the dev case …
|
|
611
|
+
let devResume: string | null = null;
|
|
612
|
+
const devClients = new Set<any>();
|
|
613
|
+
// Set once, when the dev server wraps its handler: this process serves dev documents, so
|
|
614
|
+
// sendHtml answers them buffered and uncompressed …
|
|
615
|
+
let devMode = false;
|
|
616
|
+
|
|
617
|
+
function devReload(req: any, res: any): void {
|
|
618
|
+
res.writeHead(200, {
|
|
619
|
+
'Content-Type': 'text/event-stream',
|
|
620
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
621
|
+
Connection: 'keep-alive',
|
|
622
|
+
});
|
|
623
|
+
res.write(': ok\n\n');
|
|
624
|
+
devClients.add(res);
|
|
625
|
+
req.on('close', () => devClients.delete(res));
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function devSaveState(req: any, res: any): void {
|
|
629
|
+
let body = '';
|
|
630
|
+
req.on('data', (c: any) => {
|
|
631
|
+
body += c;
|
|
632
|
+
if (body.length > 1e6) req.destroy(); // a state snapshot is kilobytes; refuse a runaway
|
|
633
|
+
});
|
|
634
|
+
req.on('end', () => {
|
|
635
|
+
try {
|
|
636
|
+
JSON.parse(body);
|
|
637
|
+
devResume = body;
|
|
638
|
+
} catch { /* a corrupt snapshot is dropped: the next render is simply fresh */ }
|
|
639
|
+
res.writeHead(204).end();
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** Push the rebuild signal to every open dev tab. */
|
|
644
|
+
function devNotify(): void {
|
|
645
|
+
for (const res of devClients) {
|
|
646
|
+
try {
|
|
647
|
+
res.write('data: rebuild\n\n');
|
|
648
|
+
} catch {
|
|
649
|
+
devClients.delete(res);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Wrap a dev response so every HTML document carries the bridge (and the
|
|
656
|
+
* resumed state, once). Wrapping res is the one choke point that covers the
|
|
657
|
+
* buffered and the streamed paths alike - the alternative is a flag threaded
|
|
658
|
+
* through five call sites plus the generated server bundle's own shell writer.
|
|
659
|
+
* The bridge script is not hashed, so dev also drops the CSP header: the hash
|
|
660
|
+
* policy is a production guarantee and dev documents are localhost-only.
|
|
661
|
+
*/
|
|
662
|
+
function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => void {
|
|
663
|
+
devMode = true;
|
|
664
|
+
return (req, res) => {
|
|
665
|
+
const url = req.url || '/';
|
|
666
|
+
if (url.startsWith('/__rosetack_reload')) return devReload(req, res);
|
|
667
|
+
if (url.startsWith('/__rosetack_state') && req.method === 'POST') return devSaveState(req, res);
|
|
668
|
+
let injected = false;
|
|
669
|
+
// The resumed snapshot belongs to the NEXT request, whatever it turns out to be: a
|
|
670
|
+
// document that answers 304 (nothing changed) consumes it too …
|
|
671
|
+
const seed = devResume;
|
|
672
|
+
devResume = null;
|
|
673
|
+
const isHtml = () => String(res.getHeader('content-type') || '').includes('text/html');
|
|
674
|
+
const inject = (chunk: any): any => {
|
|
675
|
+
if (injected || !isHtml()) return chunk;
|
|
676
|
+
const s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
|
|
677
|
+
const at = s.indexOf('<head>');
|
|
678
|
+
if (at < 0) return chunk; // not a document (an asset, a JSON body): leave it alone
|
|
679
|
+
injected = true;
|
|
680
|
+
const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\//g, '<\\/')}</script>` : '';
|
|
681
|
+
const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
|
|
682
|
+
return Buffer.isBuffer(chunk) ? Buffer.from(out, 'utf8') : out;
|
|
683
|
+
};
|
|
684
|
+
const write = res.write.bind(res);
|
|
685
|
+
res.write = (chunk: any, ...rest: any[]) => write(inject(chunk), ...rest);
|
|
686
|
+
const end = res.end.bind(res);
|
|
687
|
+
res.end = (chunk: any, ...rest: any[]) => {
|
|
688
|
+
if (!res.headersSent && isHtml()) res.removeHeader('Content-Security-Policy');
|
|
689
|
+
end(chunk === undefined || chunk === null ? chunk : inject(chunk), ...rest);
|
|
690
|
+
};
|
|
691
|
+
inner(req, res);
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any) => void {
|
|
519
696
|
return (req, res) => {
|
|
520
697
|
// The origin guard runs before everything else - middleware, api dispatch, the static
|
|
521
698
|
// lookup - because a cross-site write must not reach any of them.
|
|
@@ -569,6 +746,9 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
569
746
|
headers,
|
|
570
747
|
body: body.length > 0 ? body : undefined,
|
|
571
748
|
});
|
|
749
|
+
// P0-1: an api handler reads the query from its Request's URL (the full one,
|
|
750
|
+
// query included) …
|
|
751
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
572
752
|
let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
|
|
573
753
|
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
574
754
|
writeWebHeaders(apiRes, res);
|
|
@@ -600,17 +780,27 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
600
780
|
return;
|
|
601
781
|
}
|
|
602
782
|
}
|
|
603
|
-
|
|
783
|
+
// P0-1: the POST is routed by pathname too, and its query (if the form was
|
|
784
|
+
// posted to /search?ref=x) reaches the render through $query() like every other …
|
|
785
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
786
|
+
const page = await ssrModule.renderPage(pathnameOf(req.url || '/'), form);
|
|
604
787
|
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
|
|
605
|
-
} catch {
|
|
606
|
-
|
|
607
|
-
|
|
788
|
+
} catch (err) {
|
|
789
|
+
// A silent "Bad request" is how a framework bug hides: the stack goes to stderr
|
|
790
|
+
// (the same rule the GET path follows) …
|
|
791
|
+
console.error(`rosetack: POST ${pathnameOf(req.url || '/')} failed:`, err instanceof Error ? err.stack : err);
|
|
792
|
+
if (!res.headersSent) {
|
|
793
|
+
res.statusCode = 400;
|
|
794
|
+
res.end('Bad request');
|
|
795
|
+
}
|
|
608
796
|
}
|
|
609
797
|
});
|
|
610
798
|
return;
|
|
611
799
|
}
|
|
612
800
|
|
|
613
|
-
|
|
801
|
+
// P0-1: routing matches the PATHNAME. The query string rides along to the handlers
|
|
802
|
+
// ($query(), the api Request) but never into a route pattern …
|
|
803
|
+
let safe = path.normalize(pathnameOf(req.url || '/')).replace(/^(\.\.(\/)?)+/, '');
|
|
614
804
|
if (safe === '\\' || safe === '/') safe = '/';
|
|
615
805
|
let filePath = path.join(dir, safe);
|
|
616
806
|
// A file in public/ answers at the root too: pages link /logo.svg, not
|
|
@@ -698,7 +888,9 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
698
888
|
res.end();
|
|
699
889
|
return;
|
|
700
890
|
}
|
|
701
|
-
|
|
891
|
+
// Dev answers the file uncompressed: the reload bridge injects into the body, and a
|
|
892
|
+
// compressed body has no `<head>` left to find.
|
|
893
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
702
894
|
res.statusCode = status;
|
|
703
895
|
if (enc) {
|
|
704
896
|
res.setHeader('Content-Encoding', enc);
|
|
@@ -715,16 +907,22 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
715
907
|
try {
|
|
716
908
|
broken = new Set(JSON.parse(fs.readFileSync(path.join(dir, 'broken.json'), 'utf-8')));
|
|
717
909
|
} catch { /* no manifest: nothing known-broken */ }
|
|
718
|
-
|
|
719
|
-
|
|
910
|
+
// P0-1: the pathname, never the raw url - see the static branch above. The query
|
|
911
|
+
// reaches the render through $query() (setQuery below) …
|
|
912
|
+
const safe2 = pathnameOf(req.url || '/');
|
|
913
|
+
// P0-1: the query is per request and belongs to the render, not the
|
|
914
|
+
// route - set once, before either path below reads $query().
|
|
915
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
916
|
+
// P0-2: `buffer = true` routes take the buffered path even when they could stream …
|
|
917
|
+
if (!dev && !broken.has(safe2) && !ssrModule.isBuffered?.(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
720
918
|
const enc = pickEncoding(req);
|
|
721
919
|
// onResponse runs BEFORE the first flush, while the status and headers can still change:
|
|
722
920
|
// the hook is handed a bodyless Response carrying them …
|
|
723
921
|
let status = 200;
|
|
724
922
|
// The nonce is minted before the first flush, because a streamed response cannot change
|
|
725
923
|
// its headers afterwards - and the document's script tag is written into that same stream …
|
|
726
|
-
const nonce = nonceFor(ssrModule,
|
|
727
|
-
let headers: Record<string, any> = pageHeaders(ssrModule,
|
|
924
|
+
const nonce = nonceFor(ssrModule, safe2);
|
|
925
|
+
let headers: Record<string, any> = pageHeaders(ssrModule, safe2, nonce);
|
|
728
926
|
if (hookCtx) {
|
|
729
927
|
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers }));
|
|
730
928
|
status = out.status;
|
|
@@ -768,10 +966,20 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
768
966
|
// buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
|
|
769
967
|
// = false routes …
|
|
770
968
|
const page = await ssrModule.renderPage(safe2);
|
|
771
|
-
await sendPage(req, res, ssrModule, hookCtx, page,
|
|
772
|
-
}).catch(() => {
|
|
773
|
-
|
|
774
|
-
|
|
969
|
+
await sendPage(req, res, ssrModule, hookCtx, page, safe2);
|
|
970
|
+
}).catch((err: unknown) => {
|
|
971
|
+
// P0-4: a failure in the pipeline is a 500 with the reason on stderr, never a 9-byte
|
|
972
|
+
// 404 …
|
|
973
|
+
console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
|
|
974
|
+
if (res.headersSent) {
|
|
975
|
+
// a stream already left: the status is committed, so the only honest
|
|
976
|
+
// move is to drop the socket and let the client retry
|
|
977
|
+
res.destroy();
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
res.statusCode = 500;
|
|
981
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
982
|
+
res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
775
983
|
});
|
|
776
984
|
};
|
|
777
985
|
}
|
|
@@ -785,6 +993,71 @@ function pathnameOf(url: string | undefined): string {
|
|
|
785
993
|
}
|
|
786
994
|
}
|
|
787
995
|
|
|
996
|
+
/**
|
|
997
|
+
* The parsed query string of a URL (?page=2&q=x -> {page:'2',q:'x'}), for
|
|
998
|
+
* $query() (P0-1). First value wins per key, the way every server-side
|
|
999
|
+
* framework reads a repeated parameter.
|
|
1000
|
+
*/
|
|
1001
|
+
function queryOf(url: string | undefined): Record<string, string> {
|
|
1002
|
+
const q: Record<string, string> = {};
|
|
1003
|
+
try {
|
|
1004
|
+
new URL(url || '/', 'http://localhost').searchParams.forEach((v, k) => { if (!(k in q)) q[k] = v; });
|
|
1005
|
+
} catch { /* an unparsable url carries no query */ }
|
|
1006
|
+
return q;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* P0-0 (bug report): listen on `port`, hopping to the next free one when it
|
|
1011
|
+
* is taken instead of crashing with EADDRINUSE. Two projects on one machine
|
|
1012
|
+
* (or a dev server that did not exit cleanly) is the everyday case, and a
|
|
1013
|
+
* stack trace plus a dead process is the worst possible answer to it: the
|
|
1014
|
+
* banner names the port actually used, so the URL is never a guess.
|
|
1015
|
+
*
|
|
1016
|
+
* The hop is bounded (20 tries) and every other error is fatal - silently
|
|
1017
|
+
* retrying a real fault would hide it.
|
|
1018
|
+
*/
|
|
1019
|
+
function listenFree(server: any, port: number, onReady: (port: number) => void): void {
|
|
1020
|
+
const attempt = (p: number): void => {
|
|
1021
|
+
const onError = (err: any) => {
|
|
1022
|
+
server.removeListener('error', onError);
|
|
1023
|
+
if (err && err.code === 'EADDRINUSE' && p - port < 20) {
|
|
1024
|
+
console.log(`🌹 port ${p} is in use - trying ${p + 1}`);
|
|
1025
|
+
attempt(p + 1);
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
|
|
1029
|
+
process.exit(1);
|
|
1030
|
+
};
|
|
1031
|
+
server.once('error', onError);
|
|
1032
|
+
server.listen(p, () => {
|
|
1033
|
+
server.removeListener('error', onError);
|
|
1034
|
+
onReady(p);
|
|
1035
|
+
});
|
|
1036
|
+
};
|
|
1037
|
+
attempt(port);
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* P0-0 (bug report): the first free port at or after `from`, probed with a
|
|
1042
|
+
* throwaway socket. The cluster's primary needs this because the workers must
|
|
1043
|
+
* all land on the SAME port - letting each of them hop on its own would put
|
|
1044
|
+
* them on different ports and split the traffic between them. Racy by nature
|
|
1045
|
+
* (a port can be taken between the probe and the workers' listen); the
|
|
1046
|
+
* workers' own listenFree fallback covers that last step.
|
|
1047
|
+
*/
|
|
1048
|
+
async function freePort(from: number): Promise<number> {
|
|
1049
|
+
const net = await import('node:net');
|
|
1050
|
+
for (let p = from; p < from + 20; p++) {
|
|
1051
|
+
const free = await new Promise<boolean>((resolve) => {
|
|
1052
|
+
const probe = net.createServer();
|
|
1053
|
+
probe.once('error', () => resolve(false));
|
|
1054
|
+
probe.listen(p, () => probe.close(() => resolve(true)));
|
|
1055
|
+
});
|
|
1056
|
+
if (free) return p;
|
|
1057
|
+
}
|
|
1058
|
+
return from;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
788
1061
|
/**
|
|
789
1062
|
* The version from package.json - one source of truth, no constant to drift.
|
|
790
1063
|
* Resolved from THIS module (not the cwd): the banner names the framework's
|
|
@@ -819,18 +1092,23 @@ async function dev(): Promise<void> {
|
|
|
819
1092
|
try {
|
|
820
1093
|
console.log('Rebuilding...');
|
|
821
1094
|
await build();
|
|
1095
|
+
// Tell the open tabs. Without this the rebuild lands on disk and the browser keeps showing
|
|
1096
|
+
// the previous document until the developer thinks to refresh …
|
|
1097
|
+
devNotify();
|
|
822
1098
|
} catch (err) {
|
|
823
1099
|
// Never let a user-code error kill the dev server.
|
|
824
|
-
console.error('Build failed (server still running):', err instanceof Error ? err.message : err);
|
|
1100
|
+
console.error('Build failed (server still running):', err instanceof Error ? err.message : String(err));
|
|
825
1101
|
}
|
|
826
1102
|
}, 200);
|
|
827
1103
|
});
|
|
828
1104
|
|
|
829
1105
|
const http = await import('http');
|
|
830
|
-
const server = http.createServer(serveStatic(OUT_DIR));
|
|
1106
|
+
const server = http.createServer(devWrap(serveStatic(OUT_DIR, false, true)));
|
|
831
1107
|
|
|
832
|
-
|
|
833
|
-
|
|
1108
|
+
// P0-0: an occupied port hops to the next free one (and says so) instead of
|
|
1109
|
+
// killing the server with EADDRINUSE.
|
|
1110
|
+
listenFree(server, PORT, (port) => {
|
|
1111
|
+
console.log('🌹 http://localhost:' + port);
|
|
834
1112
|
});
|
|
835
1113
|
}
|
|
836
1114
|
|
|
@@ -841,8 +1119,10 @@ async function preview(): Promise<void> {
|
|
|
841
1119
|
// from disk . Dev passes nothing (it rebuilds on change).
|
|
842
1120
|
const server = http.createServer(serveStatic(OUT_DIR, true));
|
|
843
1121
|
|
|
844
|
-
server
|
|
845
|
-
|
|
1122
|
+
// P0-0: same hop as the dev server - a preview that cannot bind its port
|
|
1123
|
+
// moves to the next one and prints it.
|
|
1124
|
+
listenFree(server, PORT, (port) => {
|
|
1125
|
+
console.log(`🌹 RoseTack v${version()} preview at http://localhost:` + port);
|
|
846
1126
|
});
|
|
847
1127
|
}
|
|
848
1128
|
|
|
@@ -878,9 +1158,11 @@ async function serve(): Promise<void> {
|
|
|
878
1158
|
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
879
1159
|
const os = await import('node:os');
|
|
880
1160
|
const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
|
|
881
|
-
const PORT = Number(process.env.PORT) || 3000;
|
|
882
1161
|
if (cluster.isPrimary) {
|
|
883
|
-
|
|
1162
|
+
// P0-0 (bug report): ONE port for the whole cluster, chosen once by the primary and
|
|
1163
|
+
// handed to every worker through the environment.
|
|
1164
|
+
const port = await freePort(Number(process.env.PORT) || 3000);
|
|
1165
|
+
for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
|
|
884
1166
|
// The store relay. A worker broadcasts every $store write here; the primary forwards each
|
|
885
1167
|
// patch to every OTHER worker …
|
|
886
1168
|
cluster.on('message', (worker: any, msg: any) => {
|
|
@@ -897,7 +1179,7 @@ async function serve(): Promise<void> {
|
|
|
897
1179
|
process.on('SIGTERM', stop);
|
|
898
1180
|
process.on('SIGINT', stop);
|
|
899
1181
|
cluster.on('exit', () => { if (--live <= 0) process.exit(0); });
|
|
900
|
-
console.log(`🌹 RoseTack v${version()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${
|
|
1182
|
+
console.log(`🌹 RoseTack v${version()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
901
1183
|
return;
|
|
902
1184
|
}
|
|
903
1185
|
// worker the primary's death is the worker's death: no orphan holding the port
|
|
@@ -917,11 +1199,13 @@ async function serve(): Promise<void> {
|
|
|
917
1199
|
server.requestTimeout = 30_000;
|
|
918
1200
|
server.headersTimeout = 65_000; // must exceed requestTimeout
|
|
919
1201
|
server.keepAliveTimeout = 5_000;
|
|
920
|
-
|
|
921
|
-
|
|
1202
|
+
// P0-0: the worker binds the port the primary chose; if that one was taken in the
|
|
1203
|
+
// meantime it hops instead of dying with an unhandled 'error' …
|
|
1204
|
+
listenFree(server, PORT, async (port) => {
|
|
1205
|
+
console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${port}`);
|
|
922
1206
|
for (const p of servicePlugins) {
|
|
923
1207
|
try {
|
|
924
|
-
await p.onServe({ port
|
|
1208
|
+
await p.onServe({ port, workers });
|
|
925
1209
|
} catch (err) {
|
|
926
1210
|
console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : err);
|
|
927
1211
|
}
|
|
@@ -1223,11 +1507,35 @@ async function check(): Promise<void> {
|
|
|
1223
1507
|
process.exit(1);
|
|
1224
1508
|
}
|
|
1225
1509
|
|
|
1226
|
-
const
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1510
|
+
const argv = process.argv.slice(2);
|
|
1511
|
+
const cmd = argv[0];
|
|
1512
|
+
// --json: failures print as a machine-readable envelope on stdout - the code, the file, the
|
|
1513
|
+
// line and the hint, one JSON object an agent can parse and act on.
|
|
1514
|
+
const asJson = argv.includes('--json');
|
|
1515
|
+
|
|
1516
|
+
/** Print a failure the way its reader needs it. A RoseError is the
|
|
1517
|
+
* developer's (or the agent's) to fix from its code alone; anything else
|
|
1518
|
+
* keeps its stack, because it is not. Always exits non-zero: a build that
|
|
1519
|
+
* says nothing and succeeds is the worst failure mode there is. */
|
|
1520
|
+
function reportFailure(err: unknown): never {
|
|
1521
|
+
if (asJson) {
|
|
1522
|
+
process.stdout.write(`${JSON.stringify({ ok: false, errors: [errorInfo(err)] })}\n`);
|
|
1523
|
+
} else if (err instanceof RoseError) {
|
|
1524
|
+
console.error(`rosetack: ${err.message}`);
|
|
1525
|
+
if (err.hint) console.error(` hint: ${err.hint}`);
|
|
1526
|
+
const at = err.file ? `${err.file}${err.line ? `:${err.line}` : ''}` : null;
|
|
1527
|
+
if (at) console.error(` at ${at}`);
|
|
1528
|
+
} else {
|
|
1529
|
+
console.error(err instanceof Error ? err.stack ?? err.message : String(err));
|
|
1530
|
+
}
|
|
1531
|
+
process.exit(1);
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
if (cmd === 'dev') void dev().catch(reportFailure);
|
|
1535
|
+
else if (cmd === 'build') void build().catch(reportFailure);
|
|
1536
|
+
else if (cmd === 'preview') void preview().catch(reportFailure);
|
|
1537
|
+
else if (cmd === 'serve') void serve().catch(reportFailure);
|
|
1538
|
+
else if (cmd === 'new') void scaffold().catch(reportFailure);
|
|
1539
|
+
else if (cmd === 'check') void check().catch(reportFailure);
|
|
1540
|
+
else if (cmd === 'prompt') console.log(AI_PROMPT);
|
|
1541
|
+
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)');
|