rosetack 0.0.0 → 0.1.0
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/.github/workflows/ci.yml +72 -0
- package/.github/workflows/release.yml +122 -0
- package/LICENSE +21 -0
- package/benchmark.ts +227 -0
- package/deploy/Dockerfile.node +25 -0
- package/deploy/Dockerfile.static +34 -0
- package/deploy/api/rosetack.ts +29 -0
- package/deploy/docker-compose.yml +33 -0
- package/deploy/fly.toml +28 -0
- package/deploy/vercel.json +13 -0
- package/example/public/favicon.ico +0 -0
- package/example/public/logo.svg +148 -0
- package/example/public/rose-mark-black.png +0 -0
- package/example/public/rose-mark.png +0 -0
- package/example/public/rose-mono.png +0 -0
- package/example/rosetack.config.js +10 -0
- package/example/src/locales/en.json +8 -0
- package/example/src/locales/zh.json +8 -0
- package/example/src/pages/404.rose +15 -0
- package/example/src/pages/500.rose +10 -0
- package/example/src/pages/[lang]/about.rose +40 -0
- package/example/src/pages/_layout.rose +33 -0
- package/example/src/pages/_middleware.rose +37 -0
- package/example/src/pages/about.rose +67 -0
- package/example/src/pages/admin.rose +27 -0
- package/example/src/pages/api/hello.rose +19 -0
- package/example/src/pages/api/login.rose +55 -0
- package/example/src/pages/api/posts.rose +80 -0
- package/example/src/pages/api/secret.rose +14 -0
- package/example/src/pages/blog/[id].rose +25 -0
- package/example/src/pages/broken.rose +16 -0
- package/example/src/pages/fresh.rose +22 -0
- package/example/src/pages/garden.rose +27 -0
- package/example/src/pages/index.rose +84 -0
- package/example/src/pages/sign.rose +45 -0
- package/example/src/pages/thorn.rose +23 -0
- package/example/src/pages/vault.rose +14 -0
- package/go.mod +3 -0
- package/main.go +470 -0
- package/package.json +32 -11
- package/src/FRAMEWORK_VERSION +1 -0
- package/src/cli/edge.ts +127 -0
- package/src/cli/index.ts +777 -0
- package/src/cli/shell.ts +284 -0
- package/src/compiler/index.ts +1990 -0
- package/src/runtime/index.ts +624 -0
- package/tools/release-notes.mjs +113 -0
- package/tsconfig.json +17 -0
- package/README.md +0 -3
- package/index.js +0 -12
package/src/cli/index.ts
ADDED
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rosetack CLI - simplest possible SSR + static server
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from 'fs';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import * as zlib from 'zlib';
|
|
8
|
+
import { pathToFileURL, fileURLToPath } from 'url';
|
|
9
|
+
import { buildProject, type RouteInfo } from '../compiler/index.js';
|
|
10
|
+
import { getHtmlShell, getClientSource, shellOpen, clientScriptTag, securityHeaders, setBundleMode } from './shell.js';
|
|
11
|
+
|
|
12
|
+
// --- wire performance: compression + conditional caching (stdlib only) --- The Go binary
|
|
13
|
+
// already compresses …
|
|
14
|
+
type Encoding = 'br' | 'gzip' | 'deflate';
|
|
15
|
+
|
|
16
|
+
function pickEncoding(req: any): Encoding | null {
|
|
17
|
+
const ae: string = req.headers['accept-encoding'] || '';
|
|
18
|
+
// ponytail: substring match, no q-value parsing - every browser that sends
|
|
19
|
+
// br also accepts gzip, and br > gzip > deflate is the quality order.
|
|
20
|
+
if (ae.includes('br')) return 'br';
|
|
21
|
+
if (ae.includes('gzip')) return 'gzip';
|
|
22
|
+
if (ae.includes('deflate')) return 'deflate';
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function compress(enc: Encoding, data: string | Buffer): Buffer {
|
|
27
|
+
if (enc === 'br') return zlib.brotliCompressSync(data);
|
|
28
|
+
if (enc === 'gzip') return zlib.gzipSync(data);
|
|
29
|
+
return zlib.deflateSync(data);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function createCompressor(enc: Encoding): zlib.Gzip | zlib.Deflate | zlib.BrotliCompress {
|
|
33
|
+
if (enc === 'br') return zlib.createBrotliCompress();
|
|
34
|
+
if (enc === 'gzip') return zlib.createGzip();
|
|
35
|
+
return zlib.createDeflate();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Send a full HTML document, compressed when the client accepts it. */
|
|
39
|
+
function sendHtml(req: any, res: any, status: number, html: string, extraHeaders?: Record<string, string>): void {
|
|
40
|
+
res.statusCode = status;
|
|
41
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
42
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
43
|
+
if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
|
|
44
|
+
// A weak ETag over the rendered bytes: revalidation answers a bodiless 304 for dynamic
|
|
45
|
+
// renders too …
|
|
46
|
+
let hash = 0x811c9dc5;
|
|
47
|
+
for (let i = 0; i < html.length; i++) {
|
|
48
|
+
hash ^= html.charCodeAt(i);
|
|
49
|
+
hash = (hash * 0x01000193) >>> 0;
|
|
50
|
+
}
|
|
51
|
+
const etag = `W/"${html.length}-${hash.toString(16)}"`;
|
|
52
|
+
if (req.headers['if-none-match'] === etag) {
|
|
53
|
+
res.statusCode = 304;
|
|
54
|
+
res.end();
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
res.setHeader('ETag', etag);
|
|
58
|
+
const enc = pickEncoding(req);
|
|
59
|
+
if (enc) {
|
|
60
|
+
res.setHeader('Content-Encoding', enc);
|
|
61
|
+
res.end(compress(enc, html));
|
|
62
|
+
} else {
|
|
63
|
+
res.end(html);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Copy a Web-standard Response's headers onto the Node response. set-cookie is the one
|
|
68
|
+
// header that may legally repeat, and res.setHeader overwrites …
|
|
69
|
+
function writeWebHeaders(web: any, res: any): void {
|
|
70
|
+
const cookies = web.headers.getSetCookie?.() ?? [];
|
|
71
|
+
web.headers.forEach((v: string, k: string) => {
|
|
72
|
+
if (cookies.length && k.toLowerCase() === 'set-cookie') return;
|
|
73
|
+
res.setHeader(k, v);
|
|
74
|
+
});
|
|
75
|
+
if (cookies.length) res.setHeader('set-cookie', cookies);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A middleware's short-circuit: a Web-standard Response (status, headers, body) written
|
|
79
|
+
// straight to the Node response - a redirect, an auth wall, a rewrite.
|
|
80
|
+
async function sendWebResponse(web: any, res: any): Promise<void> {
|
|
81
|
+
writeWebHeaders(web, res);
|
|
82
|
+
res.statusCode = web.status;
|
|
83
|
+
res.end(Buffer.from(await web.arrayBuffer()));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Static files: raw + both compressed forms cached per mtime (dev rebuilds change mtime;
|
|
87
|
+
// preview never does).
|
|
88
|
+
const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
|
|
89
|
+
|
|
90
|
+
// Phase 0 (the "the framework is real" gate): the CLI builds ANY project, not just this
|
|
91
|
+
// repo's demo.
|
|
92
|
+
const SRC_DIR = process.argv[3] ? path.resolve(process.argv[3]) : process.cwd();
|
|
93
|
+
const OUT_DIR = path.join(process.cwd(), 'dist');
|
|
94
|
+
// PORT env override (default 3000): lets a preview server run beside a dev
|
|
95
|
+
// server on the same machine - the e2e ISR test does exactly that.
|
|
96
|
+
const PORT = Number(process.env.PORT) || 3000;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Import dist/server.js, cached until the file changes on disk.
|
|
100
|
+
*
|
|
101
|
+
* The dev server rebuilds it on file changes, so a plain import() would
|
|
102
|
+
* serve the cached (stale) module - re-import when mtime moves. But the
|
|
103
|
+
* import must NOT be per-request: server state (stores mutated by server
|
|
104
|
+
* actions) lives in that module, and a fresh import per request would
|
|
105
|
+
* reset it on every hit, so an action's effect would vanish immediately.
|
|
106
|
+
*/
|
|
107
|
+
let serverModule: any = null;
|
|
108
|
+
let serverMtime = -1;
|
|
109
|
+
let serverVersion = 0;
|
|
110
|
+
|
|
111
|
+
async function loadServer(): Promise<any> {
|
|
112
|
+
const file = path.join(OUT_DIR, 'server.js');
|
|
113
|
+
const mtimeMs = fs.statSync(file).mtimeMs;
|
|
114
|
+
if (!serverModule || mtimeMs !== serverMtime) {
|
|
115
|
+
serverMtime = mtimeMs;
|
|
116
|
+
serverVersion++;
|
|
117
|
+
serverModule = await import(pathToFileURL(file).href + '?v=' + serverVersion);
|
|
118
|
+
}
|
|
119
|
+
return serverModule;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function build(): Promise<void> {
|
|
123
|
+
// P0 §1: the build reports the bundle mode ('inline' | 'split') so the
|
|
124
|
+
// shell follows it for every document, header and streaming tag it emits
|
|
125
|
+
const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR);
|
|
126
|
+
// The previous build's prerendered output must not survive: a route that stopped being
|
|
127
|
+
// static (it started reading getContext() or $store()) would otherwise leave its old
|
|
128
|
+
// baked …
|
|
129
|
+
await clearPrerendered(OUT_DIR);
|
|
130
|
+
setBundleMode(bundle);
|
|
131
|
+
const skipped = await prerender(routes);
|
|
132
|
+
// The broken-route manifest: the server reads it to pick the buffered path for these
|
|
133
|
+
// routes, so their real 500 status survives (a flushed response cannot change its
|
|
134
|
+
// status).
|
|
135
|
+
await fs.promises.writeFile(path.join(OUT_DIR, 'broken.json'), JSON.stringify(skipped));
|
|
136
|
+
// Per-route response headers (innovation #26) for the Go binary, which has no compiler:
|
|
137
|
+
// it reads this file and merges the entries over its own responses.
|
|
138
|
+
const ssrModule = await loadServer();
|
|
139
|
+
await fs.promises.writeFile(path.join(OUT_DIR, 'headers.json'), JSON.stringify({
|
|
140
|
+
default: securityHeaders(getClientSource()),
|
|
141
|
+
routes: ssrModule.routeHeaders ?? [],
|
|
142
|
+
}));
|
|
143
|
+
// Innovation #28: precompressed brotli siblings (dist/<file>.br) for the Go single
|
|
144
|
+
// binary.
|
|
145
|
+
await writeBrotli(OUT_DIR);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Write dist/<file>.br next to every compressible text file. ponytail:
|
|
150
|
+
* extension allowlist + zlib's default quality - a 30 KB document
|
|
151
|
+
* compresses in ~10 ms at build time, once, forever.
|
|
152
|
+
*/
|
|
153
|
+
const BROTLI_EXT = new Set(['.html', '.js', '.css', '.json', '.svg', '.txt']);
|
|
154
|
+
async function writeBrotli(dir: string): Promise<void> {
|
|
155
|
+
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
156
|
+
const p = path.join(dir, e.name);
|
|
157
|
+
if (e.isDirectory()) {
|
|
158
|
+
await writeBrotli(p);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (!BROTLI_EXT.has(path.extname(e.name).toLowerCase())) continue;
|
|
162
|
+
await fs.promises.writeFile(p + '.br', zlib.brotliCompressSync(await fs.promises.readFile(p)));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Delete the prerendered output of a previous build: HTML documents and
|
|
168
|
+
* baked API bodies, with their brotli siblings. Everything else in dist/
|
|
169
|
+
* (the bundles, styles) was just rewritten by buildProject.
|
|
170
|
+
*
|
|
171
|
+
* ponytail: Windows hands out transient EPERM/EBUSY when an antivirus or
|
|
172
|
+
* the search indexer holds a just-written file, so a couple of retries
|
|
173
|
+
* per file - a build that fails because a scanner blinked is the worst
|
|
174
|
+
* kind of flake.
|
|
175
|
+
*/
|
|
176
|
+
async function clearPrerendered(dir: string): Promise<void> {
|
|
177
|
+
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
178
|
+
const p = path.join(dir, e.name);
|
|
179
|
+
if (e.isDirectory()) {
|
|
180
|
+
await clearPrerendered(p);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (!/\.(?:html|json)(?:\.br)?$/.test(e.name)) continue;
|
|
184
|
+
for (let attempt = 0; ; attempt++) {
|
|
185
|
+
try {
|
|
186
|
+
await fs.promises.rm(p, { force: true });
|
|
187
|
+
break;
|
|
188
|
+
} catch (err) {
|
|
189
|
+
if (attempt >= 2 || !/EPERM|EBUSY|EACCES/.test(String(err))) throw err;
|
|
190
|
+
await new Promise((r) => setTimeout(r, 50 * (attempt + 1)));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Prerender every static route to dist/<route>/index.html at build time.
|
|
198
|
+
* Those files are served straight from disk: zero server work, instant TTFB.
|
|
199
|
+
* Dynamic routes with an exported `params` map (e.g. blog posts) are
|
|
200
|
+
* enumerated and prerendered per value; params without `params` keep
|
|
201
|
+
* rendering on demand. A route exporting `revalidate = N` is baked like
|
|
202
|
+
* any other and then kept fresh by the preview server's stale-while-
|
|
203
|
+
* revalidate pass (ISR, innovation #24).
|
|
204
|
+
*/
|
|
205
|
+
async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
206
|
+
const ssrModule = await loadServer();
|
|
207
|
+
const skipped: string[] = [];
|
|
208
|
+
const write = async (routePath: string) => {
|
|
209
|
+
// a synthetic cookie-less request: the middleware runs at build time too, and a route
|
|
210
|
+
// it short-circuits (an auth wall, a maintenance rewrite) simply is not static …
|
|
211
|
+
const mw = await ssrModule.runMiddleware({ method: 'GET', url: routePath, headers: {} });
|
|
212
|
+
if (mw) {
|
|
213
|
+
console.error(`prerender skipped for ${routePath}: the middleware short-circuits at build time`);
|
|
214
|
+
skipped.push(routePath);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const page = await ssrModule.renderPage(routePath);
|
|
218
|
+
if (page.status === 500) {
|
|
219
|
+
// The route's render failed and the error page rendered instead. Do NOT bake that
|
|
220
|
+
// into a static file: a static server can only answer 200 …
|
|
221
|
+
console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
|
|
222
|
+
skipped.push(routePath);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const routeDir = routePath === '/' ? OUT_DIR : path.join(OUT_DIR, routePath.slice(1));
|
|
226
|
+
await fs.promises.mkdir(routeDir, { recursive: true });
|
|
227
|
+
// csr = false routes bake a JS-free document (innovation #25): the file on disk carries
|
|
228
|
+
// no bundle and no state script, so a visitor who lands on it runs zero JavaScript.
|
|
229
|
+
await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false));
|
|
230
|
+
console.log(`prerendered ${routePath} -> ${path.relative(process.cwd(), path.join(routeDir, 'index.html'))}`);
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
for (const info of routes) {
|
|
234
|
+
// routes that read the request context (getContext()) or a shared store ($store()) are
|
|
235
|
+
// dynamic by construction: the bag is per-request and the store is per-process …
|
|
236
|
+
if ((ssrModule.dynamicRoutes as string[]).includes(info.routePath)) {
|
|
237
|
+
console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (info.paramNames.length === 0) {
|
|
241
|
+
try {
|
|
242
|
+
await write(info.routePath);
|
|
243
|
+
} catch (err) {
|
|
244
|
+
// One broken route (e.g. throwing $data) must not fail the whole build;
|
|
245
|
+
// it simply keeps rendering on demand.
|
|
246
|
+
console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
|
|
247
|
+
skipped.push(info.routePath);
|
|
248
|
+
}
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
// dynamic route: enumerate the exported params map, if any. The maps are re-exported by
|
|
252
|
+
// the server bundle (routeParams) …
|
|
253
|
+
try {
|
|
254
|
+
const paramsExport = (ssrModule.routeParams as Record<string, unknown>)?.[info.routePath];
|
|
255
|
+
const raw = typeof paramsExport === 'function' ? await (paramsExport as () => unknown)() : paramsExport;
|
|
256
|
+
const paths = enumerateParams(info.pattern, info.paramNames, (raw ?? {}) as Record<string, unknown>);
|
|
257
|
+
for (const p of paths) await write(p);
|
|
258
|
+
if (paths.length === 0) console.log(`dynamic route ${info.routePath}: no params export, rendered on demand`);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
|
|
261
|
+
skipped.push(info.routePath);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// API routes that opt in (export const prerender = true) bake their GET body into
|
|
266
|
+
// dist/api/<route>.json: the Go single binary then serves the read-only API with zero
|
|
267
|
+
// Node.
|
|
268
|
+
const apiPrerender = (ssrModule.apiPrerender as Record<string, boolean>) ?? {};
|
|
269
|
+
for (const [routePath, on] of Object.entries(apiPrerender)) {
|
|
270
|
+
if (!on) continue;
|
|
271
|
+
try {
|
|
272
|
+
const res = await ssrModule.handleApi('GET', routePath, new Request('http://localhost' + routePath));
|
|
273
|
+
if (res.status !== 200) {
|
|
274
|
+
console.error(`api prerender skipped for ${routePath}: GET answered ${res.status}`);
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
const body = await res.text();
|
|
278
|
+
const outFile = path.join(OUT_DIR, routePath.slice(1) + '.json');
|
|
279
|
+
await fs.promises.mkdir(path.dirname(outFile), { recursive: true });
|
|
280
|
+
await fs.promises.writeFile(outFile, body);
|
|
281
|
+
console.log(`prerendered api ${routePath} -> ${path.relative(process.cwd(), outFile)}`);
|
|
282
|
+
} catch (err) {
|
|
283
|
+
console.error(`api prerender skipped for ${routePath}: ${err instanceof Error ? err.message : err}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return skipped;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Cartesian product of the params map -> concrete URL paths for the pattern. */
|
|
290
|
+
function enumerateParams(pattern: string, names: string[], raw: Record<string, unknown>): string[] {
|
|
291
|
+
let combos: string[][] = [[]];
|
|
292
|
+
for (const name of names) {
|
|
293
|
+
const values = (Array.isArray(raw[name]) ? raw[name] : []).map((v) => String(v));
|
|
294
|
+
combos = combos.flatMap((c) => values.map((v) => [...c, v]));
|
|
295
|
+
}
|
|
296
|
+
return combos.map((values) => {
|
|
297
|
+
let i = 0;
|
|
298
|
+
return pattern
|
|
299
|
+
.split('/')
|
|
300
|
+
.map((seg) => (seg.startsWith(':') ? encodeURIComponent(values[i++]) : seg))
|
|
301
|
+
.join('/');
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Extensions the static branch serves without touching the router: assets keep their fast
|
|
306
|
+
// path even when a middleware exists (a middleware guards pages, not files).
|
|
307
|
+
const ASSET_EXT = new Set(['.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.woff', '.woff2', '.txt', '.xml']);
|
|
308
|
+
|
|
309
|
+
// Response headers for a page document (innovation #26): the strict CSP …
|
|
310
|
+
function pageHeaders(ssrModule: any, pathname: string): Record<string, string> {
|
|
311
|
+
const headers: Record<string, string> = {};
|
|
312
|
+
for (const [k, v] of Object.entries(securityHeaders(getClientSource()))) headers[k.toLowerCase()] = v;
|
|
313
|
+
const own = ssrModule.headersFor?.(pathname) as Record<string, string> | null | undefined;
|
|
314
|
+
if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
|
|
315
|
+
return headers;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ISR background pass (innovation #24): re-render a stale baked route and swap its file,
|
|
319
|
+
// while the triggering request was already answered from disk (stale-while-revalidate).
|
|
320
|
+
const isrBusy = new Set<string>();
|
|
321
|
+
function revalidateInBackground(routePath: string, filePath: string): void {
|
|
322
|
+
if (isrBusy.has(filePath)) return;
|
|
323
|
+
isrBusy.add(filePath);
|
|
324
|
+
void (async () => {
|
|
325
|
+
try {
|
|
326
|
+
const ssrModule = await loadServer();
|
|
327
|
+
const page = await ssrModule.renderPage(routePath);
|
|
328
|
+
if (page.status === 200) {
|
|
329
|
+
// the swap must honor the route's csr decision (innovation #29): a zero-JS route
|
|
330
|
+
// revalidated here stays zero-JS …
|
|
331
|
+
await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false));
|
|
332
|
+
fileCache.delete(filePath);
|
|
333
|
+
console.log(`rosetack: revalidated ${routePath} in the background`);
|
|
334
|
+
}
|
|
335
|
+
} catch (err) {
|
|
336
|
+
console.error('rosetack: background revalidation failed for', routePath, err instanceof Error ? err.message : err);
|
|
337
|
+
} finally {
|
|
338
|
+
isrBusy.delete(filePath);
|
|
339
|
+
}
|
|
340
|
+
})();
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// --- Phase 1: production server posture -------------------------------------- "Can run a
|
|
344
|
+
// real app" is a threshold …
|
|
345
|
+
|
|
346
|
+
/** A request body is bounded. 1 MB holds any form and any JSON API call a
|
|
347
|
+
* site this size makes; a deployment that needs more sets it explicitly. */
|
|
348
|
+
const MAX_BODY = Number(process.env.rosetack_MAX_BODY) || 1024 * 1024;
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Collect a request body, refusing anything past MAX_BODY with a 413. The
|
|
352
|
+
* refusal stops buffering immediately, so a client streaming 10 GB gets one
|
|
353
|
+
* small response instead of a 10 GB buffer.
|
|
354
|
+
*/
|
|
355
|
+
function readBody(req: any, res: any, onDone: (body: any) => void): void {
|
|
356
|
+
const chunks: Buffer[] = [];
|
|
357
|
+
let size = 0;
|
|
358
|
+
let refused = false;
|
|
359
|
+
req.on('data', (c: Buffer) => {
|
|
360
|
+
if (refused) return;
|
|
361
|
+
size += c.length;
|
|
362
|
+
if (size > MAX_BODY) {
|
|
363
|
+
refused = true;
|
|
364
|
+
res.statusCode = 413;
|
|
365
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
366
|
+
res.end(`Payload too large (limit ${MAX_BODY} bytes)`);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
chunks.push(c);
|
|
370
|
+
});
|
|
371
|
+
req.on('end', () => { if (!refused) onDone(Buffer.concat(chunks)); });
|
|
372
|
+
// an aborted upload must not throw an unhandled 'error' and take the process down with it
|
|
373
|
+
req.on('error', () => {});
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* CSRF: a state-changing request that did not come from this site is
|
|
378
|
+
* refused before anything else runs. Browsers stamp every cross-origin POST
|
|
379
|
+
* with an Origin header, so the check is free for real browsers; a client
|
|
380
|
+
* that sends neither Origin nor Sec-Fetch-Site (curl, a health check, the
|
|
381
|
+
* test suites) is not attackable by CSRF - the attack rides the victim's
|
|
382
|
+
* cookies in a browser - so it passes. Returns the refusal, or null.
|
|
383
|
+
*/
|
|
384
|
+
function crossSiteWrite(req: any): { status: number; body: string } | null {
|
|
385
|
+
const m = req.method;
|
|
386
|
+
if (m !== 'POST' && m !== 'PUT' && m !== 'PATCH' && m !== 'DELETE') return null;
|
|
387
|
+
const origin = req.headers.origin;
|
|
388
|
+
if (origin) {
|
|
389
|
+
let host: string;
|
|
390
|
+
try {
|
|
391
|
+
host = new URL(origin).host;
|
|
392
|
+
} catch {
|
|
393
|
+
return { status: 403, body: 'Cross-site request blocked (unparsable Origin header)' };
|
|
394
|
+
}
|
|
395
|
+
return host === req.headers.host ? null : { status: 403, body: 'Cross-site request blocked (Origin does not match Host)' };
|
|
396
|
+
}
|
|
397
|
+
const site = req.headers['sec-fetch-site'];
|
|
398
|
+
if (site && site !== 'same-origin' && site !== 'same-site' && site !== 'none') {
|
|
399
|
+
return { status: 403, body: `Cross-site request blocked (sec-fetch-site: ${site})` };
|
|
400
|
+
}
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* One access line per request on stdout - the same greppable shape the Go
|
|
406
|
+
* binary writes (`ts method path status bytes duration`), with the worker id
|
|
407
|
+
* in front when several workers share one stdout. Logged on the response's
|
|
408
|
+
* finish, so a streamed route is recorded when it is actually done.
|
|
409
|
+
*/
|
|
410
|
+
function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (req: any, res: any) => void {
|
|
411
|
+
return (req, res) => {
|
|
412
|
+
const started = process.hrtime.bigint();
|
|
413
|
+
let bytes = 0;
|
|
414
|
+
const write = res.write.bind(res);
|
|
415
|
+
const end = res.end.bind(res);
|
|
416
|
+
res.write = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return write(chunk, ...rest); };
|
|
417
|
+
res.end = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return end(chunk, ...rest); };
|
|
418
|
+
res.on('finish', () => {
|
|
419
|
+
const ms = Number(process.hrtime.bigint() - started) / 1e6;
|
|
420
|
+
const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1000).toFixed(0)}us`;
|
|
421
|
+
console.log(`${new Date().toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ''} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
|
|
422
|
+
});
|
|
423
|
+
handler(req, res);
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
428
|
+
return (req, res) => {
|
|
429
|
+
// The origin guard runs before everything else - middleware, api dispatch, the static
|
|
430
|
+
// lookup - because a cross-site write must not reach any of them.
|
|
431
|
+
const blocked = crossSiteWrite(req);
|
|
432
|
+
if (blocked) {
|
|
433
|
+
res.statusCode = blocked.status;
|
|
434
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
435
|
+
res.end(blocked.body);
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
// Everything below needs the server module (API dispatch, POST actions, SSR), so load
|
|
439
|
+
// it once up front: the import is cached until dist/server.js changes on disk …
|
|
440
|
+
loadServer().then(async (ssrModule: any) => {
|
|
441
|
+
// Middleware (pages/_middleware.rose) runs exactly once per request, before anything
|
|
442
|
+
// else: a returned Response short-circuits the whole request …
|
|
443
|
+
const apiPath0 = pathnameOf(req.url);
|
|
444
|
+
const isPagePost = req.method === 'POST' && !ssrModule.isApi(apiPath0);
|
|
445
|
+
if (!isPagePost && ssrModule.middleware) {
|
|
446
|
+
const mw = await ssrModule.runMiddleware(req);
|
|
447
|
+
if (mw) {
|
|
448
|
+
await sendWebResponse(mw, res);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
// API routes (pages/api/*.rose) dispatch FIRST: the /api namespace answers JSON,
|
|
453
|
+
// never the static shell or an HTML page …
|
|
454
|
+
const apiPath = pathnameOf(req.url);
|
|
455
|
+
if (ssrModule.isApi(apiPath)) {
|
|
456
|
+
readBody(req, res, async (body) => {
|
|
457
|
+
try {
|
|
458
|
+
const headers: Record<string, string> = {};
|
|
459
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
460
|
+
if (v !== undefined) headers[k] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
461
|
+
}
|
|
462
|
+
const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
|
|
463
|
+
method: req.method || 'GET',
|
|
464
|
+
headers,
|
|
465
|
+
body: body.length > 0 ? body : undefined,
|
|
466
|
+
});
|
|
467
|
+
const apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
|
|
468
|
+
writeWebHeaders(apiRes, res);
|
|
469
|
+
res.statusCode = apiRes.status;
|
|
470
|
+
res.end(Buffer.from(await apiRes.arrayBuffer()));
|
|
471
|
+
} catch {
|
|
472
|
+
res.statusCode = 500;
|
|
473
|
+
res.setHeader('Content-Type', 'application/json');
|
|
474
|
+
res.end('{"error":"api handler failed"}');
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// POST: run the matched route's server action (progressive-enhancement form). This
|
|
481
|
+
// must precede the static lookup: prerendered files exist on disk and would otherwise …
|
|
482
|
+
if (req.method === 'POST') {
|
|
483
|
+
readBody(req, res, async (body) => {
|
|
484
|
+
try {
|
|
485
|
+
const form = await new Response(body, {
|
|
486
|
+
headers: { 'content-type': req.headers['content-type'] || 'application/x-www-form-urlencoded' },
|
|
487
|
+
}).formData();
|
|
488
|
+
// the middleware pass for page POSTs: it rides with the parsed FormData so it
|
|
489
|
+
// can read form fields, and its context seeds the action + render below
|
|
490
|
+
if (ssrModule.middleware) {
|
|
491
|
+
const mw = await ssrModule.runMiddleware(req, form);
|
|
492
|
+
if (mw) {
|
|
493
|
+
await sendWebResponse(mw, res);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
const page = await ssrModule.renderPage(req.url || '/', form);
|
|
498
|
+
sendHtml(req, res, page.status ?? 200, getHtmlShell(page.html, page.state, page.head, page.csr !== false), pageHeaders(ssrModule, pathnameOf(req.url || '/')));
|
|
499
|
+
} catch {
|
|
500
|
+
res.statusCode = 400;
|
|
501
|
+
res.end('Bad request');
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
let safe = path.normalize(req.url || '/').replace(/^(\.\.(\/)?)+/, '');
|
|
508
|
+
if (safe === '\\' || safe === '/') safe = '/';
|
|
509
|
+
let filePath = path.join(dir, safe);
|
|
510
|
+
// A file in public/ answers at the root too: pages link /logo.svg, not
|
|
511
|
+
// /public/logo.svg, and the build keeps the bytes under public/.
|
|
512
|
+
if (!fs.existsSync(filePath) && ASSET_EXT.has(path.extname(safe).toLowerCase())) {
|
|
513
|
+
const pubFile = path.join(dir, 'public', safe);
|
|
514
|
+
if (fs.existsSync(pubFile)) filePath = pubFile;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// Directory -> index.html (prerendered routes live at /<route>/index.html)
|
|
518
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
|
|
519
|
+
filePath = path.join(filePath, 'index.html');
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// Build-time precompression siblings (innovation #28: dist/<file>.br, read by the Go
|
|
523
|
+
// binary) are internal artifacts.
|
|
524
|
+
if (/\.(?:br|gz)$/i.test(safe)) {
|
|
525
|
+
const base = filePath.replace(/\.(?:br|gz)$/i, '');
|
|
526
|
+
if (fs.existsSync(base)) filePath = base;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// Serve real files directly - compressed + conditionally cached, so a repeat visit
|
|
530
|
+
// costs a 304 instead of the full document. Assets always take this path.
|
|
531
|
+
const isAsset = ASSET_EXT.has(path.extname(safe).toLowerCase());
|
|
532
|
+
const isDynamic = !isAsset && (ssrModule.dynamicRoutes as string[] | undefined)?.includes(pathnameOf(req.url));
|
|
533
|
+
if (!isDynamic && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
534
|
+
const st = fs.statSync(filePath);
|
|
535
|
+
// ISR (innovation #24): a route exporting `revalidate = N` keeps its baked file for
|
|
536
|
+
// N seconds.
|
|
537
|
+
const rev = isAsset ? undefined : ((ssrModule.revalidate as { pattern: string; seconds: number }[]) || [])
|
|
538
|
+
.find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
|
|
539
|
+
if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1000) {
|
|
540
|
+
revalidateInBackground(pathnameOf(req.url), filePath);
|
|
541
|
+
}
|
|
542
|
+
let entry = fileCache.get(filePath);
|
|
543
|
+
if (!entry || entry.mtimeMs !== st.mtimeMs) {
|
|
544
|
+
const raw = fs.readFileSync(filePath);
|
|
545
|
+
entry = {
|
|
546
|
+
mtimeMs: st.mtimeMs,
|
|
547
|
+
raw,
|
|
548
|
+
br: zlib.brotliCompressSync(raw),
|
|
549
|
+
gzip: zlib.gzipSync(raw),
|
|
550
|
+
etag: `W/"${st.size}-${st.mtimeMs}"`,
|
|
551
|
+
};
|
|
552
|
+
fileCache.set(filePath, entry);
|
|
553
|
+
}
|
|
554
|
+
const ext = path.extname(filePath);
|
|
555
|
+
const types: Record<string, string> = {
|
|
556
|
+
'.html': 'text/html',
|
|
557
|
+
'.js': 'application/javascript',
|
|
558
|
+
'.css': 'text/css',
|
|
559
|
+
'.json': 'application/json',
|
|
560
|
+
'.png': 'image/png',
|
|
561
|
+
'.svg': 'image/svg+xml',
|
|
562
|
+
'.ico': 'image/x-icon',
|
|
563
|
+
'.woff2': 'font/woff2',
|
|
564
|
+
'.mp4': 'video/mp4',
|
|
565
|
+
'.mp3': 'audio/mpeg',
|
|
566
|
+
};
|
|
567
|
+
res.setHeader('Content-Type', types[ext] || 'application/octet-stream');
|
|
568
|
+
// An ISR route's file is swapped every `revalidate` seconds, so the cache must not
|
|
569
|
+
// outlive the window: revalidate every visit (a bodiless 304 when nothing changed) …
|
|
570
|
+
res.setHeader('Cache-Control', rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600');
|
|
571
|
+
res.setHeader('ETag', entry.etag);
|
|
572
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
573
|
+
// Per-route response headers (innovation #26): a prerendered document carries the
|
|
574
|
+
// same policy the live render would send …
|
|
575
|
+
if (ext === '.html') {
|
|
576
|
+
for (const [k, v] of Object.entries(pageHeaders(ssrModule, pathnameOf(req.url)))) res.setHeader(k, v);
|
|
577
|
+
}
|
|
578
|
+
if (req.headers['if-none-match'] === entry.etag) {
|
|
579
|
+
res.statusCode = 304;
|
|
580
|
+
res.end();
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
const enc = pickEncoding(req);
|
|
584
|
+
res.statusCode = 200;
|
|
585
|
+
if (enc) {
|
|
586
|
+
res.setHeader('Content-Encoding', enc);
|
|
587
|
+
res.end(enc === 'br' ? entry.br : enc === 'gzip' ? entry.gzip : compress('deflate', entry.raw));
|
|
588
|
+
} else {
|
|
589
|
+
res.end(entry.raw);
|
|
590
|
+
}
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// Otherwise render the route via SSR (dynamic routes, 404s, and every page route when
|
|
595
|
+
// a middleware exists: its per-request context must be live …
|
|
596
|
+
let broken = new Set<string>();
|
|
597
|
+
try {
|
|
598
|
+
broken = new Set(JSON.parse(fs.readFileSync(path.join(dir, 'broken.json'), 'utf-8')));
|
|
599
|
+
} catch { /* no manifest: nothing known-broken */ }
|
|
600
|
+
const safe2 = req.url || '/';
|
|
601
|
+
if (!broken.has(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
602
|
+
const enc = pickEncoding(req);
|
|
603
|
+
res.statusCode = 200;
|
|
604
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
605
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
606
|
+
for (const [k, v] of Object.entries(pageHeaders(ssrModule, pathnameOf(safe2)))) res.setHeader(k, v);
|
|
607
|
+
let write: (chunk: string) => void;
|
|
608
|
+
let done: () => void;
|
|
609
|
+
if (enc) {
|
|
610
|
+
res.setHeader('Content-Encoding', enc);
|
|
611
|
+
const compressor = createCompressor(enc);
|
|
612
|
+
compressor.pipe(res);
|
|
613
|
+
write = (chunk) => compressor.write(chunk);
|
|
614
|
+
done = () => compressor.end();
|
|
615
|
+
} else {
|
|
616
|
+
write = (chunk) => res.write(chunk);
|
|
617
|
+
done = () => res.end();
|
|
618
|
+
}
|
|
619
|
+
await ssrModule.renderPageStream(safe2, write, shellOpen(), clientScriptTag(getClientSource()));
|
|
620
|
+
done();
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
// buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
|
|
624
|
+
// = false routes …
|
|
625
|
+
const page = await ssrModule.renderPage(safe2);
|
|
626
|
+
sendHtml(req, res, page.status ?? 200, getHtmlShell(page.html, page.state, page.head, page.csr !== false), pageHeaders(ssrModule, pathnameOf(safe2)));
|
|
627
|
+
}).catch(() => {
|
|
628
|
+
res.statusCode = 404;
|
|
629
|
+
res.end('Not found');
|
|
630
|
+
});
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Strip the query string: routing matches the pathname, handlers read the full URL. */
|
|
635
|
+
function pathnameOf(url: string | undefined): string {
|
|
636
|
+
try {
|
|
637
|
+
return new URL(url || '/', 'http://localhost').pathname;
|
|
638
|
+
} catch {
|
|
639
|
+
return (url || '/').split('?')[0];
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* The version from package.json - one source of truth, no constant to drift.
|
|
645
|
+
* Resolved from THIS module (not the cwd): the banner names the framework's
|
|
646
|
+
* version even when it builds somebody else's project.
|
|
647
|
+
*/
|
|
648
|
+
function version(): string {
|
|
649
|
+
try {
|
|
650
|
+
return JSON.parse(fs.readFileSync(fileURLToPath(new URL('../../package.json', import.meta.url)), 'utf-8')).version ?? '0.0.0';
|
|
651
|
+
} catch {
|
|
652
|
+
return '0.0.0';
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
async function dev(): Promise<void> {
|
|
657
|
+
console.log(`🌹 RoseTack v${version()} dev server starting...`);
|
|
658
|
+
try {
|
|
659
|
+
await build();
|
|
660
|
+
} catch (err) {
|
|
661
|
+
// A broken .rose file must not prevent the server from starting; the
|
|
662
|
+
// watcher below rebuilds as soon as the file is fixed.
|
|
663
|
+
console.error('Initial build failed (server still running):', err instanceof Error ? err.message : err);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
let timeout: any;
|
|
667
|
+
fs.watch(SRC_DIR, { recursive: true }, () => {
|
|
668
|
+
clearTimeout(timeout);
|
|
669
|
+
timeout = setTimeout(async () => {
|
|
670
|
+
try {
|
|
671
|
+
console.log('Rebuilding...');
|
|
672
|
+
await build();
|
|
673
|
+
} catch (err) {
|
|
674
|
+
// Never let a user-code error kill the dev server.
|
|
675
|
+
console.error('Build failed (server still running):', err instanceof Error ? err.message : err);
|
|
676
|
+
}
|
|
677
|
+
}, 200);
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
const http = await import('http');
|
|
681
|
+
const server = http.createServer(serveStatic(OUT_DIR));
|
|
682
|
+
|
|
683
|
+
server.listen(PORT, () => {
|
|
684
|
+
console.log('🌹 http://localhost:' + PORT);
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async function preview(): Promise<void> {
|
|
689
|
+
await build();
|
|
690
|
+
const http = await import('http');
|
|
691
|
+
// isr=true: routes exporting `revalidate = N` are served stale-then-swapped
|
|
692
|
+
// from disk (innovation #24). Dev passes nothing (it rebuilds on change).
|
|
693
|
+
const server = http.createServer(serveStatic(OUT_DIR, true));
|
|
694
|
+
|
|
695
|
+
server.listen(PORT, () => {
|
|
696
|
+
console.log(`🌹 RoseTack v${version()} preview at http://localhost:` + PORT);
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Phase 1: `rosetack serve` runs what `build` produced - no rebuild, no
|
|
702
|
+
* watcher, production semantics (a preview that re-rendered on the fly
|
|
703
|
+
* could serve a half-written file). Multi-core through the stdlib cluster:
|
|
704
|
+
* the primary supervises and serves no traffic, the workers serve; every
|
|
705
|
+
* request is logged; SIGTERM drains in-flight work and exits.
|
|
706
|
+
*
|
|
707
|
+
* ponytail boundaries, stated plainly:
|
|
708
|
+
* - each worker is its own process with its own dist/server.js module.
|
|
709
|
+
* Module-scope state is therefore per-worker, which is what $store()
|
|
710
|
+
* (Phase 2) fixes: writes broadcast through the primary, reads stay
|
|
711
|
+
* local-synchronous. ISR revalidation may run in more than one worker
|
|
712
|
+
* for one route: the guard is per-worker and the cost is one duplicate
|
|
713
|
+
* render.
|
|
714
|
+
* - the signal-driven drain is POSIX behavior. On Windows a kill() is
|
|
715
|
+
* abrupt by the platform's design, so the worker instead exits on the
|
|
716
|
+
* primary's death (the disconnect handler below) - a killed primary must
|
|
717
|
+
* never leave orphans holding the port.
|
|
718
|
+
*/
|
|
719
|
+
async function serve(): Promise<void> {
|
|
720
|
+
if (!fs.existsSync(path.join(OUT_DIR, 'server.js'))) {
|
|
721
|
+
console.error(`rosetack: ${OUT_DIR} has no server.js - run rosetack build first`);
|
|
722
|
+
process.exit(1);
|
|
723
|
+
}
|
|
724
|
+
// .default: node:cluster is an `export =` module, so the dynamic import
|
|
725
|
+
// hands back the namespace with the real module on `.default`
|
|
726
|
+
const cluster = (await import('node:cluster')).default as any;
|
|
727
|
+
// Round-robin the accepts between workers. The default leaves the handout to the
|
|
728
|
+
// operating system …
|
|
729
|
+
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
730
|
+
const os = await import('node:os');
|
|
731
|
+
const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
|
|
732
|
+
const PORT = Number(process.env.PORT) || 3000;
|
|
733
|
+
if (cluster.isPrimary) {
|
|
734
|
+
for (let i = 0; i < workers; i++) cluster.fork();
|
|
735
|
+
// Phase 2: the store relay. A worker broadcasts every $store write here …
|
|
736
|
+
cluster.on('message', (worker: any, msg: any) => {
|
|
737
|
+
if (!msg || msg.type !== 'rosetack:store') return;
|
|
738
|
+
for (const w of Object.values<any>(cluster.workers ?? {})) {
|
|
739
|
+
if (w && w.id !== worker.id) w.send(msg);
|
|
740
|
+
}
|
|
741
|
+
});
|
|
742
|
+
let live = workers;
|
|
743
|
+
const stop = () => {
|
|
744
|
+
for (const w of Object.values<any>(cluster.workers ?? {})) w.kill();
|
|
745
|
+
setTimeout(() => process.exit(0), 5000).unref();
|
|
746
|
+
};
|
|
747
|
+
process.on('SIGTERM', stop);
|
|
748
|
+
process.on('SIGINT', stop);
|
|
749
|
+
cluster.on('exit', () => { if (--live <= 0) process.exit(0); });
|
|
750
|
+
console.log(`🌹 RoseTack v${version()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${PORT} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
// worker the primary's death is the worker's death: no orphan holding the port
|
|
754
|
+
process.on('disconnect', () => process.exit(0));
|
|
755
|
+
const http = await import('node:http');
|
|
756
|
+
const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
|
|
757
|
+
// A client that stalls mid-request is dropped instead of holding a worker;
|
|
758
|
+
// idle keep-alive sockets close so a drained worker can actually exit.
|
|
759
|
+
server.requestTimeout = 30_000;
|
|
760
|
+
server.headersTimeout = 65_000; // must exceed requestTimeout
|
|
761
|
+
server.keepAliveTimeout = 5_000;
|
|
762
|
+
server.listen(PORT, () => console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${PORT}`));
|
|
763
|
+
const stop = () => {
|
|
764
|
+
server.close(() => process.exit(0)); // finish what is in flight
|
|
765
|
+
server.closeIdleConnections?.(); // drop the idle keep-alive sockets
|
|
766
|
+
setTimeout(() => process.exit(0), 5000).unref(); // a stuck one must not hold the worker
|
|
767
|
+
};
|
|
768
|
+
process.on('SIGTERM', stop);
|
|
769
|
+
process.on('SIGINT', stop);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const cmd = process.argv[2];
|
|
773
|
+
if (cmd === 'dev') dev();
|
|
774
|
+
else if (cmd === 'build') build();
|
|
775
|
+
else if (cmd === 'preview') preview();
|
|
776
|
+
else if (cmd === 'serve') serve();
|
|
777
|
+
else console.log('Usage: rosetack dev|build|preview|serve [dir] (dir defaults to the current directory; dist/ is written there)');
|