rosetack 0.1.4 → 0.1.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rosetack",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Zero-hydration full-stack web framework with compile-time reactivity and zero-JS content routes.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -11,6 +11,14 @@
11
11
  "release:notes": "node tools/release-notes.mjs",
12
12
  "pack": "node pack.mjs",
13
13
  "prepublishOnly": "npm run pack",
14
+ "benchmark": "tsx tests/benchmark.ts",
15
+ "test": "tsx src/cli/index.ts build example && tsx tests/test-client.ts",
16
+ "test:cli": "node tests/test-cli.mjs",
17
+ "test:e2e": "tsx tests/test-e2e.ts",
18
+ "test:edge": "tsx tests/test-edge.ts",
19
+ "test:harness": "tsx tests/test-harness.ts",
20
+ "test:go": "tsx src/cli/index.ts build example && node tests/test-go.mjs",
21
+ "test:pack": "node tests/test-pack.mjs",
14
22
  "build:go": "go build -o rosetack-server ."
15
23
  },
16
24
  "bin": {
@@ -1 +1 @@
1
- 0.1.4
1
+ 0.1.5
package/src/cli/edge.ts CHANGED
@@ -42,7 +42,9 @@ type ServerModule = {
42
42
  setQuery(query: Record<string, string>): void;
43
43
  };
44
44
 
45
- // CSRF: the edge twin of the Node server's guard.
45
+ export { onShutdown, runShutdownHooks, shutdownHookCount } from './shutdown.js';
46
+
47
+ // CSRF guard: a state-changing request that did not come from this site is refused before middleware, hooks and routing see it.
46
48
  function crossSiteWrite(request: Request): Response | null {
47
49
  const m = request.method;
48
50
  if (m !== 'POST' && m !== 'PUT' && m !== 'PATCH' && m !== 'DELETE') return null;
@@ -113,7 +115,8 @@ export async function createEdgeHandler(
113
115
 
114
116
  const pageHeaders = (pathname: string, nonce = ''): Record<string, string> => {
115
117
  const headers: Record<string, string> = {};
116
- if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
118
+ for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
119
+ if (!headers['cache-control']) headers['cache-control'] = 'no-cache';
117
120
  const own = mod.headersFor?.(pathname);
118
121
  if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
119
122
  return headers;
@@ -140,11 +143,18 @@ export async function createEdgeHandler(
140
143
  if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
141
144
  }
142
145
  if (mod.isApi(pathname)) {
146
+ if (request.method !== 'GET') {
147
+ const fn = (mod as any).invalidateRenderCache;
148
+ if (typeof fn === 'function') fn();
149
+ }
143
150
  const apiRes = await mod.handleApi(request.method, pathname, request);
144
151
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
145
152
  }
146
153
  const form = request.method === 'POST' ? await request.formData() : undefined;
147
- if (form) (mod as any).invalidateRenderCache?.();
154
+ if (form) {
155
+ const fn = (mod as any).invalidateRenderCache;
156
+ if (typeof fn === 'function') fn();
157
+ }
148
158
  if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
149
159
  const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
150
160
  const streamed = new Response(null, {
package/src/cli/index.ts CHANGED
@@ -11,6 +11,8 @@ import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, s
11
11
  import { AI_PROMPT } from './prompt.js';
12
12
  import { Readable } from 'stream';
13
13
  import { createEdgeHandler } from './edge.js';
14
+ import { runShutdownHooks } from './shutdown.js';
15
+ import { requestOrigin } from './origin.js';
14
16
  import type * as ts from 'typescript';
15
17
 
16
18
  type Encoding = 'br' | 'gzip' | 'deflate';
@@ -42,6 +44,9 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
42
44
  res.statusCode = status;
43
45
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
44
46
  res.setHeader('Vary', 'Accept-Encoding');
47
+ if (!Object.keys(extraHeaders || {}).some((k) => k.toLowerCase() === 'cache-control')) {
48
+ res.setHeader('Cache-Control', 'no-cache');
49
+ }
45
50
  if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
46
51
  let hash = 0x811c9dc5;
47
52
  for (let i = 0; i < html.length; i++) {
@@ -332,7 +337,7 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
332
337
  };
333
338
 
334
339
  for (const info of routes) {
335
- if ((ssrModule.dynamicRoutes as string[]).includes(info.routePath)) {
340
+ if (((ssrModule.prerenderSkipRoutes as string[]) ?? []).includes(info.routePath)) {
336
341
  console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
337
342
  continue;
338
343
  }
@@ -502,6 +507,18 @@ function crossSiteWrite(req: any): { status: number; body: string } | null {
502
507
  * in front when several workers share one stdout. Logged on the response's
503
508
  * finish, so a streamed route is recorded when it is actually done.
504
509
  */
510
+ /**
511
+ * The access line itself, shared by withAccessLog and the dynamic-render
512
+ * branch of `serve` (which returns before baseHandler, so it never goes
513
+ * through the wrapper). One formatter means both paths emit byte-identical
514
+ * shapes - the greppable contract test-cli asserts on.
515
+ */
516
+ function writeAccessLine(req: any, res: any, bytes: number, tag?: string, startedNs?: bigint): void {
517
+ const ms = Number(process.hrtime.bigint() - (startedNs ?? process.hrtime.bigint())) / 1e6;
518
+ const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1000).toFixed(0)}us`;
519
+ console.log(`${new Date().toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ''} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
520
+ }
521
+
505
522
  function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (req: any, res: any) => void {
506
523
  return (req, res) => {
507
524
  const started = process.hrtime.bigint();
@@ -510,11 +527,7 @@ function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (re
510
527
  const end = res.end.bind(res);
511
528
  res.write = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return write(chunk, ...rest); };
512
529
  res.end = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return end(chunk, ...rest); };
513
- res.on('finish', () => {
514
- const ms = Number(process.hrtime.bigint() - started) / 1e6;
515
- const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1000).toFixed(0)}us`;
516
- console.log(`${new Date().toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ''} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
517
- });
530
+ res.on('finish', () => writeAccessLine(req, res, bytes, tag, started));
518
531
  handler(req, res);
519
532
  };
520
533
  }
@@ -973,33 +986,29 @@ function queryOf(url: string | undefined): Record<string, string> {
973
986
  return q;
974
987
  }
975
988
 
976
- /**
977
- * P0-0 (bug report): listen on `port`, hopping to the next free one when it
978
- * is taken instead of crashing with EADDRINUSE. Two projects on one machine
979
- * (or a dev server that did not exit cleanly) is the everyday case, and a
980
- * stack trace plus a dead process is the worst possible answer to it: the
981
- * banner names the port actually used, so the URL is never a guess.
982
- *
983
- * The hop is bounded (20 tries) and every other error is fatal - silently
984
- * retrying a real fault would hide it.
985
- */
989
+ /** Listen on `port`, hopping to the next free one on EADDRINUSE. */
986
990
  function listenFree(server: any, port: number, onReady: (port: number) => void): void {
987
991
  const attempt = (p: number): void => {
988
- const onError = (err: any) => {
992
+ const cleanup = (): void => {
989
993
  server.removeListener('error', onError);
994
+ server.removeListener('listening', onListening);
995
+ };
996
+ const onError = (err: any): void => {
997
+ cleanup();
990
998
  if (err && err.code === 'EADDRINUSE' && p - port < 20) {
991
- console.log(`🌹 port ${p} is in use - trying ${p + 1}`);
992
999
  attempt(p + 1);
993
1000
  return;
994
1001
  }
995
1002
  console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
996
1003
  process.exit(1);
997
1004
  };
998
- server.once('error', onError);
999
- server.listen(p, () => {
1000
- server.removeListener('error', onError);
1005
+ const onListening = (): void => {
1006
+ cleanup();
1001
1007
  onReady(p);
1002
- });
1008
+ };
1009
+ server.once('error', onError);
1010
+ server.once('listening', onListening);
1011
+ server.listen(p);
1003
1012
  };
1004
1013
  attempt(port);
1005
1014
  }
@@ -1026,18 +1035,9 @@ async function freePort(from: number): Promise<number> {
1026
1035
  }
1027
1036
 
1028
1037
  /**
1029
- * The FRAMEWORK's version - one source of truth, no constant to drift.
1030
- *
1031
- * Three layouts answer, in order:
1032
- * 1. src/FRAMEWORK_VERSION, a one-line stamp that ships beside the CLI
1033
- * source. It is the only candidate that survives EMBEDDING: a real app
1034
- * copies the framework's src/ into its own tree, where the nearest
1035
- * package.json is the APP's - which is how a banner ended up naming the
1036
- * app's version as the framework's for weeks, with no way to tell which
1037
- * framework build was actually running.
1038
- * 2. the package.json two directories up (this repo: the framework's own),
1039
- * 3. the one beside the bundle (the published package: dist-cli/ + src/).
1040
- * A test asserts the stamp equals package.json, so the two cannot drift.
1038
+ * The FRAMEWORK's version. FRAMEWORK_VERSION first because it is the only
1039
+ * candidate that survives embedding: an app copies this src/ into its own
1040
+ * tree, where the nearest package.json is the APP's.
1041
1041
  */
1042
1042
  function version(): string {
1043
1043
  for (const rel of ['../FRAMEWORK_VERSION', '../../FRAMEWORK_VERSION', '../../package.json', '../package.json']) {
@@ -1194,14 +1194,17 @@ async function serve(): Promise<void> {
1194
1194
  return dynRouteSet;
1195
1195
  };
1196
1196
  const server = http.createServer(async (req: any, res: any) => {
1197
+ let bytesWritten = 0;
1198
+ const started = process.hrtime.bigint();
1197
1199
  try {
1198
1200
  if ((req.method === 'GET' || req.method === 'HEAD') && dynRoutesOf().has(pathnameOf(req.url || '/'))) {
1199
1201
  const handle = await edgeReady;
1200
1202
  if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
1201
1203
  try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
1202
1204
  }
1203
- const url = 'http://' + (req.headers.host || `localhost:${PORT}`) + (req.url || '/');
1205
+ const url = requestOrigin(req, PORT) + (req.url || '/');
1204
1206
  const response = await handle(new Request(url, { method: req.method, headers: req.headers }));
1207
+ const access = () => writeAccessLine(req, res, bytesWritten, `w${process.pid}`, started);
1205
1208
  res.statusCode = response.status;
1206
1209
  response.headers.forEach((v: string, k: string) => res.setHeader(k, v));
1207
1210
  const htmlDoc = (response.headers.get('content-type') ?? '').startsWith('text/html');
@@ -1211,7 +1214,9 @@ async function serve(): Promise<void> {
1211
1214
  const etag = 'W/"' + createHash('sha1').update(raw).digest('base64url').slice(0, 24) + '"';
1212
1215
  if (req.headers['if-none-match'] === etag) {
1213
1216
  res.statusCode = 304;
1217
+ bytesWritten = 0;
1214
1218
  res.end();
1219
+ access();
1215
1220
  return;
1216
1221
  }
1217
1222
  const body = compress(enc, raw);
@@ -1219,12 +1224,19 @@ async function serve(): Promise<void> {
1219
1224
  res.setHeader('Content-Encoding', enc);
1220
1225
  res.setHeader('Content-Length', String(body.length));
1221
1226
  res.end(body);
1227
+ bytesWritten = body.length;
1228
+ access();
1222
1229
  return;
1223
1230
  }
1224
1231
  if (response.body) {
1225
- Readable.fromWeb(response.body as any).pipe(res);
1232
+ const raw = Buffer.from(await response.arrayBuffer());
1233
+ bytesWritten = raw.length;
1234
+ res.end(raw);
1235
+ access();
1226
1236
  } else {
1227
1237
  res.end();
1238
+ bytesWritten = 0;
1239
+ access();
1228
1240
  }
1229
1241
  return;
1230
1242
  }
@@ -1255,7 +1267,9 @@ async function serve(): Promise<void> {
1255
1267
  console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
1256
1268
  }
1257
1269
  }
1258
- server.close(() => process.exit(0));
1270
+ server.close(() => {
1271
+ void runShutdownHooks('worker signal').finally(() => process.exit(0));
1272
+ });
1259
1273
  server.closeIdleConnections?.();
1260
1274
  setTimeout(() => process.exit(0), 5000).unref();
1261
1275
  };
@@ -0,0 +1,9 @@
1
+
2
+ export function requestOrigin(req: any, fallbackPort: number | string): string {
3
+ const rawProto = String(req.headers?.['x-forwarded-proto'] || '');
4
+ const proto = rawProto.split(',')[0]!.trim();
5
+ const scheme = proto === 'https' || proto === 'http' ? proto : 'http';
6
+ const rawHost = String(req.headers?.['x-forwarded-host'] || '');
7
+ const host = rawHost.split(',')[0]!.trim() || req.headers?.host || `localhost:${fallbackPort}`;
8
+ return `${scheme}://${host}`;
9
+ }
@@ -6,8 +6,11 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import zlib from 'node:zlib';
8
8
  import { createHash } from 'node:crypto';
9
+ import { AsyncLocalStorage } from 'node:async_hooks';
9
10
  import { fileURLToPath } from 'node:url';
10
11
  import { createEdgeHandler } from './edge.ts';
12
+ import { onShutdown, runShutdownHooks } from './shutdown.ts';
13
+ import { requestOrigin } from './origin.ts';
11
14
 
12
15
  const dist = fileURLToPath(new URL('./', import.meta.url));
13
16
  const port = Number(process.env.PORT || 8080);
@@ -15,6 +18,44 @@ let handle: ((request: Request) => Promise<Response>) | null = null;
15
18
  let mod: any = null;
16
19
  let warmList: string[] = [];
17
20
 
21
+ const requestAls = new AsyncLocalStorage<Record<string, unknown>>();
22
+
23
+ /** Run `fn` with a private per-request context bag. */
24
+ function runIsolated<T>(fn: () => T): T {
25
+ return requestAls.run({}, fn);
26
+ }
27
+
28
+ // Extra roots searched for baked assets, after `dist` itself.
29
+ let extraRoots: string[] | null = null;
30
+ function resolveStaticRoots(): string[] {
31
+ if (extraRoots) return extraRoots;
32
+ const seen = new Set<string>([dist]);
33
+ const add = (p: string) => {
34
+ if (p && !seen.has(p)) seen.add(p);
35
+ };
36
+ if (process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME) {
37
+ add(path.join(dist, '..'));
38
+ add(path.join(dist, '..', '..'));
39
+ add(path.resolve(dist, '..', 'public'));
40
+ add(path.resolve(dist, '..', 'oboext'));
41
+ }
42
+ add(path.join(dist, 'oboext'));
43
+ add(path.resolve(dist, '..', 'oboext'));
44
+ add(path.resolve(process.cwd(), 'oboext'));
45
+ extraRoots = [...seen];
46
+ return extraRoots;
47
+ }
48
+
49
+ // A request path that must never reach the dynamic render.
50
+ function isBakedAssetPath(pathname: string): boolean {
51
+ return (
52
+ pathname.startsWith('/public/') ||
53
+ pathname.startsWith('/icons/') ||
54
+ pathname.startsWith('/vendor/') ||
55
+ pathname === '/favicon.ico'
56
+ );
57
+ }
58
+
18
59
  const earlyHintLinks: string[] = (() => {
19
60
  try {
20
61
  const html = fs.readFileSync(path.join(dist, 'index.html'), 'utf8');
@@ -40,12 +81,46 @@ const ready = createEdgeHandler(dist).then(async (h) => {
40
81
  try {
41
82
  mod = await import(new URL('./server.js', import.meta.url).href);
42
83
  warmList = ['/', ...((mod.dynamicRoutes as string[]) || []).filter((r: string) => !r.includes(':'))];
84
+ mod.invalidateRenderCache?.();
43
85
  } catch { /* warm list stays just the home route */ }
86
+ mod?.installContextStore?.({
87
+ getStore: () => requestAls.getStore(),
88
+ run: (store: Record<string, unknown>, fn: () => unknown) => requestAls.run(store, fn),
89
+ });
90
+ return h;
44
91
  });
45
92
 
93
+ const shouldWarm = !process.env.VERCEL;
94
+ if (shouldWarm) ready.then(async (h) => {
95
+ for (const r of warmList) {
96
+ try {
97
+ const res = await runIsolated(() => h(new Request('http://localhost' + r)));
98
+ const buf = await res.arrayBuffer();
99
+ const suspect = res.status === 200 && res.headers.get('content-type')?.includes('text/html') && buf.byteLength < 2048;
100
+ console.log('[rosetack] warm', r, 'status=' + res.status, 'bytes=' + buf.byteLength, suspect ? 'SUSPECT-EMPTY' : '');
101
+ } catch (e) {
102
+ console.error('[rosetack] warm', r, 'FAILED:', (e as Error)?.stack ?? e);
103
+ }
104
+ }
105
+ }).catch((e) => console.error('[rosetack] warm loop aborted:', (e as Error)?.stack ?? e));
106
+
46
107
  const hotCache = new Map<string, { raw: Buffer; br: Buffer; gzip: Buffer; headers: Record<string, string>; etag: string; fetchedAt: number; refreshing?: boolean }>();
47
108
  const HOT_TTL = 10_000;
48
109
 
110
+ /**
111
+ * One access line per request on stdout - the same greppable shape the CLI's
112
+ * `rosetack serve` writes, so one grep works across every rosetack server.
113
+ *
114
+ * prod-server had NO access log at all: the platform request log showed a
115
+ * status and a duration, and the server itself said nothing, so a blank first
116
+ * visit was reported repeatedly with nothing to read. Every response exit in
117
+ * the http handler calls this, which makes a log export readable line by line
118
+ * against what the render actually produced.
119
+ */
120
+ function writeAccessLine(req: any, res: any, bytes: number): void {
121
+ console.log(`${new Date().toISOString().slice(0, 19)}Z ${req.method} ${req.url} ${res.statusCode} ${bytes}B`);
122
+ }
123
+
49
124
  function fnv(s: string): string {
50
125
  let h = 0x811c9dc5;
51
126
  for (let i = 0; i < s.length; i++) {
@@ -58,7 +133,7 @@ function fnv(s: string): string {
58
133
  async function refetchHot(pathname: string, cookieHeader: string): Promise<void> {
59
134
  const headers: Record<string, string> = { 'user-agent': 'rosetack-hot' };
60
135
  if (cookieHeader) headers.cookie = cookieHeader;
61
- const response = await handle!(new Request('http://localhost' + pathname, { headers }));
136
+ const response = await runIsolated(() => handle!(new Request('http://localhost' + pathname, { headers })));
62
137
  const csp = response.headers.get('content-security-policy') || '';
63
138
  const key = pathname + '|' + fnv(cookieHeader);
64
139
  if (response.status !== 200 || csp.includes('nonce-')) {
@@ -112,6 +187,7 @@ function tryHot(req: http.IncomingMessage, res: http.ServerResponse): boolean {
112
187
  if (req.headers['if-none-match'] === entry.etag) {
113
188
  res.statusCode = 304;
114
189
  res.end();
190
+ writeAccessLine(req, res, 0);
115
191
  return true;
116
192
  }
117
193
  const compressed = (entry as any).compressed !== false;
@@ -119,9 +195,12 @@ function tryHot(req: http.IncomingMessage, res: http.ServerResponse): boolean {
119
195
  const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
120
196
  if (enc) {
121
197
  res.setHeader('Content-Encoding', enc);
122
- res.end(enc === 'br' ? entry.br : entry.gzip);
198
+ const body = enc === 'br' ? entry.br : entry.gzip;
199
+ res.end(body);
200
+ writeAccessLine(req, res, body.length);
123
201
  } else {
124
202
  res.end(entry.raw);
203
+ writeAccessLine(req, res, entry.raw.length);
125
204
  }
126
205
  return true;
127
206
  }
@@ -214,17 +293,24 @@ function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, rawUrl
214
293
  return false;
215
294
  }
216
295
  if (pathname.includes('\0') || pathname.includes('..')) return false;
217
- const filePath = path.join(dist, pathname);
218
- if (!filePath.startsWith(dist)) return false;
219
- let st: fs.Stats;
220
- try {
221
- st = fs.statSync(filePath);
222
- if (!st.isFile()) return false;
223
- } catch {
224
- return false;
225
- }
226
- const ext = path.extname(filePath).toLowerCase();
296
+ const ext = path.extname(pathname).toLowerCase();
227
297
  if (!TYPES[ext]) return false;
298
+ let filePath = '';
299
+ let st: fs.Stats | null = null;
300
+ for (const root of resolveStaticRoots()) {
301
+ const candidate = path.join(root, pathname);
302
+ if (!candidate.startsWith(root)) continue;
303
+ try {
304
+ const s = fs.statSync(candidate);
305
+ if (!s.isFile()) continue;
306
+ filePath = candidate;
307
+ st = s;
308
+ break;
309
+ } catch {
310
+ // not under this root; try the next one
311
+ }
312
+ }
313
+ if (!st) return false;
228
314
  let entry = fileCache.get(filePath);
229
315
  if (!entry || entry.mtimeMs !== st.mtimeMs) {
230
316
  const raw = fs.readFileSync(filePath);
@@ -248,24 +334,33 @@ function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, rawUrl
248
334
  if (req.headers['if-none-match'] === entry.etag) {
249
335
  res.statusCode = 304;
250
336
  res.end();
337
+ writeAccessLine(req, res, 0);
251
338
  return true;
252
339
  }
253
340
  const compressed = (entry as any).compressed !== false;
254
- const accept = String(req.headers['accept-encoding'] || '');
341
+ const accept = String(req.headers['accept-encoding'] || '');
255
342
  const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
256
343
  if (enc) {
257
344
  res.setHeader('Content-Encoding', enc);
258
- res.end(enc === 'br' ? entry.br : entry.gzip);
345
+ const body = enc === 'br' ? entry.br : entry.gzip;
346
+ res.end(body);
347
+ writeAccessLine(req, res, body.length);
259
348
  } else {
260
349
  res.end(entry.raw);
350
+ writeAccessLine(req, res, entry.raw.length);
261
351
  }
262
352
  return true;
263
353
  }
264
354
 
265
- http.createServer(async (req, res) => {
355
+ const server = http.createServer(async (req, res) => {
266
356
  try {
267
357
  await ready;
268
358
  if (handleRevalidate(req, res)) return;
359
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
360
+ hotCache.clear();
361
+ const fn = (mod as any).invalidateRenderCache;
362
+ if (typeof fn === 'function') fn();
363
+ }
269
364
  if (hotCache.size > 0 && tryHot(req, res)) return;
270
365
  if (req.method === 'GET' && !req.headers.cookie && hotCache.size === 0) {
271
366
  for (const r of warmList) warmHot(r, '');
@@ -273,8 +368,23 @@ http.createServer(async (req, res) => {
273
368
  if (hotCache.size > 0 && tryHot(req, res)) return;
274
369
  if (req.method === 'GET' || req.method === 'HEAD') {
275
370
  if (serveStatic(req, res, req.url || '/')) return;
371
+ let p = '/';
372
+ try {
373
+ p = decodeURIComponent(new URL('http://localhost' + (req.url || '/')).pathname);
374
+ } catch {
375
+ p = req.url || '/';
376
+ }
377
+ p = p.split('?')[0]!;
378
+ if (isBakedAssetPath(p)) {
379
+ res.statusCode = 404;
380
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
381
+ res.setHeader('Cache-Control', 'public, max-age=60');
382
+ res.end('not found');
383
+ writeAccessLine(req, res, 0);
384
+ return;
385
+ }
276
386
  }
277
- const url = 'http://' + (req.headers.host || `localhost:${port}`) + (req.url || '/');
387
+ const url = requestOrigin(req, port) + (req.url || '/');
278
388
  const init: RequestInit = { method: req.method, headers: req.headers as any };
279
389
  if (req.method !== 'GET' && req.method !== 'HEAD') {
280
390
  (init as any).body = Readable.toWeb(req) as any;
@@ -284,7 +394,16 @@ http.createServer(async (req, res) => {
284
394
  if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
285
395
  try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
286
396
  }
287
- const response = await handle!(new Request(url, init));
397
+ const replayable = req.method === 'GET' || req.method === 'HEAD';
398
+ let response: Response;
399
+ try {
400
+ response = await runIsolated(() => handle!(new Request(url, init)));
401
+ } catch (err) {
402
+ if (!replayable) throw err;
403
+ console.warn('[rosetack] render failed, retrying once:', (err as Error)?.message ?? err);
404
+ await new Promise((r) => setTimeout(r, 200));
405
+ response = await runIsolated(() => handle!(new Request(url, init)));
406
+ }
288
407
  if (req.method === 'GET') fillHot(req.url || '/', cookieHeader, response.clone());
289
408
  res.statusCode = response.status;
290
409
  response.headers.forEach((v, k) => res.setHeader(k, v));
@@ -296,29 +415,61 @@ http.createServer(async (req, res) => {
296
415
  if (req.method === 'GET' && req.headers['if-none-match'] === etag) {
297
416
  res.statusCode = 304;
298
417
  res.end();
418
+ writeAccessLine(req, res, 0);
299
419
  return;
300
420
  }
301
421
  res.setHeader('ETag', etag);
302
- res.setHeader('Content-Length', String(raw.length));
303
- if (accept.includes('br')) {
304
- res.setHeader('Content-Encoding', 'br');
305
- res.end(zlib.brotliCompressSync(raw));
306
- } else {
307
- res.setHeader('Content-Encoding', 'gzip');
308
- res.end(zlib.gzipSync(raw));
309
- }
422
+ const compressed = accept.includes('br')
423
+ ? zlib.brotliCompressSync(raw)
424
+ : zlib.gzipSync(raw);
425
+ res.setHeader('Content-Encoding', accept.includes('br') ? 'br' : 'gzip');
426
+ res.setHeader('Content-Length', String(compressed.length));
427
+ res.end(compressed);
428
+ writeAccessLine(req, res, compressed.length);
310
429
  } else if (response.body) {
311
- Readable.fromWeb(response.body as any).pipe(res);
430
+ const raw = Buffer.from(await response.arrayBuffer());
431
+ res.end(raw);
432
+ writeAccessLine(req, res, raw.length);
312
433
  } else {
313
434
  res.end();
435
+ writeAccessLine(req, res, 0);
314
436
  }
315
437
  } catch (err) {
438
+ console.error('[rosetack] request failed:', (err as Error)?.stack ?? err);
316
439
  if (!res.headersSent) {
317
440
  res.statusCode = 500;
318
441
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
319
442
  }
320
443
  res.end('server error');
444
+ writeAccessLine(req, res, 13);
321
445
  }
322
- }).listen(port, () => {
323
- console.log(`🌹 RoseTack prod server on http://localhost:${port}`);
324
446
  });
447
+
448
+ if (!process.env.VERCEL) {
449
+ server.listen(port, () => {
450
+ console.log(`🌹 RoseTack prod server on http://localhost:${port}`);
451
+ });
452
+
453
+ let stopping = false;
454
+ const stop = (signal: NodeJS.Signals) => {
455
+ if (stopping) return;
456
+ stopping = true;
457
+ const force = setTimeout(() => process.exit(1), 10_000);
458
+ force.unref?.();
459
+ server.close(() => {
460
+ void runShutdownHooks(signal).finally(() => {
461
+ clearTimeout(force);
462
+ process.exit(0);
463
+ });
464
+ });
465
+ server.closeIdleConnections?.();
466
+ };
467
+ process.on('SIGINT', () => stop('SIGINT'));
468
+ process.on('SIGTERM', () => stop('SIGTERM'));
469
+ }
470
+
471
+ export default server;
472
+
473
+ export { onShutdown, runShutdownHooks };
474
+
475
+ void mod?.invalidateRenderCache;