rosetack 0.1.0 → 0.1.1

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 (49) hide show
  1. package/dist-cli/compiler.mjs +2302 -0
  2. package/dist-cli/edge.mjs +297 -0
  3. package/dist-cli/rosetack.mjs +3411 -0
  4. package/dist-cli/runtime.mjs +619 -0
  5. package/dist-cli/test.mjs +2696 -0
  6. package/pack.mjs +49 -0
  7. package/package.json +25 -7
  8. package/src/FRAMEWORK_VERSION +1 -1
  9. package/src/cli/edge.ts +58 -23
  10. package/src/cli/index.ts +521 -65
  11. package/src/cli/shell.ts +75 -22
  12. package/src/cli/test.ts +400 -0
  13. package/src/compiler/index.ts +1277 -191
  14. package/src/runtime/index.ts +356 -65
  15. package/src/types/rosetack.d.ts +142 -0
  16. package/.github/workflows/ci.yml +0 -72
  17. package/.github/workflows/release.yml +0 -122
  18. package/benchmark.ts +0 -227
  19. package/example/public/favicon.ico +0 -0
  20. package/example/public/logo.svg +0 -148
  21. package/example/public/rose-mark-black.png +0 -0
  22. package/example/public/rose-mark.png +0 -0
  23. package/example/public/rose-mono.png +0 -0
  24. package/example/rosetack.config.js +0 -10
  25. package/example/src/locales/en.json +0 -8
  26. package/example/src/locales/zh.json +0 -8
  27. package/example/src/pages/404.rose +0 -15
  28. package/example/src/pages/500.rose +0 -10
  29. package/example/src/pages/[lang]/about.rose +0 -40
  30. package/example/src/pages/_layout.rose +0 -33
  31. package/example/src/pages/_middleware.rose +0 -37
  32. package/example/src/pages/about.rose +0 -67
  33. package/example/src/pages/admin.rose +0 -27
  34. package/example/src/pages/api/hello.rose +0 -19
  35. package/example/src/pages/api/login.rose +0 -55
  36. package/example/src/pages/api/posts.rose +0 -80
  37. package/example/src/pages/api/secret.rose +0 -14
  38. package/example/src/pages/blog/[id].rose +0 -25
  39. package/example/src/pages/broken.rose +0 -16
  40. package/example/src/pages/fresh.rose +0 -22
  41. package/example/src/pages/garden.rose +0 -27
  42. package/example/src/pages/index.rose +0 -84
  43. package/example/src/pages/sign.rose +0 -45
  44. package/example/src/pages/thorn.rose +0 -23
  45. package/example/src/pages/vault.rose +0 -14
  46. package/go.mod +0 -3
  47. package/main.go +0 -470
  48. package/tools/release-notes.mjs +0 -113
  49. package/tsconfig.json +0 -17
package/src/cli/shell.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The client bundle is INLINED into the document, so a full page load costs
5
5
  * exactly one request: the HTML itself. No other framework in the comparison
6
- * set (Next.js, SvelteKit, Qwik City, SolidStart) achieves that - they all
6
+ * set achieves that - they all
7
7
  * ship a separate JS bundle, doubling the round-trips before first paint.
8
8
  */
9
9
 
@@ -16,7 +16,7 @@ const OUT_DIR = path.join(process.cwd(), 'dist');
16
16
 
17
17
  let clientCache: { mtimeMs: number; source: string } | null = null;
18
18
 
19
- // P0 §1: the bundle mode the last build decided ('inline' | 'split'). In split mode
19
+ // The bundle mode the last build decided ('inline' | 'split'). In split mode
20
20
  // getClientSource() answers null - "nothing to inline" - so every shell caller …
21
21
  let splitMode = false;
22
22
  export function setBundleMode(mode: string): void {
@@ -82,7 +82,7 @@ document.addEventListener('click', (e) => {
82
82
  });
83
83
  // Prefetch the target route's full render (including $data) on hover, keyboard
84
84
  // focus, or touch - the click that follows paints from cache: no await, no
85
- // request. SvelteKit/Qwik prefetch data only; rosetack prefetches the render
85
+ // request. Other frameworks prefetch data only; rosetack prefetches the render
86
86
  // because the inlined bundle already contains every route.
87
87
  function __prefetchHandler(e) {
88
88
  const a = e.target.closest && e.target.closest('a[href^="/"]');
@@ -91,8 +91,8 @@ function __prefetchHandler(e) {
91
91
  document.addEventListener('mouseover', __prefetchHandler);
92
92
  document.addEventListener('focusin', __prefetchHandler);
93
93
  document.addEventListener('touchstart', __prefetchHandler, { passive: true });
94
- // Viewport + idle prefetch (Qwik-style): once a link scrolls into view and the
95
- // browser is idle, its route renders ahead of any interaction. ponytail: both
94
+ // Viewport + idle prefetch (viewport-triggered): once a link scrolls into view and the
95
+ // browser is idle, its route renders ahead of any interaction. trade-off: both
96
96
  // APIs are feature-detected; without them the hover/focus/touch path above
97
97
  // still covers every link.
98
98
  if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
@@ -139,6 +139,7 @@ if (__state.__route === window.location.pathname) {
139
139
 
140
140
  // The document inlines its entire runtime, so rosetack can ship a STRICT content security
141
141
  // policy without 'unsafe-inline' in script-src …
142
+ 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'`;
142
143
  let cspCache: { for: string | null; value: string } | null = null;
143
144
  // The exact bytes between the external bootstrap's script tags - the single source of truth
144
145
  // shared by the tag and the CSP hash …
@@ -148,7 +149,40 @@ const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm } from '/client
148
149
  function inlineScript(client: string): string {
149
150
  return `\n${client}\n${BOOTSTRAP}`;
150
151
  }
151
- export function securityHeaders(client: string | null): Record<string, string> {
152
+ /**
153
+ * A fresh CSP nonce: 128 bits from the platform RNG, base64 - the syntax the
154
+ * header and the tag share . Web Crypto on purpose: the same helper
155
+ * serves the Node server and the edge adapter, and an edge runtime has no
156
+ * node:crypto. Minted per response and never reused: a nonce is only worth
157
+ * anything an attacker cannot predict, and a repeated one would hand a
158
+ * guessed value unlimited script execution.
159
+ */
160
+ export function mintNonce(): string {
161
+ const bytes = new Uint8Array(16);
162
+ crypto.getRandomValues(bytes);
163
+ let raw = '';
164
+ for (const b of bytes) raw += String.fromCharCode(b);
165
+ return btoa(raw);
166
+ }
167
+
168
+ /**
169
+ * The document's CSP. Two shapes, chosen per response:
170
+ *
171
+ * - no nonce (the default): `script-src 'sha256-…'` over the exact bytes the
172
+ * tag will carry. Nothing else may run - the strongest policy rosetack has,
173
+ * and the reason a rosetack document needs no 'unsafe-inline'.
174
+ * - a nonce (a route exporting `csp = { nonce: true }`):
175
+ * `script-src 'nonce-…' 'strict-dynamic'`. A hash dies the moment anything
176
+ * between the server and the browser touches the document - a CDN, a WAF,
177
+ * an A/B injector that adds one byte blocks the page's own bundle. A nonce
178
+ * survives that, and 'strict-dynamic' lets the page's own code load more
179
+ * code (a third-party loader, a lazily imported chunk), which is the reason
180
+ * a deployment reaches for a nonce in the first place. It is weaker in one
181
+ * way: whatever the document's script loads is trusted. That is the trade
182
+ * the route opts into, per route, not a framework default.
183
+ */
184
+ export function securityHeaders(client: string | null, nonce = ''): Record<string, string> {
185
+ if (nonce) return { 'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
152
186
  if (!cspCache || cspCache.for !== client) {
153
187
  // client === null: split mode (or the edge without a built client.js). 'self' covers
154
188
  // the external modules and chunks, the hash covers the inline bootstrap …
@@ -157,7 +191,7 @@ export function securityHeaders(client: string | null): Record<string, string> {
157
191
  : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
158
192
  cspCache = {
159
193
  for: client,
160
- value: `script-src ${scriptSrc}; 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'`,
194
+ value: `script-src ${scriptSrc}; ${CSP_TAIL}`,
161
195
  };
162
196
  }
163
197
  return { 'Content-Security-Policy': cspCache.value };
@@ -188,6 +222,12 @@ const STYLES = `
188
222
  ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
189
223
  `;
190
224
 
225
+ // The stylesheet ships inside every document, so its source formatting is a tax on every
226
+ // route: collapse whitespace outside strings once, here.
227
+ const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g, (m) =>
228
+ m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, ' ').replace(/\s*([:;{},])\s*/g, '$1').trim()
229
+ ).trim();
230
+
191
231
  /**
192
232
  * Merge the route chain's <head> blocks (document order: page first, then its
193
233
  * layouts) into one clean <head> fragment. First occurrence wins per key, so a
@@ -220,27 +260,40 @@ function mergeHeadBlocks(blocks: string[]): string {
220
260
  return order.map((k) => byKey.get(k)!).join('\n ');
221
261
  }
222
262
 
223
- /** The script tag carrying the inlined bundle (+ bootstrap), or the external fallback. */
224
- export function clientScriptTag(client: string | null): string {
263
+ /**
264
+ * The script tag carrying the inlined bundle (+ bootstrap), or the external
265
+ * fallback. `nonce` stamps the same value the CSP header carries, so
266
+ * a route running a nonce policy has its own code allowed to run; without it
267
+ * the tag is byte-identical to what the sha256 in the header was computed
268
+ * over. Both tags in split mode get it: the external module and the inline
269
+ * bootstrap are the same trust root.
270
+ */
271
+ export function clientScriptTag(client: string | null, nonce = ''): string {
272
+ const n = nonce ? ` nonce="${nonce}"` : '';
225
273
  return client
226
- ? `<script type="module">${inlineScript(client)}</script>`
227
- : `<script type="module" src="/client.js"></script>\n<script type="module">${EXTERNAL_BOOTSTRAP}</script>`;
274
+ ? `<script type="module"${n}>${inlineScript(client)}</script>`
275
+ : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
228
276
  }
229
277
 
230
278
  /**
231
279
  * The static half of the document for streaming SSR: everything up to (and
232
280
  * including) the open `<div id="app">`. No route tags - the route's <head>
233
281
  * content is applied by the client at boot from the body's head markers.
282
+ *
283
+ * `lang`/`dir` are the document's locale and reading direction ( the
284
+ * servers compute them from the [lang] segment with the server bundle's
285
+ * docAttrs). The streaming path flushes this string BEFORE the render, so
286
+ * the browser gets the language metadata in the first byte.
234
287
  */
235
- export function shellOpen(styles: string = getStyles()): string {
288
+ export function shellOpen(styles: string = getStyles(), lang = 'en', dir = ''): string {
236
289
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
237
290
  return `<!DOCTYPE html>
238
- <html lang="en">
291
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
239
292
  <head>
240
293
  <meta charset="UTF-8">
241
294
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
242
295
  <title>RoseTack</title>
243
- <style>${STYLES}</style>${styleTag}
296
+ <style>${STYLES_MIN}</style>${styleTag}
244
297
  ${FAVICON}
245
298
  </head>
246
299
  <body>
@@ -248,8 +301,8 @@ export function shellOpen(styles: string = getStyles()): string {
248
301
  }
249
302
 
250
303
  /** Build the document from an explicit client source (edge runtimes have no fs). */
251
- export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true): string {
252
- const clientTag = clientScriptTag(client);
304
+ export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true, lang = 'en', dir = '', nonce = ''): string {
305
+ const clientTag = clientScriptTag(client, nonce);
253
306
 
254
307
  const mergedHead = mergeHeadBlocks(head);
255
308
  // a route-provided <title> replaces the default one
@@ -258,19 +311,19 @@ export function buildShell(ssrHtml: string, stateJson: string, client: string |
258
311
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? '' : `\n ${FAVICON}`;
259
312
  const headTags = mergedHead ? `\n ${mergedHead}` : '';
260
313
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
261
- // js=false (a route exporting csr = false, innovation #25): the document ends at the
262
- // container - no state script, no inlined bundle, zero JavaScript.
314
+ // js=false (a route exporting csr = false): the document ends at the container - no state
315
+ // script, no inlined bundle, zero JavaScript.
263
316
  const jsTail = js
264
317
  ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
265
318
  : '';
266
319
 
267
320
  return `<!DOCTYPE html>
268
- <html lang="en">
321
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
269
322
  <head>
270
323
  <meta charset="UTF-8">
271
324
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
272
325
  ${titleTag}
273
- <style>${STYLES}</style>${styleTag}
326
+ <style>${STYLES_MIN}</style>${styleTag}
274
327
  </head>
275
328
  <body>
276
329
  <div id="app">${ssrHtml}</div>${jsTail}
@@ -279,6 +332,6 @@ export function buildShell(ssrHtml: string, stateJson: string, client: string |
279
332
  }
280
333
 
281
334
  /** Node entry: reads dist/client.js from disk (mtime-cached). */
282
- export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true): string {
283
- return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js);
335
+ export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true, lang = 'en', dir = '', nonce = ''): string {
336
+ return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce);
284
337
  }
@@ -0,0 +1,400 @@
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
+ */
35
+
36
+ import * as fs from 'fs';
37
+ import * as os from 'os';
38
+ import * as path from 'path';
39
+ import { pathToFileURL } from 'url';
40
+ import { buildProject } from '../compiler/index.js';
41
+ import { buildShell } from './shell.js';
42
+
43
+ /** A request the harness can make: headers (cookies included) and a body. */
44
+ export interface TestRequest {
45
+ headers?: Record<string, string>;
46
+ cookies?: Record<string, string>;
47
+ }
48
+
49
+ /** What a render answers: the page the server would have sent, in pieces. */
50
+ export interface TestResult {
51
+ status: number;
52
+ /** the route's own HTML (what lands inside <div id="app">) */
53
+ html: string;
54
+ /** the serialized state, parsed - what the client resumes */
55
+ state: Record<string, unknown>;
56
+ head: string[];
57
+ csr?: boolean;
58
+ lang: string;
59
+ dir: string;
60
+ /** the complete document, byte-identical to what the servers send */
61
+ document: string;
62
+ /** a middleware short-circuit's target, when it redirected */
63
+ redirect?: string;
64
+ }
65
+
66
+ /** The mounted component: a live DOM plus the interactions a user performs. */
67
+ export interface TestHandle {
68
+ /** the pathname this mount is on (what location.pathname reads) */
69
+ route: string;
70
+ document: Document;
71
+ window: Window & typeof globalThis;
72
+ /** textContent of a selector (or of the whole container) */
73
+ text(sel?: string): string;
74
+ /** outerHTML of a selector, or null when it matches nothing */
75
+ html(sel?: string): string | null;
76
+ exists(sel: string): boolean;
77
+ /** dispatch a real click (bubbles, cancelable) and let the handler run */
78
+ click(sel: string): Promise<void>;
79
+ /** set an input's value the way a user typing would */
80
+ fill(sel: string, value: string): void;
81
+ /** submit a form the way the bootstrap does: one POST, in-place adopt */
82
+ submit(formSel?: string, fields?: Record<string, unknown>): Promise<void>;
83
+ /** call a server action by name, from no event at all */
84
+ action(name: string, fields?: Record<string, unknown>): Promise<void>;
85
+ /** client-side navigation to another route of the built app */
86
+ navigate(pathname: string): Promise<void>;
87
+ /** the live state map */
88
+ state(): Record<string, unknown>;
89
+ /** how many requests the client half has made (the zero-request proof) */
90
+ requestCount(): number;
91
+ }
92
+
93
+ export interface TestOptions {
94
+ /** the component's props (`export let`), plain JSON data only */
95
+ props?: Record<string, unknown>;
96
+ /** the route to render for a PAGE target (default: the page's own URL) */
97
+ route?: string;
98
+ /** where to build (default: a fresh temp dir, removed on process exit) */
99
+ dir?: string;
100
+ /** keep the built dir and print its path, for inspecting the artifacts */
101
+ 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
+ */
108
+ dom?: unknown;
109
+ }
110
+
111
+ export interface TestApp {
112
+ /** the route under test (the synthesized page's URL, or the page's own) */
113
+ route: string;
114
+ /** the built project's dir (dist is inside it) */
115
+ dir: string;
116
+ /** render a route of the built app (GET) */
117
+ get(pathname?: string, req?: TestRequest): Promise<TestResult>;
118
+ /** render a route with a POST body: runs the server action, re-renders */
119
+ post(fields?: Record<string, unknown>, req?: TestRequest & { route?: string }): Promise<TestResult>;
120
+ /** call an api route: the parsed JSON body (or the raw Response) */
121
+ api(method: string, pathname: string, req?: TestRequest): Promise<{ status: number; body: unknown; headers: Record<string, string> }>;
122
+ /** mount the route in a DOM and drive it like a user would */
123
+ mount(req?: TestRequest): Promise<TestHandle>;
124
+ }
125
+
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
+ const GRAFTED = ['document', 'Node', 'NodeFilter', 'FormData', 'DOMParser', 'location', 'fetch', 'Event', 'CustomEvent', 'MutationObserver', 'requestAnimationFrame'] as const;
129
+
130
+ /** Absolute path of the project root that owns `file` (the dir holding src/pages). */
131
+ function projectRootOf(file: string): string {
132
+ let dir = path.dirname(path.resolve(file));
133
+ for (;;) {
134
+ if (fs.existsSync(path.join(dir, 'src', 'pages'))) return dir;
135
+ const parent = path.dirname(dir);
136
+ if (parent === dir) throw new Error(`rosetack/test: ${file} is not inside a project (no src/pages found above it)`);
137
+ dir = parent;
138
+ }
139
+ }
140
+
141
+ /** `src/pages/blog/[id].rose` -> `/blog/:id`; `src/pages/index.rose` -> `/`. */
142
+ function routeOf(file: string, root: string): string {
143
+ const rel = path.relative(path.join(root, 'src', 'pages'), path.resolve(file)).replace(/\\/g, '/').replace(/\.rose$/, '');
144
+ if (rel === 'index') return '/';
145
+ const segs = rel.split('/').map((s) => (s.startsWith('[') && s.endsWith(']') ? `:${s.slice(1, -1)}` : s));
146
+ return '/' + segs.join('/');
147
+ }
148
+
149
+ /** A concrete URL for a pattern: `:id` -> 1, `:lang` -> the app's default locale. */
150
+ function concreteRoute(pattern: string, defaultLocale: string | null): string {
151
+ return pattern.split('/').map((s) => (s.startsWith(':') ? (s === ':lang' ? defaultLocale ?? 'en' : '1') : s)).join('/');
152
+ }
153
+
154
+ /** Copy a directory tree, skipping nothing (a test fixture is small). */
155
+ function copyTree(from: string, to: string): void {
156
+ fs.mkdirSync(to, { recursive: true });
157
+ for (const e of fs.readdirSync(from, { withFileTypes: true })) {
158
+ const src = path.join(from, e.name);
159
+ const dst = path.join(to, e.name);
160
+ if (e.isDirectory()) copyTree(src, dst);
161
+ else fs.copyFileSync(src, dst);
162
+ }
163
+ }
164
+
165
+ /** `key={value}` attributes from a props object, as JS literals. */
166
+ function propAttrs(props: Record<string, unknown>): string {
167
+ return Object.entries(props)
168
+ .map(([k, v]) => `${k}={${JSON.stringify(v) ?? 'undefined'}}`)
169
+ .join(' ');
170
+ }
171
+
172
+ let tmpCount = 0;
173
+
174
+ /**
175
+ * Compile `file` into a throwaway project and return a driver over the
176
+ * bundles that build produced. `file` is a `.rose` component
177
+ * (`src/components/**`) or page (`src/pages/**`).
178
+ */
179
+ export async function test(file: string, opts: TestOptions = {}): Promise<TestApp> {
180
+ const target = path.resolve(file);
181
+ if (!fs.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
182
+ const root = projectRootOf(target);
183
+ const rel = path.relative(root, target).replace(/\\/g, '/');
184
+ const isComponent = rel.startsWith('src/components/');
185
+
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
+ const dir = opts.dir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'rosetack-test-'));
189
+ for (const item of ['src', 'public']) {
190
+ const from = path.join(root, item);
191
+ if (fs.existsSync(from)) copyTree(from, path.join(dir, item));
192
+ }
193
+ for (const item of ['rosetack.config.js']) {
194
+ const from = path.join(root, item);
195
+ if (fs.existsSync(from)) fs.copyFileSync(from, path.join(dir, item));
196
+ }
197
+
198
+ let route: string;
199
+ if (isComponent) {
200
+ const specifier = path.relative(path.join(dir, 'src', 'pages'), path.join(dir, rel)).replace(/\\/g, '/');
201
+ const attrs = propAttrs(opts.props ?? {});
202
+ const page = `<script>\n import Target from '${specifier}';\n</script>\n\n<template>\n <Target ${attrs} />\n</template>\n`;
203
+ fs.writeFileSync(path.join(dir, 'src', 'pages', '__rosetack_test.rose'), page);
204
+ route = '/__rosetack_test';
205
+ } else {
206
+ route = opts.route ?? routeOf(target, root);
207
+ }
208
+
209
+ const outDir = path.join(dir, 'dist');
210
+ await buildProject(dir, outDir);
211
+
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
+ const serverUrl = pathToFileURL(path.join(outDir, 'server.js')).href;
215
+ const clientUrl = pathToFileURL(path.join(outDir, 'client.js')).href;
216
+ const mod = await import(serverUrl);
217
+ const clientSource = fs.readFileSync(path.join(outDir, 'client.js'), 'utf-8');
218
+ let styles = '';
219
+ try {
220
+ styles = fs.readFileSync(path.join(outDir, 'styles.css'), 'utf-8');
221
+ } catch { /* no component styles: shell styles only */ }
222
+
223
+ if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
224
+ 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
+ process.once('exit', () => {
228
+ try {
229
+ fs.rmSync(dir, { recursive: true, force: true });
230
+ } catch { /* the OS temp dir will reap it */ }
231
+ });
232
+ }
233
+
234
+ /** A page result from a rendered page (or a middleware short-circuit). */
235
+ const result = (page: any, redirect?: string): TestResult => ({
236
+ status: page.status ?? 200,
237
+ html: page.html,
238
+ state: page.state ? JSON.parse(page.state) : {},
239
+ head: page.head ?? [],
240
+ csr: page.csr,
241
+ lang: page.lang ?? 'en',
242
+ dir: page.dir ?? '',
243
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? 'en', page.dir ?? ''),
244
+ redirect,
245
+ });
246
+
247
+ /** The Web-standard Request a server would build, for the middleware. */
248
+ const toRequest = (pathname: string, req: TestRequest = {}, body?: FormData) => {
249
+ const headers = new Headers(req.headers ?? {});
250
+ 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 });
252
+ };
253
+
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
+ */
260
+ const request = async (pathname: string, req: TestRequest, body?: FormData): Promise<TestResult> => {
261
+ if (mod.middleware) {
262
+ const mw = await mod.runMiddleware(toRequest(pathname, req, body), body);
263
+ if (mw) return { status: mw.status, html: await mw.text(), state: {}, head: [], lang: 'en', dir: '', document: await mw.text(), redirect: mw.headers.get('location') ?? undefined };
264
+ }
265
+ const page = await mod.renderPage(pathname, body);
266
+ return result(page);
267
+ };
268
+
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
+ let requests = 0;
273
+ let currentRoute = route;
274
+
275
+ 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
+ const win = ((opts.dom as any)?.window ?? opts.dom ?? globalThis) as any;
279
+ if (!win?.document || !win?.DOMParser) {
280
+ 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.');
281
+ }
282
+ const page = await request(route, req);
283
+
284
+ const doc = win.document;
285
+ 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
+ let stateEl = doc.getElementById('__rosetack_state');
289
+ if (!stateEl) {
290
+ stateEl = doc.createElement('script');
291
+ stateEl.id = '__rosetack_state';
292
+ doc.body.appendChild(stateEl);
293
+ }
294
+ stateEl.textContent = page.state;
295
+ app.innerHTML = page.html;
296
+
297
+ const saved = new Map<string, unknown>();
298
+ for (const key of GRAFTED) {
299
+ saved.set(key, (globalThis as any)[key]);
300
+ (globalThis as any)[key] = win[key] ?? (globalThis as any)[key];
301
+ }
302
+ (globalThis as any).location = { pathname: currentRoute, href: `http://localhost${currentRoute}` };
303
+ (globalThis as any).fetch = async (url: string | URL, init: any) => {
304
+ 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
+ if (pathname.startsWith('/locales/') && pathname.endsWith('.json')) {
308
+ const file = path.join(outDir, pathname.slice(1));
309
+ if (!fs.existsSync(file)) return { ok: false, json: async () => ({}) };
310
+ return { ok: true, json: async () => JSON.parse(fs.readFileSync(file, 'utf-8')) };
311
+ }
312
+ requests++;
313
+ const next = await request(pathname, req, init?.body);
314
+ return { ok: next.status < 400, status: next.status, text: async () => next.document };
315
+ };
316
+
317
+ const client = await import(clientUrl);
318
+ await client.start(app, route, true);
319
+
320
+ const one = (sel?: string): Element | null => (sel ? doc.querySelector(sel) : app);
321
+ const handle: TestHandle = {
322
+ route,
323
+ document: doc,
324
+ window: win,
325
+ text: (sel?: string) => one(sel)?.textContent ?? '',
326
+ html: (sel?: string) => one(sel)?.outerHTML ?? null,
327
+ exists: (sel: string) => !!doc.querySelector(sel),
328
+ click: async (sel: string) => {
329
+ const el = doc.querySelector(sel);
330
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
331
+ el.dispatchEvent(new win.MouseEvent('click', { bubbles: true, cancelable: true }));
332
+ await new Promise((r) => setTimeout(r, 0));
333
+ },
334
+ fill: (sel: string, value: string) => {
335
+ const el = doc.querySelector(sel) as any;
336
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
337
+ el.value = value;
338
+ },
339
+ submit: async (formSel = 'form', fields?: Record<string, unknown>) => {
340
+ const form = doc.querySelector(formSel) as any;
341
+ if (!form) throw new Error(`rosetack/test: no form matches ${formSel}`);
342
+ const body = new win.FormData(form);
343
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
344
+ await client.postForm(body);
345
+ },
346
+ action: async (name: string, fields?: Record<string, unknown>) => {
347
+ const body = new win.FormData();
348
+ body.append('__action', name);
349
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
350
+ await client.postForm(body);
351
+ },
352
+ navigate: async (pathname: string) => {
353
+ currentRoute = pathname;
354
+ (globalThis as any).location = { pathname, href: `http://localhost${pathname}` };
355
+ await client.start(app, pathname, false);
356
+ },
357
+ state: () => {
358
+ const el = doc.getElementById('__rosetack_state');
359
+ return el?.textContent ? JSON.parse(el.textContent) : {};
360
+ },
361
+ requestCount: () => requests,
362
+ };
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
+ (handle as any).restore = () => { for (const [k, v] of saved) (globalThis as any)[k] = v; };
366
+ return handle;
367
+ };
368
+
369
+ return {
370
+ route,
371
+ dir,
372
+ get: async (pathname = route, req?: TestRequest) => request(pathname, req ?? {}),
373
+ post: async (fields?: Record<string, unknown>, req: TestRequest & { route?: string } = {}) => {
374
+ const pathname = req.route ?? route;
375
+ const body = new FormData();
376
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
377
+ return request(pathname, req, body);
378
+ },
379
+ 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
+ if (mod.middleware) {
383
+ const mw = await mod.runMiddleware(toRequest(pathname, req));
384
+ if (mw) return { status: mw.status, body: await mw.text(), headers: { location: mw.headers.get('location') ?? '' } };
385
+ }
386
+ const res = await mod.handleApi(method, pathname, toRequest(pathname, req));
387
+ const text = await res.text();
388
+ let body: unknown = text;
389
+ try {
390
+ body = JSON.parse(text);
391
+ } catch { /* not JSON: hand back the raw text */ }
392
+ const headers: Record<string, string> = {};
393
+ res.headers.forEach((v: string, k: string) => { headers[k] = v; });
394
+ return { status: res.status, body, headers };
395
+ },
396
+ mount,
397
+ };
398
+ }
399
+
400
+ export default test;