rosetack 0.1.2 → 0.1.4

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 (57) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/netlify/functions/rosetack.ts +38 -0
  4. package/deploy/netlify.toml +17 -0
  5. package/devtools/devtools.html +7 -0
  6. package/devtools/devtools.js +1 -0
  7. package/devtools/manifest.json +8 -0
  8. package/devtools/panel.html +28 -0
  9. package/devtools/panel.js +54 -0
  10. package/dist-cli/compiler.mjs +2194 -561
  11. package/dist-cli/edge.mjs +159 -48
  12. package/dist-cli/rosetack.mjs +2899 -739
  13. package/dist-cli/runtime.mjs +305 -43
  14. package/dist-cli/test.mjs +2332 -630
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/content.ts +186 -0
  18. package/src/cli/edge.ts +78 -62
  19. package/src/cli/image-size.ts +83 -0
  20. package/src/cli/index.ts +391 -334
  21. package/src/cli/prod-server.ts +324 -0
  22. package/src/cli/prompt.ts +51 -20
  23. package/src/cli/shell.ts +105 -74
  24. package/src/cli/test.ts +9 -70
  25. package/src/compiler/index.ts +2107 -913
  26. package/src/runtime/index.ts +367 -168
  27. package/src/types/rosetack.d.ts +16 -66
  28. package/templates/admin/package.json +14 -0
  29. package/templates/admin/rosetack.config.js +1 -0
  30. package/templates/admin/src/pages/_middleware.rose +33 -0
  31. package/templates/admin/src/pages/api/items.rose +37 -0
  32. package/templates/admin/src/pages/api/login.rose +25 -0
  33. package/templates/admin/src/pages/index.rose +79 -0
  34. package/templates/api/package.json +14 -0
  35. package/templates/api/rosetack.config.js +1 -0
  36. package/templates/api/src/pages/api/health.rose +7 -0
  37. package/templates/api/src/pages/api/items.rose +46 -0
  38. package/templates/api/src/pages/api/login.rose +24 -0
  39. package/templates/api/src/pages/index.rose +25 -0
  40. package/templates/blog/package.json +14 -0
  41. package/templates/blog/rosetack.config.js +1 -0
  42. package/templates/blog/src/pages/404.rose +2 -0
  43. package/templates/blog/src/pages/_layout.rose +42 -0
  44. package/templates/blog/src/pages/_middleware.rose +74 -0
  45. package/templates/blog/src/pages/admin.rose +85 -0
  46. package/templates/blog/src/pages/api/login.rose +46 -0
  47. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  48. package/templates/blog/src/pages/api/posts.rose +72 -0
  49. package/templates/blog/src/pages/index.rose +31 -0
  50. package/templates/blog/src/pages/post/[id].rose +36 -0
  51. package/templates/site/package.json +14 -0
  52. package/templates/site/rosetack.config.js +1 -0
  53. package/templates/site/src/pages/404.rose +2 -0
  54. package/templates/site/src/pages/_layout.rose +40 -0
  55. package/templates/site/src/pages/about.rose +6 -0
  56. package/templates/site/src/pages/index.rose +13 -0
  57. package/templates/site/src/pages/pricing.rose +8 -0
package/src/cli/index.ts CHANGED
@@ -1,35 +1,28 @@
1
- /**
2
- * rosetack CLI - simplest possible SSR + static server
3
- */
1
+ // rosetack CLI - simplest possible SSR + static server
4
2
 
5
3
  import * as fs from 'fs';
6
4
  import * as path from 'path';
7
5
  import * as zlib from 'zlib';
6
+ import { createHash } from 'crypto';
8
7
  import { createRequire } from 'module';
9
8
  import { pathToFileURL, fileURLToPath } from 'url';
10
9
  import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, RoseError, errorInfo, type RouteInfo } from '../compiler/index.js';
11
10
  import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
12
11
  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.
12
+ import { Readable } from 'stream';
13
+ import { createEdgeHandler } from './edge.js';
15
14
  import type * as ts from 'typescript';
16
15
 
17
- // --- wire performance: compression + conditional caching (stdlib only) --- The Go binary
18
- // already compresses …
19
16
  type Encoding = 'br' | 'gzip' | 'deflate';
20
17
 
21
18
  function pickEncoding(req: any): Encoding | null {
22
19
  const ae: string = req.headers['accept-encoding'] || '';
23
- // Trade-off: substring match, no q-value parsing - every browser that sends
24
- // br also accepts gzip, and br > gzip > deflate is the quality order.
25
20
  if (ae.includes('br')) return 'br';
26
21
  if (ae.includes('gzip')) return 'gzip';
27
22
  if (ae.includes('deflate')) return 'deflate';
28
23
  return null;
29
24
  }
30
25
 
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
26
  const brotliFast = { [zlib.constants.BROTLI_PARAM_QUALITY]: 5 };
34
27
 
35
28
  function compress(enc: Encoding, data: string | Buffer): Buffer {
@@ -50,8 +43,6 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
50
43
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
51
44
  res.setHeader('Vary', 'Accept-Encoding');
52
45
  if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
53
- // A weak ETag over the rendered bytes: revalidation answers a bodiless 304 for dynamic
54
- // renders too …
55
46
  let hash = 0x811c9dc5;
56
47
  for (let i = 0; i < html.length; i++) {
57
48
  hash ^= html.charCodeAt(i);
@@ -73,8 +64,6 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
73
64
  }
74
65
  }
75
66
 
76
- // Copy a Web-standard Response's headers onto the Node response. set-cookie is the one
77
- // header that may legally repeat, and res.setHeader overwrites …
78
67
  function writeWebHeaders(web: any, res: any): void {
79
68
  const cookies = web.headers.getSetCookie?.() ?? [];
80
69
  web.headers.forEach((v: string, k: string) => {
@@ -84,90 +73,83 @@ function writeWebHeaders(web: any, res: any): void {
84
73
  if (cookies.length) res.setHeader('set-cookie', cookies);
85
74
  }
86
75
 
87
- // A middleware's short-circuit: a Web-standard Response (status, headers, body) written
88
- // straight to the Node response - a redirect, an auth wall, a rewrite.
89
76
  async function sendWebResponse(web: any, res: any): Promise<void> {
90
77
  writeWebHeaders(web, res);
91
78
  res.statusCode = web.status;
92
79
  res.end(Buffer.from(await web.arrayBuffer()));
93
80
  }
94
81
 
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
- */
82
+ // Send a rendered page document - through onResponse first .
102
83
  async function sendPage(req: any, res: any, ssrModule: any, hookCtx: any, page: any, routePath: string): Promise<void> {
103
84
  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.
85
+ if (page.redirect) {
86
+ const body = `<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${page.redirect}">${page.redirect}</a>.</p>`;
87
+ let headers: Record<string, any> = pageHeaders(ssrModule, routePath, '');
88
+ if (hookCtx) {
89
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(body, {
90
+ status,
91
+ headers: { 'content-type': 'text/html; charset=utf-8', location: page.redirect, ...headers },
92
+ }));
93
+ status = out.status;
94
+ headers = webHeadersToNode(out);
95
+ }
96
+ headers.location = page.redirect;
97
+ res.statusCode = status;
98
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
99
+ res.setHeader('Location', page.redirect);
100
+ for (const [k, v] of Object.entries(headers)) if (k !== 'location') res.setHeader(k, v);
101
+ res.end(body);
102
+ return;
103
+ }
106
104
  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);
105
+ let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
110
106
  let headers: Record<string, any> = pageHeaders(ssrModule, routePath, nonce);
111
107
  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
108
  const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
115
109
  status,
116
110
  headers: { 'content-type': 'text/html; charset=utf-8', ...headers },
117
111
  }));
118
112
  status = out.status;
119
113
  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
114
  html = out.bodyUsed ? html : await out.text();
123
115
  }
124
116
  sendHtml(req, res, status, html, headers);
125
117
  }
126
118
 
127
- // Static files: raw + both compressed forms cached per mtime (dev rebuilds change mtime;
128
- // preview never does).
129
119
  const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
130
120
 
131
- // P0-0 (bug report): `--port N` (or `--port=N`), the same override the PORT env gives, as
132
- // an argument …
133
121
  const __portArg = process.argv.find((a) => a === '--port' || a.startsWith('--port='));
134
122
  if (__portArg) {
135
123
  const __v = __portArg.includes('=') ? __portArg.slice('--port='.length) : process.argv[process.argv.indexOf(__portArg) + 1];
136
124
  if (__v && Number(__v) > 0) process.env.PORT = __v;
137
125
  }
138
126
 
139
- // (the "the framework is real" gate): the CLI builds ANY project, not just this repo's
140
- // demo.
141
127
  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 …
144
128
  const OUT_DIR = path.join(process.cwd(), 'dist');
145
- // PORT env override (default 3000): lets a preview server run beside a dev
146
- // server on the same machine - the e2e ISR test does exactly that.
147
129
  const PORT = Number(process.env.PORT) || 3000;
148
130
 
149
- /**
150
- * Import dist/server.js, cached until the file changes on disk.
151
- *
152
- * The dev server rebuilds it on file changes, so a plain import() would
153
- * serve the cached (stale) module - re-import when mtime moves. But the
154
- * import must NOT be per-request: server state (stores mutated by server
155
- * actions) lives in that module, and a fresh import per request would
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.
166
- */
131
+ // Import dist/server.js, cached until the file changes on disk. Preview and serve never rebuild, so they import dist/server.js itself.
167
132
  let serverModule: any = null;
168
133
  let serverMtime = -1;
169
134
  let serverVersion = 0;
170
135
 
136
+ function loadDotEnv(dir: string): void {
137
+ try {
138
+ const raw = fs.readFileSync(path.join(dir, '.env'), 'utf-8');
139
+ for (const line of raw.split(/\r?\n/)) {
140
+ const t = line.trim();
141
+ if (!t || t.startsWith('#')) continue;
142
+ const eq = t.indexOf('=');
143
+ if (eq <= 0) continue;
144
+ const k = t.slice(0, eq).trim();
145
+ let v = t.slice(eq + 1).trim();
146
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
147
+ if (!(k in process.env)) process.env[k] = v;
148
+ }
149
+ } catch { }
150
+ }
151
+ loadDotEnv(process.cwd());
152
+
171
153
  async function loadServer(): Promise<any> {
172
154
  const file = path.join(OUT_DIR, 'server.js');
173
155
  const mtimeMs = fs.statSync(file).mtimeMs;
@@ -186,32 +168,37 @@ async function loadServer(): Promise<any> {
186
168
  }
187
169
 
188
170
  async function build(): Promise<void> {
189
- // The build reports the bundle mode ('inline' | 'split') so the
190
- // shell follows it for every document, header and streaming tag it emits
191
171
  const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR);
192
- // The previous build's prerendered output must not survive: a route that stopped being
193
- // static (it started reading getContext() or $store()) would otherwise leave its old
194
- // baked …
195
172
  await clearPrerendered(OUT_DIR);
196
173
  setBundleMode(bundle);
197
174
  const skipped = await prerender(routes);
198
- // The broken-route manifest: the server reads it to pick the buffered path for these
199
- // routes, so their real 500 status survives (a flushed response cannot change its
200
- // status).
201
175
  await fs.promises.writeFile(path.join(OUT_DIR, 'broken.json'), JSON.stringify(skipped));
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.
204
176
  const ssrModule = await loadServer();
205
177
  await fs.promises.writeFile(path.join(OUT_DIR, 'headers.json'), JSON.stringify({
206
178
  default: securityHeaders(getClientSource()),
207
179
  routes: ssrModule.routeHeaders ?? [],
208
180
  }));
209
- // Precompressed brotli siblings (dist/<file>.br) for the Go single binary. The binary
210
- // embeds dist/ verbatim …
211
181
  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
182
  await analyze(OUT_DIR, (ssrModule.dynamicRoutes as string[] | undefined) ?? []);
183
+
184
+ if (argv.includes('--static')) {
185
+ const dyn = (ssrModule.dynamicRoutes as string[] | undefined) ?? [];
186
+ const unbakedApi = Object.entries((ssrModule.apiPrerender ?? {}) as Record<string, boolean>)
187
+ .filter(([, baked]) => !baked)
188
+ .map(([routePath]) => routePath);
189
+ const paramless = routes
190
+ .filter((r) => r.paramNames.length > 0 && !((ssrModule.routeParams ?? {}) as Record<string, unknown>)[r.routePath])
191
+ .map((r) => r.routePath);
192
+ const problems = [...new Set([...dyn, ...unbakedApi, ...paramless, ...skipped])];
193
+ if (problems.length > 0) {
194
+ console.error('rosetack: --static export refused - these routes need a server:');
195
+ for (const p of problems) console.error(` ${p}`);
196
+ console.error('(getContext()/$store()/$query(), csp.nonce, buffer = true, an unbaked /api route, a param route with no export const params, or a route the middleware walled)');
197
+ console.error('drop --static to build the normal dist (the dynamic half renders on demand on Node/edge)');
198
+ process.exit(1);
199
+ }
200
+ console.log('rosetack: static export verified - every route is a baked file, no server needed');
201
+ }
215
202
  }
216
203
 
217
204
  /**
@@ -293,8 +280,6 @@ async function analyze(outDir: string, dynamic: string[]): Promise<void> {
293
280
  */
294
281
  async function clearPrerendered(dir: string, depth = 0): Promise<void> {
295
282
  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
283
  if (depth === 0 && e.name === 'locales' && e.isDirectory()) continue;
299
284
  const p = path.join(dir, e.name);
300
285
  if (e.isDirectory()) {
@@ -327,36 +312,26 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
327
312
  const ssrModule = await loadServer();
328
313
  const skipped: string[] = [];
329
314
  const write = async (routePath: string) => {
330
- // a synthetic cookie-less request: the middleware runs at build time too, and a route
331
- // it short-circuits (an auth wall, a maintenance rewrite) simply is not static …
332
315
  const mw = await ssrModule.runMiddleware({ method: 'GET', url: routePath, headers: {} });
333
316
  if (mw) {
334
317
  console.error(`prerender skipped for ${routePath}: the middleware short-circuits at build time`);
335
318
  skipped.push(routePath);
336
319
  return;
337
320
  }
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
321
  ssrModule.setQuery?.({});
341
322
  const page = await ssrModule.renderPage(routePath);
342
323
  if (page.status === 500) {
343
- // The route's render failed and the error page rendered instead. Do NOT bake that
344
- // into a static file: a static server can only answer 200 …
345
324
  console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
346
325
  skipped.push(routePath);
347
326
  return;
348
327
  }
349
328
  const routeDir = routePath === '/' ? OUT_DIR : path.join(OUT_DIR, routePath.slice(1));
350
329
  await fs.promises.mkdir(routeDir, { recursive: true });
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));
330
+ await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, '', page.shell !== false));
354
331
  console.log(`prerendered ${routePath} -> ${path.relative(process.cwd(), path.join(routeDir, 'index.html'))}`);
355
332
  };
356
333
 
357
334
  for (const info of routes) {
358
- // routes that read the request context (getContext()) or a shared store ($store()) are
359
- // dynamic by construction: the bag is per-request and the store is per-process …
360
335
  if ((ssrModule.dynamicRoutes as string[]).includes(info.routePath)) {
361
336
  console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
362
337
  continue;
@@ -365,15 +340,11 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
365
340
  try {
366
341
  await write(info.routePath);
367
342
  } catch (err) {
368
- // One broken route (e.g. throwing $data) must not fail the whole build;
369
- // it simply keeps rendering on demand.
370
343
  console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
371
344
  skipped.push(info.routePath);
372
345
  }
373
346
  continue;
374
347
  }
375
- // dynamic route: enumerate the exported params map, if any. The maps are re-exported by
376
- // the server bundle (routeParams) …
377
348
  try {
378
349
  const paramsExport = (ssrModule.routeParams as Record<string, unknown>)?.[info.routePath];
379
350
  const raw = typeof paramsExport === 'function' ? await (paramsExport as () => unknown)() : paramsExport;
@@ -386,9 +357,6 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
386
357
  }
387
358
  }
388
359
 
389
- // API routes that opt in (export const prerender = true) bake their GET body into
390
- // dist/api/<route>.json: the Go single binary then serves the read-only API with zero
391
- // Node.
392
360
  const apiPrerender = (ssrModule.apiPrerender as Record<string, boolean>) ?? {};
393
361
  for (const [routePath, on] of Object.entries(apiPrerender)) {
394
362
  if (!on) continue;
@@ -421,17 +389,17 @@ function enumerateParams(pattern: string, names: string[], raw: Record<string, u
421
389
  let i = 0;
422
390
  return pattern
423
391
  .split('/')
424
- .map((seg) => (seg.startsWith(':') ? encodeURIComponent(values[i++]) : seg))
392
+ .map((seg) => {
393
+ if (seg.startsWith(':')) return encodeURIComponent(values[i++]);
394
+ if (seg.startsWith('*')) return values[i++].split('/').map(encodeURIComponent).join('/');
395
+ return seg;
396
+ })
425
397
  .join('/');
426
398
  });
427
399
  }
428
400
 
429
- // Extensions the static branch serves without touching the router: assets keep their fast
430
- // path even when a middleware exists (a middleware guards pages, not files).
431
401
  const ASSET_EXT = new Set(['.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.woff', '.woff2', '.txt', '.xml']);
432
402
 
433
- // Response headers for a page document: the strict CSP (hashed over the exact inlined
434
- // bundle + bootstrap bytes …
435
403
  function pageHeaders(ssrModule: any, pathname: string, nonce = ''): Record<string, string> {
436
404
  const headers: Record<string, string> = {};
437
405
  for (const [k, v] of Object.entries(securityHeaders(getClientSource(), nonce))) headers[k.toLowerCase()] = v;
@@ -449,8 +417,6 @@ function nonceFor(ssrModule: any, pathname: string): string {
449
417
  return ssrModule.cspNonce?.(pathname) ? mintNonce() : '';
450
418
  }
451
419
 
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).
454
420
  const isrBusy = new Set<string>();
455
421
  function revalidateInBackground(routePath: string, filePath: string): void {
456
422
  if (isrBusy.has(filePath)) return;
@@ -458,14 +424,10 @@ function revalidateInBackground(routePath: string, filePath: string): void {
458
424
  void (async () => {
459
425
  try {
460
426
  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
427
  ssrModule.setQuery?.({});
464
428
  const page = await ssrModule.renderPage(routePath);
465
429
  if (page.status === 200) {
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));
430
+ await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, '', page.shell !== false));
469
431
  fileCache.delete(filePath);
470
432
  console.log(`rosetack: revalidated ${routePath} in the background`);
471
433
  }
@@ -477,9 +439,6 @@ function revalidateInBackground(routePath: string, filePath: string): void {
477
439
  })();
478
440
  }
479
441
 
480
- // --- production server posture -------------------------------------- "Can run a real app"
481
- // is a threshold …
482
-
483
442
  /** A request body is bounded. 1 MB holds any form and any JSON API call a
484
443
  * site this size makes; a deployment that needs more sets it explicitly. */
485
444
  const MAX_BODY = Number(process.env.rosetack_MAX_BODY) || 1024 * 1024;
@@ -506,7 +465,6 @@ function readBody(req: any, res: any, onDone: (body: any) => void): void {
506
465
  chunks.push(c);
507
466
  });
508
467
  req.on('end', () => { if (!refused) onDone(Buffer.concat(chunks)); });
509
- // an aborted upload must not throw an unhandled 'error' and take the process down with it
510
468
  req.on('error', () => {});
511
469
  }
512
470
 
@@ -584,7 +542,7 @@ async function hookContext(req: any): Promise<{
584
542
  for (const [k, v] of Object.entries(req.headers)) {
585
543
  if (v !== undefined) headers[k] = Array.isArray(v) ? v.join(', ') : String(v);
586
544
  }
587
- const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
545
+ const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
588
546
  method: req.method || 'GET',
589
547
  headers,
590
548
  });
@@ -604,14 +562,9 @@ function webHeadersToNode(web: any): Record<string, any> {
604
562
  return out;
605
563
  }
606
564
 
607
- // --- dev-only live reload + state bridge --- The dev server rebuilds on change …
608
565
  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
566
  let devResume: string | null = null;
612
567
  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
568
  let devMode = false;
616
569
 
617
570
  function devReload(req: any, res: any): void {
@@ -629,7 +582,7 @@ function devSaveState(req: any, res: any): void {
629
582
  let body = '';
630
583
  req.on('data', (c: any) => {
631
584
  body += c;
632
- if (body.length > 1e6) req.destroy(); // a state snapshot is kilobytes; refuse a runaway
585
+ if (body.length > 1e6) req.destroy();
633
586
  });
634
587
  req.on('end', () => {
635
588
  try {
@@ -651,14 +604,36 @@ function devNotify(): void {
651
604
  }
652
605
  }
653
606
 
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
- */
607
+ let devBuild: Promise<void> | null = null;
608
+ let devBuildPending = false;
609
+
610
+ function startDevBuild(): Promise<void> {
611
+ if (!devBuild) {
612
+ devBuild = (async () => {
613
+ try {
614
+ console.log('Rebuilding...');
615
+ await build();
616
+ devNotify();
617
+ } catch (err) {
618
+ console.error('Build failed (server still running):', err instanceof Error ? err.message : String(err));
619
+ } finally {
620
+ devBuild = null;
621
+ devBuildPending = false;
622
+ }
623
+ })();
624
+ }
625
+ return devBuild;
626
+ }
627
+
628
+ /** Q2: the promise to await before routing, or null when nothing is building. */
629
+ function settleDevBuild(): Promise<void> | null {
630
+ if (!devMode || (!devBuild && !devBuildPending)) return null;
631
+ return startDevBuild();
632
+ }
633
+
634
+ // Wrap a dev response so every HTML document carries the bridge (and the resumed state, once).
635
+ let invalidateHook: (() => void) | null = null;
636
+
662
637
  function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => void {
663
638
  devMode = true;
664
639
  return (req, res) => {
@@ -666,8 +641,6 @@ function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => v
666
641
  if (url.startsWith('/__rosetack_reload')) return devReload(req, res);
667
642
  if (url.startsWith('/__rosetack_state') && req.method === 'POST') return devSaveState(req, res);
668
643
  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
644
  const seed = devResume;
672
645
  devResume = null;
673
646
  const isHtml = () => String(res.getHeader('content-type') || '').includes('text/html');
@@ -675,9 +648,9 @@ function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => v
675
648
  if (injected || !isHtml()) return chunk;
676
649
  const s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
677
650
  const at = s.indexOf('<head>');
678
- if (at < 0) return chunk; // not a document (an asset, a JSON body): leave it alone
651
+ if (at < 0) return chunk;
679
652
  injected = true;
680
- const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\//g, '<\\/')}</script>` : '';
653
+ const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\/script>/g, '')}</script>` : '';
681
654
  const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
682
655
  return Buffer.isBuffer(chunk) ? Buffer.from(out, 'utf8') : out;
683
656
  };
@@ -694,8 +667,6 @@ function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => v
694
667
 
695
668
  function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any) => void {
696
669
  return (req, res) => {
697
- // The origin guard runs before everything else - middleware, api dispatch, the static
698
- // lookup - because a cross-site write must not reach any of them.
699
670
  const blocked = crossSiteWrite(req);
700
671
  if (blocked) {
701
672
  res.statusCode = blocked.status;
@@ -703,25 +674,52 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
703
674
  res.end(blocked.body);
704
675
  return;
705
676
  }
706
- // Everything below needs the server module (API dispatch, POST actions, SSR), so load
707
- // it once up front: the import is cached until dist/server.js changes on disk …
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 …
677
+ if (req.method === 'POST' && (req.url || '').startsWith('/__rosetack/revalidate')) {
678
+ const token = process.env.rosetack_REVALIDATE_TOKEN || '';
679
+ if (!token) { res.statusCode = 404; res.end(); return; }
680
+ if (req.headers['x-rosetack-token'] !== token) {
681
+ res.statusCode = 403; res.setHeader('content-type', 'application/json');
682
+ res.end(JSON.stringify({ error: 'invalid token' })); return;
683
+ }
684
+ let body = '';
685
+ req.on('data', (c) => { body += c; if (body.length > 1e6) req.destroy(); });
686
+ req.on('end', () => {
687
+ try {
688
+ const payload = JSON.parse(body || '{}');
689
+ if (invalidateHook) invalidateHook();
690
+ res.setHeader('content-type', 'application/json');
691
+ res.end(JSON.stringify({ revalidated: true, scope: payload.all ? 'all' : 'paths' }));
692
+ } catch (e: any) {
693
+ res.statusCode = 400; res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
694
+ }
695
+ });
696
+ return;
697
+ }
698
+ const want = pathnameOf(req.url || '/');
699
+ const canonical = want.replace(/\/+$/, '') || '/';
700
+ if (canonical !== want) {
701
+ let search = '';
702
+ try { search = new URL(req.url || '/', 'http://localhost').search; } catch { }
703
+ const to = canonical + search;
704
+ res.statusCode = 308;
705
+ res.setHeader('Location', to);
706
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
707
+ res.end(`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${to}">${to}</a>.</p>`);
708
+ return;
709
+ }
710
+ const settled = settleDevBuild();
711
+ const ready = settled ? settled.then(() => loadServer()) : loadServer();
712
+ ready.then(async (ssrModule: any) => {
711
713
  const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true
712
714
  ? await hookContext(req)
713
715
  : null;
714
716
  if (hookCtx) {
715
717
  const short = await ssrModule.runRequestHooks(hookCtx);
716
718
  if (short) {
717
- // the short-circuit rides through onResponse like every other
718
- // response, so a header-adding hook sees it too
719
719
  await sendWebResponse(await ssrModule.runResponseHooks(hookCtx, short), res);
720
720
  return;
721
721
  }
722
722
  }
723
- // Middleware (pages/_middleware.rose) runs exactly once per request, before anything
724
- // else: a returned Response short-circuits the whole request …
725
723
  const apiPath0 = pathnameOf(req.url);
726
724
  const isPagePost = req.method === 'POST' && !ssrModule.isApi(apiPath0);
727
725
  if (!isPagePost && ssrModule.middleware) {
@@ -731,8 +729,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
731
729
  return;
732
730
  }
733
731
  }
734
- // API routes (pages/api/*.rose) dispatch FIRST: the /api namespace answers JSON,
735
- // never the static shell or an HTML page …
736
732
  const apiPath = pathnameOf(req.url);
737
733
  if (ssrModule.isApi(apiPath)) {
738
734
  readBody(req, res, async (body) => {
@@ -746,15 +742,15 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
746
742
  headers,
747
743
  body: body.length > 0 ? body : undefined,
748
744
  });
749
- // P0-1: an api handler reads the query from its Request's URL (the full one,
750
- // query included) …
751
745
  ssrModule.setQuery?.(queryOf(req.url));
746
+ if ((req.method || 'GET') !== 'GET') ssrModule.invalidateRenderCache?.();
752
747
  let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
753
748
  if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
754
749
  writeWebHeaders(apiRes, res);
755
750
  res.statusCode = apiRes.status;
756
751
  res.end(Buffer.from(await apiRes.arrayBuffer()));
757
- } catch {
752
+ } catch (err) {
753
+ console.error(`rosetack: ${req.method} ${req.url} api handler failed:`, err instanceof Error ? err.stack ?? err.message : String(err));
758
754
  res.statusCode = 500;
759
755
  res.setHeader('Content-Type', 'application/json');
760
756
  res.end('{"error":"api handler failed"}');
@@ -763,16 +759,12 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
763
759
  return;
764
760
  }
765
761
 
766
- // POST: run the matched route's server action (progressive-enhancement form). This
767
- // must precede the static lookup: prerendered files exist on disk and would otherwise …
768
762
  if (req.method === 'POST') {
769
763
  readBody(req, res, async (body) => {
770
764
  try {
771
765
  const form = await new Response(body, {
772
766
  headers: { 'content-type': req.headers['content-type'] || 'application/x-www-form-urlencoded' },
773
767
  }).formData();
774
- // the middleware pass for page POSTs: it rides with the parsed FormData so it
775
- // can read form fields, and its context seeds the action + render below
776
768
  if (ssrModule.middleware) {
777
769
  const mw = await ssrModule.runMiddleware(req, form);
778
770
  if (mw) {
@@ -780,14 +772,11 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
780
772
  return;
781
773
  }
782
774
  }
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
775
  ssrModule.setQuery?.(queryOf(req.url));
776
+ ssrModule.invalidateRenderCache?.();
786
777
  const page = await ssrModule.renderPage(pathnameOf(req.url || '/'), form);
787
778
  await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
788
779
  } 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
780
  console.error(`rosetack: POST ${pathnameOf(req.url || '/')} failed:`, err instanceof Error ? err.stack : err);
792
781
  if (!res.headersSent) {
793
782
  res.statusCode = 400;
@@ -798,8 +787,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
798
787
  return;
799
788
  }
800
789
 
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
790
  let safe = path.normalize(pathnameOf(req.url || '/')).replace(/^(\.\.(\/)?)+/, '');
804
791
  if (safe === '\\' || safe === '/') safe = '/';
805
792
  let filePath = path.join(dir, safe);
@@ -810,26 +797,19 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
810
797
  if (fs.existsSync(pubFile)) filePath = pubFile;
811
798
  }
812
799
 
813
- // Directory -> index.html (prerendered routes live at /<route>/index.html)
814
800
  if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
815
801
  filePath = path.join(filePath, 'index.html');
816
802
  }
817
803
 
818
- // Build-time precompression siblings (dist/<file>.br, read by the Go binary) are internal
819
- // artifacts.
820
804
  if (/\.(?:br|gz)$/i.test(safe)) {
821
805
  const base = filePath.replace(/\.(?:br|gz)$/i, '');
822
806
  if (fs.existsSync(base)) filePath = base;
823
807
  }
824
808
 
825
- // Serve real files directly - compressed + conditionally cached, so a repeat visit
826
- // costs a 304 instead of the full document. Assets always take this path.
827
809
  const isAsset = ASSET_EXT.has(path.extname(safe).toLowerCase());
828
810
  const isDynamic = !isAsset && (ssrModule.dynamicRoutes as string[] | undefined)?.includes(pathnameOf(req.url));
829
811
  if (!isDynamic && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
830
812
  const st = fs.statSync(filePath);
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 …
833
813
  const rev = isAsset ? undefined : ((ssrModule.revalidate as { pattern: string; seconds: number }[]) || [])
834
814
  .find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
835
815
  if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1000) {
@@ -841,8 +821,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
841
821
  entry = {
842
822
  mtimeMs: st.mtimeMs,
843
823
  raw,
844
- // A file's compressed forms are computed ONCE and then served from this cache
845
- // forever …
846
824
  br: zlib.brotliCompressSync(raw),
847
825
  gzip: zlib.gzipSync(raw, { level: 9 }),
848
826
  etag: `W/"${st.size}-${st.mtimeMs}"`,
@@ -862,19 +840,13 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
862
840
  '.mp4': 'video/mp4',
863
841
  '.mp3': 'audio/mpeg',
864
842
  };
865
- // An ISR route's file is swapped every `revalidate` seconds, so the cache must not
866
- // outlive the window: revalidate every visit (a bodiless 304 when nothing changed) …
867
843
  const fileHeaders: Record<string, string> = {
868
844
  'Content-Type': types[ext] || 'application/octet-stream',
869
- 'Cache-Control': rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
845
+ 'Cache-Control': devMode ? 'no-cache' : rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
870
846
  'ETag': entry.etag,
871
847
  'Vary': 'Accept-Encoding',
872
848
  };
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
849
  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
850
  let status = 200;
879
851
  if (hookCtx) {
880
852
  const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers: fileHeaders }));
@@ -888,8 +860,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
888
860
  res.end();
889
861
  return;
890
862
  }
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
863
  const enc = devMode ? null : pickEncoding(req);
894
864
  res.statusCode = status;
895
865
  if (enc) {
@@ -901,26 +871,15 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
901
871
  return;
902
872
  }
903
873
 
904
- // Otherwise render the route via SSR (dynamic routes, 404s, and every page route when
905
- // a middleware exists: its per-request context must be live …
906
874
  let broken = new Set<string>();
907
875
  try {
908
876
  broken = new Set(JSON.parse(fs.readFileSync(path.join(dir, 'broken.json'), 'utf-8')));
909
877
  } catch { /* no manifest: nothing known-broken */ }
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
878
  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
879
  ssrModule.setQuery?.(queryOf(req.url));
916
- // P0-2: `buffer = true` routes take the buffered path even when they could stream …
917
880
  if (!dev && !broken.has(safe2) && !ssrModule.isBuffered?.(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
918
881
  const enc = pickEncoding(req);
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
882
  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
883
  const nonce = nonceFor(ssrModule, safe2);
925
884
  let headers: Record<string, any> = pageHeaders(ssrModule, safe2, nonce);
926
885
  if (hookCtx) {
@@ -938,8 +897,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
938
897
  res.setHeader('Content-Encoding', enc);
939
898
  const compressor = createCompressor(enc);
940
899
  compressor.pipe(res);
941
- // The shell must reach the socket NOW. Without a flush zlib emits nothing until
942
- // end() …
943
900
  let flushed = false;
944
901
  write = (chunk) => {
945
902
  compressor.write(chunk);
@@ -948,45 +905,55 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
948
905
  compressor.flush(zlib.constants.Z_FULL_FLUSH);
949
906
  }
950
907
  };
951
- // pipe() forwards data but not errors, and an unhandled 'error' event kills the
952
- // worker.
953
908
  compressor.on('error', () => res.destroy());
954
909
  done = () => compressor.end();
955
910
  } else {
956
911
  write = (chunk) => res.write(chunk);
957
912
  done = () => res.end();
958
913
  }
959
- // The streamed shell opens before the render, so its <html
960
- // lang>/<dir> come from the pathname (the server bundle's docAttrs)
961
914
  const doc = ssrModule.docAttrs(safe2);
962
- await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
915
+ await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir, !ssrModule.shellOff(safe2)), clientScriptTag(getClientSource(), nonce));
963
916
  done();
964
917
  return;
965
918
  }
966
- // buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
967
- // = false routes …
968
- const page = await ssrModule.renderPage(safe2);
919
+ const hasQuery = (req.url || '').includes('?');
920
+ const page = req.method === 'GET' && !hasQuery && ssrModule.renderPageCached
921
+ ? await ssrModule.renderPageCached(safe2, String(req.headers.cookie || ''))
922
+ : await ssrModule.renderPage(safe2);
969
923
  await sendPage(req, res, ssrModule, hookCtx, page, safe2);
970
924
  }).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
925
  console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
974
926
  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
927
  res.destroy();
978
928
  return;
979
929
  }
980
930
  res.statusCode = 500;
981
931
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
982
- res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>');
932
+ const devErr = err as { file?: string; line?: number | string; hint?: string };
933
+ let devDetail = '';
934
+ if (process.env.rosetack_DEV === '1' && err) {
935
+ const stack = err instanceof Error ? (err.stack || '').split('\n').slice(1, 7).join('\n') : '';
936
+ devDetail =
937
+ '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">' +
938
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + escapeHtml(req.url || '') + '</div>' +
939
+ '<div style="margin:10px 0 0;color:#ffd479">' + escapeHtml(err instanceof Error ? err.message : err) + '</div>' +
940
+ (devErr.file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + escapeHtml(devErr.file) + (devErr.line != null ? ':' + devErr.line : '') + '</div>' : '') +
941
+ (devErr.hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + escapeHtml(devErr.hint) + '</div>' : '') +
942
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + escapeHtml(stack) + '</pre>' : '') +
943
+ '</div>';
944
+ }
945
+ res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail);
983
946
  });
984
947
  };
985
948
  }
986
949
 
950
+ /** HTML-escape for the dev error overlay (F10). */
951
+ function escapeHtml(v: unknown): string {
952
+ return String(v ?? '').replace(/[<>&"]/g, (ch) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[ch] as string));
953
+ }
954
+
987
955
  /** Strip the query string: routing matches the pathname, handlers read the full URL. */
988
- function pathnameOf(url: string | undefined): string {
989
- try {
956
+ function pathnameOf(url: string | undefined): string { try {
990
957
  return new URL(url || '/', 'http://localhost').pathname;
991
958
  } catch {
992
959
  return (url || '/').split('?')[0];
@@ -1059,54 +1026,69 @@ async function freePort(from: number): Promise<number> {
1059
1026
  }
1060
1027
 
1061
1028
  /**
1062
- * The version from package.json - one source of truth, no constant to drift.
1063
- * Resolved from THIS module (not the cwd): the banner names the framework's
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.
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.
1067
1041
  */
1068
1042
  function version(): string {
1069
- for (const rel of ['../../package.json', '../package.json']) {
1043
+ for (const rel of ['../FRAMEWORK_VERSION', '../../FRAMEWORK_VERSION', '../../package.json', '../package.json']) {
1070
1044
  try {
1071
- const v = JSON.parse(fs.readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf-8')).version;
1045
+ const raw = fs.readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf-8');
1046
+ const v = rel.endsWith('FRAMEWORK_VERSION') ? raw.trim() : JSON.parse(raw).version;
1072
1047
  if (v) return v;
1073
1048
  } catch { /* not this layout */ }
1074
1049
  }
1075
1050
  return '0.0.0';
1076
1051
  }
1077
1052
 
1053
+ /**
1054
+ * The PROJECT's version, when it is a different package from the framework.
1055
+ * A project that embeds the CLI source (the way a real app does) has its own
1056
+ * package.json, and a banner that named only that one left the operator
1057
+ * unable to tell which FRAMEWORK build was actually running - the two
1058
+ * versions advanced independently for weeks. The banner now names both:
1059
+ * "rosetack v0.4.0 - project: my-app v0.1.1". Absent (running inside the
1060
+ * framework repo itself, or a directory with no package.json) -> nothing.
1061
+ */
1062
+ function projectTag(): string {
1063
+ try {
1064
+ const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8'));
1065
+ if (!pkg.version || pkg.name === 'rosetack') return '';
1066
+ return ` - project: ${pkg.name} v${pkg.version}`;
1067
+ } catch {
1068
+ return '';
1069
+ }
1070
+ }
1071
+
1078
1072
  async function dev(): Promise<void> {
1079
- console.log(`🌹 RoseTack v${version()} dev server starting...`);
1073
+ devMode = true;
1074
+ process.env.rosetack_DEV = '1';
1075
+ console.log(`🌹 RoseTack v${version()}${projectTag()} dev server starting...`);
1080
1076
  try {
1081
1077
  await build();
1082
1078
  } catch (err) {
1083
- // A broken .rose file must not prevent the server from starting; the
1084
- // watcher below rebuilds as soon as the file is fixed.
1085
1079
  console.error('Initial build failed (server still running):', err instanceof Error ? err.message : err);
1086
1080
  }
1087
1081
 
1088
1082
  let timeout: any;
1089
1083
  fs.watch(SRC_DIR, { recursive: true }, () => {
1084
+ devBuildPending = true;
1090
1085
  clearTimeout(timeout);
1091
- timeout = setTimeout(async () => {
1092
- try {
1093
- console.log('Rebuilding...');
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();
1098
- } catch (err) {
1099
- // Never let a user-code error kill the dev server.
1100
- console.error('Build failed (server still running):', err instanceof Error ? err.message : String(err));
1101
- }
1102
- }, 200);
1086
+ timeout = setTimeout(() => { void startDevBuild(); }, 200);
1103
1087
  });
1104
1088
 
1105
1089
  const http = await import('http');
1106
1090
  const server = http.createServer(devWrap(serveStatic(OUT_DIR, false, true)));
1107
1091
 
1108
- // P0-0: an occupied port hops to the next free one (and says so) instead of
1109
- // killing the server with EADDRINUSE.
1110
1092
  listenFree(server, PORT, (port) => {
1111
1093
  console.log('🌹 http://localhost:' + port);
1112
1094
  });
@@ -1115,56 +1097,26 @@ async function dev(): Promise<void> {
1115
1097
  async function preview(): Promise<void> {
1116
1098
  await build();
1117
1099
  const http = await import('http');
1118
- // isr=true: routes exporting `revalidate = N` are served stale-then-swapped
1119
- // from disk . Dev passes nothing (it rebuilds on change).
1120
1100
  const server = http.createServer(serveStatic(OUT_DIR, true));
1121
1101
 
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
1102
  listenFree(server, PORT, (port) => {
1125
- console.log(`🌹 RoseTack v${version()} preview at http://localhost:` + port);
1103
+ console.log(`🌹 RoseTack v${version()}${projectTag()} preview at http://localhost:${port}`);
1126
1104
  });
1127
1105
  }
1128
1106
 
1129
- /**
1130
- * `rosetack serve` runs what `build` produced - no rebuild, no
1131
- * watcher, production semantics (a preview that re-rendered on the fly
1132
- * could serve a half-written file). Multi-core through the stdlib cluster:
1133
- * the primary supervises and serves no traffic, the workers serve; every
1134
- * request is logged; SIGTERM drains in-flight work and exits.
1135
- *
1136
- * Boundaries, stated plainly:
1137
- * - each worker is its own process with its own dist/server.js module.
1138
- * Module-scope state is therefore per-worker, which is what $store()
1139
- * fixes: writes broadcast through the primary, reads stay
1140
- * local-synchronous. ISR revalidation may run in more than one worker
1141
- * for one route: the guard is per-worker and the cost is one duplicate
1142
- * render.
1143
- * - the signal-driven drain is POSIX behavior. On Windows a kill() is
1144
- * abrupt by the platform's design, so the worker instead exits on the
1145
- * primary's death (the disconnect handler below) - a killed primary must
1146
- * never leave orphans holding the port.
1147
- */
1107
+
1148
1108
  async function serve(): Promise<void> {
1149
1109
  if (!fs.existsSync(path.join(OUT_DIR, 'server.js'))) {
1150
1110
  console.error(`rosetack: ${OUT_DIR} has no server.js - run rosetack build first`);
1151
1111
  process.exit(1);
1152
1112
  }
1153
- // .default: node:cluster is an `export =` module, so the dynamic import
1154
- // hands back the namespace with the real module on `.default`
1155
1113
  const cluster = (await import('node:cluster')).default as any;
1156
- // Round-robin the accepts between workers. The default leaves the handout to the
1157
- // operating system …
1158
1114
  cluster.schedulingPolicy = cluster.SCHED_RR;
1159
1115
  const os = await import('node:os');
1160
1116
  const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
1161
1117
  if (cluster.isPrimary) {
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
1118
  const port = await freePort(Number(process.env.PORT) || 3000);
1165
1119
  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 …
1168
1120
  cluster.on('message', (worker: any, msg: any) => {
1169
1121
  if (!msg || msg.type !== 'rosetack:store') return;
1170
1122
  for (const w of Object.values<any>(cluster.workers ?? {})) {
@@ -1179,41 +1131,120 @@ async function serve(): Promise<void> {
1179
1131
  process.on('SIGTERM', stop);
1180
1132
  process.on('SIGINT', stop);
1181
1133
  cluster.on('exit', () => { if (--live <= 0) process.exit(0); });
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)`);
1134
+ console.log(`🌹 RoseTack v${version()}${projectTag()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
1183
1135
  return;
1184
1136
  }
1185
- // worker the primary's death is the worker's death: no orphan holding the port
1186
1137
  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
1138
  let servicePlugins: any[] = [];
1190
1139
  try {
1191
1140
  servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
1192
1141
  } catch (err) {
1193
- console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : err);
1142
+ console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
1143
+ }
1144
+ const storeBridge = {
1145
+ install: (send: ((name: string, value: unknown) => void) | null) => {
1146
+ try { serverModule?.__installStoreTransport?.(send); } catch { /* a stale dist: no bridge, no crash */ }
1147
+ },
1148
+ deliver: (name: string, value: unknown) => {
1149
+ try { serverModule?.__deliverStorePatch?.(name, value); } catch { }
1150
+ },
1151
+ };
1152
+ try {
1153
+ const hooksMod = await loadServer();
1154
+ invalidateHook = () => { try { hooksMod.invalidateRenderCache(); } catch { } };
1155
+ } catch (err) {
1156
+ console.error('rosetack: dist/server.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
1194
1157
  }
1195
1158
  const http = await import('node:http');
1196
- const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
1197
- // A client that stalls mid-request is dropped instead of holding a worker;
1198
- // idle keep-alive sockets close so a drained worker can actually exit.
1159
+ const edgeReady = createEdgeHandler(OUT_DIR);
1160
+ edgeReady.then(async (handle) => {
1161
+ await ready;
1162
+ for (const r of (serverModule?.dynamicRoutes as string[] | undefined) || []) {
1163
+ if (r.includes(':')) continue;
1164
+ try {
1165
+ const res = await handle(new Request('http://localhost' + r));
1166
+ await res.arrayBuffer();
1167
+ } catch { /* a warm-up failure just means that route renders cold */ }
1168
+ }
1169
+ }).catch(() => {});
1170
+ const baseHandler = withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`);
1171
+ const earlyHintLinks: string[] = (() => {
1172
+ try {
1173
+ const html = fs.readFileSync(path.join(OUT_DIR, 'index.html'), 'utf8');
1174
+ const links: string[] = [];
1175
+ for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
1176
+ const v = `<${m[1]}>; rel=preload; as=script`;
1177
+ if (!links.includes(v)) links.push(v);
1178
+ }
1179
+ for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
1180
+ const href = /href="([^"]+)"/.exec(m[0])?.[1];
1181
+ if (href) { const v = `<${href}>; rel=preload; as=style`; if (!links.includes(v)) links.push(v); }
1182
+ }
1183
+ for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
1184
+ const v = `<${m[1]}>; rel=preload; as=style`;
1185
+ if (!links.includes(v)) links.push(v);
1186
+ }
1187
+ return links;
1188
+ } catch { return []; }
1189
+ })();
1190
+ let dynRouteSet: Set<string> | null = null;
1191
+ const dynRoutesOf = (): Set<string> => {
1192
+ const list = (serverModule?.dynamicRoutes as string[] | undefined) || [];
1193
+ if (!dynRouteSet || dynRouteSet.size !== list.length) dynRouteSet = new Set(list);
1194
+ return dynRouteSet;
1195
+ };
1196
+ const server = http.createServer(async (req: any, res: any) => {
1197
+ try {
1198
+ if ((req.method === 'GET' || req.method === 'HEAD') && dynRoutesOf().has(pathnameOf(req.url || '/'))) {
1199
+ const handle = await edgeReady;
1200
+ if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
1201
+ try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
1202
+ }
1203
+ const url = 'http://' + (req.headers.host || `localhost:${PORT}`) + (req.url || '/');
1204
+ const response = await handle(new Request(url, { method: req.method, headers: req.headers }));
1205
+ res.statusCode = response.status;
1206
+ response.headers.forEach((v: string, k: string) => res.setHeader(k, v));
1207
+ const htmlDoc = (response.headers.get('content-type') ?? '').startsWith('text/html');
1208
+ const enc = htmlDoc && req.method === 'GET' ? pickEncoding(req) : null;
1209
+ if (response.body && enc) {
1210
+ const raw = Buffer.from(await response.arrayBuffer());
1211
+ const etag = 'W/"' + createHash('sha1').update(raw).digest('base64url').slice(0, 24) + '"';
1212
+ if (req.headers['if-none-match'] === etag) {
1213
+ res.statusCode = 304;
1214
+ res.end();
1215
+ return;
1216
+ }
1217
+ const body = compress(enc, raw);
1218
+ res.setHeader('ETag', etag);
1219
+ res.setHeader('Content-Encoding', enc);
1220
+ res.setHeader('Content-Length', String(body.length));
1221
+ res.end(body);
1222
+ return;
1223
+ }
1224
+ if (response.body) {
1225
+ Readable.fromWeb(response.body as any).pipe(res);
1226
+ } else {
1227
+ res.end();
1228
+ }
1229
+ return;
1230
+ }
1231
+ } catch { /* any edge hiccup falls through to the proven pipeline */ }
1232
+ baseHandler(req, res);
1233
+ });
1199
1234
  server.requestTimeout = 30_000;
1200
- server.headersTimeout = 65_000; // must exceed requestTimeout
1235
+ server.headersTimeout = 65_000;
1201
1236
  server.keepAliveTimeout = 5_000;
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
1237
  listenFree(server, PORT, async (port) => {
1205
1238
  console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${port}`);
1206
1239
  for (const p of servicePlugins) {
1207
1240
  try {
1208
- await p.onServe({ port, workers });
1241
+ await p.onServe({ port, workers, store: storeBridge });
1209
1242
  } catch (err) {
1210
- console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : err);
1243
+ console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : String(err));
1211
1244
  }
1212
1245
  }
1213
1246
  });
1214
1247
  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
1248
  for (const p of servicePlugins) {
1218
1249
  if (!p.onShutdown) continue;
1219
1250
  try {
@@ -1224,28 +1255,94 @@ async function serve(): Promise<void> {
1224
1255
  console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
1225
1256
  }
1226
1257
  }
1227
- server.close(() => process.exit(0)); // finish what is in flight
1228
- server.closeIdleConnections?.(); // drop the idle keep-alive sockets
1229
- setTimeout(() => process.exit(0), 5000).unref(); // a stuck one must not hold the worker
1258
+ server.close(() => process.exit(0));
1259
+ server.closeIdleConnections?.();
1260
+ setTimeout(() => process.exit(0), 5000).unref();
1230
1261
  };
1231
1262
  process.on('SIGTERM', stop);
1232
1263
  process.on('SIGINT', stop);
1233
1264
  }
1234
1265
 
1266
+
1267
+ function templatesDir(): string | null {
1268
+ for (const rel of ['../../templates', '../templates']) {
1269
+ const p = fileURLToPath(new URL(rel, import.meta.url));
1270
+ if (fs.existsSync(p)) return p;
1271
+ }
1272
+ return null;
1273
+ }
1274
+
1275
+ /** The TypeScript-ready files every scaffolded project gets: the ambient
1276
+ * globals (editors and tsc both see them) and a strict tsconfig. */
1277
+ function writeTypeScriptReady(dir: string): void {
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
+ include: ['rosetack-env.d.ts', 'src/**/*.ts'],
1290
+ }, null, 2) + '\n');
1291
+ }
1292
+
1293
+
1294
+ function copyTemplate(dir: string, name: string, display: string): void {
1295
+ const base = templatesDir();
1296
+ const shipped = base ? path.resolve(base, name) : '';
1297
+ const src = fs.existsSync(shipped) ? shipped : path.resolve(name);
1298
+ if (!fs.existsSync(src) || !fs.statSync(src).isDirectory()) {
1299
+ const available = base ? fs.readdirSync(base).join(', ') : '(none found)';
1300
+ console.error(`rosetack: no template '${name}' - available: ${available} (or pass a path to any project directory)`);
1301
+ process.exit(1);
1302
+ }
1303
+ fs.cpSync(src, dir, {
1304
+ recursive: true,
1305
+ filter: (s) => !/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(s),
1306
+ });
1307
+ const pkgFile = path.join(dir, 'package.json');
1308
+ if (fs.existsSync(pkgFile)) {
1309
+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
1310
+ pkg.name = path.basename(dir);
1311
+ if (pkg.dependencies?.rosetack) pkg.dependencies.rosetack = `^${version()}`;
1312
+ pkg.devDependencies = { ...pkg.devDependencies, typescript: '^5.6.0' };
1313
+ fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
1314
+ }
1315
+ writeTypeScriptReady(dir);
1316
+ console.log(`🌹 RoseTack new: ${display}/ from the '${path.basename(src)}' template`);
1317
+ console.log(`\n cd ${display}`);
1318
+ console.log(` npm install && npm run dev`);
1319
+ console.log(` npm run build # then deploy dist/`);
1320
+ }
1321
+
1235
1322
  /**
1236
1323
  * `rosetack new <name>` - a starting project. The smallest thing that builds
1237
1324
  * and runs and shows the syntax: one page (state, {#if}, {#each}, a scoped
1238
1325
  * style), one README naming the three commands. Not a second demo app - the
1239
1326
  * point is that a new developer's first `rosetack build` works in seconds.
1240
1327
  *
1328
+ * `rosetack new <name> --template <t>` - the
1329
+ * official templates (blog, api, admin, site) copied verbatim, with the
1330
+ * dependency rewritten to the published package. A name that is not a
1331
+ * shipped template is resolved as a PATH, so any project directory works as
1332
+ * a template (a team's own starter, a checkout's examples/).
1333
+ *
1241
1334
  * Trade-off: three files, written from strings. No template engine, no
1242
1335
  * dependency, no `npm install` run on the developer's behalf (they may use
1243
1336
  * pnpm/yarn/bun, and a surprise install is worse than a printed command).
1244
1337
  */
1245
1338
  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)');
1339
+ const args = argv.slice(1);
1340
+ const tplIdx = args.indexOf('--template');
1341
+ const template = tplIdx >= 0 ? args[tplIdx + 1] : null;
1342
+ const name = args.find((a, i) => !a.startsWith('-') && i !== (tplIdx >= 0 ? tplIdx + 1 : -1));
1343
+ if (!name || (tplIdx >= 0 && !template)) {
1344
+ const available = templatesDir() ? fs.readdirSync(templatesDir()!).join(', ') : 'blog, api, admin, site';
1345
+ console.log(`Usage: rosetack new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${available} - or any project directory)`);
1249
1346
  return;
1250
1347
  }
1251
1348
  const dir = path.resolve(name);
@@ -1253,6 +1350,12 @@ async function scaffold(): Promise<void> {
1253
1350
  console.error(`rosetack: ${dir} already exists - pick another name`);
1254
1351
  process.exit(1);
1255
1352
  }
1353
+
1354
+ if (template) {
1355
+ copyTemplate(dir, template, name);
1356
+ return;
1357
+ }
1358
+
1256
1359
  const pages = path.join(dir, 'src', 'pages');
1257
1360
  fs.mkdirSync(pages, { recursive: true });
1258
1361
 
@@ -1268,33 +1371,13 @@ async function scaffold(): Promise<void> {
1268
1371
  check: 'rosetack check',
1269
1372
  },
1270
1373
  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
1374
  devDependencies: { typescript: '^5.6.0' },
1274
1375
  }, null, 2) + '\n');
1275
1376
 
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');
1377
+ writeTypeScriptReady(dir);
1293
1378
 
1294
1379
  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.
1380
+
1298
1381
  interface Item { label: string }
1299
1382
 
1300
1383
  let count = $state(0);
@@ -1303,8 +1386,8 @@ async function scaffold(): Promise<void> {
1303
1386
 
1304
1387
  function increment() { $setState('count', count() + 1); }
1305
1388
  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)
1389
+
1390
+
1308
1391
  let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
1309
1392
  </script>
1310
1393
 
@@ -1342,7 +1425,6 @@ npm run check # type-checks every .rose script
1342
1425
  Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
1343
1426
  \`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
1344
1427
  runs before every request, \`src/pages/api/*.rose\` answers JSON.
1345
- Full syntax: the README of the rosetack package.
1346
1428
  `);
1347
1429
 
1348
1430
  fs.writeFileSync(path.join(dir, '.gitignore'), 'node_modules/\ndist/\n');
@@ -1377,8 +1459,6 @@ async function check(): Promise<void> {
1377
1459
  process.exit(1);
1378
1460
  }
1379
1461
 
1380
- // The project's typescript, resolved FROM the project: the framework must not drag its
1381
- // own copy into a user's install …
1382
1462
  let tsMod: typeof ts;
1383
1463
  try {
1384
1464
  const req = createRequire(pathToFileURL(path.join(SRC_DIR, 'package.json')));
@@ -1388,21 +1468,14 @@ async function check(): Promise<void> {
1388
1468
  process.exit(1);
1389
1469
  }
1390
1470
 
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
1471
  const nextTo = (rel: string[]) => rel.map((r) => fileURLToPath(new URL(r, import.meta.url))).find((p) => fs.existsSync(p));
1395
1472
  const typesFile = nextTo(['../types/rosetack.d.ts', '../src/types/rosetack.d.ts']);
1396
1473
  if (!typesFile) {
1397
1474
  console.error('rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler');
1398
1475
  process.exit(1);
1399
1476
  }
1400
- // The runtime source, for scripts that import helpers from './runtime.js' (the module the
1401
- // compiler generates beside the intermediates).
1402
1477
  const runtimeSource = nextTo(['../runtime/index.ts', '../src/runtime/index.ts']);
1403
1478
 
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
1479
  const norm = (f: string) => path.resolve(f).replace(/\\/g, '/');
1407
1480
  const virtual = new Map<string, string>();
1408
1481
  let checked = 0;
@@ -1410,7 +1483,7 @@ async function check(): Promise<void> {
1410
1483
  const source = await fs.promises.readFile(file, 'utf-8');
1411
1484
  const m = /<script>/.exec(source);
1412
1485
  const script = scriptOf(source);
1413
- if (!script) continue; // a pure-markup component has nothing to check
1486
+ if (!script) continue;
1414
1487
  const tagLine = source.slice(0, m!.index + '<script>'.length).split('\n').length;
1415
1488
  const wired = runtimeSource
1416
1489
  ? script.replace(/['"]\.\/runtime\.js['"]/g, JSON.stringify(runtimeSource.replace(/\\/g, '/')))
@@ -1423,14 +1496,12 @@ async function check(): Promise<void> {
1423
1496
  return;
1424
1497
  }
1425
1498
 
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
1499
  const propType = (def: string | null): string => {
1429
- if (!def) return 'unknown'; // `export let x;`
1500
+ if (!def) return 'unknown';
1430
1501
  if (/^['"`]/.test(def)) return 'string';
1431
1502
  if (/^-?\d+(\.\d+)?$/.test(def)) return 'number';
1432
1503
  if (/^(true|false)$/.test(def)) return 'boolean';
1433
- return 'unknown'; // null, a call, an object: the honest answer
1504
+ return 'unknown';
1434
1505
  };
1435
1506
  const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
1436
1507
  const declared = new Set<string>();
@@ -1441,7 +1512,7 @@ async function check(): Promise<void> {
1441
1512
  const target = norm(path.resolve(path.dirname(file), spec[1]));
1442
1513
  if (target === file || declared.has(target)) continue;
1443
1514
  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
1515
+ if (targetSource === null) continue;
1445
1516
  const props = extractExports(scriptOf(targetSource) ?? '').props;
1446
1517
  virtual.set(`${target}.d.ts`, [
1447
1518
  `declare function render(closes: unknown[], children: string, __props: { ${props.map((p) => `${p.name}?: ${propType(p.def)}`).join('; ')} }, __slots?: Record<string, unknown>): string;`,
@@ -1459,18 +1530,11 @@ async function check(): Promise<void> {
1459
1530
  module: tsMod.ModuleKind.ESNext,
1460
1531
  moduleResolution: tsMod.ModuleResolutionKind.Bundler,
1461
1532
  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
1533
  allowNonTsExtensions: true,
1465
- // the rewired './runtime.js' import points at a real .ts source
1466
1534
  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
1535
  skipLibCheck: true,
1470
1536
  };
1471
1537
  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
1538
  host.getCurrentDirectory = () => path.resolve(SRC_DIR);
1475
1539
  const realRead = host.readFile.bind(host);
1476
1540
  const realGet = host.getSourceFile.bind(host);
@@ -1481,11 +1545,7 @@ async function check(): Promise<void> {
1481
1545
  return src ? tsMod.createSourceFile(f, src, version, true) : realGet(f, version, onError, shouldCreate);
1482
1546
  };
1483
1547
 
1484
- // rosetack's ambient globals as a program root: a global .d.ts contributes its
1485
- // declarations to every file in the program …
1486
1548
  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
1549
  const diagnostics = tsMod.getPreEmitDiagnostics(program)
1490
1550
  .filter((d) => d.file && virtual.has(norm(d.file.fileName)));
1491
1551
  if (diagnostics.length === 0) {
@@ -1493,7 +1553,6 @@ async function check(): Promise<void> {
1493
1553
  return;
1494
1554
  }
1495
1555
  for (const d of diagnostics) {
1496
- // paths relative to the project root, the way tsc prints them
1497
1556
  const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
1498
1557
  const where = d.file && at
1499
1558
  ? `${path.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})`
@@ -1509,8 +1568,6 @@ async function check(): Promise<void> {
1509
1568
 
1510
1569
  const argv = process.argv.slice(2);
1511
1570
  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
1571
  const asJson = argv.includes('--json');
1515
1572
 
1516
1573
  /** Print a failure the way its reader needs it. A RoseError is the
@@ -1538,4 +1595,4 @@ else if (cmd === 'serve') void serve().catch(reportFailure);
1538
1595
  else if (cmd === 'new') void scaffold().catch(reportFailure);
1539
1596
  else if (cmd === 'check') void check().catch(reportFailure);
1540
1597
  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)');
1598
+ else console.log('Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] [--static] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON; --static verifies the build is deployable with no server at all; `new <name> [--template blog|api|admin|site]` scaffolds a project)');