rosetack 0.1.2 → 0.1.3

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 (54) 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 +818 -445
  11. package/dist-cli/edge.mjs +115 -39
  12. package/dist-cli/rosetack.mjs +1078 -529
  13. package/dist-cli/runtime.mjs +115 -34
  14. package/dist-cli/test.mjs +875 -464
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/edge.ts +69 -61
  18. package/src/cli/index.ts +243 -328
  19. package/src/cli/prompt.ts +4 -1
  20. package/src/cli/shell.ts +67 -69
  21. package/src/cli/test.ts +9 -70
  22. package/src/compiler/index.ts +921 -851
  23. package/src/runtime/index.ts +155 -158
  24. package/src/types/rosetack.d.ts +16 -66
  25. package/templates/admin/package.json +14 -0
  26. package/templates/admin/rosetack.config.js +1 -0
  27. package/templates/admin/src/pages/_middleware.rose +33 -0
  28. package/templates/admin/src/pages/api/items.rose +37 -0
  29. package/templates/admin/src/pages/api/login.rose +25 -0
  30. package/templates/admin/src/pages/index.rose +79 -0
  31. package/templates/api/package.json +14 -0
  32. package/templates/api/rosetack.config.js +1 -0
  33. package/templates/api/src/pages/api/health.rose +7 -0
  34. package/templates/api/src/pages/api/items.rose +46 -0
  35. package/templates/api/src/pages/api/login.rose +24 -0
  36. package/templates/api/src/pages/index.rose +25 -0
  37. package/templates/blog/package.json +14 -0
  38. package/templates/blog/rosetack.config.js +1 -0
  39. package/templates/blog/src/pages/404.rose +2 -0
  40. package/templates/blog/src/pages/_layout.rose +42 -0
  41. package/templates/blog/src/pages/_middleware.rose +74 -0
  42. package/templates/blog/src/pages/admin.rose +85 -0
  43. package/templates/blog/src/pages/api/login.rose +46 -0
  44. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  45. package/templates/blog/src/pages/api/posts.rose +72 -0
  46. package/templates/blog/src/pages/index.rose +31 -0
  47. package/templates/blog/src/pages/post/[id].rose +36 -0
  48. package/templates/site/package.json +14 -0
  49. package/templates/site/rosetack.config.js +1 -0
  50. package/templates/site/src/pages/404.rose +2 -0
  51. package/templates/site/src/pages/_layout.rose +40 -0
  52. package/templates/site/src/pages/about.rose +6 -0
  53. package/templates/site/src/pages/index.rose +13 -0
  54. package/templates/site/src/pages/pricing.rose +8 -0
package/src/cli/prompt.ts CHANGED
@@ -47,7 +47,7 @@ the smallest thing that works - the compiler decides what ships.
47
47
  <h1>Posts</h1>
48
48
  <p>Total: {total}</p>
49
49
  <button on:click={() => $setState('count', count() + 1)}>+1</button>
50
- <form method="POST"><button formaction="?__action=like">Like</button></form>
50
+ <form method="POST"><input type="hidden" name="__action" value="like"><button type="submit">Like</button></form>
51
51
  \`\`\`
52
52
 
53
53
  Rules the compiler enforces (breaking one fails the build):
@@ -87,6 +87,9 @@ Rules the compiler enforces (breaking one fails the build):
87
87
  (method="POST", no JS needed - progressive enhancement) or from any event
88
88
  (on:click={like} - one POST, in-place adopt). Its return value is an
89
89
  incremental patch: $append(row) / $prepend(row) / $merge({...}).
90
+ - A form selects its action by the __action FIELD: name the function
91
+ \`action\` (the default) or add <input type="hidden" name="__action"
92
+ value="like">. The server reads the field, not the URL.
90
93
  - Business failures: throw new ActionError('message', 422, 'field'). It lands
91
94
  in ordinary state - $actionError() reads it back, a {#boundary} contains it.
92
95
  - beforeAction(name, form) is the per-page guard that vetoes an action.
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
48
  const BOOTSTRAP = esbuild.transformSync(`
64
- const __app = document.getElementById('app');
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,7 +154,14 @@ 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);
@@ -158,15 +170,9 @@ if (__resumed) {
158
170
  }
159
171
  `, { minify: true }).code;
160
172
 
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'`;
173
+ 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
174
  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.
175
+ const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm, prefetchStats } from '/client.js';\n${BOOTSTRAP}`;
170
176
  function inlineScript(client: string): string {
171
177
  return `\n${client}\n${BOOTSTRAP}`;
172
178
  }
@@ -205,8 +211,6 @@ export function mintNonce(): string {
205
211
  export function securityHeaders(client: string | null, nonce = ''): Record<string, string> {
206
212
  if (nonce) return { 'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
207
213
  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
214
  const scriptSrc = client
211
215
  ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
212
216
  : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
@@ -218,12 +222,8 @@ export function securityHeaders(client: string | null, nonce = ''): Record<strin
218
222
  return { 'Content-Security-Policy': cspCache.value };
219
223
  }
220
224
 
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
225
  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
226
 
225
- // Shared by the buffered shell and the streaming shell-open so both produce
226
- // byte-identical static markup.
227
227
  const STYLES = `
228
228
  body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
229
229
  button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
@@ -243,8 +243,6 @@ const STYLES = `
243
243
  ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
244
244
  `;
245
245
 
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
246
  const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g, (m) =>
249
247
  m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, ' ').replace(/\s*([:;{},])\s*/g, '$1').trim()
250
248
  ).trim();
@@ -271,10 +269,7 @@ const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
271
269
  function mergeHeadBlocks(blocks: string[]): string {
272
270
  const byKey = new Map<string, string>();
273
271
  const order: string[] = [];
274
- // positional keys: tag -> how many unkeyed elements of that tag came before
275
272
  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
273
  const put = (key: string, html: string) => {
279
274
  if (!byKey.has(key)) {
280
275
  byKey.set(key, html);
@@ -282,13 +277,10 @@ function mergeHeadBlocks(blocks: string[]): string {
282
277
  }
283
278
  };
284
279
  for (const block of blocks) {
285
- // title carries content, so it needs its own pattern
286
280
  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
281
  for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
290
282
  const tag = m[1].toLowerCase();
291
- if (tag === 'title') continue; // handled above, with its own key
283
+ if (tag === 'title') continue;
292
284
  const attrs = m[2];
293
285
  const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
294
286
  const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
@@ -299,8 +291,6 @@ function mergeHeadBlocks(blocks: string[]): string {
299
291
  key = `${tag}:#${positional.get(tag) ?? 0}`;
300
292
  positional.set(tag, (positional.get(tag) ?? 0) + 1);
301
293
  }
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
294
  const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
305
295
  put(key, marked);
306
296
  }
@@ -333,55 +323,63 @@ export function clientScriptTag(client: string | null, nonce = ''): string {
333
323
  * docAttrs). The streaming path flushes this string BEFORE the render, so
334
324
  * the browser gets the language metadata in the first byte.
335
325
  */
336
- export function shellOpen(styles: string = getStyles(), lang = 'en', dir = ''): string {
326
+ export function shellOpen(styles: string = getStyles(), lang = 'en', dir = '', shell = true): string {
337
327
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
328
+ const demoStyles = shell ? `\n <style>${STYLES_MIN}</style>` : '';
329
+ const appOpen = shell ? `\n <div id="app">` : '';
338
330
  return `<!DOCTYPE html>
339
331
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
340
332
  <head>
341
333
  <meta charset="UTF-8">
342
334
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
343
- <title>RoseTack</title>
344
- <style>${STYLES_MIN}</style>${styleTag}
335
+ <title>RoseTack</title>${demoStyles}${styleTag}
345
336
  ${FAVICON}
346
337
  </head>
347
- <body>
348
- <div id="app">`;
338
+ <body>${appOpen}`;
349
339
  }
350
340
 
351
341
  /** 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 {
342
+ 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
343
  const clientTag = clientScriptTag(client, nonce);
354
344
 
355
345
  const mergedHead = mergeHeadBlocks(head);
356
- // a route-provided <title> replaces the default one
346
+ const headStamped = nonce
347
+ ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs: string) => (/\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`))
348
+ : mergedHead;
349
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ''}`;
350
+ let bodyAttrs = '';
351
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag: string, attrs: string) => {
352
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, '');
353
+ if (tag === 'html') htmlAttrs = clean;
354
+ else bodyAttrs = clean;
355
+ return '';
356
+ });
357
357
  const titleTag = /<title>/i.test(mergedHead) ? '' : '<title>RoseTack</title>';
358
- // a route-provided icon replaces the inline favicon
359
358
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? '' : `\n ${FAVICON}`;
360
- const headTags = mergedHead ? `\n ${mergedHead}` : '';
359
+ const headTags = headClean ? `\n ${headClean}` : '';
361
360
  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.
361
+ const stateSafe = stateJson.replace(/</g, '\\u003c');
364
362
  const jsTail = js
365
- ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
363
+ ? `\n <script type="application/json" id="__rosetack_state">${stateSafe}</script>\n ${clientTag}`
366
364
  : '';
367
- const open = js ? '<div id="app">' : '';
368
- const close = js ? '</div>' : '';
369
- const shellStyles = js ? `\n <style>${STYLES_MIN}</style>` : '';
365
+ const open = js && shell ? '<div id="app">' : '';
366
+ const close = js && shell ? '</div>' : '';
367
+ const shellStyles = js && shell ? `\n <style>${STYLES_MIN}</style>` : '';
370
368
 
371
369
  return `<!DOCTYPE html>
372
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
370
+ <html${htmlAttrs}>
373
371
  <head>
374
372
  <meta charset="UTF-8">
375
373
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
376
374
  ${titleTag}${shellStyles}${styleTag}
377
375
  </head>
378
- <body>
376
+ <body${bodyAttrs}>
379
377
  ${open}${ssrHtml}${close}${jsTail}
380
378
  </body>
381
379
  </html>`;
382
380
  }
383
381
 
384
382
  /** 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);
383
+ export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true, lang = 'en', dir = '', nonce = '', shell = true): string {
384
+ return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce, shell);
387
385
  }
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 };