rosetack 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/deploy/k8s/rosetack.yaml +107 -0
  2. package/dist-cli/compiler.mjs +2783 -0
  3. package/dist-cli/edge.mjs +332 -0
  4. package/dist-cli/rosetack.mjs +4230 -0
  5. package/dist-cli/runtime.mjs +703 -0
  6. package/dist-cli/test.mjs +3202 -0
  7. package/pack.mjs +49 -0
  8. package/package.json +25 -7
  9. package/src/FRAMEWORK_VERSION +1 -1
  10. package/src/cli/edge.ts +67 -25
  11. package/src/cli/index.ts +858 -94
  12. package/src/cli/prompt.ts +127 -0
  13. package/src/cli/shell.ts +133 -30
  14. package/src/cli/test.ts +400 -0
  15. package/src/compiler/errors.ts +74 -0
  16. package/src/compiler/index.ts +1955 -264
  17. package/src/runtime/index.ts +465 -66
  18. package/src/types/rosetack.d.ts +151 -0
  19. package/.github/workflows/ci.yml +0 -72
  20. package/.github/workflows/release.yml +0 -122
  21. package/benchmark.ts +0 -227
  22. package/example/public/favicon.ico +0 -0
  23. package/example/public/logo.svg +0 -148
  24. package/example/public/rose-mark-black.png +0 -0
  25. package/example/public/rose-mark.png +0 -0
  26. package/example/public/rose-mono.png +0 -0
  27. package/example/rosetack.config.js +0 -10
  28. package/example/src/locales/en.json +0 -8
  29. package/example/src/locales/zh.json +0 -8
  30. package/example/src/pages/404.rose +0 -15
  31. package/example/src/pages/500.rose +0 -10
  32. package/example/src/pages/[lang]/about.rose +0 -40
  33. package/example/src/pages/_layout.rose +0 -33
  34. package/example/src/pages/_middleware.rose +0 -37
  35. package/example/src/pages/about.rose +0 -67
  36. package/example/src/pages/admin.rose +0 -27
  37. package/example/src/pages/api/hello.rose +0 -19
  38. package/example/src/pages/api/login.rose +0 -55
  39. package/example/src/pages/api/posts.rose +0 -80
  40. package/example/src/pages/api/secret.rose +0 -14
  41. package/example/src/pages/blog/[id].rose +0 -25
  42. package/example/src/pages/broken.rose +0 -16
  43. package/example/src/pages/fresh.rose +0 -22
  44. package/example/src/pages/garden.rose +0 -27
  45. package/example/src/pages/index.rose +0 -84
  46. package/example/src/pages/sign.rose +0 -45
  47. package/example/src/pages/thorn.rose +0 -23
  48. package/example/src/pages/vault.rose +0 -14
  49. package/go.mod +0 -3
  50. package/main.go +0 -470
  51. package/tools/release-notes.mjs +0 -113
  52. package/tsconfig.json +0 -17
package/src/cli/index.ts CHANGED
@@ -5,9 +5,14 @@
5
5
  import * as fs from 'fs';
6
6
  import * as path from 'path';
7
7
  import * as zlib from 'zlib';
8
+ import { createRequire } from 'module';
8
9
  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';
10
+ import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, RoseError, errorInfo, type RouteInfo } from '../compiler/index.js';
11
+ import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
12
+ import { AI_PROMPT } from './prompt.js';
13
+ // Type-only: erased by esbuild/tsx, so the published CLI stays a ~100 KB bundle with no
14
+ // TypeScript dependency.
15
+ import type * as ts from 'typescript';
11
16
 
12
17
  // --- wire performance: compression + conditional caching (stdlib only) --- The Go binary
13
18
  // already compresses …
@@ -15,7 +20,7 @@ type Encoding = 'br' | 'gzip' | 'deflate';
15
20
 
16
21
  function pickEncoding(req: any): Encoding | null {
17
22
  const ae: string = req.headers['accept-encoding'] || '';
18
- // ponytail: substring match, no q-value parsing - every browser that sends
23
+ // Trade-off: substring match, no q-value parsing - every browser that sends
19
24
  // br also accepts gzip, and br > gzip > deflate is the quality order.
20
25
  if (ae.includes('br')) return 'br';
21
26
  if (ae.includes('gzip')) return 'gzip';
@@ -23,14 +28,18 @@ function pickEncoding(req: any): Encoding | null {
23
28
  return null;
24
29
  }
25
30
 
31
+ // Brotli's default quality (11) spends ~108 ms of CPU on a 32 KB document; quality 5 does
32
+ // the same document in ~2.4 ms for 9% more bytes (measured, Node 22).
33
+ const brotliFast = { [zlib.constants.BROTLI_PARAM_QUALITY]: 5 };
34
+
26
35
  function compress(enc: Encoding, data: string | Buffer): Buffer {
27
- if (enc === 'br') return zlib.brotliCompressSync(data);
36
+ if (enc === 'br') return zlib.brotliCompressSync(data, { params: brotliFast });
28
37
  if (enc === 'gzip') return zlib.gzipSync(data);
29
38
  return zlib.deflateSync(data);
30
39
  }
31
40
 
32
41
  function createCompressor(enc: Encoding): zlib.Gzip | zlib.Deflate | zlib.BrotliCompress {
33
- if (enc === 'br') return zlib.createBrotliCompress();
42
+ if (enc === 'br') return zlib.createBrotliCompress({ params: brotliFast });
34
43
  if (enc === 'gzip') return zlib.createGzip();
35
44
  return zlib.createDeflate();
36
45
  }
@@ -55,7 +64,7 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
55
64
  return;
56
65
  }
57
66
  res.setHeader('ETag', etag);
58
- const enc = pickEncoding(req);
67
+ const enc = devMode ? null : pickEncoding(req);
59
68
  if (enc) {
60
69
  res.setHeader('Content-Encoding', enc);
61
70
  res.end(compress(enc, html));
@@ -83,13 +92,55 @@ async function sendWebResponse(web: any, res: any): Promise<void> {
83
92
  res.end(Buffer.from(await web.arrayBuffer()));
84
93
  }
85
94
 
95
+ /**
96
+ * Send a rendered page document - through onResponse first . The
97
+ * hook sees the status, headers and body exactly as they will go on the
98
+ * wire and may replace them, so the ETag inside sendHtml is then computed
99
+ * over the bytes actually sent. One helper for the POST-action path and the
100
+ * buffered GET path: same hook, same order, no drift between them.
101
+ */
102
+ async function sendPage(req: any, res: any, ssrModule: any, hookCtx: any, page: any, routePath: string): Promise<void> {
103
+ let status = page.status ?? 200;
104
+ // page.lang/page.dir are the locale the render used: the document's <html> attributes
105
+ // follow the route's [lang] segment.
106
+ const nonce = nonceFor(ssrModule, routePath);
107
+ // a nonce route is dynamic by construction (the compiler put it in dynamicRoutes), so it
108
+ // always lands here or in the stream below - never on the baked-file path …
109
+ let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
110
+ let headers: Record<string, any> = pageHeaders(ssrModule, routePath, nonce);
111
+ if (hookCtx) {
112
+ // P0-3: the document's content-type travels WITH the Response. The WHATWG constructor
113
+ // fills in text/plain when it is missing …
114
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
115
+ status,
116
+ headers: { 'content-type': 'text/html; charset=utf-8', ...headers },
117
+ }));
118
+ status = out.status;
119
+ headers = webHeadersToNode(out);
120
+ // P0-4: a hook that READ the body and returned the same Response cannot have it read
121
+ // again (TypeError: body already used) …
122
+ html = out.bodyUsed ? html : await out.text();
123
+ }
124
+ sendHtml(req, res, status, html, headers);
125
+ }
126
+
86
127
  // Static files: raw + both compressed forms cached per mtime (dev rebuilds change mtime;
87
128
  // preview never does).
88
129
  const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
89
130
 
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();
131
+ // P0-0 (bug report): `--port N` (or `--port=N`), the same override the PORT env gives, as
132
+ // an argument …
133
+ const __portArg = process.argv.find((a) => a === '--port' || a.startsWith('--port='));
134
+ if (__portArg) {
135
+ const __v = __portArg.includes('=') ? __portArg.slice('--port='.length) : process.argv[process.argv.indexOf(__portArg) + 1];
136
+ if (__v && Number(__v) > 0) process.env.PORT = __v;
137
+ }
138
+
139
+ // (the "the framework is real" gate): the CLI builds ANY project, not just this repo's
140
+ // demo.
141
+ const SRC_DIR = process.argv[3] && !process.argv[3].startsWith('-') ? path.resolve(process.argv[3]) : process.cwd();
142
+ // The deploy dir is ./dist of the directory the command ran from - a documented contract
143
+ // (test-cli.mjs asserts it): building a project that is not the cwd still drops its output …
93
144
  const OUT_DIR = path.join(process.cwd(), 'dist');
94
145
  // PORT env override (default 3000): lets a preview server run beside a dev
95
146
  // server on the same machine - the e2e ISR test does exactly that.
@@ -103,6 +154,15 @@ const PORT = Number(process.env.PORT) || 3000;
103
154
  * import must NOT be per-request: server state (stores mutated by server
104
155
  * actions) lives in that module, and a fresh import per request would
105
156
  * reset it on every hit, so an action's effect would vanish immediately.
157
+ *
158
+ * The dev re-import needs a NEW PATH, not a new `?v=` query: tsx's ESM
159
+ * loader (which `npm run dev` runs the CLI through) caches by resolved
160
+ * path and ignores the search string, so the query trick silently handed
161
+ * back the previous module - a rebuild that served the OLD code until the
162
+ * NEXT rebuild landed, which is exactly the "hot reload" a developer
163
+ * cannot trust. A copied file under dist/.build/ (which every build
164
+ * deletes, and which never ships) is a new module under any loader.
165
+ * Preview and serve never rebuild, so they import dist/server.js itself.
106
166
  */
107
167
  let serverModule: any = null;
108
168
  let serverMtime = -1;
@@ -114,13 +174,19 @@ async function loadServer(): Promise<any> {
114
174
  if (!serverModule || mtimeMs !== serverMtime) {
115
175
  serverMtime = mtimeMs;
116
176
  serverVersion++;
117
- serverModule = await import(pathToFileURL(file).href + '?v=' + serverVersion);
177
+ let target = file;
178
+ if (devMode) {
179
+ target = path.join(OUT_DIR, '.build', `server-${serverVersion}.mjs`);
180
+ await fs.promises.mkdir(path.dirname(target), { recursive: true });
181
+ await fs.promises.copyFile(file, target);
182
+ }
183
+ serverModule = await import(pathToFileURL(target).href);
118
184
  }
119
185
  return serverModule;
120
186
  }
121
187
 
122
188
  async function build(): Promise<void> {
123
- // P0 §1: the build reports the bundle mode ('inline' | 'split') so the
189
+ // The build reports the bundle mode ('inline' | 'split') so the
124
190
  // shell follows it for every document, header and streaming tag it emits
125
191
  const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR);
126
192
  // The previous build's prerendered output must not survive: a route that stopped being
@@ -133,20 +199,23 @@ async function build(): Promise<void> {
133
199
  // routes, so their real 500 status survives (a flushed response cannot change its
134
200
  // status).
135
201
  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.
202
+ // Per-route response headers for the Go binary, which has no compiler: it reads this file
203
+ // and merges the entries over its own responses.
138
204
  const ssrModule = await loadServer();
139
205
  await fs.promises.writeFile(path.join(OUT_DIR, 'headers.json'), JSON.stringify({
140
206
  default: securityHeaders(getClientSource()),
141
207
  routes: ssrModule.routeHeaders ?? [],
142
208
  }));
143
- // Innovation #28: precompressed brotli siblings (dist/<file>.br) for the Go single
144
- // binary.
209
+ // Precompressed brotli siblings (dist/<file>.br) for the Go single binary. The binary
210
+ // embeds dist/ verbatim …
145
211
  await writeBrotli(OUT_DIR);
212
+ // What this build actually costs on the wire, per route. Runs
213
+ // after writeBrotli so the br column is the file the Go binary serves.
214
+ await analyze(OUT_DIR, (ssrModule.dynamicRoutes as string[] | undefined) ?? []);
146
215
  }
147
216
 
148
217
  /**
149
- * Write dist/<file>.br next to every compressible text file. ponytail:
218
+ * Write dist/<file>.br next to every compressible text file. trade-off:
150
219
  * extension allowlist + zlib's default quality - a 30 KB document
151
220
  * compresses in ~10 ms at build time, once, forever.
152
221
  */
@@ -163,21 +232,73 @@ async function writeBrotli(dir: string): Promise<void> {
163
232
  }
164
233
  }
165
234
 
235
+ /**
236
+ * The build analysis. The zero-JS report says
237
+ * WHICH routes ship no runtime; this says what every route costs on the
238
+ * wire, measured from the files this build just wrote - never from a number
239
+ * quoted from memory. Brotli is the `.br` sibling the build already wrote
240
+ * (the exact bytes the Go binary serves); gzip is computed here because the
241
+ * Node server compresses per request and gzip is the fallback every proxy
242
+ * eventually falls back to. Dynamic routes are not baked, so they are
243
+ * LISTED, not measured: their numbers come from `npm run benchmark`, which
244
+ * renders them live against `rosetack serve`.
245
+ */
246
+ async function analyze(outDir: string, dynamic: string[]): Promise<void> {
247
+ const rows: Array<{ route: string; raw: number; gzip: number; br: number; js: boolean }> = [];
248
+ const walk = async (dir: string, prefix: string): Promise<void> => {
249
+ for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
250
+ if (e.isDirectory()) {
251
+ await walk(path.join(dir, e.name), `${prefix}/${e.name}`);
252
+ continue;
253
+ }
254
+ if (!e.name.endsWith('.html')) continue;
255
+ const file = path.join(dir, e.name);
256
+ const raw = await fs.promises.readFile(file);
257
+ const brFile = `${file}.br`;
258
+ rows.push({
259
+ route: prefix || '/',
260
+ raw: raw.length,
261
+ gzip: zlib.gzipSync(raw, { level: 9 }).length,
262
+ br: fs.existsSync(brFile) ? (await fs.promises.stat(brFile)).size : 0,
263
+ js: /<script type="module"/.test(raw.toString('utf8')),
264
+ });
265
+ }
266
+ };
267
+ await walk(outDir, '');
268
+ const kb = (n: number) => `${(n / 1024).toFixed(1)} KB`;
269
+ const lines = ['rosetack build analysis (measured from dist/; br = the precompressed bytes the Go binary serves):'];
270
+ for (const r of rows.sort((a, b) => (a.route < b.route ? -1 : 1))) {
271
+ lines.push(` ${r.route.padEnd(16)}${kb(r.raw).padStart(9)} raw ${kb(r.gzip).padStart(8)} gzip ${kb(r.br).padStart(8)} br ${r.js ? 'bundle inlined' : 'zero-JS'}`);
272
+ }
273
+ const client = path.join(outDir, 'client.js');
274
+ if (fs.existsSync(client)) {
275
+ const raw = await fs.promises.readFile(client);
276
+ lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs.existsSync(`${client}.br`) ? (await fs.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
277
+ }
278
+ if (dynamic.length > 0) {
279
+ lines.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${dynamic.join(' ')}`);
280
+ }
281
+ for (const l of lines) console.log(l);
282
+ }
283
+
166
284
  /**
167
285
  * Delete the prerendered output of a previous build: HTML documents and
168
286
  * baked API bodies, with their brotli siblings. Everything else in dist/
169
287
  * (the bundles, styles) was just rewritten by buildProject.
170
288
  *
171
- * ponytail: Windows hands out transient EPERM/EBUSY when an antivirus or
289
+ * Trade-off: Windows hands out transient EPERM/EBUSY when an antivirus or
172
290
  * the search indexer holds a just-written file, so a couple of retries
173
291
  * per file - a build that fails because a scanner blinked is the worst
174
292
  * kind of flake.
175
293
  */
176
- async function clearPrerendered(dir: string): Promise<void> {
294
+ async function clearPrerendered(dir: string, depth = 0): Promise<void> {
177
295
  for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
296
+ // Dist/locales/ holds the runtime locale packs the build just wrote (i18n.preload's
297
+ // leftovers) - they are .json files like any prerendered body, but they are build output …
298
+ if (depth === 0 && e.name === 'locales' && e.isDirectory()) continue;
178
299
  const p = path.join(dir, e.name);
179
300
  if (e.isDirectory()) {
180
- await clearPrerendered(p);
301
+ await clearPrerendered(p, depth + 1);
181
302
  continue;
182
303
  }
183
304
  if (!/\.(?:html|json)(?:\.br)?$/.test(e.name)) continue;
@@ -200,7 +321,7 @@ async function clearPrerendered(dir: string): Promise<void> {
200
321
  * enumerated and prerendered per value; params without `params` keep
201
322
  * rendering on demand. A route exporting `revalidate = N` is baked like
202
323
  * any other and then kept fresh by the preview server's stale-while-
203
- * revalidate pass (ISR, innovation #24).
324
+ * revalidate pass (ISR).
204
325
  */
205
326
  async function prerender(routes: RouteInfo[]): Promise<string[]> {
206
327
  const ssrModule = await loadServer();
@@ -214,6 +335,9 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
214
335
  skipped.push(routePath);
215
336
  return;
216
337
  }
338
+ // P0-1: a baked document has no request and therefore no query - say so
339
+ // explicitly, so a query from the previous render can never leak in.
340
+ ssrModule.setQuery?.({});
217
341
  const page = await ssrModule.renderPage(routePath);
218
342
  if (page.status === 500) {
219
343
  // The route's render failed and the error page rendered instead. Do NOT bake that
@@ -224,9 +348,9 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
224
348
  }
225
349
  const routeDir = routePath === '/' ? OUT_DIR : path.join(OUT_DIR, routePath.slice(1));
226
350
  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));
351
+ // csr = false routes bake a JS-free document: the file on disk carries no bundle and no
352
+ // state script, so a visitor who lands on it runs zero JavaScript.
353
+ await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
230
354
  console.log(`prerendered ${routePath} -> ${path.relative(process.cwd(), path.join(routeDir, 'index.html'))}`);
231
355
  };
232
356
 
@@ -306,17 +430,27 @@ function enumerateParams(pattern: string, names: string[], raw: Record<string, u
306
430
  // path even when a middleware exists (a middleware guards pages, not files).
307
431
  const ASSET_EXT = new Set(['.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.woff', '.woff2', '.txt', '.xml']);
308
432
 
309
- // Response headers for a page document (innovation #26): the strict CSP …
310
- function pageHeaders(ssrModule: any, pathname: string): Record<string, string> {
433
+ // Response headers for a page document: the strict CSP (hashed over the exact inlined
434
+ // bundle + bootstrap bytes …
435
+ function pageHeaders(ssrModule: any, pathname: string, nonce = ''): Record<string, string> {
311
436
  const headers: Record<string, string> = {};
312
- for (const [k, v] of Object.entries(securityHeaders(getClientSource()))) headers[k.toLowerCase()] = v;
437
+ for (const [k, v] of Object.entries(securityHeaders(getClientSource(), nonce))) headers[k.toLowerCase()] = v;
313
438
  const own = ssrModule.headersFor?.(pathname) as Record<string, string> | null | undefined;
314
439
  if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
315
440
  return headers;
316
441
  }
317
442
 
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).
443
+ /**
444
+ * The nonce for one response, or '' when the route keeps the hashed policy
445
+ * . Only the routes that exported `csp = { nonce: true }` ask for one,
446
+ * so every other document is byte-for-byte what it was.
447
+ */
448
+ function nonceFor(ssrModule: any, pathname: string): string {
449
+ return ssrModule.cspNonce?.(pathname) ? mintNonce() : '';
450
+ }
451
+
452
+ // ISR background pass: re-render a stale baked route and swap its file, while the
453
+ // triggering request was already answered from disk (stale-while-revalidate).
320
454
  const isrBusy = new Set<string>();
321
455
  function revalidateInBackground(routePath: string, filePath: string): void {
322
456
  if (isrBusy.has(filePath)) return;
@@ -324,11 +458,14 @@ function revalidateInBackground(routePath: string, filePath: string): void {
324
458
  void (async () => {
325
459
  try {
326
460
  const ssrModule = await loadServer();
461
+ // P0-1: the background pass has no request either - an empty query, so
462
+ // the swapped file never carries another visitor's search terms.
463
+ ssrModule.setQuery?.({});
327
464
  const page = await ssrModule.renderPage(routePath);
328
465
  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));
466
+ // the swap must honor the route's csr decision: a zero-JS route revalidated here stays
467
+ // zero-JS, or the first stale window would silently inline the bundle into its baked file
468
+ await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
332
469
  fileCache.delete(filePath);
333
470
  console.log(`rosetack: revalidated ${routePath} in the background`);
334
471
  }
@@ -340,8 +477,8 @@ function revalidateInBackground(routePath: string, filePath: string): void {
340
477
  })();
341
478
  }
342
479
 
343
- // --- Phase 1: production server posture -------------------------------------- "Can run a
344
- // real app" is a threshold …
480
+ // --- production server posture -------------------------------------- "Can run a real app"
481
+ // is a threshold …
345
482
 
346
483
  /** A request body is bounded. 1 MB holds any form and any JSON API call a
347
484
  * site this size makes; a deployment that needs more sets it explicitly. */
@@ -424,7 +561,138 @@ function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (re
424
561
  };
425
562
  }
426
563
 
427
- function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
564
+ /**
565
+ * The context a runtime plugin hook receives. Node's
566
+ * IncomingMessage is not a Web Request and a hook must not care which server
567
+ * it runs on, so the CLI builds the same object the edge adapter already
568
+ * has. Built only when the project declares a runtime hook (the server
569
+ * bundle exports the flags) - the hot path never pays for the feature.
570
+ *
571
+ * The body is deliberately not attached: the servers read it lazily, and
572
+ * buffering it for every request would cost the fast path. A hook that needs
573
+ * the submitted form uses pages/_middleware.rose, which already rides with
574
+ * the parsed FormData.
575
+ */
576
+ async function hookContext(req: any): Promise<{
577
+ request: Request;
578
+ url: URL;
579
+ method: string;
580
+ pathname: string;
581
+ state: Record<string, unknown>;
582
+ }> {
583
+ const headers: Record<string, string> = {};
584
+ for (const [k, v] of Object.entries(req.headers)) {
585
+ if (v !== undefined) headers[k] = Array.isArray(v) ? v.join(', ') : String(v);
586
+ }
587
+ const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
588
+ method: req.method || 'GET',
589
+ headers,
590
+ });
591
+ const url = new URL(request.url);
592
+ return { request, url, method: request.method, pathname: url.pathname, state: {} };
593
+ }
594
+
595
+ /** A Web Response's headers as a Node header record, set-cookie kept whole. */
596
+ function webHeadersToNode(web: any): Record<string, any> {
597
+ const out: Record<string, any> = {};
598
+ const cookies = web.headers.getSetCookie?.() ?? [];
599
+ web.headers.forEach((v: string, k: string) => {
600
+ if (cookies.length && k.toLowerCase() === 'set-cookie') return;
601
+ out[k] = v;
602
+ });
603
+ if (cookies.length) out['set-cookie'] = cookies;
604
+ return out;
605
+ }
606
+
607
+ // --- dev-only live reload + state bridge --- The dev server rebuilds on change …
608
+ const DEV_BRIDGE = `<script>(function(){var es=new EventSource('/__rosetack_reload');es.onmessage=function(m){if(m.data!=='rebuild')return;es.close();var s=window.__rosetack?window.__rosetack.state():null;if(s)fetch('/__rosetack_state',{method:'POST',body:s,headers:{'content-type':'application/json'}}).catch(function(){});setTimeout(function(){location.reload()},40)}})()</script>`;
609
+ // One slot: the next document a dev client asks for carries it back. trade-off: a single
610
+ // browser tab is the dev case …
611
+ let devResume: string | null = null;
612
+ const devClients = new Set<any>();
613
+ // Set once, when the dev server wraps its handler: this process serves dev documents, so
614
+ // sendHtml answers them buffered and uncompressed …
615
+ let devMode = false;
616
+
617
+ function devReload(req: any, res: any): void {
618
+ res.writeHead(200, {
619
+ 'Content-Type': 'text/event-stream',
620
+ 'Cache-Control': 'no-cache, no-transform',
621
+ Connection: 'keep-alive',
622
+ });
623
+ res.write(': ok\n\n');
624
+ devClients.add(res);
625
+ req.on('close', () => devClients.delete(res));
626
+ }
627
+
628
+ function devSaveState(req: any, res: any): void {
629
+ let body = '';
630
+ req.on('data', (c: any) => {
631
+ body += c;
632
+ if (body.length > 1e6) req.destroy(); // a state snapshot is kilobytes; refuse a runaway
633
+ });
634
+ req.on('end', () => {
635
+ try {
636
+ JSON.parse(body);
637
+ devResume = body;
638
+ } catch { /* a corrupt snapshot is dropped: the next render is simply fresh */ }
639
+ res.writeHead(204).end();
640
+ });
641
+ }
642
+
643
+ /** Push the rebuild signal to every open dev tab. */
644
+ function devNotify(): void {
645
+ for (const res of devClients) {
646
+ try {
647
+ res.write('data: rebuild\n\n');
648
+ } catch {
649
+ devClients.delete(res);
650
+ }
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Wrap a dev response so every HTML document carries the bridge (and the
656
+ * resumed state, once). Wrapping res is the one choke point that covers the
657
+ * buffered and the streamed paths alike - the alternative is a flag threaded
658
+ * through five call sites plus the generated server bundle's own shell writer.
659
+ * The bridge script is not hashed, so dev also drops the CSP header: the hash
660
+ * policy is a production guarantee and dev documents are localhost-only.
661
+ */
662
+ function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => void {
663
+ devMode = true;
664
+ return (req, res) => {
665
+ const url = req.url || '/';
666
+ if (url.startsWith('/__rosetack_reload')) return devReload(req, res);
667
+ if (url.startsWith('/__rosetack_state') && req.method === 'POST') return devSaveState(req, res);
668
+ let injected = false;
669
+ // The resumed snapshot belongs to the NEXT request, whatever it turns out to be: a
670
+ // document that answers 304 (nothing changed) consumes it too …
671
+ const seed = devResume;
672
+ devResume = null;
673
+ const isHtml = () => String(res.getHeader('content-type') || '').includes('text/html');
674
+ const inject = (chunk: any): any => {
675
+ if (injected || !isHtml()) return chunk;
676
+ const s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
677
+ const at = s.indexOf('<head>');
678
+ if (at < 0) return chunk; // not a document (an asset, a JSON body): leave it alone
679
+ injected = true;
680
+ const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\//g, '<\\/')}</script>` : '';
681
+ const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
682
+ return Buffer.isBuffer(chunk) ? Buffer.from(out, 'utf8') : out;
683
+ };
684
+ const write = res.write.bind(res);
685
+ res.write = (chunk: any, ...rest: any[]) => write(inject(chunk), ...rest);
686
+ const end = res.end.bind(res);
687
+ res.end = (chunk: any, ...rest: any[]) => {
688
+ if (!res.headersSent && isHtml()) res.removeHeader('Content-Security-Policy');
689
+ end(chunk === undefined || chunk === null ? chunk : inject(chunk), ...rest);
690
+ };
691
+ inner(req, res);
692
+ };
693
+ }
694
+
695
+ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any) => void {
428
696
  return (req, res) => {
429
697
  // The origin guard runs before everything else - middleware, api dispatch, the static
430
698
  // lookup - because a cross-site write must not reach any of them.
@@ -438,6 +706,20 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
438
706
  // Everything below needs the server module (API dispatch, POST actions, SSR), so load
439
707
  // it once up front: the import is cached until dist/server.js changes on disk …
440
708
  loadServer().then(async (ssrModule: any) => {
709
+ // Runtime hooks: onRequest runs after the origin guard and BEFORE middleware and routing,
710
+ // and may short-circuit the request with its own Response …
711
+ const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true
712
+ ? await hookContext(req)
713
+ : null;
714
+ if (hookCtx) {
715
+ const short = await ssrModule.runRequestHooks(hookCtx);
716
+ if (short) {
717
+ // the short-circuit rides through onResponse like every other
718
+ // response, so a header-adding hook sees it too
719
+ await sendWebResponse(await ssrModule.runResponseHooks(hookCtx, short), res);
720
+ return;
721
+ }
722
+ }
441
723
  // Middleware (pages/_middleware.rose) runs exactly once per request, before anything
442
724
  // else: a returned Response short-circuits the whole request …
443
725
  const apiPath0 = pathnameOf(req.url);
@@ -445,7 +727,7 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
445
727
  if (!isPagePost && ssrModule.middleware) {
446
728
  const mw = await ssrModule.runMiddleware(req);
447
729
  if (mw) {
448
- await sendWebResponse(mw, res);
730
+ await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
449
731
  return;
450
732
  }
451
733
  }
@@ -464,7 +746,11 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
464
746
  headers,
465
747
  body: body.length > 0 ? body : undefined,
466
748
  });
467
- const apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
749
+ // P0-1: an api handler reads the query from its Request's URL (the full one,
750
+ // query included) …
751
+ ssrModule.setQuery?.(queryOf(req.url));
752
+ let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
753
+ if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
468
754
  writeWebHeaders(apiRes, res);
469
755
  res.statusCode = apiRes.status;
470
756
  res.end(Buffer.from(await apiRes.arrayBuffer()));
@@ -490,21 +776,31 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
490
776
  if (ssrModule.middleware) {
491
777
  const mw = await ssrModule.runMiddleware(req, form);
492
778
  if (mw) {
493
- await sendWebResponse(mw, res);
779
+ await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
494
780
  return;
495
781
  }
496
782
  }
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');
783
+ // P0-1: the POST is routed by pathname too, and its query (if the form was
784
+ // posted to /search?ref=x) reaches the render through $query() like every other …
785
+ ssrModule.setQuery?.(queryOf(req.url));
786
+ const page = await ssrModule.renderPage(pathnameOf(req.url || '/'), form);
787
+ await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
788
+ } catch (err) {
789
+ // A silent "Bad request" is how a framework bug hides: the stack goes to stderr
790
+ // (the same rule the GET path follows) …
791
+ console.error(`rosetack: POST ${pathnameOf(req.url || '/')} failed:`, err instanceof Error ? err.stack : err);
792
+ if (!res.headersSent) {
793
+ res.statusCode = 400;
794
+ res.end('Bad request');
795
+ }
502
796
  }
503
797
  });
504
798
  return;
505
799
  }
506
800
 
507
- let safe = path.normalize(req.url || '/').replace(/^(\.\.(\/)?)+/, '');
801
+ // P0-1: routing matches the PATHNAME. The query string rides along to the handlers
802
+ // ($query(), the api Request) but never into a route pattern …
803
+ let safe = path.normalize(pathnameOf(req.url || '/')).replace(/^(\.\.(\/)?)+/, '');
508
804
  if (safe === '\\' || safe === '/') safe = '/';
509
805
  let filePath = path.join(dir, safe);
510
806
  // A file in public/ answers at the root too: pages link /logo.svg, not
@@ -519,8 +815,8 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
519
815
  filePath = path.join(filePath, 'index.html');
520
816
  }
521
817
 
522
- // Build-time precompression siblings (innovation #28: dist/<file>.br, read by the Go
523
- // binary) are internal artifacts.
818
+ // Build-time precompression siblings (dist/<file>.br, read by the Go binary) are internal
819
+ // artifacts.
524
820
  if (/\.(?:br|gz)$/i.test(safe)) {
525
821
  const base = filePath.replace(/\.(?:br|gz)$/i, '');
526
822
  if (fs.existsSync(base)) filePath = base;
@@ -532,8 +828,8 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
532
828
  const isDynamic = !isAsset && (ssrModule.dynamicRoutes as string[] | undefined)?.includes(pathnameOf(req.url));
533
829
  if (!isDynamic && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
534
830
  const st = fs.statSync(filePath);
535
- // ISR (innovation #24): a route exporting `revalidate = N` keeps its baked file for
536
- // N seconds.
831
+ // ISR: a route exporting `revalidate = N` keeps its baked file for N seconds. Once stale,
832
+ // THIS request is still served from disk - stale-while-revalidate: instant TTFB …
537
833
  const rev = isAsset ? undefined : ((ssrModule.revalidate as { pattern: string; seconds: number }[]) || [])
538
834
  .find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
539
835
  if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1000) {
@@ -545,8 +841,10 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
545
841
  entry = {
546
842
  mtimeMs: st.mtimeMs,
547
843
  raw,
844
+ // A file's compressed forms are computed ONCE and then served from this cache
845
+ // forever …
548
846
  br: zlib.brotliCompressSync(raw),
549
- gzip: zlib.gzipSync(raw),
847
+ gzip: zlib.gzipSync(raw, { level: 9 }),
550
848
  etag: `W/"${st.size}-${st.mtimeMs}"`,
551
849
  };
552
850
  fileCache.set(filePath, entry);
@@ -564,24 +862,36 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
564
862
  '.mp4': 'video/mp4',
565
863
  '.mp3': 'audio/mpeg',
566
864
  };
567
- res.setHeader('Content-Type', types[ext] || 'application/octet-stream');
568
865
  // An ISR route's file is swapped every `revalidate` seconds, so the cache must not
569
866
  // 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);
867
+ const fileHeaders: Record<string, string> = {
868
+ 'Content-Type': types[ext] || 'application/octet-stream',
869
+ 'Cache-Control': rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
870
+ 'ETag': entry.etag,
871
+ 'Vary': 'Accept-Encoding',
872
+ };
873
+ // Per-route response headers: a prerendered document carries the same policy the live
874
+ // render would send - the strict CSP plus the route's own exported headers.
875
+ if (ext === '.html') Object.assign(fileHeaders, pageHeaders(ssrModule, pathnameOf(req.url)));
876
+ // OnResponse on the file path too, so a header-adding plugin sees EVERY response and not
877
+ // just the rendered ones.
878
+ let status = 200;
879
+ if (hookCtx) {
880
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers: fileHeaders }));
881
+ status = out.status;
882
+ for (const [k, v] of Object.entries(webHeadersToNode(out))) res.setHeader(k, v);
883
+ } else {
884
+ for (const [k, v] of Object.entries(fileHeaders)) res.setHeader(k, v);
577
885
  }
578
886
  if (req.headers['if-none-match'] === entry.etag) {
579
887
  res.statusCode = 304;
580
888
  res.end();
581
889
  return;
582
890
  }
583
- const enc = pickEncoding(req);
584
- res.statusCode = 200;
891
+ // Dev answers the file uncompressed: the reload bridge injects into the body, and a
892
+ // compressed body has no `<head>` left to find.
893
+ const enc = devMode ? null : pickEncoding(req);
894
+ res.statusCode = status;
585
895
  if (enc) {
586
896
  res.setHeader('Content-Encoding', enc);
587
897
  res.end(enc === 'br' ? entry.br : enc === 'gzip' ? entry.gzip : compress('deflate', entry.raw));
@@ -597,36 +907,79 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
597
907
  try {
598
908
  broken = new Set(JSON.parse(fs.readFileSync(path.join(dir, 'broken.json'), 'utf-8')));
599
909
  } catch { /* no manifest: nothing known-broken */ }
600
- const safe2 = req.url || '/';
601
- if (!broken.has(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
910
+ // P0-1: the pathname, never the raw url - see the static branch above. The query
911
+ // reaches the render through $query() (setQuery below) …
912
+ const safe2 = pathnameOf(req.url || '/');
913
+ // P0-1: the query is per request and belongs to the render, not the
914
+ // route - set once, before either path below reads $query().
915
+ ssrModule.setQuery?.(queryOf(req.url));
916
+ // P0-2: `buffer = true` routes take the buffered path even when they could stream …
917
+ if (!dev && !broken.has(safe2) && !ssrModule.isBuffered?.(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
602
918
  const enc = pickEncoding(req);
603
- res.statusCode = 200;
919
+ // onResponse runs BEFORE the first flush, while the status and headers can still change:
920
+ // the hook is handed a bodyless Response carrying them …
921
+ let status = 200;
922
+ // The nonce is minted before the first flush, because a streamed response cannot change
923
+ // its headers afterwards - and the document's script tag is written into that same stream …
924
+ const nonce = nonceFor(ssrModule, safe2);
925
+ let headers: Record<string, any> = pageHeaders(ssrModule, safe2, nonce);
926
+ if (hookCtx) {
927
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers }));
928
+ status = out.status;
929
+ headers = webHeadersToNode(out);
930
+ }
931
+ res.statusCode = status;
604
932
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
605
933
  res.setHeader('Vary', 'Accept-Encoding');
606
- for (const [k, v] of Object.entries(pageHeaders(ssrModule, pathnameOf(safe2)))) res.setHeader(k, v);
934
+ for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
607
935
  let write: (chunk: string) => void;
608
936
  let done: () => void;
609
937
  if (enc) {
610
938
  res.setHeader('Content-Encoding', enc);
611
939
  const compressor = createCompressor(enc);
612
940
  compressor.pipe(res);
613
- write = (chunk) => compressor.write(chunk);
941
+ // The shell must reach the socket NOW. Without a flush zlib emits nothing until
942
+ // end() …
943
+ let flushed = false;
944
+ write = (chunk) => {
945
+ compressor.write(chunk);
946
+ if (!flushed) {
947
+ flushed = true;
948
+ compressor.flush(zlib.constants.Z_FULL_FLUSH);
949
+ }
950
+ };
951
+ // pipe() forwards data but not errors, and an unhandled 'error' event kills the
952
+ // worker.
953
+ compressor.on('error', () => res.destroy());
614
954
  done = () => compressor.end();
615
955
  } else {
616
956
  write = (chunk) => res.write(chunk);
617
957
  done = () => res.end();
618
958
  }
619
- await ssrModule.renderPageStream(safe2, write, shellOpen(), clientScriptTag(getClientSource()));
959
+ // The streamed shell opens before the render, so its <html
960
+ // lang>/<dir> come from the pathname (the server bundle's docAttrs)
961
+ const doc = ssrModule.docAttrs(safe2);
962
+ await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
620
963
  done();
621
964
  return;
622
965
  }
623
966
  // buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
624
967
  // = false routes …
625
968
  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');
969
+ await sendPage(req, res, ssrModule, hookCtx, page, safe2);
970
+ }).catch((err: unknown) => {
971
+ // P0-4: a failure in the pipeline is a 500 with the reason on stderr, never a 9-byte
972
+ // 404 …
973
+ console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
974
+ if (res.headersSent) {
975
+ // a stream already left: the status is committed, so the only honest
976
+ // move is to drop the socket and let the client retry
977
+ res.destroy();
978
+ return;
979
+ }
980
+ res.statusCode = 500;
981
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
982
+ res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>');
630
983
  });
631
984
  };
632
985
  }
@@ -640,17 +993,86 @@ function pathnameOf(url: string | undefined): string {
640
993
  }
641
994
  }
642
995
 
996
+ /**
997
+ * The parsed query string of a URL (?page=2&q=x -> {page:'2',q:'x'}), for
998
+ * $query() (P0-1). First value wins per key, the way every server-side
999
+ * framework reads a repeated parameter.
1000
+ */
1001
+ function queryOf(url: string | undefined): Record<string, string> {
1002
+ const q: Record<string, string> = {};
1003
+ try {
1004
+ new URL(url || '/', 'http://localhost').searchParams.forEach((v, k) => { if (!(k in q)) q[k] = v; });
1005
+ } catch { /* an unparsable url carries no query */ }
1006
+ return q;
1007
+ }
1008
+
1009
+ /**
1010
+ * P0-0 (bug report): listen on `port`, hopping to the next free one when it
1011
+ * is taken instead of crashing with EADDRINUSE. Two projects on one machine
1012
+ * (or a dev server that did not exit cleanly) is the everyday case, and a
1013
+ * stack trace plus a dead process is the worst possible answer to it: the
1014
+ * banner names the port actually used, so the URL is never a guess.
1015
+ *
1016
+ * The hop is bounded (20 tries) and every other error is fatal - silently
1017
+ * retrying a real fault would hide it.
1018
+ */
1019
+ function listenFree(server: any, port: number, onReady: (port: number) => void): void {
1020
+ const attempt = (p: number): void => {
1021
+ const onError = (err: any) => {
1022
+ server.removeListener('error', onError);
1023
+ if (err && err.code === 'EADDRINUSE' && p - port < 20) {
1024
+ console.log(`🌹 port ${p} is in use - trying ${p + 1}`);
1025
+ attempt(p + 1);
1026
+ return;
1027
+ }
1028
+ console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
1029
+ process.exit(1);
1030
+ };
1031
+ server.once('error', onError);
1032
+ server.listen(p, () => {
1033
+ server.removeListener('error', onError);
1034
+ onReady(p);
1035
+ });
1036
+ };
1037
+ attempt(port);
1038
+ }
1039
+
1040
+ /**
1041
+ * P0-0 (bug report): the first free port at or after `from`, probed with a
1042
+ * throwaway socket. The cluster's primary needs this because the workers must
1043
+ * all land on the SAME port - letting each of them hop on its own would put
1044
+ * them on different ports and split the traffic between them. Racy by nature
1045
+ * (a port can be taken between the probe and the workers' listen); the
1046
+ * workers' own listenFree fallback covers that last step.
1047
+ */
1048
+ async function freePort(from: number): Promise<number> {
1049
+ const net = await import('node:net');
1050
+ for (let p = from; p < from + 20; p++) {
1051
+ const free = await new Promise<boolean>((resolve) => {
1052
+ const probe = net.createServer();
1053
+ probe.once('error', () => resolve(false));
1054
+ probe.listen(p, () => probe.close(() => resolve(true)));
1055
+ });
1056
+ if (free) return p;
1057
+ }
1058
+ return from;
1059
+ }
1060
+
643
1061
  /**
644
1062
  * The version from package.json - one source of truth, no constant to drift.
645
1063
  * Resolved from THIS module (not the cwd): the banner names the framework's
646
- * version even when it builds somebody else's project.
1064
+ * version even when it builds somebody else's project. Two layouts answer:
1065
+ * in the repo this module sits at src/cli/, in the published package the CLI
1066
+ * is bundled to dist-cli/ with the sources beside it - so try both.
647
1067
  */
648
1068
  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';
1069
+ for (const rel of ['../../package.json', '../package.json']) {
1070
+ try {
1071
+ const v = JSON.parse(fs.readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf-8')).version;
1072
+ if (v) return v;
1073
+ } catch { /* not this layout */ }
653
1074
  }
1075
+ return '0.0.0';
654
1076
  }
655
1077
 
656
1078
  async function dev(): Promise<void> {
@@ -670,18 +1092,23 @@ async function dev(): Promise<void> {
670
1092
  try {
671
1093
  console.log('Rebuilding...');
672
1094
  await build();
1095
+ // Tell the open tabs. Without this the rebuild lands on disk and the browser keeps showing
1096
+ // the previous document until the developer thinks to refresh …
1097
+ devNotify();
673
1098
  } catch (err) {
674
1099
  // Never let a user-code error kill the dev server.
675
- console.error('Build failed (server still running):', err instanceof Error ? err.message : err);
1100
+ console.error('Build failed (server still running):', err instanceof Error ? err.message : String(err));
676
1101
  }
677
1102
  }, 200);
678
1103
  });
679
1104
 
680
1105
  const http = await import('http');
681
- const server = http.createServer(serveStatic(OUT_DIR));
1106
+ const server = http.createServer(devWrap(serveStatic(OUT_DIR, false, true)));
682
1107
 
683
- server.listen(PORT, () => {
684
- console.log('🌹 http://localhost:' + PORT);
1108
+ // P0-0: an occupied port hops to the next free one (and says so) instead of
1109
+ // killing the server with EADDRINUSE.
1110
+ listenFree(server, PORT, (port) => {
1111
+ console.log('🌹 http://localhost:' + port);
685
1112
  });
686
1113
  }
687
1114
 
@@ -689,25 +1116,27 @@ async function preview(): Promise<void> {
689
1116
  await build();
690
1117
  const http = await import('http');
691
1118
  // isr=true: routes exporting `revalidate = N` are served stale-then-swapped
692
- // from disk (innovation #24). Dev passes nothing (it rebuilds on change).
1119
+ // from disk . Dev passes nothing (it rebuilds on change).
693
1120
  const server = http.createServer(serveStatic(OUT_DIR, true));
694
1121
 
695
- server.listen(PORT, () => {
696
- console.log(`🌹 RoseTack v${version()} preview at http://localhost:` + PORT);
1122
+ // P0-0: same hop as the dev server - a preview that cannot bind its port
1123
+ // moves to the next one and prints it.
1124
+ listenFree(server, PORT, (port) => {
1125
+ console.log(`🌹 RoseTack v${version()} preview at http://localhost:` + port);
697
1126
  });
698
1127
  }
699
1128
 
700
1129
  /**
701
- * Phase 1: `rosetack serve` runs what `build` produced - no rebuild, no
1130
+ * `rosetack serve` runs what `build` produced - no rebuild, no
702
1131
  * watcher, production semantics (a preview that re-rendered on the fly
703
1132
  * could serve a half-written file). Multi-core through the stdlib cluster:
704
1133
  * the primary supervises and serves no traffic, the workers serve; every
705
1134
  * request is logged; SIGTERM drains in-flight work and exits.
706
1135
  *
707
- * ponytail boundaries, stated plainly:
1136
+ * Boundaries, stated plainly:
708
1137
  * - each worker is its own process with its own dist/server.js module.
709
1138
  * Module-scope state is therefore per-worker, which is what $store()
710
- * (Phase 2) fixes: writes broadcast through the primary, reads stay
1139
+ * fixes: writes broadcast through the primary, reads stay
711
1140
  * local-synchronous. ISR revalidation may run in more than one worker
712
1141
  * for one route: the guard is per-worker and the cost is one duplicate
713
1142
  * render.
@@ -729,10 +1158,13 @@ async function serve(): Promise<void> {
729
1158
  cluster.schedulingPolicy = cluster.SCHED_RR;
730
1159
  const os = await import('node:os');
731
1160
  const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
732
- const PORT = Number(process.env.PORT) || 3000;
733
1161
  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 …
1162
+ // P0-0 (bug report): ONE port for the whole cluster, chosen once by the primary and
1163
+ // handed to every worker through the environment.
1164
+ const port = await freePort(Number(process.env.PORT) || 3000);
1165
+ for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
1166
+ // The store relay. A worker broadcasts every $store write here; the primary forwards each
1167
+ // patch to every OTHER worker …
736
1168
  cluster.on('message', (worker: any, msg: any) => {
737
1169
  if (!msg || msg.type !== 'rosetack:store') return;
738
1170
  for (const w of Object.values<any>(cluster.workers ?? {})) {
@@ -747,11 +1179,19 @@ async function serve(): Promise<void> {
747
1179
  process.on('SIGTERM', stop);
748
1180
  process.on('SIGINT', stop);
749
1181
  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)`);
1182
+ console.log(`🌹 RoseTack v${version()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
751
1183
  return;
752
1184
  }
753
1185
  // worker the primary's death is the worker's death: no orphan holding the port
754
1186
  process.on('disconnect', () => process.exit(0));
1187
+ // OnServe / onShutdown - the worker's lifecycle. A plugin that owns a resource (a
1188
+ // connection pool, a warm cache) opens it here and closes it in the drain …
1189
+ let servicePlugins: any[] = [];
1190
+ try {
1191
+ servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
1192
+ } catch (err) {
1193
+ console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : err);
1194
+ }
755
1195
  const http = await import('node:http');
756
1196
  const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
757
1197
  // A client that stalls mid-request is dropped instead of holding a worker;
@@ -759,8 +1199,31 @@ async function serve(): Promise<void> {
759
1199
  server.requestTimeout = 30_000;
760
1200
  server.headersTimeout = 65_000; // must exceed requestTimeout
761
1201
  server.keepAliveTimeout = 5_000;
762
- server.listen(PORT, () => console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${PORT}`));
1202
+ // P0-0: the worker binds the port the primary chose; if that one was taken in the
1203
+ // meantime it hops instead of dying with an unhandled 'error' …
1204
+ listenFree(server, PORT, async (port) => {
1205
+ console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${port}`);
1206
+ for (const p of servicePlugins) {
1207
+ try {
1208
+ await p.onServe({ port, workers });
1209
+ } catch (err) {
1210
+ console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : err);
1211
+ }
1212
+ }
1213
+ });
763
1214
  const stop = () => {
1215
+ // onShutdown first: close what onServe opened, then drain. A throwing
1216
+ // hook must not stop the drain - the process still exits on the timer.
1217
+ for (const p of servicePlugins) {
1218
+ if (!p.onShutdown) continue;
1219
+ try {
1220
+ void Promise.resolve(p.onShutdown()).catch((err: unknown) => {
1221
+ console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
1222
+ });
1223
+ } catch (err) {
1224
+ console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
1225
+ }
1226
+ }
764
1227
  server.close(() => process.exit(0)); // finish what is in flight
765
1228
  server.closeIdleConnections?.(); // drop the idle keep-alive sockets
766
1229
  setTimeout(() => process.exit(0), 5000).unref(); // a stuck one must not hold the worker
@@ -769,9 +1232,310 @@ async function serve(): Promise<void> {
769
1232
  process.on('SIGINT', stop);
770
1233
  }
771
1234
 
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)');
1235
+ /**
1236
+ * `rosetack new <name>` - a starting project. The smallest thing that builds
1237
+ * and runs and shows the syntax: one page (state, {#if}, {#each}, a scoped
1238
+ * style), one README naming the three commands. Not a second demo app - the
1239
+ * point is that a new developer's first `rosetack build` works in seconds.
1240
+ *
1241
+ * Trade-off: three files, written from strings. No template engine, no
1242
+ * dependency, no `npm install` run on the developer's behalf (they may use
1243
+ * pnpm/yarn/bun, and a surprise install is worse than a printed command).
1244
+ */
1245
+ async function scaffold(): Promise<void> {
1246
+ const name = process.argv[3];
1247
+ if (!name || name.startsWith('-')) {
1248
+ console.log('Usage: rosetack new <name> (creates <name>/ with a page that builds)');
1249
+ return;
1250
+ }
1251
+ const dir = path.resolve(name);
1252
+ if (fs.existsSync(dir)) {
1253
+ console.error(`rosetack: ${dir} already exists - pick another name`);
1254
+ process.exit(1);
1255
+ }
1256
+ const pages = path.join(dir, 'src', 'pages');
1257
+ fs.mkdirSync(pages, { recursive: true });
1258
+
1259
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
1260
+ name: path.basename(dir),
1261
+ private: true,
1262
+ type: 'module',
1263
+ scripts: {
1264
+ dev: 'rosetack dev',
1265
+ build: 'rosetack build',
1266
+ preview: 'rosetack preview',
1267
+ serve: 'rosetack serve',
1268
+ check: 'rosetack check',
1269
+ },
1270
+ dependencies: { rosetack: `^${version()}` },
1271
+ // TypeScript is a first-class citizen: .rose scripts are typed, and `npm run check`
1272
+ // type-checks every one of them with THIS project's TypeScript …
1273
+ devDependencies: { typescript: '^5.6.0' },
1274
+ }, null, 2) + '\n');
1275
+
1276
+ // The ambient globals a .rose script can call ($state, $data, $t, ...),
1277
+ // pulled in from the installed package: editors and tsc both see them.
1278
+ fs.writeFileSync(path.join(dir, 'rosetack-env.d.ts'), `/// <reference types="rosetack" />\n`);
1279
+ fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
1280
+ compilerOptions: {
1281
+ target: 'ES2022',
1282
+ module: 'ESNext',
1283
+ moduleResolution: 'bundler',
1284
+ lib: ['ES2022', 'DOM', 'DOM.Iterable'],
1285
+ strict: true,
1286
+ noEmit: true,
1287
+ skipLibCheck: true,
1288
+ },
1289
+ // the env file first (it is what makes the globals visible), then any
1290
+ // .ts the project grows - .rose scripts are checked by `npm run check`
1291
+ include: ['rosetack-env.d.ts', 'src/**/*.ts'],
1292
+ }, null, 2) + '\n');
1293
+
1294
+ fs.writeFileSync(path.join(pages, 'index.rose'), `<script>
1295
+ // One file per route: markup, script and styles together.
1296
+ // The script block is TypeScript - interfaces, annotations, generics and
1297
+ // casts all compile, and \`npm run check\` type-checks them.
1298
+ interface Item { label: string }
1299
+
1300
+ let count = $state(0);
1301
+ let items = $state<string[]>(['zero hydration', 'one request', 'no build config']);
1302
+ let showList = $state(true);
1303
+
1304
+ function increment() { $setState('count', count() + 1); }
1305
+ function toggleList() { $setState('showList', !showList()); }
1306
+ // typed server data: the body runs per request on the server (and ships
1307
+ // to the client, where it re-runs on a client-side navigation)
1308
+ let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
1309
+ </script>
1310
+
1311
+ <h1>🌹 RoseTack</h1>
1312
+ <p>Count: <strong>{count()}</strong> - first item: {first().label}</p>
1313
+ <button on:click={increment}>Increment</button>
1314
+ <button on:click={toggleList}>{showList() ? 'Hide' : 'Show'} the list</button>
1315
+
1316
+ {#if showList()}
1317
+ <ul>
1318
+ {#each items() as item}
1319
+ <li>{item}</li>
1320
+ {/each}
1321
+ </ul>
1322
+ {/if}
1323
+
1324
+ <style>
1325
+ body { font-family: system-ui, sans-serif; margin: 2rem; }
1326
+ button { padding: 0.5rem 1rem; margin-right: 0.5rem; }
1327
+ </style>
1328
+ `);
1329
+
1330
+ fs.writeFileSync(path.join(dir, 'README.md'), `# ${path.basename(dir)}
1331
+
1332
+ A rosetack project. One file per route in \`src/pages/\`.
1333
+
1334
+ \`\`\`bash
1335
+ npm install # pulls the rosetack package (and typescript, for checking)
1336
+ npm run dev # dev server with hot rebuild: http://localhost:3000
1337
+ npm run build # compiles to dist/
1338
+ npm run serve # production runner (cluster, access log, graceful shutdown)
1339
+ npm run check # type-checks every .rose script
1340
+ \`\`\`
1341
+
1342
+ Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
1343
+ \`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
1344
+ runs before every request, \`src/pages/api/*.rose\` answers JSON.
1345
+ Full syntax: the README of the rosetack package.
1346
+ `);
1347
+
1348
+ fs.writeFileSync(path.join(dir, '.gitignore'), 'node_modules/\ndist/\n');
1349
+
1350
+ console.log(`🌹 Created ${dir}`);
1351
+ console.log(` src/pages/index.rose - a typed page that builds and runs`);
1352
+ console.log(` rosetack-env.d.ts + tsconfig.json - the script globals, typed`);
1353
+ console.log(`\n cd ${name}`);
1354
+ console.log(` npm install && npm run dev`);
1355
+ console.log(` npm run check # type-checks every .rose script`);
1356
+ }
1357
+
1358
+ /**
1359
+ * `rosetack check [dir]` - type-check every .rose script with the
1360
+ * PROJECT's own TypeScript.
1361
+ *
1362
+ * esbuild strips types without checking them, so a wrong argument type or a
1363
+ * typo in an interface is invisible at build time: the build succeeds and the
1364
+ * bug ships. This closes that hole - it extracts the exact block the compiler
1365
+ * embeds (scriptOf, one regex, one truth), pads it so line and column numbers
1366
+ * still point at the .rose file, and runs the project's TypeScript over all
1367
+ * of them in one program, with rosetack's own globals in scope.
1368
+ *
1369
+ * No TypeScript in the project is a hard error: a check that cannot run must
1370
+ * never pass silently. trade-off: no temp files, no tsconfig parsing - an
1371
+ * in-memory compiler host and fixed strict options, documented.
1372
+ */
1373
+ async function check(): Promise<void> {
1374
+ const files = [...(await scanRoseFiles(SRC_DIR)), ...(await scanComponentFiles(SRC_DIR))];
1375
+ if (files.length === 0) {
1376
+ console.error(`rosetack: no .rose pages found under ${path.join(SRC_DIR, 'src', 'pages')} - run rosetack check from a project root, or pass one: rosetack check <dir>`);
1377
+ process.exit(1);
1378
+ }
1379
+
1380
+ // The project's typescript, resolved FROM the project: the framework must not drag its
1381
+ // own copy into a user's install …
1382
+ let tsMod: typeof ts;
1383
+ try {
1384
+ const req = createRequire(pathToFileURL(path.join(SRC_DIR, 'package.json')));
1385
+ tsMod = await import(pathToFileURL(req.resolve('typescript')).href) as typeof ts;
1386
+ } catch {
1387
+ console.error(`rosetack: type checking needs typescript in this project - npm i -D typescript`);
1388
+ process.exit(1);
1389
+ }
1390
+
1391
+ // rosetack's ambient globals, resolved from the COMPILER's own location:
1392
+ // src/types/rosetack.d.ts is a sibling in the repo and two levels down in
1393
+ // the published package (same two layouts as the runtime entry).
1394
+ const nextTo = (rel: string[]) => rel.map((r) => fileURLToPath(new URL(r, import.meta.url))).find((p) => fs.existsSync(p));
1395
+ const typesFile = nextTo(['../types/rosetack.d.ts', '../src/types/rosetack.d.ts']);
1396
+ if (!typesFile) {
1397
+ console.error('rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler');
1398
+ process.exit(1);
1399
+ }
1400
+ // The runtime source, for scripts that import helpers from './runtime.js' (the module the
1401
+ // compiler generates beside the intermediates).
1402
+ const runtimeSource = nextTo(['../runtime/index.ts', '../src/runtime/index.ts']);
1403
+
1404
+ // Each script becomes a virtual file NAMED after its .rose file, padded so a diagnostic's
1405
+ // line/column are the .rose file's own: the <script> tag sits on line L …
1406
+ const norm = (f: string) => path.resolve(f).replace(/\\/g, '/');
1407
+ const virtual = new Map<string, string>();
1408
+ let checked = 0;
1409
+ for (const file of files) {
1410
+ const source = await fs.promises.readFile(file, 'utf-8');
1411
+ const m = /<script>/.exec(source);
1412
+ const script = scriptOf(source);
1413
+ if (!script) continue; // a pure-markup component has nothing to check
1414
+ const tagLine = source.slice(0, m!.index + '<script>'.length).split('\n').length;
1415
+ const wired = runtimeSource
1416
+ ? script.replace(/['"]\.\/runtime\.js['"]/g, JSON.stringify(runtimeSource.replace(/\\/g, '/')))
1417
+ : script;
1418
+ virtual.set(norm(file), '\n'.repeat(tagLine - 1) + wired);
1419
+ checked++;
1420
+ }
1421
+ if (checked === 0) {
1422
+ console.log('rosetack: no .rose scripts to check');
1423
+ return;
1424
+ }
1425
+
1426
+ // An imported component's binding IS its render function (the compiler rewrites `import
1427
+ // Card from '...Card.rose'` to `import { render as Card }`) …
1428
+ const propType = (def: string | null): string => {
1429
+ if (!def) return 'unknown'; // `export let x;`
1430
+ if (/^['"`]/.test(def)) return 'string';
1431
+ if (/^-?\d+(\.\d+)?$/.test(def)) return 'number';
1432
+ if (/^(true|false)$/.test(def)) return 'boolean';
1433
+ return 'unknown'; // null, a call, an object: the honest answer
1434
+ };
1435
+ const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
1436
+ const declared = new Set<string>();
1437
+ for (const file of [...virtual.keys()]) {
1438
+ const script = scriptOf(await fs.promises.readFile(file, 'utf-8').catch(() => ''));
1439
+ if (!script) continue;
1440
+ for (const spec of script.matchAll(ROSE_IMPORT_RE)) {
1441
+ const target = norm(path.resolve(path.dirname(file), spec[1]));
1442
+ if (target === file || declared.has(target)) continue;
1443
+ const targetSource = await fs.promises.readFile(target, 'utf-8').catch(() => null);
1444
+ if (targetSource === null) continue; // the build reports a missing import loudly; the checker stays out of its way
1445
+ const props = extractExports(scriptOf(targetSource) ?? '').props;
1446
+ virtual.set(`${target}.d.ts`, [
1447
+ `declare function render(closes: unknown[], children: string, __props: { ${props.map((p) => `${p.name}?: ${propType(p.def)}`).join('; ')} }, __slots?: Record<string, unknown>): string;`,
1448
+ 'export default render;',
1449
+ '',
1450
+ ].join('\n'));
1451
+ declared.add(target);
1452
+ }
1453
+ }
1454
+
1455
+ const options: ts.CompilerOptions = {
1456
+ noEmit: true,
1457
+ strict: true,
1458
+ target: tsMod.ScriptTarget.ES2022,
1459
+ module: tsMod.ModuleKind.ESNext,
1460
+ moduleResolution: tsMod.ModuleResolutionKind.Bundler,
1461
+ lib: ['lib.es2022.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
1462
+ // the virtual files are named after the .rose files (so a diagnostic points at the real
1463
+ // path) …
1464
+ allowNonTsExtensions: true,
1465
+ // the rewired './runtime.js' import points at a real .ts source
1466
+ allowImportingTsExtensions: true,
1467
+ // `types` is deliberately NOT set: the project's own @types packages (@types/node for
1468
+ // node:sqlite, say) load automatically, the way they do for the user's own .ts files.
1469
+ skipLibCheck: true,
1470
+ };
1471
+ const host = tsMod.createCompilerHost(options);
1472
+ // @types discovery starts at the project root, not the process cwd - the
1473
+ // command works from anywhere, like every other rosetack command.
1474
+ host.getCurrentDirectory = () => path.resolve(SRC_DIR);
1475
+ const realRead = host.readFile.bind(host);
1476
+ const realGet = host.getSourceFile.bind(host);
1477
+ host.readFile = (f) => virtual.get(norm(f)) ?? realRead(f);
1478
+ host.fileExists = (f) => virtual.has(norm(f)) || tsMod.sys.fileExists(f);
1479
+ host.getSourceFile = (f, version, onError, shouldCreate) => {
1480
+ const src = virtual.get(norm(f));
1481
+ return src ? tsMod.createSourceFile(f, src, version, true) : realGet(f, version, onError, shouldCreate);
1482
+ };
1483
+
1484
+ // rosetack's ambient globals as a program root: a global .d.ts contributes its
1485
+ // declarations to every file in the program …
1486
+ const program = tsMod.createProgram([...virtual.keys(), typesFile], options, host);
1487
+ // Only the project's own scripts: an error inside @types/node or inside rosetack's
1488
+ // runtime source is not the user's bug …
1489
+ const diagnostics = tsMod.getPreEmitDiagnostics(program)
1490
+ .filter((d) => d.file && virtual.has(norm(d.file.fileName)));
1491
+ if (diagnostics.length === 0) {
1492
+ console.log(`rosetack: ${checked} script${checked === 1 ? '' : 's'} type-checked, no errors`);
1493
+ return;
1494
+ }
1495
+ for (const d of diagnostics) {
1496
+ // paths relative to the project root, the way tsc prints them
1497
+ const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
1498
+ const where = d.file && at
1499
+ ? `${path.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})`
1500
+ : 'rosetack';
1501
+ const text = tsMod.flattenDiagnosticMessageText(d.messageText, '\n');
1502
+ const kind = d.category === 1 ? 'error' : 'warning';
1503
+ console.error(`${where}: ${kind} TS${d.code}: ${text}`);
1504
+ }
1505
+ const errors = diagnostics.filter((d) => d.category === 1).length;
1506
+ console.error(`rosetack: ${errors} type error${errors === 1 ? '' : 's'} in ${checked} script${checked === 1 ? '' : 's'}`);
1507
+ process.exit(1);
1508
+ }
1509
+
1510
+ const argv = process.argv.slice(2);
1511
+ const cmd = argv[0];
1512
+ // --json: failures print as a machine-readable envelope on stdout - the code, the file, the
1513
+ // line and the hint, one JSON object an agent can parse and act on.
1514
+ const asJson = argv.includes('--json');
1515
+
1516
+ /** Print a failure the way its reader needs it. A RoseError is the
1517
+ * developer's (or the agent's) to fix from its code alone; anything else
1518
+ * keeps its stack, because it is not. Always exits non-zero: a build that
1519
+ * says nothing and succeeds is the worst failure mode there is. */
1520
+ function reportFailure(err: unknown): never {
1521
+ if (asJson) {
1522
+ process.stdout.write(`${JSON.stringify({ ok: false, errors: [errorInfo(err)] })}\n`);
1523
+ } else if (err instanceof RoseError) {
1524
+ console.error(`rosetack: ${err.message}`);
1525
+ if (err.hint) console.error(` hint: ${err.hint}`);
1526
+ const at = err.file ? `${err.file}${err.line ? `:${err.line}` : ''}` : null;
1527
+ if (at) console.error(` at ${at}`);
1528
+ } else {
1529
+ console.error(err instanceof Error ? err.stack ?? err.message : String(err));
1530
+ }
1531
+ process.exit(1);
1532
+ }
1533
+
1534
+ if (cmd === 'dev') void dev().catch(reportFailure);
1535
+ else if (cmd === 'build') void build().catch(reportFailure);
1536
+ else if (cmd === 'preview') void preview().catch(reportFailure);
1537
+ else if (cmd === 'serve') void serve().catch(reportFailure);
1538
+ else if (cmd === 'new') void scaffold().catch(reportFailure);
1539
+ else if (cmd === 'check') void check().catch(reportFailure);
1540
+ else if (cmd === 'prompt') console.log(AI_PROMPT);
1541
+ else console.log('Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON)');