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/shell.ts CHANGED
@@ -1,11 +1,4 @@
1
- /**
2
- * HTML shell - the document wrapper for every rosetack page.
3
- *
4
- * The client bundle is INLINED into the document, so a full page load costs
5
- * exactly one request: the HTML itself. No other framework in the comparison
6
- * set achieves that - they all
7
- * ship a separate JS bundle, doubling the round-trips before first paint.
8
- */
1
+
9
2
 
10
3
  import * as fs from 'fs';
11
4
  import * as path from 'path';
@@ -16,8 +9,6 @@ const OUT_DIR = path.join(process.cwd(), 'dist');
16
9
 
17
10
  let clientCache: { mtimeMs: number; source: string } | null = null;
18
11
 
19
- // The bundle mode the last build decided ('inline' | 'split'). In split mode
20
- // getClientSource() answers null - "nothing to inline" - so every shell caller …
21
12
  let splitMode = false;
22
13
  export function setBundleMode(mode: string): void {
23
14
  splitMode = mode === 'split';
@@ -25,7 +16,7 @@ export function setBundleMode(mode: string): void {
25
16
 
26
17
  /** Read dist/client.js with an mtime-based cache (dev server rebuilds it). */
27
18
  export function getClientSource(): string | null {
28
- if (splitMode) return null; // mode B: the document references /client.js
19
+ if (splitMode) return null;
29
20
  const file = path.join(OUT_DIR, 'client.js');
30
21
  try {
31
22
  const st = fs.statSync(file);
@@ -40,11 +31,7 @@ export function getClientSource(): string | null {
40
31
 
41
32
  let styleCache: { mtimeMs: number; source: string } | null = null;
42
33
 
43
- /**
44
- * Read dist/styles.css (every component's scoped <style>, merged at build
45
- * time) with an mtime-based cache. '' when the app declares no component
46
- * styles - the document then carries only the shell's own STYLES.
47
- */
34
+ // Read dist/styles.css (every component's scoped <style>, merged at build time) with an mtime-based cache.
48
35
  export function getStyles(): string {
49
36
  const file = path.join(OUT_DIR, 'styles.css');
50
37
  try {
@@ -58,10 +45,26 @@ export function getStyles(): string {
58
45
  }
59
46
  }
60
47
 
61
- // Bootstrap appended after the inlined bundle: client-side navigation. Distinct names avoid
62
- // any collision with minified bundle identifiers.
63
- const BOOTSTRAP = esbuild.transformSync(`
64
- const __app = document.getElementById('app');
48
+ const BOOTSTRAP_SOURCE = `
49
+ // shell = false: the document's SSR content sits directly in <body> - no
50
+ // #app wrapper, no demo styles, so a real theme's CSS owns the document from
51
+ // the first byte (and a JS-less visitor never sees either). The bundle still
52
+ // runs, and it still needs its container: wrap the content once, here, before
53
+ // any theme script executes (module scripts run before DOMContentLoaded). The
54
+ // wrapper is a plain unstyled div, so the re-parent is visually inert; every
55
+ // later path - adoption, navigation, forms - is then the ordinary one.
56
+ let __app = document.getElementById('app');
57
+ if (!__app) {
58
+ __app = document.createElement('div');
59
+ __app.id = 'app';
60
+ // scripts stay outside the wrapper, exactly where the dressed document
61
+ // keeps them: the state element and the running module must survive a
62
+ // navigation's innerHTML swap (they are the document's, not the route's).
63
+ for (const node of Array.from(document.body.children)) {
64
+ if (node.tagName !== 'SCRIPT') __app.appendChild(node);
65
+ }
66
+ document.body.appendChild(__app);
67
+ }
65
68
  // Native View Transitions around client-side navigation (progressive:
66
69
  // browsers without the API navigate normally, no polyfill, no CSS required).
67
70
  function __navigate(pathname) {
@@ -124,13 +127,15 @@ document.addEventListener('submit', (e) => {
124
127
  e.preventDefault();
125
128
  postForm(new FormData(f));
126
129
  });
127
- // Dev seam: the live signal graph, readable as JSON. Two callers, one
130
+ // Dev seam: the live signal graph, readable as JSON. Three callers, one
128
131
  // implementation: the dev server's reload bridge snapshots it before a
129
132
  // rebuild-triggered reload so the edit lands on the state the developer had,
130
- // and a devtools extension reads it the same way. It is the same
131
- // serializeState the zero-hydration resume already ships, so the only new
132
- // bytes are the assignment.
133
- window.__rosetack = { state: () => serializeState() };
133
+ // and the devtools extension (devtools/) reads it the same way - the signal
134
+ // graph plus the prefetch counters, which is the whole observable state of a
135
+ // running page. Both are DIRECT references (no wrapper arrow): the names take
136
+ // no arguments, so the call is identical and every document that carries the
137
+ // bundle pays eleven bytes for the pair instead of forty.
138
+ window.__rosetack = { state: serializeState, prefetch: prefetchStats };
134
139
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
135
140
  // If the document was rendered for a DIFFERENT route (a static-file server's
136
141
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
@@ -149,26 +154,60 @@ if (__resumed) {
149
154
  __state = Object.assign(__state, __resumed);
150
155
  __state.__route = __route;
151
156
  }
152
- if (__resumed) {
157
+ // A NOT-FOUND document (the server stamps __notFound onto its state) boots
158
+ // into the app's own 404 route: the URL matches no route - or a catch-all
159
+ // whose resolver threw notFound(), whose key sits null in the resumed state
160
+ // and whose template would dereference it into a 500. startNotFound paints
161
+ // the not-found route from the resumed state instead (zero requests).
162
+ if (__state.__notFound) {
163
+ startNotFound(__app, window.location.pathname);
164
+ } else if (__resumed) {
153
165
  start(__app, window.location.pathname);
154
166
  } else if (__state.__route === window.location.pathname) {
155
167
  start(__app, window.location.pathname, true);
156
168
  } else {
157
169
  start(__app, window.location.pathname);
158
170
  }
159
- `, { minify: true }).code;
171
+ `;
172
+ let BOOTSTRAP_CACHE: string | null = null;
173
+ function bootstrap(): string {
174
+ if (BOOTSTRAP_CACHE === null) {
175
+ if ((globalThis as any).__rosetack_SKIP_MINIFY) {
176
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
177
+ } else {
178
+ try {
179
+ BOOTSTRAP_CACHE = esbuild.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
180
+ } catch {
181
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
182
+ }
183
+ }
184
+ }
185
+ return BOOTSTRAP_CACHE;
186
+ }
160
187
 
161
- // The document inlines its entire runtime, so rosetack can ship a STRICT content security
162
- // policy without 'unsafe-inline' in script-src …
163
- const CSP_TAIL = `style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
188
+ const CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
164
189
  let cspCache: { for: string | null; value: string } | null = null;
165
- // The exact bytes between the external bootstrap's script tags - the single source of truth
166
- // shared by the tag and the CSP hash …
167
- const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm } from '/client.js';\n${BOOTSTRAP}`;
168
- // The exact bytes between the module script's tags - the single source of truth shared by
169
- // the tag and the CSP hash, so the policy can never drift from what actually ships.
190
+ let EXTERNAL_BOOTSTRAP_CACHE: string | null = null;
191
+ function externalBootstrap(): string {
192
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `\nimport { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';\n${bootstrap()}`;
193
+ return EXTERNAL_BOOTSTRAP_CACHE;
194
+ }
170
195
  function inlineScript(client: string): string {
171
- return `\n${client}\n${BOOTSTRAP}`;
196
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
197
+ let body = client;
198
+ let aliases = "";
199
+ if (m) {
200
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
201
+ aliases = m[1]
202
+ .split(",")
203
+ .map((pair) => {
204
+ const parts = pair.split(" as ").map((x) => x.trim());
205
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
206
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
207
+ })
208
+ .join("");
209
+ }
210
+ return `\n${body}\n${aliases}\n${bootstrap()}`;
172
211
  }
173
212
  /**
174
213
  * A fresh CSP nonce: 128 bits from the platform RNG, base64 - the syntax the
@@ -205,11 +244,9 @@ export function mintNonce(): string {
205
244
  export function securityHeaders(client: string | null, nonce = ''): Record<string, string> {
206
245
  if (nonce) return { 'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
207
246
  if (!cspCache || cspCache.for !== client) {
208
- // client === null: split mode (or the edge without a built client.js). 'self' covers
209
- // the external modules and chunks, the hash covers the inline bootstrap …
210
247
  const scriptSrc = client
211
248
  ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
212
- : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
249
+ : `'self' 'sha256-${createHash('sha256').update(externalBootstrap(), 'utf-8').digest('base64')}'`;
213
250
  cspCache = {
214
251
  for: client,
215
252
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`,
@@ -218,12 +255,8 @@ export function securityHeaders(client: string | null, nonce = ''): Record<strin
218
255
  return { 'Content-Security-Policy': cspCache.value };
219
256
  }
220
257
 
221
- // An inline SVG favicon (the rose). Without it every browser requests /favicon.ico on every
222
- // page load - one wasted request per visit.
223
258
  const FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
224
259
 
225
- // Shared by the buffered shell and the streaming shell-open so both produce
226
- // byte-identical static markup.
227
260
  const STYLES = `
228
261
  body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
229
262
  button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
@@ -243,8 +276,6 @@ const STYLES = `
243
276
  ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
244
277
  `;
245
278
 
246
- // The stylesheet ships inside every document, so its source formatting is a tax on every
247
- // route: collapse whitespace outside strings once, here.
248
279
  const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g, (m) =>
249
280
  m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, ' ').replace(/\s*([:;{},])\s*/g, '$1').trim()
250
281
  ).trim();
@@ -271,10 +302,7 @@ const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
271
302
  function mergeHeadBlocks(blocks: string[]): string {
272
303
  const byKey = new Map<string, string>();
273
304
  const order: string[] = [];
274
- // positional keys: tag -> how many unkeyed elements of that tag came before
275
305
  const positional = new Map<string, number>();
276
- // first occurrence wins: blocks arrive page-first (a page renders inside its
277
- // layouts' <slot/>), so the page's title/meta override the layouts'
278
306
  const put = (key: string, html: string) => {
279
307
  if (!byKey.has(key)) {
280
308
  byKey.set(key, html);
@@ -282,13 +310,10 @@ function mergeHeadBlocks(blocks: string[]): string {
282
310
  }
283
311
  };
284
312
  for (const block of blocks) {
285
- // title carries content, so it needs its own pattern
286
313
  for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put('title', m[0]);
287
- // One pass over every other head element: a void tag (meta/link/base), a paired one
288
- // (style/script/noscript, and any tag a route writes), or a self-closed one.
289
314
  for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
290
315
  const tag = m[1].toLowerCase();
291
- if (tag === 'title') continue; // handled above, with its own key
316
+ if (tag === 'title') continue;
292
317
  const attrs = m[2];
293
318
  const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
294
319
  const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
@@ -299,8 +324,6 @@ function mergeHeadBlocks(blocks: string[]): string {
299
324
  key = `${tag}:#${positional.get(tag) ?? 0}`;
300
325
  positional.set(tag, (positional.get(tag) ?? 0) + 1);
301
326
  }
302
- // keyed tags carry their key (must match HEAD_ATTR in the runtime) so the client
303
- // adopts these SSR-injected elements in place on the first navigation instead of …
304
327
  const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
305
328
  put(key, marked);
306
329
  }
@@ -320,7 +343,7 @@ export function clientScriptTag(client: string | null, nonce = ''): string {
320
343
  const n = nonce ? ` nonce="${nonce}"` : '';
321
344
  return client
322
345
  ? `<script type="module"${n}>${inlineScript(client)}</script>`
323
- : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
346
+ : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${externalBootstrap()}</script>`;
324
347
  }
325
348
 
326
349
  /**
@@ -333,55 +356,63 @@ export function clientScriptTag(client: string | null, nonce = ''): string {
333
356
  * docAttrs). The streaming path flushes this string BEFORE the render, so
334
357
  * the browser gets the language metadata in the first byte.
335
358
  */
336
- export function shellOpen(styles: string = getStyles(), lang = 'en', dir = ''): string {
359
+ export function shellOpen(styles: string = getStyles(), lang = 'en', dir = '', shell = true): string {
337
360
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
361
+ const demoStyles = shell ? `\n <style>${STYLES_MIN}</style>` : '';
362
+ const appOpen = shell ? `\n <div id="app">` : '';
338
363
  return `<!DOCTYPE html>
339
364
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
340
365
  <head>
341
366
  <meta charset="UTF-8">
342
367
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
343
- <title>RoseTack</title>
344
- <style>${STYLES_MIN}</style>${styleTag}
368
+ <title>RoseTack</title>${demoStyles}${styleTag}
345
369
  ${FAVICON}
346
370
  </head>
347
- <body>
348
- <div id="app">`;
371
+ <body>${appOpen}`;
349
372
  }
350
373
 
351
374
  /** Build the document from an explicit client source (edge runtimes have no fs). */
352
- export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true, lang = 'en', dir = '', nonce = ''): string {
375
+ export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true, lang = 'en', dir = '', nonce = '', shell = true): string {
353
376
  const clientTag = clientScriptTag(client, nonce);
354
377
 
355
378
  const mergedHead = mergeHeadBlocks(head);
356
- // a route-provided <title> replaces the default one
379
+ const headStamped = nonce
380
+ ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs: string) => (/\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`))
381
+ : mergedHead;
382
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ''}`;
383
+ let bodyAttrs = '';
384
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag: string, attrs: string) => {
385
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, '');
386
+ if (tag === 'html') htmlAttrs = clean;
387
+ else bodyAttrs = clean;
388
+ return '';
389
+ });
357
390
  const titleTag = /<title>/i.test(mergedHead) ? '' : '<title>RoseTack</title>';
358
- // a route-provided icon replaces the inline favicon
359
391
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? '' : `\n ${FAVICON}`;
360
- const headTags = mergedHead ? `\n ${mergedHead}` : '';
392
+ const headTags = headClean ? `\n ${headClean}` : '';
361
393
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
362
- // js=false (a route exporting csr = false): the document ends at the container - no state
363
- // script, no inlined bundle, zero JavaScript.
394
+ const stateSafe = stateJson.replace(/</g, '\\u003c');
364
395
  const jsTail = js
365
- ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
396
+ ? `\n <script type="application/json" id="__rosetack_state">${stateSafe}</script>\n ${clientTag}`
366
397
  : '';
367
- const open = js ? '<div id="app">' : '';
368
- const close = js ? '</div>' : '';
369
- const shellStyles = js ? `\n <style>${STYLES_MIN}</style>` : '';
398
+ const open = js && shell ? '<div id="app">' : '';
399
+ const close = js && shell ? '</div>' : '';
400
+ const shellStyles = js && shell ? `\n <style>${STYLES_MIN}</style>` : '';
370
401
 
371
402
  return `<!DOCTYPE html>
372
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
403
+ <html${htmlAttrs}>
373
404
  <head>
374
405
  <meta charset="UTF-8">
375
406
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
376
407
  ${titleTag}${shellStyles}${styleTag}
377
408
  </head>
378
- <body>
409
+ <body${bodyAttrs}>
379
410
  ${open}${ssrHtml}${close}${jsTail}
380
411
  </body>
381
412
  </html>`;
382
413
  }
383
414
 
384
415
  /** Node entry: reads dist/client.js from disk (mtime-cached). */
385
- export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true, lang = 'en', dir = '', nonce = ''): string {
386
- return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce);
416
+ export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true, lang = 'en', dir = '', nonce = '', shell = true): string {
417
+ return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce, shell);
387
418
  }
package/src/cli/test.ts CHANGED
@@ -1,37 +1,4 @@
1
- /**
2
- * rosetack/test - the public testing surface.
3
- *
4
- * The framework's own suites proved the pipeline; this module lets a PROJECT
5
- * prove its own. Two halves, one entry point:
6
- *
7
- * const c = await test('src/components/Counter.rose', { props: { start: 5 } });
8
- * const r = await c.get(); // the server half: rendered HTML + state
9
- * r.html.includes('5');
10
- * const after = await c.post({ name: 'Ada' }); // a server action / form POST
11
- *
12
- * const dom = new JSDOM('<!DOCTYPE html><html><body><div id="app"></div></body></html>');
13
- * const p = await test('src/pages/sign.rose', { dom }).then((a) => a.mount());
14
- * await p.click('button'); // a real event -> fine-grained patch
15
- * p.text('p');
16
- * p.requestCount(); // the zero-request story, asserted
17
- *
18
- * The design rule: NO second implementation of anything. The
19
- * harness compiles a throwaway project with the SAME compiler the app uses,
20
- * then drives the SAME server bundle and client bundle the app ships. There
21
- * is nothing here that can pass while the real app fails, because there is
22
- * nothing here that is not the real app.
23
- *
24
- * A `.rose` component is not independently renderable in rosetack's
25
- * architecture - it compiles INTO the app's bundles - so a component test
26
- * builds the project it lives in with one synthesized page that renders it
27
- * with the given props. That page is the only thing added; every other route
28
- * of the app still exists, so navigation and api routes are testable too.
29
- *
30
- * Vitest/jest compatible: every entry point is an async function returning
31
- * plain data. No test-runner dependency, no globals beyond the DOM ones a
32
- * browser has (and those are grafted from the window `mount()` runs in, so
33
- * jsdom, happy-dom and vitest's jsdom environment all work unchanged).
34
- */
1
+
35
2
 
36
3
  import * as fs from 'fs';
37
4
  import * as os from 'os';
@@ -55,6 +22,8 @@ export interface TestResult {
55
22
  state: Record<string, unknown>;
56
23
  head: string[];
57
24
  csr?: boolean;
25
+ /** the route exported `shell = false`: the document keeps the bundle but drops the #app wrapper + STYLES_MIN */
26
+ shell?: boolean;
58
27
  lang: string;
59
28
  dir: string;
60
29
  /** the complete document, byte-identical to what the servers send */
@@ -99,12 +68,7 @@ export interface TestOptions {
99
68
  dir?: string;
100
69
  /** keep the built dir and print its path, for inspecting the artifacts */
101
70
  keep?: boolean;
102
- /**
103
- * A DOM for `mount()`: a jsdom `new JSDOM()` instance or its `.window`
104
- * (happy-dom's Window works too - anything with `.window`). Omit it under
105
- * a jsdom test environment (vitest's `environment: 'jsdom'`), where the
106
- * globals are already there.
107
- */
71
+
108
72
  dom?: unknown;
109
73
  }
110
74
 
@@ -123,8 +87,6 @@ export interface TestApp {
123
87
  mount(req?: TestRequest): Promise<TestHandle>;
124
88
  }
125
89
 
126
- // The globals a browser has and a Node test process does not. `mount()` grafts them from
127
- // the document it parses, exactly like the repo's own client suite does …
128
90
  const GRAFTED = ['document', 'Node', 'NodeFilter', 'FormData', 'DOMParser', 'location', 'fetch', 'Event', 'CustomEvent', 'MutationObserver', 'requestAnimationFrame'] as const;
129
91
 
130
92
  /** Absolute path of the project root that owns `file` (the dir holding src/pages). */
@@ -183,8 +145,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
183
145
  const rel = path.relative(root, target).replace(/\\/g, '/');
184
146
  const isComponent = rel.startsWith('src/components/');
185
147
 
186
- // The fixture project: the app's own sources (so every route, component, config and
187
- // public asset resolves exactly as it does for the app) plus, for a component target …
188
148
  const dir = opts.dir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'rosetack-test-'));
189
149
  for (const item of ['src', 'public']) {
190
150
  const from = path.join(root, item);
@@ -209,8 +169,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
209
169
  const outDir = path.join(dir, 'dist');
210
170
  await buildProject(dir, outDir);
211
171
 
212
- // The two bundles the app ships - the same ones the servers run. Imported once per test()
213
- // call: the server module holds module state …
214
172
  const serverUrl = pathToFileURL(path.join(outDir, 'server.js')).href;
215
173
  const clientUrl = pathToFileURL(path.join(outDir, 'client.js')).href;
216
174
  const mod = await import(serverUrl);
@@ -222,8 +180,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
222
180
 
223
181
  if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
224
182
  if (!opts.dir && !opts.keep) {
225
- // a temp fixture is not the developer's to clean up by hand. On exit, not now: the
226
- // locale packs and chunks below are read from disk while the mounted half runs …
227
183
  process.once('exit', () => {
228
184
  try {
229
185
  fs.rmSync(dir, { recursive: true, force: true });
@@ -238,9 +194,10 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
238
194
  state: page.state ? JSON.parse(page.state) : {},
239
195
  head: page.head ?? [],
240
196
  csr: page.csr,
197
+ shell: page.shell,
241
198
  lang: page.lang ?? 'en',
242
199
  dir: page.dir ?? '',
243
- document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? 'en', page.dir ?? ''),
200
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? 'en', page.dir ?? '', '', page.shell !== false),
244
201
  redirect,
245
202
  });
246
203
 
@@ -248,15 +205,10 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
248
205
  const toRequest = (pathname: string, req: TestRequest = {}, body?: FormData) => {
249
206
  const headers = new Headers(req.headers ?? {});
250
207
  for (const [k, v] of Object.entries(req.cookies ?? {})) headers.append('cookie', `${k}=${v}`);
251
- return new Request(`http://localhost${pathname}`, { method: body ? 'POST' : 'GET', headers, body });
208
+ return new Request(`http://localhost${pathname}`, { method: req.method ?? 'GET', headers, body: body ?? undefined });
252
209
  };
253
210
 
254
- /**
255
- * One request through the real server pipeline: middleware first (it can
256
- * short-circuit - a redirect, an auth wall), then the render. This is the
257
- * order the servers use, so a middleware's effect is visible here or it is
258
- * not visible at all.
259
- */
211
+ // One request through the real server pipeline: middleware first (it can short-circuit - a redirect, an auth wall), then the render.
260
212
  const request = async (pathname: string, req: TestRequest, body?: FormData): Promise<TestResult> => {
261
213
  if (mod.middleware) {
262
214
  const mw = await mod.runMiddleware(toRequest(pathname, req, body), body);
@@ -266,15 +218,10 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
266
218
  return result(page);
267
219
  };
268
220
 
269
- // The client half's request counter and fetch proxy: the bundle POSTs to
270
- // location.pathname like a browser, and the answer is the same document the Node server
271
- // would send …
272
221
  let requests = 0;
273
222
  let currentRoute = route;
274
223
 
275
224
  const mount = async (req: TestRequest = {}): Promise<TestHandle> => {
276
- // The window the bundle will live in: the caller's DOM, or the ambient one under a
277
- // jsdom test environment.
278
225
  const win = ((opts.dom as any)?.window ?? opts.dom ?? globalThis) as any;
279
226
  if (!win?.document || !win?.DOMParser) {
280
227
  throw new Error('rosetack/test: mount() needs a DOM. Pass one - test("src/components/Counter.rose", { dom: new JSDOM() }) - or run under a jsdom environment.');
@@ -283,8 +230,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
283
230
 
284
231
  const doc = win.document;
285
232
  const app = doc.getElementById('app') ?? doc.body;
286
- // reuse the state element across mounts of the same document: a second one would lose
287
- // getElementById's first-match race and the client would resume the FIRST mount's state
288
233
  let stateEl = doc.getElementById('__rosetack_state');
289
234
  if (!stateEl) {
290
235
  stateEl = doc.createElement('script');
@@ -302,8 +247,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
302
247
  (globalThis as any).location = { pathname: currentRoute, href: `http://localhost${currentRoute}` };
303
248
  (globalThis as any).fetch = async (url: string | URL, init: any) => {
304
249
  const pathname = String(url).startsWith('http') ? new URL(String(url)).pathname : String(url);
305
- // an i18n route's runtime language pack: the same request the browser
306
- // makes, served from the file this build wrote
307
250
  if (pathname.startsWith('/locales/') && pathname.endsWith('.json')) {
308
251
  const file = path.join(outDir, pathname.slice(1));
309
252
  if (!fs.existsSync(file)) return { ok: false, json: async () => ({}) };
@@ -360,8 +303,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
360
303
  },
361
304
  requestCount: () => requests,
362
305
  };
363
- // The graft is intentional and documented: a second mount() re-grafts
364
- // over the first. `restore` puts the process back the way it was.
365
306
  (handle as any).restore = () => { for (const [k, v] of saved) (globalThis as any)[k] = v; };
366
307
  return handle;
367
308
  };
@@ -377,8 +318,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
377
318
  return request(pathname, req, body);
378
319
  },
379
320
  api: async (method: string, pathname: string, req: TestRequest = {}) => {
380
- // the middleware runs first here too - the servers do, and an api
381
- // route's auth usually lives in it
382
321
  if (mod.middleware) {
383
322
  const mw = await mod.runMiddleware(toRequest(pathname, req));
384
323
  if (mw) return { status: mw.status, body: await mw.text(), headers: { location: mw.headers.get('location') ?? '' } };
@@ -388,7 +327,7 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
388
327
  let body: unknown = text;
389
328
  try {
390
329
  body = JSON.parse(text);
391
- } catch { /* not JSON: hand back the raw text */ }
330
+ } catch { }
392
331
  const headers: Record<string, string> = {};
393
332
  res.headers.forEach((v: string, k: string) => { headers[k] = v; });
394
333
  return { status: res.status, body, headers };