rosetack 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/deploy/cloudflare/functions/[[path]].ts +61 -0
- package/deploy/cloudflare/wrangler.toml +14 -0
- package/deploy/k8s/rosetack.yaml +107 -0
- package/deploy/netlify/functions/rosetack.ts +38 -0
- package/deploy/netlify.toml +17 -0
- package/devtools/devtools.html +7 -0
- package/devtools/devtools.js +1 -0
- package/devtools/manifest.json +8 -0
- package/devtools/panel.html +28 -0
- package/devtools/panel.js +54 -0
- package/dist-cli/compiler.mjs +1346 -492
- package/dist-cli/edge.mjs +152 -41
- package/dist-cli/rosetack.mjs +1974 -606
- package/dist-cli/runtime.mjs +205 -40
- package/dist-cli/test.mjs +1425 -508
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/edge.ts +76 -61
- package/src/cli/index.ts +516 -293
- package/src/cli/prompt.ts +130 -0
- package/src/cli/shell.ts +113 -65
- package/src/cli/test.ts +9 -70
- package/src/compiler/errors.ts +74 -0
- package/src/compiler/index.ts +1514 -839
- package/src/runtime/index.ts +255 -150
- package/src/types/rosetack.d.ts +18 -59
- package/templates/admin/package.json +14 -0
- package/templates/admin/rosetack.config.js +1 -0
- package/templates/admin/src/pages/_middleware.rose +33 -0
- package/templates/admin/src/pages/api/items.rose +37 -0
- package/templates/admin/src/pages/api/login.rose +25 -0
- package/templates/admin/src/pages/index.rose +79 -0
- package/templates/api/package.json +14 -0
- package/templates/api/rosetack.config.js +1 -0
- package/templates/api/src/pages/api/health.rose +7 -0
- package/templates/api/src/pages/api/items.rose +46 -0
- package/templates/api/src/pages/api/login.rose +24 -0
- package/templates/api/src/pages/index.rose +25 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/rosetack.config.js +1 -0
- package/templates/blog/src/pages/404.rose +2 -0
- package/templates/blog/src/pages/_layout.rose +42 -0
- package/templates/blog/src/pages/_middleware.rose +74 -0
- package/templates/blog/src/pages/admin.rose +85 -0
- package/templates/blog/src/pages/api/login.rose +46 -0
- package/templates/blog/src/pages/api/posts/[id].rose +37 -0
- package/templates/blog/src/pages/api/posts.rose +72 -0
- package/templates/blog/src/pages/index.rose +31 -0
- package/templates/blog/src/pages/post/[id].rose +36 -0
- package/templates/site/package.json +14 -0
- package/templates/site/rosetack.config.js +1 -0
- package/templates/site/src/pages/404.rose +2 -0
- package/templates/site/src/pages/_layout.rose +40 -0
- package/templates/site/src/pages/about.rose +6 -0
- package/templates/site/src/pages/index.rose +13 -0
- package/templates/site/src/pages/pricing.rose +8 -0
package/src/cli/index.ts
CHANGED
|
@@ -1,34 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
* rosetack CLI - simplest possible SSR + static server
|
|
3
|
-
*/
|
|
1
|
+
// rosetack CLI - simplest possible SSR + static server
|
|
4
2
|
|
|
5
3
|
import * as fs from 'fs';
|
|
6
4
|
import * as path from 'path';
|
|
7
5
|
import * as zlib from 'zlib';
|
|
8
6
|
import { createRequire } from 'module';
|
|
9
7
|
import { pathToFileURL, fileURLToPath } from 'url';
|
|
10
|
-
import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, type RouteInfo } from '../compiler/index.js';
|
|
8
|
+
import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, RoseError, errorInfo, type RouteInfo } from '../compiler/index.js';
|
|
11
9
|
import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
|
|
12
|
-
|
|
13
|
-
// TypeScript dependency.
|
|
10
|
+
import { AI_PROMPT } from './prompt.js';
|
|
14
11
|
import type * as ts from 'typescript';
|
|
15
12
|
|
|
16
|
-
// --- wire performance: compression + conditional caching (stdlib only) --- The Go binary
|
|
17
|
-
// already compresses …
|
|
18
13
|
type Encoding = 'br' | 'gzip' | 'deflate';
|
|
19
14
|
|
|
20
15
|
function pickEncoding(req: any): Encoding | null {
|
|
21
16
|
const ae: string = req.headers['accept-encoding'] || '';
|
|
22
|
-
// Trade-off: substring match, no q-value parsing - every browser that sends
|
|
23
|
-
// br also accepts gzip, and br > gzip > deflate is the quality order.
|
|
24
17
|
if (ae.includes('br')) return 'br';
|
|
25
18
|
if (ae.includes('gzip')) return 'gzip';
|
|
26
19
|
if (ae.includes('deflate')) return 'deflate';
|
|
27
20
|
return null;
|
|
28
21
|
}
|
|
29
22
|
|
|
30
|
-
// Brotli's default quality (11) spends ~108 ms of CPU on a 32 KB document; quality 5 does
|
|
31
|
-
// the same document in ~2.4 ms for 9% more bytes (measured, Node 22).
|
|
32
23
|
const brotliFast = { [zlib.constants.BROTLI_PARAM_QUALITY]: 5 };
|
|
33
24
|
|
|
34
25
|
function compress(enc: Encoding, data: string | Buffer): Buffer {
|
|
@@ -49,8 +40,6 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
|
|
|
49
40
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
50
41
|
res.setHeader('Vary', 'Accept-Encoding');
|
|
51
42
|
if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
|
|
52
|
-
// A weak ETag over the rendered bytes: revalidation answers a bodiless 304 for dynamic
|
|
53
|
-
// renders too …
|
|
54
43
|
let hash = 0x811c9dc5;
|
|
55
44
|
for (let i = 0; i < html.length; i++) {
|
|
56
45
|
hash ^= html.charCodeAt(i);
|
|
@@ -63,7 +52,7 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
|
|
|
63
52
|
return;
|
|
64
53
|
}
|
|
65
54
|
res.setHeader('ETag', etag);
|
|
66
|
-
const enc = pickEncoding(req);
|
|
55
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
67
56
|
if (enc) {
|
|
68
57
|
res.setHeader('Content-Encoding', enc);
|
|
69
58
|
res.end(compress(enc, html));
|
|
@@ -72,8 +61,6 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
|
|
|
72
61
|
}
|
|
73
62
|
}
|
|
74
63
|
|
|
75
|
-
// Copy a Web-standard Response's headers onto the Node response. set-cookie is the one
|
|
76
|
-
// header that may legally repeat, and res.setHeader overwrites …
|
|
77
64
|
function writeWebHeaders(web: any, res: any): void {
|
|
78
65
|
const cookies = web.headers.getSetCookie?.() ?? [];
|
|
79
66
|
web.headers.forEach((v: string, k: string) => {
|
|
@@ -83,62 +70,62 @@ function writeWebHeaders(web: any, res: any): void {
|
|
|
83
70
|
if (cookies.length) res.setHeader('set-cookie', cookies);
|
|
84
71
|
}
|
|
85
72
|
|
|
86
|
-
// A middleware's short-circuit: a Web-standard Response (status, headers, body) written
|
|
87
|
-
// straight to the Node response - a redirect, an auth wall, a rewrite.
|
|
88
73
|
async function sendWebResponse(web: any, res: any): Promise<void> {
|
|
89
74
|
writeWebHeaders(web, res);
|
|
90
75
|
res.statusCode = web.status;
|
|
91
76
|
res.end(Buffer.from(await web.arrayBuffer()));
|
|
92
77
|
}
|
|
93
78
|
|
|
94
|
-
|
|
95
|
-
* Send a rendered page document - through onResponse first . The
|
|
96
|
-
* hook sees the status, headers and body exactly as they will go on the
|
|
97
|
-
* wire and may replace them, so the ETag inside sendHtml is then computed
|
|
98
|
-
* over the bytes actually sent. One helper for the POST-action path and the
|
|
99
|
-
* buffered GET path: same hook, same order, no drift between them.
|
|
100
|
-
*/
|
|
79
|
+
// Send a rendered page document - through onResponse first .
|
|
101
80
|
async function sendPage(req: any, res: any, ssrModule: any, hookCtx: any, page: any, routePath: string): Promise<void> {
|
|
102
81
|
let status = page.status ?? 200;
|
|
103
|
-
|
|
104
|
-
|
|
82
|
+
if (page.redirect) {
|
|
83
|
+
const body = `<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${page.redirect}">${page.redirect}</a>.</p>`;
|
|
84
|
+
let headers: Record<string, any> = pageHeaders(ssrModule, routePath, '');
|
|
85
|
+
if (hookCtx) {
|
|
86
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(body, {
|
|
87
|
+
status,
|
|
88
|
+
headers: { 'content-type': 'text/html; charset=utf-8', location: page.redirect, ...headers },
|
|
89
|
+
}));
|
|
90
|
+
status = out.status;
|
|
91
|
+
headers = webHeadersToNode(out);
|
|
92
|
+
}
|
|
93
|
+
headers.location = page.redirect;
|
|
94
|
+
res.statusCode = status;
|
|
95
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
96
|
+
res.setHeader('Location', page.redirect);
|
|
97
|
+
for (const [k, v] of Object.entries(headers)) if (k !== 'location') res.setHeader(k, v);
|
|
98
|
+
res.end(body);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
105
101
|
const nonce = nonceFor(ssrModule, routePath);
|
|
106
|
-
|
|
107
|
-
// always lands here or in the stream below - never on the baked-file path …
|
|
108
|
-
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
|
|
102
|
+
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
|
|
109
103
|
let headers: Record<string, any> = pageHeaders(ssrModule, routePath, nonce);
|
|
110
104
|
if (hookCtx) {
|
|
111
|
-
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
105
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
106
|
+
status,
|
|
107
|
+
headers: { 'content-type': 'text/html; charset=utf-8', ...headers },
|
|
108
|
+
}));
|
|
112
109
|
status = out.status;
|
|
113
110
|
headers = webHeadersToNode(out);
|
|
114
|
-
html = await out.text();
|
|
111
|
+
html = out.bodyUsed ? html : await out.text();
|
|
115
112
|
}
|
|
116
113
|
sendHtml(req, res, status, html, headers);
|
|
117
114
|
}
|
|
118
115
|
|
|
119
|
-
// Static files: raw + both compressed forms cached per mtime (dev rebuilds change mtime;
|
|
120
|
-
// preview never does).
|
|
121
116
|
const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
|
|
122
117
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
118
|
+
const __portArg = process.argv.find((a) => a === '--port' || a.startsWith('--port='));
|
|
119
|
+
if (__portArg) {
|
|
120
|
+
const __v = __portArg.includes('=') ? __portArg.slice('--port='.length) : process.argv[process.argv.indexOf(__portArg) + 1];
|
|
121
|
+
if (__v && Number(__v) > 0) process.env.PORT = __v;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const SRC_DIR = process.argv[3] && !process.argv[3].startsWith('-') ? path.resolve(process.argv[3]) : process.cwd();
|
|
128
125
|
const OUT_DIR = path.join(process.cwd(), 'dist');
|
|
129
|
-
// PORT env override (default 3000): lets a preview server run beside a dev
|
|
130
|
-
// server on the same machine - the e2e ISR test does exactly that.
|
|
131
126
|
const PORT = Number(process.env.PORT) || 3000;
|
|
132
127
|
|
|
133
|
-
|
|
134
|
-
* Import dist/server.js, cached until the file changes on disk.
|
|
135
|
-
*
|
|
136
|
-
* The dev server rebuilds it on file changes, so a plain import() would
|
|
137
|
-
* serve the cached (stale) module - re-import when mtime moves. But the
|
|
138
|
-
* import must NOT be per-request: server state (stores mutated by server
|
|
139
|
-
* actions) lives in that module, and a fresh import per request would
|
|
140
|
-
* reset it on every hit, so an action's effect would vanish immediately.
|
|
141
|
-
*/
|
|
128
|
+
// Import dist/server.js, cached until the file changes on disk. Preview and serve never rebuild, so they import dist/server.js itself.
|
|
142
129
|
let serverModule: any = null;
|
|
143
130
|
let serverMtime = -1;
|
|
144
131
|
let serverVersion = 0;
|
|
@@ -149,35 +136,49 @@ async function loadServer(): Promise<any> {
|
|
|
149
136
|
if (!serverModule || mtimeMs !== serverMtime) {
|
|
150
137
|
serverMtime = mtimeMs;
|
|
151
138
|
serverVersion++;
|
|
152
|
-
|
|
139
|
+
let target = file;
|
|
140
|
+
if (devMode) {
|
|
141
|
+
target = path.join(OUT_DIR, '.build', `server-${serverVersion}.mjs`);
|
|
142
|
+
await fs.promises.mkdir(path.dirname(target), { recursive: true });
|
|
143
|
+
await fs.promises.copyFile(file, target);
|
|
144
|
+
}
|
|
145
|
+
serverModule = await import(pathToFileURL(target).href);
|
|
153
146
|
}
|
|
154
147
|
return serverModule;
|
|
155
148
|
}
|
|
156
149
|
|
|
157
150
|
async function build(): Promise<void> {
|
|
158
|
-
// The build reports the bundle mode ('inline' | 'split') so the
|
|
159
|
-
// shell follows it for every document, header and streaming tag it emits
|
|
160
151
|
const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR);
|
|
161
|
-
// The previous build's prerendered output must not survive: a route that stopped being
|
|
162
|
-
// static (it started reading getContext() or $store()) would otherwise leave its old
|
|
163
|
-
// baked …
|
|
164
152
|
await clearPrerendered(OUT_DIR);
|
|
165
153
|
setBundleMode(bundle);
|
|
166
154
|
const skipped = await prerender(routes);
|
|
167
|
-
// The broken-route manifest: the server reads it to pick the buffered path for these
|
|
168
|
-
// routes, so their real 500 status survives (a flushed response cannot change its
|
|
169
|
-
// status).
|
|
170
155
|
await fs.promises.writeFile(path.join(OUT_DIR, 'broken.json'), JSON.stringify(skipped));
|
|
171
|
-
// Per-route response headers for the Go binary, which has no compiler: it reads this file
|
|
172
|
-
// and merges the entries over its own responses.
|
|
173
156
|
const ssrModule = await loadServer();
|
|
174
157
|
await fs.promises.writeFile(path.join(OUT_DIR, 'headers.json'), JSON.stringify({
|
|
175
158
|
default: securityHeaders(getClientSource()),
|
|
176
159
|
routes: ssrModule.routeHeaders ?? [],
|
|
177
160
|
}));
|
|
178
|
-
// Precompressed brotli siblings (dist/<file>.br) for the Go single binary. The binary
|
|
179
|
-
// embeds dist/ verbatim …
|
|
180
161
|
await writeBrotli(OUT_DIR);
|
|
162
|
+
await analyze(OUT_DIR, (ssrModule.dynamicRoutes as string[] | undefined) ?? []);
|
|
163
|
+
|
|
164
|
+
if (argv.includes('--static')) {
|
|
165
|
+
const dyn = (ssrModule.dynamicRoutes as string[] | undefined) ?? [];
|
|
166
|
+
const unbakedApi = Object.entries((ssrModule.apiPrerender ?? {}) as Record<string, boolean>)
|
|
167
|
+
.filter(([, baked]) => !baked)
|
|
168
|
+
.map(([routePath]) => routePath);
|
|
169
|
+
const paramless = routes
|
|
170
|
+
.filter((r) => r.paramNames.length > 0 && !((ssrModule.routeParams ?? {}) as Record<string, unknown>)[r.routePath])
|
|
171
|
+
.map((r) => r.routePath);
|
|
172
|
+
const problems = [...new Set([...dyn, ...unbakedApi, ...paramless, ...skipped])];
|
|
173
|
+
if (problems.length > 0) {
|
|
174
|
+
console.error('rosetack: --static export refused - these routes need a server:');
|
|
175
|
+
for (const p of problems) console.error(` ${p}`);
|
|
176
|
+
console.error('(getContext()/$store()/$query(), csp.nonce, buffer = true, an unbaked /api route, a param route with no export const params, or a route the middleware walled)');
|
|
177
|
+
console.error('drop --static to build the normal dist (the dynamic half renders on demand on Node/edge)');
|
|
178
|
+
process.exit(1);
|
|
179
|
+
}
|
|
180
|
+
console.log('rosetack: static export verified - every route is a baked file, no server needed');
|
|
181
|
+
}
|
|
181
182
|
}
|
|
182
183
|
|
|
183
184
|
/**
|
|
@@ -198,6 +199,55 @@ async function writeBrotli(dir: string): Promise<void> {
|
|
|
198
199
|
}
|
|
199
200
|
}
|
|
200
201
|
|
|
202
|
+
/**
|
|
203
|
+
* The build analysis. The zero-JS report says
|
|
204
|
+
* WHICH routes ship no runtime; this says what every route costs on the
|
|
205
|
+
* wire, measured from the files this build just wrote - never from a number
|
|
206
|
+
* quoted from memory. Brotli is the `.br` sibling the build already wrote
|
|
207
|
+
* (the exact bytes the Go binary serves); gzip is computed here because the
|
|
208
|
+
* Node server compresses per request and gzip is the fallback every proxy
|
|
209
|
+
* eventually falls back to. Dynamic routes are not baked, so they are
|
|
210
|
+
* LISTED, not measured: their numbers come from `npm run benchmark`, which
|
|
211
|
+
* renders them live against `rosetack serve`.
|
|
212
|
+
*/
|
|
213
|
+
async function analyze(outDir: string, dynamic: string[]): Promise<void> {
|
|
214
|
+
const rows: Array<{ route: string; raw: number; gzip: number; br: number; js: boolean }> = [];
|
|
215
|
+
const walk = async (dir: string, prefix: string): Promise<void> => {
|
|
216
|
+
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
217
|
+
if (e.isDirectory()) {
|
|
218
|
+
await walk(path.join(dir, e.name), `${prefix}/${e.name}`);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (!e.name.endsWith('.html')) continue;
|
|
222
|
+
const file = path.join(dir, e.name);
|
|
223
|
+
const raw = await fs.promises.readFile(file);
|
|
224
|
+
const brFile = `${file}.br`;
|
|
225
|
+
rows.push({
|
|
226
|
+
route: prefix || '/',
|
|
227
|
+
raw: raw.length,
|
|
228
|
+
gzip: zlib.gzipSync(raw, { level: 9 }).length,
|
|
229
|
+
br: fs.existsSync(brFile) ? (await fs.promises.stat(brFile)).size : 0,
|
|
230
|
+
js: /<script type="module"/.test(raw.toString('utf8')),
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
await walk(outDir, '');
|
|
235
|
+
const kb = (n: number) => `${(n / 1024).toFixed(1)} KB`;
|
|
236
|
+
const lines = ['rosetack build analysis (measured from dist/; br = the precompressed bytes the Go binary serves):'];
|
|
237
|
+
for (const r of rows.sort((a, b) => (a.route < b.route ? -1 : 1))) {
|
|
238
|
+
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'}`);
|
|
239
|
+
}
|
|
240
|
+
const client = path.join(outDir, 'client.js');
|
|
241
|
+
if (fs.existsSync(client)) {
|
|
242
|
+
const raw = await fs.promises.readFile(client);
|
|
243
|
+
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`);
|
|
244
|
+
}
|
|
245
|
+
if (dynamic.length > 0) {
|
|
246
|
+
lines.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${dynamic.join(' ')}`);
|
|
247
|
+
}
|
|
248
|
+
for (const l of lines) console.log(l);
|
|
249
|
+
}
|
|
250
|
+
|
|
201
251
|
/**
|
|
202
252
|
* Delete the prerendered output of a previous build: HTML documents and
|
|
203
253
|
* baked API bodies, with their brotli siblings. Everything else in dist/
|
|
@@ -210,8 +260,6 @@ async function writeBrotli(dir: string): Promise<void> {
|
|
|
210
260
|
*/
|
|
211
261
|
async function clearPrerendered(dir: string, depth = 0): Promise<void> {
|
|
212
262
|
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
213
|
-
// Dist/locales/ holds the runtime locale packs the build just wrote (i18n.preload's
|
|
214
|
-
// leftovers) - they are .json files like any prerendered body, but they are build output …
|
|
215
263
|
if (depth === 0 && e.name === 'locales' && e.isDirectory()) continue;
|
|
216
264
|
const p = path.join(dir, e.name);
|
|
217
265
|
if (e.isDirectory()) {
|
|
@@ -244,33 +292,26 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
244
292
|
const ssrModule = await loadServer();
|
|
245
293
|
const skipped: string[] = [];
|
|
246
294
|
const write = async (routePath: string) => {
|
|
247
|
-
// a synthetic cookie-less request: the middleware runs at build time too, and a route
|
|
248
|
-
// it short-circuits (an auth wall, a maintenance rewrite) simply is not static …
|
|
249
295
|
const mw = await ssrModule.runMiddleware({ method: 'GET', url: routePath, headers: {} });
|
|
250
296
|
if (mw) {
|
|
251
297
|
console.error(`prerender skipped for ${routePath}: the middleware short-circuits at build time`);
|
|
252
298
|
skipped.push(routePath);
|
|
253
299
|
return;
|
|
254
300
|
}
|
|
301
|
+
ssrModule.setQuery?.({});
|
|
255
302
|
const page = await ssrModule.renderPage(routePath);
|
|
256
303
|
if (page.status === 500) {
|
|
257
|
-
// The route's render failed and the error page rendered instead. Do NOT bake that
|
|
258
|
-
// into a static file: a static server can only answer 200 …
|
|
259
304
|
console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
|
|
260
305
|
skipped.push(routePath);
|
|
261
306
|
return;
|
|
262
307
|
}
|
|
263
308
|
const routeDir = routePath === '/' ? OUT_DIR : path.join(OUT_DIR, routePath.slice(1));
|
|
264
309
|
await fs.promises.mkdir(routeDir, { recursive: true });
|
|
265
|
-
|
|
266
|
-
// state script, so a visitor who lands on it runs zero JavaScript.
|
|
267
|
-
await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
310
|
+
await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, '', page.shell !== false));
|
|
268
311
|
console.log(`prerendered ${routePath} -> ${path.relative(process.cwd(), path.join(routeDir, 'index.html'))}`);
|
|
269
312
|
};
|
|
270
313
|
|
|
271
314
|
for (const info of routes) {
|
|
272
|
-
// routes that read the request context (getContext()) or a shared store ($store()) are
|
|
273
|
-
// dynamic by construction: the bag is per-request and the store is per-process …
|
|
274
315
|
if ((ssrModule.dynamicRoutes as string[]).includes(info.routePath)) {
|
|
275
316
|
console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
|
|
276
317
|
continue;
|
|
@@ -279,15 +320,11 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
279
320
|
try {
|
|
280
321
|
await write(info.routePath);
|
|
281
322
|
} catch (err) {
|
|
282
|
-
// One broken route (e.g. throwing $data) must not fail the whole build;
|
|
283
|
-
// it simply keeps rendering on demand.
|
|
284
323
|
console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
|
|
285
324
|
skipped.push(info.routePath);
|
|
286
325
|
}
|
|
287
326
|
continue;
|
|
288
327
|
}
|
|
289
|
-
// dynamic route: enumerate the exported params map, if any. The maps are re-exported by
|
|
290
|
-
// the server bundle (routeParams) …
|
|
291
328
|
try {
|
|
292
329
|
const paramsExport = (ssrModule.routeParams as Record<string, unknown>)?.[info.routePath];
|
|
293
330
|
const raw = typeof paramsExport === 'function' ? await (paramsExport as () => unknown)() : paramsExport;
|
|
@@ -300,9 +337,6 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
300
337
|
}
|
|
301
338
|
}
|
|
302
339
|
|
|
303
|
-
// API routes that opt in (export const prerender = true) bake their GET body into
|
|
304
|
-
// dist/api/<route>.json: the Go single binary then serves the read-only API with zero
|
|
305
|
-
// Node.
|
|
306
340
|
const apiPrerender = (ssrModule.apiPrerender as Record<string, boolean>) ?? {};
|
|
307
341
|
for (const [routePath, on] of Object.entries(apiPrerender)) {
|
|
308
342
|
if (!on) continue;
|
|
@@ -335,17 +369,17 @@ function enumerateParams(pattern: string, names: string[], raw: Record<string, u
|
|
|
335
369
|
let i = 0;
|
|
336
370
|
return pattern
|
|
337
371
|
.split('/')
|
|
338
|
-
.map((seg) =>
|
|
372
|
+
.map((seg) => {
|
|
373
|
+
if (seg.startsWith(':')) return encodeURIComponent(values[i++]);
|
|
374
|
+
if (seg.startsWith('*')) return values[i++].split('/').map(encodeURIComponent).join('/');
|
|
375
|
+
return seg;
|
|
376
|
+
})
|
|
339
377
|
.join('/');
|
|
340
378
|
});
|
|
341
379
|
}
|
|
342
380
|
|
|
343
|
-
// Extensions the static branch serves without touching the router: assets keep their fast
|
|
344
|
-
// path even when a middleware exists (a middleware guards pages, not files).
|
|
345
381
|
const ASSET_EXT = new Set(['.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.woff', '.woff2', '.txt', '.xml']);
|
|
346
382
|
|
|
347
|
-
// Response headers for a page document: the strict CSP (hashed over the exact inlined
|
|
348
|
-
// bundle + bootstrap bytes …
|
|
349
383
|
function pageHeaders(ssrModule: any, pathname: string, nonce = ''): Record<string, string> {
|
|
350
384
|
const headers: Record<string, string> = {};
|
|
351
385
|
for (const [k, v] of Object.entries(securityHeaders(getClientSource(), nonce))) headers[k.toLowerCase()] = v;
|
|
@@ -363,8 +397,6 @@ function nonceFor(ssrModule: any, pathname: string): string {
|
|
|
363
397
|
return ssrModule.cspNonce?.(pathname) ? mintNonce() : '';
|
|
364
398
|
}
|
|
365
399
|
|
|
366
|
-
// ISR background pass: re-render a stale baked route and swap its file, while the
|
|
367
|
-
// triggering request was already answered from disk (stale-while-revalidate).
|
|
368
400
|
const isrBusy = new Set<string>();
|
|
369
401
|
function revalidateInBackground(routePath: string, filePath: string): void {
|
|
370
402
|
if (isrBusy.has(filePath)) return;
|
|
@@ -372,11 +404,10 @@ function revalidateInBackground(routePath: string, filePath: string): void {
|
|
|
372
404
|
void (async () => {
|
|
373
405
|
try {
|
|
374
406
|
const ssrModule = await loadServer();
|
|
407
|
+
ssrModule.setQuery?.({});
|
|
375
408
|
const page = await ssrModule.renderPage(routePath);
|
|
376
409
|
if (page.status === 200) {
|
|
377
|
-
|
|
378
|
-
// zero-JS, or the first stale window would silently inline the bundle into its baked file
|
|
379
|
-
await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
410
|
+
await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, '', page.shell !== false));
|
|
380
411
|
fileCache.delete(filePath);
|
|
381
412
|
console.log(`rosetack: revalidated ${routePath} in the background`);
|
|
382
413
|
}
|
|
@@ -388,9 +419,6 @@ function revalidateInBackground(routePath: string, filePath: string): void {
|
|
|
388
419
|
})();
|
|
389
420
|
}
|
|
390
421
|
|
|
391
|
-
// --- production server posture -------------------------------------- "Can run a real app"
|
|
392
|
-
// is a threshold …
|
|
393
|
-
|
|
394
422
|
/** A request body is bounded. 1 MB holds any form and any JSON API call a
|
|
395
423
|
* site this size makes; a deployment that needs more sets it explicitly. */
|
|
396
424
|
const MAX_BODY = Number(process.env.rosetack_MAX_BODY) || 1024 * 1024;
|
|
@@ -417,7 +445,6 @@ function readBody(req: any, res: any, onDone: (body: any) => void): void {
|
|
|
417
445
|
chunks.push(c);
|
|
418
446
|
});
|
|
419
447
|
req.on('end', () => { if (!refused) onDone(Buffer.concat(chunks)); });
|
|
420
|
-
// an aborted upload must not throw an unhandled 'error' and take the process down with it
|
|
421
448
|
req.on('error', () => {});
|
|
422
449
|
}
|
|
423
450
|
|
|
@@ -495,7 +522,7 @@ async function hookContext(req: any): Promise<{
|
|
|
495
522
|
for (const [k, v] of Object.entries(req.headers)) {
|
|
496
523
|
if (v !== undefined) headers[k] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
497
524
|
}
|
|
498
|
-
|
|
525
|
+
const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
|
|
499
526
|
method: req.method || 'GET',
|
|
500
527
|
headers,
|
|
501
528
|
});
|
|
@@ -515,10 +542,109 @@ function webHeadersToNode(web: any): Record<string, any> {
|
|
|
515
542
|
return out;
|
|
516
543
|
}
|
|
517
544
|
|
|
518
|
-
|
|
545
|
+
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>`;
|
|
546
|
+
let devResume: string | null = null;
|
|
547
|
+
const devClients = new Set<any>();
|
|
548
|
+
let devMode = false;
|
|
549
|
+
|
|
550
|
+
function devReload(req: any, res: any): void {
|
|
551
|
+
res.writeHead(200, {
|
|
552
|
+
'Content-Type': 'text/event-stream',
|
|
553
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
554
|
+
Connection: 'keep-alive',
|
|
555
|
+
});
|
|
556
|
+
res.write(': ok\n\n');
|
|
557
|
+
devClients.add(res);
|
|
558
|
+
req.on('close', () => devClients.delete(res));
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function devSaveState(req: any, res: any): void {
|
|
562
|
+
let body = '';
|
|
563
|
+
req.on('data', (c: any) => {
|
|
564
|
+
body += c;
|
|
565
|
+
if (body.length > 1e6) req.destroy();
|
|
566
|
+
});
|
|
567
|
+
req.on('end', () => {
|
|
568
|
+
try {
|
|
569
|
+
JSON.parse(body);
|
|
570
|
+
devResume = body;
|
|
571
|
+
} catch { /* a corrupt snapshot is dropped: the next render is simply fresh */ }
|
|
572
|
+
res.writeHead(204).end();
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Push the rebuild signal to every open dev tab. */
|
|
577
|
+
function devNotify(): void {
|
|
578
|
+
for (const res of devClients) {
|
|
579
|
+
try {
|
|
580
|
+
res.write('data: rebuild\n\n');
|
|
581
|
+
} catch {
|
|
582
|
+
devClients.delete(res);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
let devBuild: Promise<void> | null = null;
|
|
588
|
+
let devBuildPending = false;
|
|
589
|
+
|
|
590
|
+
function startDevBuild(): Promise<void> {
|
|
591
|
+
if (!devBuild) {
|
|
592
|
+
devBuild = (async () => {
|
|
593
|
+
try {
|
|
594
|
+
console.log('Rebuilding...');
|
|
595
|
+
await build();
|
|
596
|
+
devNotify();
|
|
597
|
+
} catch (err) {
|
|
598
|
+
console.error('Build failed (server still running):', err instanceof Error ? err.message : String(err));
|
|
599
|
+
} finally {
|
|
600
|
+
devBuild = null;
|
|
601
|
+
devBuildPending = false;
|
|
602
|
+
}
|
|
603
|
+
})();
|
|
604
|
+
}
|
|
605
|
+
return devBuild;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Q2: the promise to await before routing, or null when nothing is building. */
|
|
609
|
+
function settleDevBuild(): Promise<void> | null {
|
|
610
|
+
if (!devMode || (!devBuild && !devBuildPending)) return null;
|
|
611
|
+
return startDevBuild();
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// Wrap a dev response so every HTML document carries the bridge (and the resumed state, once).
|
|
615
|
+
function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => void {
|
|
616
|
+
devMode = true;
|
|
617
|
+
return (req, res) => {
|
|
618
|
+
const url = req.url || '/';
|
|
619
|
+
if (url.startsWith('/__rosetack_reload')) return devReload(req, res);
|
|
620
|
+
if (url.startsWith('/__rosetack_state') && req.method === 'POST') return devSaveState(req, res);
|
|
621
|
+
let injected = false;
|
|
622
|
+
const seed = devResume;
|
|
623
|
+
devResume = null;
|
|
624
|
+
const isHtml = () => String(res.getHeader('content-type') || '').includes('text/html');
|
|
625
|
+
const inject = (chunk: any): any => {
|
|
626
|
+
if (injected || !isHtml()) return chunk;
|
|
627
|
+
const s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
|
|
628
|
+
const at = s.indexOf('<head>');
|
|
629
|
+
if (at < 0) return chunk;
|
|
630
|
+
injected = true;
|
|
631
|
+
const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\/script>/g, '')}</script>` : '';
|
|
632
|
+
const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
|
|
633
|
+
return Buffer.isBuffer(chunk) ? Buffer.from(out, 'utf8') : out;
|
|
634
|
+
};
|
|
635
|
+
const write = res.write.bind(res);
|
|
636
|
+
res.write = (chunk: any, ...rest: any[]) => write(inject(chunk), ...rest);
|
|
637
|
+
const end = res.end.bind(res);
|
|
638
|
+
res.end = (chunk: any, ...rest: any[]) => {
|
|
639
|
+
if (!res.headersSent && isHtml()) res.removeHeader('Content-Security-Policy');
|
|
640
|
+
end(chunk === undefined || chunk === null ? chunk : inject(chunk), ...rest);
|
|
641
|
+
};
|
|
642
|
+
inner(req, res);
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any) => void {
|
|
519
647
|
return (req, res) => {
|
|
520
|
-
// The origin guard runs before everything else - middleware, api dispatch, the static
|
|
521
|
-
// lookup - because a cross-site write must not reach any of them.
|
|
522
648
|
const blocked = crossSiteWrite(req);
|
|
523
649
|
if (blocked) {
|
|
524
650
|
res.statusCode = blocked.status;
|
|
@@ -526,25 +652,31 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
526
652
|
res.end(blocked.body);
|
|
527
653
|
return;
|
|
528
654
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
655
|
+
const want = pathnameOf(req.url || '/');
|
|
656
|
+
const canonical = want.replace(/\/+$/, '') || '/';
|
|
657
|
+
if (canonical !== want) {
|
|
658
|
+
let search = '';
|
|
659
|
+
try { search = new URL(req.url || '/', 'http://localhost').search; } catch { }
|
|
660
|
+
const to = canonical + search;
|
|
661
|
+
res.statusCode = 308;
|
|
662
|
+
res.setHeader('Location', to);
|
|
663
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
664
|
+
res.end(`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${to}">${to}</a>.</p>`);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
const settled = settleDevBuild();
|
|
668
|
+
const ready = settled ? settled.then(() => loadServer()) : loadServer();
|
|
669
|
+
ready.then(async (ssrModule: any) => {
|
|
534
670
|
const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true
|
|
535
671
|
? await hookContext(req)
|
|
536
672
|
: null;
|
|
537
673
|
if (hookCtx) {
|
|
538
674
|
const short = await ssrModule.runRequestHooks(hookCtx);
|
|
539
675
|
if (short) {
|
|
540
|
-
// the short-circuit rides through onResponse like every other
|
|
541
|
-
// response, so a header-adding hook sees it too
|
|
542
676
|
await sendWebResponse(await ssrModule.runResponseHooks(hookCtx, short), res);
|
|
543
677
|
return;
|
|
544
678
|
}
|
|
545
679
|
}
|
|
546
|
-
// Middleware (pages/_middleware.rose) runs exactly once per request, before anything
|
|
547
|
-
// else: a returned Response short-circuits the whole request …
|
|
548
680
|
const apiPath0 = pathnameOf(req.url);
|
|
549
681
|
const isPagePost = req.method === 'POST' && !ssrModule.isApi(apiPath0);
|
|
550
682
|
if (!isPagePost && ssrModule.middleware) {
|
|
@@ -554,8 +686,6 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
554
686
|
return;
|
|
555
687
|
}
|
|
556
688
|
}
|
|
557
|
-
// API routes (pages/api/*.rose) dispatch FIRST: the /api namespace answers JSON,
|
|
558
|
-
// never the static shell or an HTML page …
|
|
559
689
|
const apiPath = pathnameOf(req.url);
|
|
560
690
|
if (ssrModule.isApi(apiPath)) {
|
|
561
691
|
readBody(req, res, async (body) => {
|
|
@@ -569,12 +699,14 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
569
699
|
headers,
|
|
570
700
|
body: body.length > 0 ? body : undefined,
|
|
571
701
|
});
|
|
702
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
572
703
|
let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
|
|
573
704
|
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
574
705
|
writeWebHeaders(apiRes, res);
|
|
575
706
|
res.statusCode = apiRes.status;
|
|
576
707
|
res.end(Buffer.from(await apiRes.arrayBuffer()));
|
|
577
|
-
} catch {
|
|
708
|
+
} catch (err) {
|
|
709
|
+
console.error(`rosetack: ${req.method} ${req.url} api handler failed:`, err instanceof Error ? err.stack ?? err.message : String(err));
|
|
578
710
|
res.statusCode = 500;
|
|
579
711
|
res.setHeader('Content-Type', 'application/json');
|
|
580
712
|
res.end('{"error":"api handler failed"}');
|
|
@@ -583,16 +715,12 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
583
715
|
return;
|
|
584
716
|
}
|
|
585
717
|
|
|
586
|
-
// POST: run the matched route's server action (progressive-enhancement form). This
|
|
587
|
-
// must precede the static lookup: prerendered files exist on disk and would otherwise …
|
|
588
718
|
if (req.method === 'POST') {
|
|
589
719
|
readBody(req, res, async (body) => {
|
|
590
720
|
try {
|
|
591
721
|
const form = await new Response(body, {
|
|
592
722
|
headers: { 'content-type': req.headers['content-type'] || 'application/x-www-form-urlencoded' },
|
|
593
723
|
}).formData();
|
|
594
|
-
// the middleware pass for page POSTs: it rides with the parsed FormData so it
|
|
595
|
-
// can read form fields, and its context seeds the action + render below
|
|
596
724
|
if (ssrModule.middleware) {
|
|
597
725
|
const mw = await ssrModule.runMiddleware(req, form);
|
|
598
726
|
if (mw) {
|
|
@@ -600,17 +728,21 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
600
728
|
return;
|
|
601
729
|
}
|
|
602
730
|
}
|
|
603
|
-
|
|
731
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
732
|
+
const page = await ssrModule.renderPage(pathnameOf(req.url || '/'), form);
|
|
604
733
|
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
|
|
605
|
-
} catch {
|
|
606
|
-
|
|
607
|
-
res.
|
|
734
|
+
} catch (err) {
|
|
735
|
+
console.error(`rosetack: POST ${pathnameOf(req.url || '/')} failed:`, err instanceof Error ? err.stack : err);
|
|
736
|
+
if (!res.headersSent) {
|
|
737
|
+
res.statusCode = 400;
|
|
738
|
+
res.end('Bad request');
|
|
739
|
+
}
|
|
608
740
|
}
|
|
609
741
|
});
|
|
610
742
|
return;
|
|
611
743
|
}
|
|
612
744
|
|
|
613
|
-
let safe = path.normalize(req.url || '/').replace(/^(\.\.(\/)?)+/, '');
|
|
745
|
+
let safe = path.normalize(pathnameOf(req.url || '/')).replace(/^(\.\.(\/)?)+/, '');
|
|
614
746
|
if (safe === '\\' || safe === '/') safe = '/';
|
|
615
747
|
let filePath = path.join(dir, safe);
|
|
616
748
|
// A file in public/ answers at the root too: pages link /logo.svg, not
|
|
@@ -620,26 +752,19 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
620
752
|
if (fs.existsSync(pubFile)) filePath = pubFile;
|
|
621
753
|
}
|
|
622
754
|
|
|
623
|
-
// Directory -> index.html (prerendered routes live at /<route>/index.html)
|
|
624
755
|
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
|
|
625
756
|
filePath = path.join(filePath, 'index.html');
|
|
626
757
|
}
|
|
627
758
|
|
|
628
|
-
// Build-time precompression siblings (dist/<file>.br, read by the Go binary) are internal
|
|
629
|
-
// artifacts.
|
|
630
759
|
if (/\.(?:br|gz)$/i.test(safe)) {
|
|
631
760
|
const base = filePath.replace(/\.(?:br|gz)$/i, '');
|
|
632
761
|
if (fs.existsSync(base)) filePath = base;
|
|
633
762
|
}
|
|
634
763
|
|
|
635
|
-
// Serve real files directly - compressed + conditionally cached, so a repeat visit
|
|
636
|
-
// costs a 304 instead of the full document. Assets always take this path.
|
|
637
764
|
const isAsset = ASSET_EXT.has(path.extname(safe).toLowerCase());
|
|
638
765
|
const isDynamic = !isAsset && (ssrModule.dynamicRoutes as string[] | undefined)?.includes(pathnameOf(req.url));
|
|
639
766
|
if (!isDynamic && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
640
767
|
const st = fs.statSync(filePath);
|
|
641
|
-
// ISR: a route exporting `revalidate = N` keeps its baked file for N seconds. Once stale,
|
|
642
|
-
// THIS request is still served from disk - stale-while-revalidate: instant TTFB …
|
|
643
768
|
const rev = isAsset ? undefined : ((ssrModule.revalidate as { pattern: string; seconds: number }[]) || [])
|
|
644
769
|
.find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
|
|
645
770
|
if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1000) {
|
|
@@ -651,8 +776,6 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
651
776
|
entry = {
|
|
652
777
|
mtimeMs: st.mtimeMs,
|
|
653
778
|
raw,
|
|
654
|
-
// A file's compressed forms are computed ONCE and then served from this cache
|
|
655
|
-
// forever …
|
|
656
779
|
br: zlib.brotliCompressSync(raw),
|
|
657
780
|
gzip: zlib.gzipSync(raw, { level: 9 }),
|
|
658
781
|
etag: `W/"${st.size}-${st.mtimeMs}"`,
|
|
@@ -672,19 +795,13 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
672
795
|
'.mp4': 'video/mp4',
|
|
673
796
|
'.mp3': 'audio/mpeg',
|
|
674
797
|
};
|
|
675
|
-
// An ISR route's file is swapped every `revalidate` seconds, so the cache must not
|
|
676
|
-
// outlive the window: revalidate every visit (a bodiless 304 when nothing changed) …
|
|
677
798
|
const fileHeaders: Record<string, string> = {
|
|
678
799
|
'Content-Type': types[ext] || 'application/octet-stream',
|
|
679
800
|
'Cache-Control': rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
|
|
680
801
|
'ETag': entry.etag,
|
|
681
802
|
'Vary': 'Accept-Encoding',
|
|
682
803
|
};
|
|
683
|
-
// Per-route response headers: a prerendered document carries the same policy the live
|
|
684
|
-
// render would send - the strict CSP plus the route's own exported headers.
|
|
685
804
|
if (ext === '.html') Object.assign(fileHeaders, pageHeaders(ssrModule, pathnameOf(req.url)));
|
|
686
|
-
// OnResponse on the file path too, so a header-adding plugin sees EVERY response and not
|
|
687
|
-
// just the rendered ones.
|
|
688
805
|
let status = 200;
|
|
689
806
|
if (hookCtx) {
|
|
690
807
|
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers: fileHeaders }));
|
|
@@ -698,7 +815,7 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
698
815
|
res.end();
|
|
699
816
|
return;
|
|
700
817
|
}
|
|
701
|
-
const enc = pickEncoding(req);
|
|
818
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
702
819
|
res.statusCode = status;
|
|
703
820
|
if (enc) {
|
|
704
821
|
res.setHeader('Content-Encoding', enc);
|
|
@@ -709,22 +826,17 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
709
826
|
return;
|
|
710
827
|
}
|
|
711
828
|
|
|
712
|
-
// Otherwise render the route via SSR (dynamic routes, 404s, and every page route when
|
|
713
|
-
// a middleware exists: its per-request context must be live …
|
|
714
829
|
let broken = new Set<string>();
|
|
715
830
|
try {
|
|
716
831
|
broken = new Set(JSON.parse(fs.readFileSync(path.join(dir, 'broken.json'), 'utf-8')));
|
|
717
832
|
} catch { /* no manifest: nothing known-broken */ }
|
|
718
|
-
const safe2 = req.url || '/';
|
|
719
|
-
|
|
833
|
+
const safe2 = pathnameOf(req.url || '/');
|
|
834
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
835
|
+
if (!dev && !broken.has(safe2) && !ssrModule.isBuffered?.(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
720
836
|
const enc = pickEncoding(req);
|
|
721
|
-
// onResponse runs BEFORE the first flush, while the status and headers can still change:
|
|
722
|
-
// the hook is handed a bodyless Response carrying them …
|
|
723
837
|
let status = 200;
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
const nonce = nonceFor(ssrModule, pathnameOf(safe2));
|
|
727
|
-
let headers: Record<string, any> = pageHeaders(ssrModule, pathnameOf(safe2), nonce);
|
|
838
|
+
const nonce = nonceFor(ssrModule, safe2);
|
|
839
|
+
let headers: Record<string, any> = pageHeaders(ssrModule, safe2, nonce);
|
|
728
840
|
if (hookCtx) {
|
|
729
841
|
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers }));
|
|
730
842
|
status = out.status;
|
|
@@ -740,8 +852,6 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
740
852
|
res.setHeader('Content-Encoding', enc);
|
|
741
853
|
const compressor = createCompressor(enc);
|
|
742
854
|
compressor.pipe(res);
|
|
743
|
-
// The shell must reach the socket NOW. Without a flush zlib emits nothing until
|
|
744
|
-
// end() …
|
|
745
855
|
let flushed = false;
|
|
746
856
|
write = (chunk) => {
|
|
747
857
|
compressor.write(chunk);
|
|
@@ -750,28 +860,28 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
750
860
|
compressor.flush(zlib.constants.Z_FULL_FLUSH);
|
|
751
861
|
}
|
|
752
862
|
};
|
|
753
|
-
// pipe() forwards data but not errors, and an unhandled 'error' event kills the
|
|
754
|
-
// worker.
|
|
755
863
|
compressor.on('error', () => res.destroy());
|
|
756
864
|
done = () => compressor.end();
|
|
757
865
|
} else {
|
|
758
866
|
write = (chunk) => res.write(chunk);
|
|
759
867
|
done = () => res.end();
|
|
760
868
|
}
|
|
761
|
-
// The streamed shell opens before the render, so its <html
|
|
762
|
-
// lang>/<dir> come from the pathname (the server bundle's docAttrs)
|
|
763
869
|
const doc = ssrModule.docAttrs(safe2);
|
|
764
|
-
await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
|
|
870
|
+
await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir, !ssrModule.shellOff(safe2)), clientScriptTag(getClientSource(), nonce));
|
|
765
871
|
done();
|
|
766
872
|
return;
|
|
767
873
|
}
|
|
768
|
-
// buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
|
|
769
|
-
// = false routes …
|
|
770
874
|
const page = await ssrModule.renderPage(safe2);
|
|
771
|
-
await sendPage(req, res, ssrModule, hookCtx, page,
|
|
772
|
-
}).catch(() => {
|
|
773
|
-
|
|
774
|
-
res.
|
|
875
|
+
await sendPage(req, res, ssrModule, hookCtx, page, safe2);
|
|
876
|
+
}).catch((err: unknown) => {
|
|
877
|
+
console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
|
|
878
|
+
if (res.headersSent) {
|
|
879
|
+
res.destroy();
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
res.statusCode = 500;
|
|
883
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
884
|
+
res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
775
885
|
});
|
|
776
886
|
};
|
|
777
887
|
}
|
|
@@ -786,103 +896,160 @@ function pathnameOf(url: string | undefined): string {
|
|
|
786
896
|
}
|
|
787
897
|
|
|
788
898
|
/**
|
|
789
|
-
* The
|
|
790
|
-
*
|
|
791
|
-
*
|
|
792
|
-
|
|
793
|
-
|
|
899
|
+
* The parsed query string of a URL (?page=2&q=x -> {page:'2',q:'x'}), for
|
|
900
|
+
* $query() (P0-1). First value wins per key, the way every server-side
|
|
901
|
+
* framework reads a repeated parameter.
|
|
902
|
+
*/
|
|
903
|
+
function queryOf(url: string | undefined): Record<string, string> {
|
|
904
|
+
const q: Record<string, string> = {};
|
|
905
|
+
try {
|
|
906
|
+
new URL(url || '/', 'http://localhost').searchParams.forEach((v, k) => { if (!(k in q)) q[k] = v; });
|
|
907
|
+
} catch { /* an unparsable url carries no query */ }
|
|
908
|
+
return q;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* P0-0 (bug report): listen on `port`, hopping to the next free one when it
|
|
913
|
+
* is taken instead of crashing with EADDRINUSE. Two projects on one machine
|
|
914
|
+
* (or a dev server that did not exit cleanly) is the everyday case, and a
|
|
915
|
+
* stack trace plus a dead process is the worst possible answer to it: the
|
|
916
|
+
* banner names the port actually used, so the URL is never a guess.
|
|
917
|
+
*
|
|
918
|
+
* The hop is bounded (20 tries) and every other error is fatal - silently
|
|
919
|
+
* retrying a real fault would hide it.
|
|
920
|
+
*/
|
|
921
|
+
function listenFree(server: any, port: number, onReady: (port: number) => void): void {
|
|
922
|
+
const attempt = (p: number): void => {
|
|
923
|
+
const onError = (err: any) => {
|
|
924
|
+
server.removeListener('error', onError);
|
|
925
|
+
if (err && err.code === 'EADDRINUSE' && p - port < 20) {
|
|
926
|
+
console.log(`🌹 port ${p} is in use - trying ${p + 1}`);
|
|
927
|
+
attempt(p + 1);
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
|
|
931
|
+
process.exit(1);
|
|
932
|
+
};
|
|
933
|
+
server.once('error', onError);
|
|
934
|
+
server.listen(p, () => {
|
|
935
|
+
server.removeListener('error', onError);
|
|
936
|
+
onReady(p);
|
|
937
|
+
});
|
|
938
|
+
};
|
|
939
|
+
attempt(port);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* P0-0 (bug report): the first free port at or after `from`, probed with a
|
|
944
|
+
* throwaway socket. The cluster's primary needs this because the workers must
|
|
945
|
+
* all land on the SAME port - letting each of them hop on its own would put
|
|
946
|
+
* them on different ports and split the traffic between them. Racy by nature
|
|
947
|
+
* (a port can be taken between the probe and the workers' listen); the
|
|
948
|
+
* workers' own listenFree fallback covers that last step.
|
|
949
|
+
*/
|
|
950
|
+
async function freePort(from: number): Promise<number> {
|
|
951
|
+
const net = await import('node:net');
|
|
952
|
+
for (let p = from; p < from + 20; p++) {
|
|
953
|
+
const free = await new Promise<boolean>((resolve) => {
|
|
954
|
+
const probe = net.createServer();
|
|
955
|
+
probe.once('error', () => resolve(false));
|
|
956
|
+
probe.listen(p, () => probe.close(() => resolve(true)));
|
|
957
|
+
});
|
|
958
|
+
if (free) return p;
|
|
959
|
+
}
|
|
960
|
+
return from;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* The FRAMEWORK's version - one source of truth, no constant to drift.
|
|
965
|
+
*
|
|
966
|
+
* Three layouts answer, in order:
|
|
967
|
+
* 1. src/FRAMEWORK_VERSION, a one-line stamp that ships beside the CLI
|
|
968
|
+
* source. It is the only candidate that survives EMBEDDING: a real app
|
|
969
|
+
* copies the framework's src/ into its own tree, where the nearest
|
|
970
|
+
* package.json is the APP's - which is how a banner ended up naming the
|
|
971
|
+
* app's version as the framework's for weeks, with no way to tell which
|
|
972
|
+
* framework build was actually running.
|
|
973
|
+
* 2. the package.json two directories up (this repo: the framework's own),
|
|
974
|
+
* 3. the one beside the bundle (the published package: dist-cli/ + src/).
|
|
975
|
+
* A test asserts the stamp equals package.json, so the two cannot drift.
|
|
794
976
|
*/
|
|
795
977
|
function version(): string {
|
|
796
|
-
for (const rel of ['../../package.json', '../package.json']) {
|
|
978
|
+
for (const rel of ['../FRAMEWORK_VERSION', '../../FRAMEWORK_VERSION', '../../package.json', '../package.json']) {
|
|
797
979
|
try {
|
|
798
|
-
const
|
|
980
|
+
const raw = fs.readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf-8');
|
|
981
|
+
const v = rel.endsWith('FRAMEWORK_VERSION') ? raw.trim() : JSON.parse(raw).version;
|
|
799
982
|
if (v) return v;
|
|
800
983
|
} catch { /* not this layout */ }
|
|
801
984
|
}
|
|
802
985
|
return '0.0.0';
|
|
803
986
|
}
|
|
804
987
|
|
|
988
|
+
/**
|
|
989
|
+
* The PROJECT's version, when it is a different package from the framework.
|
|
990
|
+
* A project that embeds the CLI source (the way a real app does) has its own
|
|
991
|
+
* package.json, and a banner that named only that one left the operator
|
|
992
|
+
* unable to tell which FRAMEWORK build was actually running - the two
|
|
993
|
+
* versions advanced independently for weeks. The banner now names both:
|
|
994
|
+
* "rosetack v0.4.0 - project: my-app v0.1.1". Absent (running inside the
|
|
995
|
+
* framework repo itself, or a directory with no package.json) -> nothing.
|
|
996
|
+
*/
|
|
997
|
+
function projectTag(): string {
|
|
998
|
+
try {
|
|
999
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8'));
|
|
1000
|
+
if (!pkg.version || pkg.name === 'rosetack') return '';
|
|
1001
|
+
return ` - project: ${pkg.name} v${pkg.version}`;
|
|
1002
|
+
} catch {
|
|
1003
|
+
return '';
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
805
1007
|
async function dev(): Promise<void> {
|
|
806
|
-
console.log(`🌹 RoseTack v${version()} dev server starting...`);
|
|
1008
|
+
console.log(`🌹 RoseTack v${version()}${projectTag()} dev server starting...`);
|
|
807
1009
|
try {
|
|
808
1010
|
await build();
|
|
809
1011
|
} catch (err) {
|
|
810
|
-
// A broken .rose file must not prevent the server from starting; the
|
|
811
|
-
// watcher below rebuilds as soon as the file is fixed.
|
|
812
1012
|
console.error('Initial build failed (server still running):', err instanceof Error ? err.message : err);
|
|
813
1013
|
}
|
|
814
1014
|
|
|
815
1015
|
let timeout: any;
|
|
816
1016
|
fs.watch(SRC_DIR, { recursive: true }, () => {
|
|
1017
|
+
devBuildPending = true;
|
|
817
1018
|
clearTimeout(timeout);
|
|
818
|
-
timeout = setTimeout(
|
|
819
|
-
try {
|
|
820
|
-
console.log('Rebuilding...');
|
|
821
|
-
await build();
|
|
822
|
-
} catch (err) {
|
|
823
|
-
// Never let a user-code error kill the dev server.
|
|
824
|
-
console.error('Build failed (server still running):', err instanceof Error ? err.message : err);
|
|
825
|
-
}
|
|
826
|
-
}, 200);
|
|
1019
|
+
timeout = setTimeout(() => { void startDevBuild(); }, 200);
|
|
827
1020
|
});
|
|
828
1021
|
|
|
829
1022
|
const http = await import('http');
|
|
830
|
-
const server = http.createServer(serveStatic(OUT_DIR));
|
|
1023
|
+
const server = http.createServer(devWrap(serveStatic(OUT_DIR, false, true)));
|
|
831
1024
|
|
|
832
|
-
server
|
|
833
|
-
console.log('🌹 http://localhost:' +
|
|
1025
|
+
listenFree(server, PORT, (port) => {
|
|
1026
|
+
console.log('🌹 http://localhost:' + port);
|
|
834
1027
|
});
|
|
835
1028
|
}
|
|
836
1029
|
|
|
837
1030
|
async function preview(): Promise<void> {
|
|
838
1031
|
await build();
|
|
839
1032
|
const http = await import('http');
|
|
840
|
-
// isr=true: routes exporting `revalidate = N` are served stale-then-swapped
|
|
841
|
-
// from disk . Dev passes nothing (it rebuilds on change).
|
|
842
1033
|
const server = http.createServer(serveStatic(OUT_DIR, true));
|
|
843
1034
|
|
|
844
|
-
server
|
|
845
|
-
console.log(`🌹 RoseTack v${version()} preview at http://localhost
|
|
1035
|
+
listenFree(server, PORT, (port) => {
|
|
1036
|
+
console.log(`🌹 RoseTack v${version()}${projectTag()} preview at http://localhost:${port}`);
|
|
846
1037
|
});
|
|
847
1038
|
}
|
|
848
1039
|
|
|
849
|
-
|
|
850
|
-
* `rosetack serve` runs what `build` produced - no rebuild, no
|
|
851
|
-
* watcher, production semantics (a preview that re-rendered on the fly
|
|
852
|
-
* could serve a half-written file). Multi-core through the stdlib cluster:
|
|
853
|
-
* the primary supervises and serves no traffic, the workers serve; every
|
|
854
|
-
* request is logged; SIGTERM drains in-flight work and exits.
|
|
855
|
-
*
|
|
856
|
-
* Boundaries, stated plainly:
|
|
857
|
-
* - each worker is its own process with its own dist/server.js module.
|
|
858
|
-
* Module-scope state is therefore per-worker, which is what $store()
|
|
859
|
-
* fixes: writes broadcast through the primary, reads stay
|
|
860
|
-
* local-synchronous. ISR revalidation may run in more than one worker
|
|
861
|
-
* for one route: the guard is per-worker and the cost is one duplicate
|
|
862
|
-
* render.
|
|
863
|
-
* - the signal-driven drain is POSIX behavior. On Windows a kill() is
|
|
864
|
-
* abrupt by the platform's design, so the worker instead exits on the
|
|
865
|
-
* primary's death (the disconnect handler below) - a killed primary must
|
|
866
|
-
* never leave orphans holding the port.
|
|
867
|
-
*/
|
|
1040
|
+
|
|
868
1041
|
async function serve(): Promise<void> {
|
|
869
1042
|
if (!fs.existsSync(path.join(OUT_DIR, 'server.js'))) {
|
|
870
1043
|
console.error(`rosetack: ${OUT_DIR} has no server.js - run rosetack build first`);
|
|
871
1044
|
process.exit(1);
|
|
872
1045
|
}
|
|
873
|
-
// .default: node:cluster is an `export =` module, so the dynamic import
|
|
874
|
-
// hands back the namespace with the real module on `.default`
|
|
875
1046
|
const cluster = (await import('node:cluster')).default as any;
|
|
876
|
-
// Round-robin the accepts between workers. The default leaves the handout to the
|
|
877
|
-
// operating system …
|
|
878
1047
|
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
879
1048
|
const os = await import('node:os');
|
|
880
1049
|
const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
|
|
881
|
-
const PORT = Number(process.env.PORT) || 3000;
|
|
882
1050
|
if (cluster.isPrimary) {
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
// patch to every OTHER worker …
|
|
1051
|
+
const port = await freePort(Number(process.env.PORT) || 3000);
|
|
1052
|
+
for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
|
|
886
1053
|
cluster.on('message', (worker: any, msg: any) => {
|
|
887
1054
|
if (!msg || msg.type !== 'rosetack:store') return;
|
|
888
1055
|
for (const w of Object.values<any>(cluster.workers ?? {})) {
|
|
@@ -897,39 +1064,45 @@ async function serve(): Promise<void> {
|
|
|
897
1064
|
process.on('SIGTERM', stop);
|
|
898
1065
|
process.on('SIGINT', stop);
|
|
899
1066
|
cluster.on('exit', () => { if (--live <= 0) process.exit(0); });
|
|
900
|
-
console.log(`🌹 RoseTack v${version()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${
|
|
1067
|
+
console.log(`🌹 RoseTack v${version()}${projectTag()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
901
1068
|
return;
|
|
902
1069
|
}
|
|
903
|
-
// worker the primary's death is the worker's death: no orphan holding the port
|
|
904
1070
|
process.on('disconnect', () => process.exit(0));
|
|
905
|
-
// OnServe / onShutdown - the worker's lifecycle. A plugin that owns a resource (a
|
|
906
|
-
// connection pool, a warm cache) opens it here and closes it in the drain …
|
|
907
1071
|
let servicePlugins: any[] = [];
|
|
908
1072
|
try {
|
|
909
1073
|
servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
|
|
910
1074
|
} catch (err) {
|
|
911
|
-
console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : err);
|
|
1075
|
+
console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
|
|
1076
|
+
}
|
|
1077
|
+
const storeBridge = {
|
|
1078
|
+
install: (send: ((name: string, value: unknown) => void) | null) => {
|
|
1079
|
+
try { serverModule?.__installStoreTransport?.(send); } catch { /* a stale dist: no bridge, no crash */ }
|
|
1080
|
+
},
|
|
1081
|
+
deliver: (name: string, value: unknown) => {
|
|
1082
|
+
try { serverModule?.__deliverStorePatch?.(name, value); } catch { }
|
|
1083
|
+
},
|
|
1084
|
+
};
|
|
1085
|
+
try {
|
|
1086
|
+
await loadServer();
|
|
1087
|
+
} catch (err) {
|
|
1088
|
+
console.error('rosetack: dist/server.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
|
|
912
1089
|
}
|
|
913
1090
|
const http = await import('node:http');
|
|
914
1091
|
const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
|
|
915
|
-
// A client that stalls mid-request is dropped instead of holding a worker;
|
|
916
|
-
// idle keep-alive sockets close so a drained worker can actually exit.
|
|
917
1092
|
server.requestTimeout = 30_000;
|
|
918
|
-
server.headersTimeout = 65_000;
|
|
1093
|
+
server.headersTimeout = 65_000;
|
|
919
1094
|
server.keepAliveTimeout = 5_000;
|
|
920
|
-
server
|
|
921
|
-
console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${
|
|
1095
|
+
listenFree(server, PORT, async (port) => {
|
|
1096
|
+
console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${port}`);
|
|
922
1097
|
for (const p of servicePlugins) {
|
|
923
1098
|
try {
|
|
924
|
-
await p.onServe({ port
|
|
1099
|
+
await p.onServe({ port, workers, store: storeBridge });
|
|
925
1100
|
} catch (err) {
|
|
926
|
-
console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : err);
|
|
1101
|
+
console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : String(err));
|
|
927
1102
|
}
|
|
928
1103
|
}
|
|
929
1104
|
});
|
|
930
1105
|
const stop = () => {
|
|
931
|
-
// onShutdown first: close what onServe opened, then drain. A throwing
|
|
932
|
-
// hook must not stop the drain - the process still exits on the timer.
|
|
933
1106
|
for (const p of servicePlugins) {
|
|
934
1107
|
if (!p.onShutdown) continue;
|
|
935
1108
|
try {
|
|
@@ -940,28 +1113,94 @@ async function serve(): Promise<void> {
|
|
|
940
1113
|
console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
|
|
941
1114
|
}
|
|
942
1115
|
}
|
|
943
|
-
server.close(() => process.exit(0));
|
|
944
|
-
server.closeIdleConnections?.();
|
|
945
|
-
setTimeout(() => process.exit(0), 5000).unref();
|
|
1116
|
+
server.close(() => process.exit(0));
|
|
1117
|
+
server.closeIdleConnections?.();
|
|
1118
|
+
setTimeout(() => process.exit(0), 5000).unref();
|
|
946
1119
|
};
|
|
947
1120
|
process.on('SIGTERM', stop);
|
|
948
1121
|
process.on('SIGINT', stop);
|
|
949
1122
|
}
|
|
950
1123
|
|
|
1124
|
+
|
|
1125
|
+
function templatesDir(): string | null {
|
|
1126
|
+
for (const rel of ['../../templates', '../templates']) {
|
|
1127
|
+
const p = fileURLToPath(new URL(rel, import.meta.url));
|
|
1128
|
+
if (fs.existsSync(p)) return p;
|
|
1129
|
+
}
|
|
1130
|
+
return null;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/** The TypeScript-ready files every scaffolded project gets: the ambient
|
|
1134
|
+
* globals (editors and tsc both see them) and a strict tsconfig. */
|
|
1135
|
+
function writeTypeScriptReady(dir: string): void {
|
|
1136
|
+
fs.writeFileSync(path.join(dir, 'rosetack-env.d.ts'), `/// <reference types="rosetack" />\n`);
|
|
1137
|
+
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
1138
|
+
compilerOptions: {
|
|
1139
|
+
target: 'ES2022',
|
|
1140
|
+
module: 'ESNext',
|
|
1141
|
+
moduleResolution: 'bundler',
|
|
1142
|
+
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
|
|
1143
|
+
strict: true,
|
|
1144
|
+
noEmit: true,
|
|
1145
|
+
skipLibCheck: true,
|
|
1146
|
+
},
|
|
1147
|
+
include: ['rosetack-env.d.ts', 'src/**/*.ts'],
|
|
1148
|
+
}, null, 2) + '\n');
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
|
|
1152
|
+
function copyTemplate(dir: string, name: string, display: string): void {
|
|
1153
|
+
const base = templatesDir();
|
|
1154
|
+
const shipped = base ? path.resolve(base, name) : '';
|
|
1155
|
+
const src = fs.existsSync(shipped) ? shipped : path.resolve(name);
|
|
1156
|
+
if (!fs.existsSync(src) || !fs.statSync(src).isDirectory()) {
|
|
1157
|
+
const available = base ? fs.readdirSync(base).join(', ') : '(none found)';
|
|
1158
|
+
console.error(`rosetack: no template '${name}' - available: ${available} (or pass a path to any project directory)`);
|
|
1159
|
+
process.exit(1);
|
|
1160
|
+
}
|
|
1161
|
+
fs.cpSync(src, dir, {
|
|
1162
|
+
recursive: true,
|
|
1163
|
+
filter: (s) => !/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(s),
|
|
1164
|
+
});
|
|
1165
|
+
const pkgFile = path.join(dir, 'package.json');
|
|
1166
|
+
if (fs.existsSync(pkgFile)) {
|
|
1167
|
+
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
|
|
1168
|
+
pkg.name = path.basename(dir);
|
|
1169
|
+
if (pkg.dependencies?.rosetack) pkg.dependencies.rosetack = `^${version()}`;
|
|
1170
|
+
pkg.devDependencies = { ...pkg.devDependencies, typescript: '^5.6.0' };
|
|
1171
|
+
fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
|
|
1172
|
+
}
|
|
1173
|
+
writeTypeScriptReady(dir);
|
|
1174
|
+
console.log(`🌹 RoseTack new: ${display}/ from the '${path.basename(src)}' template`);
|
|
1175
|
+
console.log(`\n cd ${display}`);
|
|
1176
|
+
console.log(` npm install && npm run dev`);
|
|
1177
|
+
console.log(` npm run build # then deploy dist/`);
|
|
1178
|
+
}
|
|
1179
|
+
|
|
951
1180
|
/**
|
|
952
1181
|
* `rosetack new <name>` - a starting project. The smallest thing that builds
|
|
953
1182
|
* and runs and shows the syntax: one page (state, {#if}, {#each}, a scoped
|
|
954
1183
|
* style), one README naming the three commands. Not a second demo app - the
|
|
955
1184
|
* point is that a new developer's first `rosetack build` works in seconds.
|
|
956
1185
|
*
|
|
1186
|
+
* `rosetack new <name> --template <t>` - the
|
|
1187
|
+
* official templates (blog, api, admin, site) copied verbatim, with the
|
|
1188
|
+
* dependency rewritten to the published package. A name that is not a
|
|
1189
|
+
* shipped template is resolved as a PATH, so any project directory works as
|
|
1190
|
+
* a template (a team's own starter, a checkout's examples/).
|
|
1191
|
+
*
|
|
957
1192
|
* Trade-off: three files, written from strings. No template engine, no
|
|
958
1193
|
* dependency, no `npm install` run on the developer's behalf (they may use
|
|
959
1194
|
* pnpm/yarn/bun, and a surprise install is worse than a printed command).
|
|
960
1195
|
*/
|
|
961
1196
|
async function scaffold(): Promise<void> {
|
|
962
|
-
const
|
|
963
|
-
|
|
964
|
-
|
|
1197
|
+
const args = argv.slice(1);
|
|
1198
|
+
const tplIdx = args.indexOf('--template');
|
|
1199
|
+
const template = tplIdx >= 0 ? args[tplIdx + 1] : null;
|
|
1200
|
+
const name = args.find((a, i) => !a.startsWith('-') && i !== (tplIdx >= 0 ? tplIdx + 1 : -1));
|
|
1201
|
+
if (!name || (tplIdx >= 0 && !template)) {
|
|
1202
|
+
const available = templatesDir() ? fs.readdirSync(templatesDir()!).join(', ') : 'blog, api, admin, site';
|
|
1203
|
+
console.log(`Usage: rosetack new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${available} - or any project directory)`);
|
|
965
1204
|
return;
|
|
966
1205
|
}
|
|
967
1206
|
const dir = path.resolve(name);
|
|
@@ -969,6 +1208,12 @@ async function scaffold(): Promise<void> {
|
|
|
969
1208
|
console.error(`rosetack: ${dir} already exists - pick another name`);
|
|
970
1209
|
process.exit(1);
|
|
971
1210
|
}
|
|
1211
|
+
|
|
1212
|
+
if (template) {
|
|
1213
|
+
copyTemplate(dir, template, name);
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
972
1217
|
const pages = path.join(dir, 'src', 'pages');
|
|
973
1218
|
fs.mkdirSync(pages, { recursive: true });
|
|
974
1219
|
|
|
@@ -984,33 +1229,13 @@ async function scaffold(): Promise<void> {
|
|
|
984
1229
|
check: 'rosetack check',
|
|
985
1230
|
},
|
|
986
1231
|
dependencies: { rosetack: `^${version()}` },
|
|
987
|
-
// TypeScript is a first-class citizen: .rose scripts are typed, and `npm run check`
|
|
988
|
-
// type-checks every one of them with THIS project's TypeScript …
|
|
989
1232
|
devDependencies: { typescript: '^5.6.0' },
|
|
990
1233
|
}, null, 2) + '\n');
|
|
991
1234
|
|
|
992
|
-
|
|
993
|
-
// pulled in from the installed package: editors and tsc both see them.
|
|
994
|
-
fs.writeFileSync(path.join(dir, 'rosetack-env.d.ts'), `/// <reference types="rosetack" />\n`);
|
|
995
|
-
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
996
|
-
compilerOptions: {
|
|
997
|
-
target: 'ES2022',
|
|
998
|
-
module: 'ESNext',
|
|
999
|
-
moduleResolution: 'bundler',
|
|
1000
|
-
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
|
|
1001
|
-
strict: true,
|
|
1002
|
-
noEmit: true,
|
|
1003
|
-
skipLibCheck: true,
|
|
1004
|
-
},
|
|
1005
|
-
// the env file first (it is what makes the globals visible), then any
|
|
1006
|
-
// .ts the project grows - .rose scripts are checked by `npm run check`
|
|
1007
|
-
include: ['rosetack-env.d.ts', 'src/**/*.ts'],
|
|
1008
|
-
}, null, 2) + '\n');
|
|
1235
|
+
writeTypeScriptReady(dir);
|
|
1009
1236
|
|
|
1010
1237
|
fs.writeFileSync(path.join(pages, 'index.rose'), `<script>
|
|
1011
|
-
|
|
1012
|
-
// The script block is TypeScript - interfaces, annotations, generics and
|
|
1013
|
-
// casts all compile, and \`npm run check\` type-checks them.
|
|
1238
|
+
|
|
1014
1239
|
interface Item { label: string }
|
|
1015
1240
|
|
|
1016
1241
|
let count = $state(0);
|
|
@@ -1019,8 +1244,8 @@ async function scaffold(): Promise<void> {
|
|
|
1019
1244
|
|
|
1020
1245
|
function increment() { $setState('count', count() + 1); }
|
|
1021
1246
|
function toggleList() { $setState('showList', !showList()); }
|
|
1022
|
-
|
|
1023
|
-
|
|
1247
|
+
|
|
1248
|
+
|
|
1024
1249
|
let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
|
|
1025
1250
|
</script>
|
|
1026
1251
|
|
|
@@ -1058,7 +1283,6 @@ npm run check # type-checks every .rose script
|
|
|
1058
1283
|
Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
|
|
1059
1284
|
\`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
|
|
1060
1285
|
runs before every request, \`src/pages/api/*.rose\` answers JSON.
|
|
1061
|
-
Full syntax: the README of the rosetack package.
|
|
1062
1286
|
`);
|
|
1063
1287
|
|
|
1064
1288
|
fs.writeFileSync(path.join(dir, '.gitignore'), 'node_modules/\ndist/\n');
|
|
@@ -1093,8 +1317,6 @@ async function check(): Promise<void> {
|
|
|
1093
1317
|
process.exit(1);
|
|
1094
1318
|
}
|
|
1095
1319
|
|
|
1096
|
-
// The project's typescript, resolved FROM the project: the framework must not drag its
|
|
1097
|
-
// own copy into a user's install …
|
|
1098
1320
|
let tsMod: typeof ts;
|
|
1099
1321
|
try {
|
|
1100
1322
|
const req = createRequire(pathToFileURL(path.join(SRC_DIR, 'package.json')));
|
|
@@ -1104,21 +1326,14 @@ async function check(): Promise<void> {
|
|
|
1104
1326
|
process.exit(1);
|
|
1105
1327
|
}
|
|
1106
1328
|
|
|
1107
|
-
// rosetack's ambient globals, resolved from the COMPILER's own location:
|
|
1108
|
-
// src/types/rosetack.d.ts is a sibling in the repo and two levels down in
|
|
1109
|
-
// the published package (same two layouts as the runtime entry).
|
|
1110
1329
|
const nextTo = (rel: string[]) => rel.map((r) => fileURLToPath(new URL(r, import.meta.url))).find((p) => fs.existsSync(p));
|
|
1111
1330
|
const typesFile = nextTo(['../types/rosetack.d.ts', '../src/types/rosetack.d.ts']);
|
|
1112
1331
|
if (!typesFile) {
|
|
1113
1332
|
console.error('rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler');
|
|
1114
1333
|
process.exit(1);
|
|
1115
1334
|
}
|
|
1116
|
-
// The runtime source, for scripts that import helpers from './runtime.js' (the module the
|
|
1117
|
-
// compiler generates beside the intermediates).
|
|
1118
1335
|
const runtimeSource = nextTo(['../runtime/index.ts', '../src/runtime/index.ts']);
|
|
1119
1336
|
|
|
1120
|
-
// Each script becomes a virtual file NAMED after its .rose file, padded so a diagnostic's
|
|
1121
|
-
// line/column are the .rose file's own: the <script> tag sits on line L …
|
|
1122
1337
|
const norm = (f: string) => path.resolve(f).replace(/\\/g, '/');
|
|
1123
1338
|
const virtual = new Map<string, string>();
|
|
1124
1339
|
let checked = 0;
|
|
@@ -1126,7 +1341,7 @@ async function check(): Promise<void> {
|
|
|
1126
1341
|
const source = await fs.promises.readFile(file, 'utf-8');
|
|
1127
1342
|
const m = /<script>/.exec(source);
|
|
1128
1343
|
const script = scriptOf(source);
|
|
1129
|
-
if (!script) continue;
|
|
1344
|
+
if (!script) continue;
|
|
1130
1345
|
const tagLine = source.slice(0, m!.index + '<script>'.length).split('\n').length;
|
|
1131
1346
|
const wired = runtimeSource
|
|
1132
1347
|
? script.replace(/['"]\.\/runtime\.js['"]/g, JSON.stringify(runtimeSource.replace(/\\/g, '/')))
|
|
@@ -1139,14 +1354,12 @@ async function check(): Promise<void> {
|
|
|
1139
1354
|
return;
|
|
1140
1355
|
}
|
|
1141
1356
|
|
|
1142
|
-
// An imported component's binding IS its render function (the compiler rewrites `import
|
|
1143
|
-
// Card from '...Card.rose'` to `import { render as Card }`) …
|
|
1144
1357
|
const propType = (def: string | null): string => {
|
|
1145
|
-
if (!def) return 'unknown';
|
|
1358
|
+
if (!def) return 'unknown';
|
|
1146
1359
|
if (/^['"`]/.test(def)) return 'string';
|
|
1147
1360
|
if (/^-?\d+(\.\d+)?$/.test(def)) return 'number';
|
|
1148
1361
|
if (/^(true|false)$/.test(def)) return 'boolean';
|
|
1149
|
-
return 'unknown';
|
|
1362
|
+
return 'unknown';
|
|
1150
1363
|
};
|
|
1151
1364
|
const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
|
|
1152
1365
|
const declared = new Set<string>();
|
|
@@ -1157,7 +1370,7 @@ async function check(): Promise<void> {
|
|
|
1157
1370
|
const target = norm(path.resolve(path.dirname(file), spec[1]));
|
|
1158
1371
|
if (target === file || declared.has(target)) continue;
|
|
1159
1372
|
const targetSource = await fs.promises.readFile(target, 'utf-8').catch(() => null);
|
|
1160
|
-
if (targetSource === null) continue;
|
|
1373
|
+
if (targetSource === null) continue;
|
|
1161
1374
|
const props = extractExports(scriptOf(targetSource) ?? '').props;
|
|
1162
1375
|
virtual.set(`${target}.d.ts`, [
|
|
1163
1376
|
`declare function render(closes: unknown[], children: string, __props: { ${props.map((p) => `${p.name}?: ${propType(p.def)}`).join('; ')} }, __slots?: Record<string, unknown>): string;`,
|
|
@@ -1175,18 +1388,11 @@ async function check(): Promise<void> {
|
|
|
1175
1388
|
module: tsMod.ModuleKind.ESNext,
|
|
1176
1389
|
moduleResolution: tsMod.ModuleResolutionKind.Bundler,
|
|
1177
1390
|
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
|
|
1178
|
-
// the virtual files are named after the .rose files (so a diagnostic points at the real
|
|
1179
|
-
// path) …
|
|
1180
1391
|
allowNonTsExtensions: true,
|
|
1181
|
-
// the rewired './runtime.js' import points at a real .ts source
|
|
1182
1392
|
allowImportingTsExtensions: true,
|
|
1183
|
-
// `types` is deliberately NOT set: the project's own @types packages (@types/node for
|
|
1184
|
-
// node:sqlite, say) load automatically, the way they do for the user's own .ts files.
|
|
1185
1393
|
skipLibCheck: true,
|
|
1186
1394
|
};
|
|
1187
1395
|
const host = tsMod.createCompilerHost(options);
|
|
1188
|
-
// @types discovery starts at the project root, not the process cwd - the
|
|
1189
|
-
// command works from anywhere, like every other rosetack command.
|
|
1190
1396
|
host.getCurrentDirectory = () => path.resolve(SRC_DIR);
|
|
1191
1397
|
const realRead = host.readFile.bind(host);
|
|
1192
1398
|
const realGet = host.getSourceFile.bind(host);
|
|
@@ -1197,11 +1403,7 @@ async function check(): Promise<void> {
|
|
|
1197
1403
|
return src ? tsMod.createSourceFile(f, src, version, true) : realGet(f, version, onError, shouldCreate);
|
|
1198
1404
|
};
|
|
1199
1405
|
|
|
1200
|
-
// rosetack's ambient globals as a program root: a global .d.ts contributes its
|
|
1201
|
-
// declarations to every file in the program …
|
|
1202
1406
|
const program = tsMod.createProgram([...virtual.keys(), typesFile], options, host);
|
|
1203
|
-
// Only the project's own scripts: an error inside @types/node or inside rosetack's
|
|
1204
|
-
// runtime source is not the user's bug …
|
|
1205
1407
|
const diagnostics = tsMod.getPreEmitDiagnostics(program)
|
|
1206
1408
|
.filter((d) => d.file && virtual.has(norm(d.file.fileName)));
|
|
1207
1409
|
if (diagnostics.length === 0) {
|
|
@@ -1209,7 +1411,6 @@ async function check(): Promise<void> {
|
|
|
1209
1411
|
return;
|
|
1210
1412
|
}
|
|
1211
1413
|
for (const d of diagnostics) {
|
|
1212
|
-
// paths relative to the project root, the way tsc prints them
|
|
1213
1414
|
const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
|
|
1214
1415
|
const where = d.file && at
|
|
1215
1416
|
? `${path.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})`
|
|
@@ -1223,11 +1424,33 @@ async function check(): Promise<void> {
|
|
|
1223
1424
|
process.exit(1);
|
|
1224
1425
|
}
|
|
1225
1426
|
|
|
1226
|
-
const
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1427
|
+
const argv = process.argv.slice(2);
|
|
1428
|
+
const cmd = argv[0];
|
|
1429
|
+
const asJson = argv.includes('--json');
|
|
1430
|
+
|
|
1431
|
+
/** Print a failure the way its reader needs it. A RoseError is the
|
|
1432
|
+
* developer's (or the agent's) to fix from its code alone; anything else
|
|
1433
|
+
* keeps its stack, because it is not. Always exits non-zero: a build that
|
|
1434
|
+
* says nothing and succeeds is the worst failure mode there is. */
|
|
1435
|
+
function reportFailure(err: unknown): never {
|
|
1436
|
+
if (asJson) {
|
|
1437
|
+
process.stdout.write(`${JSON.stringify({ ok: false, errors: [errorInfo(err)] })}\n`);
|
|
1438
|
+
} else if (err instanceof RoseError) {
|
|
1439
|
+
console.error(`rosetack: ${err.message}`);
|
|
1440
|
+
if (err.hint) console.error(` hint: ${err.hint}`);
|
|
1441
|
+
const at = err.file ? `${err.file}${err.line ? `:${err.line}` : ''}` : null;
|
|
1442
|
+
if (at) console.error(` at ${at}`);
|
|
1443
|
+
} else {
|
|
1444
|
+
console.error(err instanceof Error ? err.stack ?? err.message : String(err));
|
|
1445
|
+
}
|
|
1446
|
+
process.exit(1);
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
if (cmd === 'dev') void dev().catch(reportFailure);
|
|
1450
|
+
else if (cmd === 'build') void build().catch(reportFailure);
|
|
1451
|
+
else if (cmd === 'preview') void preview().catch(reportFailure);
|
|
1452
|
+
else if (cmd === 'serve') void serve().catch(reportFailure);
|
|
1453
|
+
else if (cmd === 'new') void scaffold().catch(reportFailure);
|
|
1454
|
+
else if (cmd === 'check') void check().catch(reportFailure);
|
|
1455
|
+
else if (cmd === 'prompt') console.log(AI_PROMPT);
|
|
1456
|
+
else console.log('Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] [--static] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON; --static verifies the build is deployable with no server at all; `new <name> [--template blog|api|admin|site]` scaffolds a project)');
|