rosetack 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/deploy/k8s/rosetack.yaml +107 -0
  2. package/dist-cli/compiler.mjs +2783 -0
  3. package/dist-cli/edge.mjs +332 -0
  4. package/dist-cli/rosetack.mjs +4230 -0
  5. package/dist-cli/runtime.mjs +703 -0
  6. package/dist-cli/test.mjs +3202 -0
  7. package/pack.mjs +49 -0
  8. package/package.json +25 -7
  9. package/src/FRAMEWORK_VERSION +1 -1
  10. package/src/cli/edge.ts +67 -25
  11. package/src/cli/index.ts +858 -94
  12. package/src/cli/prompt.ts +127 -0
  13. package/src/cli/shell.ts +133 -30
  14. package/src/cli/test.ts +400 -0
  15. package/src/compiler/errors.ts +74 -0
  16. package/src/compiler/index.ts +1955 -264
  17. package/src/runtime/index.ts +465 -66
  18. package/src/types/rosetack.d.ts +151 -0
  19. package/.github/workflows/ci.yml +0 -72
  20. package/.github/workflows/release.yml +0 -122
  21. package/benchmark.ts +0 -227
  22. package/example/public/favicon.ico +0 -0
  23. package/example/public/logo.svg +0 -148
  24. package/example/public/rose-mark-black.png +0 -0
  25. package/example/public/rose-mark.png +0 -0
  26. package/example/public/rose-mono.png +0 -0
  27. package/example/rosetack.config.js +0 -10
  28. package/example/src/locales/en.json +0 -8
  29. package/example/src/locales/zh.json +0 -8
  30. package/example/src/pages/404.rose +0 -15
  31. package/example/src/pages/500.rose +0 -10
  32. package/example/src/pages/[lang]/about.rose +0 -40
  33. package/example/src/pages/_layout.rose +0 -33
  34. package/example/src/pages/_middleware.rose +0 -37
  35. package/example/src/pages/about.rose +0 -67
  36. package/example/src/pages/admin.rose +0 -27
  37. package/example/src/pages/api/hello.rose +0 -19
  38. package/example/src/pages/api/login.rose +0 -55
  39. package/example/src/pages/api/posts.rose +0 -80
  40. package/example/src/pages/api/secret.rose +0 -14
  41. package/example/src/pages/blog/[id].rose +0 -25
  42. package/example/src/pages/broken.rose +0 -16
  43. package/example/src/pages/fresh.rose +0 -22
  44. package/example/src/pages/garden.rose +0 -27
  45. package/example/src/pages/index.rose +0 -84
  46. package/example/src/pages/sign.rose +0 -45
  47. package/example/src/pages/thorn.rose +0 -23
  48. package/example/src/pages/vault.rose +0 -14
  49. package/go.mod +0 -3
  50. package/main.go +0 -470
  51. package/tools/release-notes.mjs +0 -113
  52. package/tsconfig.json +0 -17
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The canonical .rose authoring contract, printed by `rosetack prompt`.
3
+ *
4
+ * Why a command and not a doc page: the audience is as often an AI agent as
5
+ * a human, and the agent needs the contract at the moment it writes code,
6
+ * not a URL to go read. One command, stdout, no network - the same shape as
7
+ * every other tool an agent already shells out to.
8
+ *
9
+ * The content is the compiler's actual rules, in the order a page meets
10
+ * them: file layout, the script block, the template, head and styles,
11
+ * events and actions, the exports, the npm boundary, and the error
12
+ * contract. Anything the compiler REFUSES is listed as a rule here, so a
13
+ * correct page compiles on the first try.
14
+ */
15
+ export const AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
16
+
17
+ rosetack is a zero-hydration web framework: a .rose file compiles to a server
18
+ render plus a client resume bundle, one request per page, no hydration. Write
19
+ the smallest thing that works - the compiler decides what ships.
20
+
21
+ ## File layout (all paths relative to the project root)
22
+
23
+ - src/pages/index.rose -> route /
24
+ - src/pages/about.rose -> route /about
25
+ - src/pages/blog/[id].rose -> route /blog/:id (the param is readable as state \`id()\`)
26
+ - src/pages/[lang]/about.rose -> localized route (see i18n below)
27
+ - src/pages/_layout.rose -> root layout wrapping every route (app-global exports live here)
28
+ - src/pages/_middleware.rose -> server-only request middleware (handle(request), getContext())
29
+ - src/pages/404.rose, 500.rose -> error pages
30
+ - src/pages/api/posts.rose -> JSON API route (export async function GET/POST/...)
31
+ - src/components/Card.rose -> reusable component, imported by relative path
32
+ - src/locales/en.json -> i18n dictionaries (one file per language)
33
+
34
+ ## A page
35
+
36
+ \`\`\`rose
37
+ <script>
38
+ let count = $state(0); // reactive state: read it as count()
39
+ let posts = $data(async () => db.query()); // server data: awaited on the server,
40
+ // resumed on the client - never re-fetched
41
+ const total = count() + 1; // a top-level read AFTER the declaration is fine
42
+ async function like() { // a server action (progressive enhancement)
43
+ return $merge({ likes: 1 });
44
+ }
45
+ </script>
46
+
47
+ <h1>Posts</h1>
48
+ <p>Total: {total}</p>
49
+ <button on:click={() => $setState('count', count() + 1)}>+1</button>
50
+ <form method="POST"><button formaction="?__action=like">Like</button></form>
51
+ \`\`\`
52
+
53
+ Rules the compiler enforces (breaking one fails the build):
54
+
55
+ - The script block is TypeScript. Types, interfaces, \`import type\`, \`as\` casts and
56
+ type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
57
+ - $state / $data declarations are top-level statements. The declared name IS the
58
+ getter: write count() in the template and the script, never bare count.
59
+ - A route param (pages/blog/[id].rose) is read as state too: declare it
60
+ (\`let id = $state('1')\`) and read id() - the server overwrites the default
61
+ with the URL's value, and export const params = { id: [...] } bakes those
62
+ values at build time.
63
+ - $data() is banned in components (src/components/**) - a component renders
64
+ synchronously inside its parent. Fetch in the page or the middleware and pass
65
+ the value down as a prop.
66
+ - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
67
+ trusted-HTML escape hatch - use it only for content you control.
68
+ - Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
69
+ {#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
70
+ - A <slot> with attributes is a named slot and must declare its name:
71
+ <slot name="row" item={post} />. A named slot must be a DIRECT child of the
72
+ component tag - never inside another element or an {#if}/{#each} block.
73
+ - Every component tag needs its matching close tag (or self-closes with />).
74
+ - In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
75
+ through. A <style> inside <head> is document CSS; a <style> in the body is
76
+ the component's scoped stylesheet.
77
+ - Node-only modules (node:fs, better-sqlite3, pg, redis, ...) are REFUSED in
78
+ pages and components: their script ships to the browser. Import them in
79
+ src/pages/_middleware.rose or a pages/api/*.rose handler instead, and pass
80
+ the rows to the page through getContext().
81
+
82
+ ## Events and server actions
83
+
84
+ - on:click={handler} wires a client event. The handler is a named function from
85
+ the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
86
+ - A server action is an exported async function. Call it from a native form
87
+ (method="POST", no JS needed - progressive enhancement) or from any event
88
+ (on:click={like} - one POST, in-place adopt). Its return value is an
89
+ incremental patch: $append(row) / $prepend(row) / $merge({...}).
90
+ - Business failures: throw new ActionError('message', 422, 'field'). It lands
91
+ in ordinary state - $actionError() reads it back, a {#boundary} contains it.
92
+ - beforeAction(name, form) is the per-page guard that vetoes an action.
93
+
94
+ ## Route exports (in the script block, validated at build time)
95
+
96
+ - export const csr = false | true force/assert zero-JS (absent = the compiler decides)
97
+ - export const buffer = true keep this route off the streaming path
98
+ - export const headers = { ... } flat string map, merged over the strict CSP default
99
+ - export const csp = { nonce: true } per-response nonce instead of the hash (route becomes dynamic)
100
+ - export const prefetch = 'off' | 'hover' | 'viewport' | 'all' app-global, root layout only
101
+ - export const bundle = 'inline' | 'split' app-global; 'split' = mode B for large apps
102
+ - export const vitals = true opt into the web-vitals hook
103
+ - export const revalidate = N stale-while-revalidate ISR window, seconds
104
+ - export const params = { id: ['1'] } prerender these param values at build time
105
+ - export const prerender = true (api routes) bake the GET body for static deploys
106
+
107
+ ## i18n
108
+
109
+ src/locales/<lang>.json is a dictionary; a [lang] route segment selects one;
110
+ $t('key', { name }) translates reactively; unknown locales answer 404.
111
+
112
+ ## When a build fails
113
+
114
+ Every compiler failure is structured: { code, file, line, message, hint }.
115
+ Run \`rosetack build --json\` to read it as JSON, fix the named file at the named
116
+ line, and build again. Codes: E-IMPORT (unresolvable .rose import), E-PLUGIN
117
+ (transform threw), E-NODE-ONLY (server-only import in a page/component),
118
+ E-EXPORT (invalid export const value), E-TEMPLATE (unclosed tag / slot
119
+ placement), E-ROUTE (no pages found), E-INTERNAL (installation problem).
120
+
121
+ ## The one invariant worth protecting
122
+
123
+ A route ships ONE request with ZERO hydration: the whole client bundle is
124
+ inlined in the document. Keep it that way - browser-only code (document.,
125
+ window., timers) belongs in onMount, and anything the predicate cannot see
126
+ (inline on* attributes, javascript: URLs, eval) is reported by the build.
127
+ `;
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) {
@@ -124,13 +124,34 @@ document.addEventListener('submit', (e) => {
124
124
  e.preventDefault();
125
125
  postForm(new FormData(f));
126
126
  });
127
+ // Dev seam: the live signal graph, readable as JSON. Two callers, one
128
+ // implementation: the dev server's reload bridge snapshots it before a
129
+ // 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() };
127
134
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
128
135
  // If the document was rendered for a DIFFERENT route (a static-file server's
129
136
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
130
137
  // client router render the requested route from scratch.
131
138
  const __st = document.getElementById('__rosetack_state');
132
- const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
133
- if (__state.__route === window.location.pathname) {
139
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
140
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
141
+ // the next document (window.__rosetack_resume). The resumed values win over the
142
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
143
+ // the route renders client-side from the bundle rather than adopting the SSR
144
+ // DOM, because a resumed list can be longer than the document's rows and
145
+ // adoption could not add them. Absent in every non-dev document.
146
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
147
+ if (__resumed) {
148
+ const __route = __state.__route;
149
+ __state = Object.assign(__state, __resumed);
150
+ __state.__route = __route;
151
+ }
152
+ if (__resumed) {
153
+ start(__app, window.location.pathname);
154
+ } else if (__state.__route === window.location.pathname) {
134
155
  start(__app, window.location.pathname, true);
135
156
  } else {
136
157
  start(__app, window.location.pathname);
@@ -139,6 +160,7 @@ if (__state.__route === window.location.pathname) {
139
160
 
140
161
  // The document inlines its entire runtime, so rosetack can ship a STRICT content security
141
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'`;
142
164
  let cspCache: { for: string | null; value: string } | null = null;
143
165
  // The exact bytes between the external bootstrap's script tags - the single source of truth
144
166
  // shared by the tag and the CSP hash …
@@ -148,7 +170,40 @@ const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm } from '/client
148
170
  function inlineScript(client: string): string {
149
171
  return `\n${client}\n${BOOTSTRAP}`;
150
172
  }
151
- export function securityHeaders(client: string | null): Record<string, string> {
173
+ /**
174
+ * A fresh CSP nonce: 128 bits from the platform RNG, base64 - the syntax the
175
+ * header and the tag share . Web Crypto on purpose: the same helper
176
+ * serves the Node server and the edge adapter, and an edge runtime has no
177
+ * node:crypto. Minted per response and never reused: a nonce is only worth
178
+ * anything an attacker cannot predict, and a repeated one would hand a
179
+ * guessed value unlimited script execution.
180
+ */
181
+ export function mintNonce(): string {
182
+ const bytes = new Uint8Array(16);
183
+ crypto.getRandomValues(bytes);
184
+ let raw = '';
185
+ for (const b of bytes) raw += String.fromCharCode(b);
186
+ return btoa(raw);
187
+ }
188
+
189
+ /**
190
+ * The document's CSP. Two shapes, chosen per response:
191
+ *
192
+ * - no nonce (the default): `script-src 'sha256-…'` over the exact bytes the
193
+ * tag will carry. Nothing else may run - the strongest policy rosetack has,
194
+ * and the reason a rosetack document needs no 'unsafe-inline'.
195
+ * - a nonce (a route exporting `csp = { nonce: true }`):
196
+ * `script-src 'nonce-…' 'strict-dynamic'`. A hash dies the moment anything
197
+ * between the server and the browser touches the document - a CDN, a WAF,
198
+ * an A/B injector that adds one byte blocks the page's own bundle. A nonce
199
+ * survives that, and 'strict-dynamic' lets the page's own code load more
200
+ * code (a third-party loader, a lazily imported chunk), which is the reason
201
+ * a deployment reaches for a nonce in the first place. It is weaker in one
202
+ * way: whatever the document's script loads is trusted. That is the trade
203
+ * the route opts into, per route, not a framework default.
204
+ */
205
+ export function securityHeaders(client: string | null, nonce = ''): Record<string, string> {
206
+ if (nonce) return { 'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
152
207
  if (!cspCache || cspCache.for !== client) {
153
208
  // client === null: split mode (or the edge without a built client.js). 'self' covers
154
209
  // the external modules and chunks, the hash covers the inline bootstrap …
@@ -157,7 +212,7 @@ export function securityHeaders(client: string | null): Record<string, string> {
157
212
  : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
158
213
  cspCache = {
159
214
  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'`,
215
+ value: `script-src ${scriptSrc}; ${CSP_TAIL}`,
161
216
  };
162
217
  }
163
218
  return { 'Content-Security-Policy': cspCache.value };
@@ -188,14 +243,36 @@ const STYLES = `
188
243
  ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
189
244
  `;
190
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
+ const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g, (m) =>
249
+ m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, ' ').replace(/\s*([:;{},])\s*/g, '$1').trim()
250
+ ).trim();
251
+
191
252
  /**
192
253
  * Merge the route chain's <head> blocks (document order: page first, then its
193
254
  * layouts) into one clean <head> fragment. First occurrence wins per key, so a
194
255
  * page overrides its layouts - matching the client's reverse-order applyHead.
256
+ *
257
+ * Bug report 2026.9.22 11:46: the keyed whitelist used to be title plus
258
+ * meta/link/base and NOTHING else, so a `<style>` block, a
259
+ * `<script type="application/ld+json">` data block and a `<noscript>`
260
+ * fallback were dropped here in silence - the compiler collected them, the
261
+ * merge threw them away, and a CMS theme system had no way to ship its
262
+ * per-request CSS. Every head element now passes through: the keyed
263
+ * singletons keep their name/property/rel/charset identity, and everything
264
+ * else is keyed by id when it has one and by tag+position when it does not,
265
+ * so two layouts' <style> blocks coexist and a page still overrides its
266
+ * layout's. Passthrough elements carry HEAD_ATTR too (the attribute the
267
+ * runtime manages) so a client-side navigation replaces or drops them like
268
+ * any other managed element instead of leaking the previous route's CSS
269
+ * into every route visited after it.
195
270
  */
196
271
  function mergeHeadBlocks(blocks: string[]): string {
197
272
  const byKey = new Map<string, string>();
198
273
  const order: string[] = [];
274
+ // positional keys: tag -> how many unkeyed elements of that tag came before
275
+ const positional = new Map<string, number>();
199
276
  // first occurrence wins: blocks arrive page-first (a page renders inside its
200
277
  // layouts' <slot/>), so the page's title/meta override the layouts'
201
278
  const put = (key: string, html: string) => {
@@ -207,40 +284,64 @@ function mergeHeadBlocks(blocks: string[]): string {
207
284
  for (const block of blocks) {
208
285
  // title carries content, so it needs its own pattern
209
286
  for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put('title', m[0]);
210
- for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
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
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
211
290
  const tag = m[1].toLowerCase();
212
- const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
213
- const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
291
+ if (tag === 'title') continue; // handled above, with its own key
292
+ const attrs = m[2];
293
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
294
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
295
+ let key: string;
296
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
297
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
298
+ else {
299
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
300
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
301
+ }
214
302
  // keyed tags carry their key (must match HEAD_ATTR in the runtime) so the client
215
303
  // adopts these SSR-injected elements in place on the first navigation instead of …
216
- const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
304
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
217
305
  put(key, marked);
218
306
  }
219
307
  }
220
308
  return order.map((k) => byKey.get(k)!).join('\n ');
221
309
  }
222
310
 
223
- /** The script tag carrying the inlined bundle (+ bootstrap), or the external fallback. */
224
- export function clientScriptTag(client: string | null): string {
311
+ /**
312
+ * The script tag carrying the inlined bundle (+ bootstrap), or the external
313
+ * fallback. `nonce` stamps the same value the CSP header carries, so
314
+ * a route running a nonce policy has its own code allowed to run; without it
315
+ * the tag is byte-identical to what the sha256 in the header was computed
316
+ * over. Both tags in split mode get it: the external module and the inline
317
+ * bootstrap are the same trust root.
318
+ */
319
+ export function clientScriptTag(client: string | null, nonce = ''): string {
320
+ const n = nonce ? ` nonce="${nonce}"` : '';
225
321
  return client
226
- ? `<script type="module">${inlineScript(client)}</script>`
227
- : `<script type="module" src="/client.js"></script>\n<script type="module">${EXTERNAL_BOOTSTRAP}</script>`;
322
+ ? `<script type="module"${n}>${inlineScript(client)}</script>`
323
+ : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
228
324
  }
229
325
 
230
326
  /**
231
327
  * The static half of the document for streaming SSR: everything up to (and
232
328
  * including) the open `<div id="app">`. No route tags - the route's <head>
233
329
  * content is applied by the client at boot from the body's head markers.
330
+ *
331
+ * `lang`/`dir` are the document's locale and reading direction ( the
332
+ * servers compute them from the [lang] segment with the server bundle's
333
+ * docAttrs). The streaming path flushes this string BEFORE the render, so
334
+ * the browser gets the language metadata in the first byte.
234
335
  */
235
- export function shellOpen(styles: string = getStyles()): string {
336
+ export function shellOpen(styles: string = getStyles(), lang = 'en', dir = ''): string {
236
337
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
237
338
  return `<!DOCTYPE html>
238
- <html lang="en">
339
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
239
340
  <head>
240
341
  <meta charset="UTF-8">
241
342
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
242
343
  <title>RoseTack</title>
243
- <style>${STYLES}</style>${styleTag}
344
+ <style>${STYLES_MIN}</style>${styleTag}
244
345
  ${FAVICON}
245
346
  </head>
246
347
  <body>
@@ -248,8 +349,8 @@ export function shellOpen(styles: string = getStyles()): string {
248
349
  }
249
350
 
250
351
  /** 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);
352
+ export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true, lang = 'en', dir = '', nonce = ''): string {
353
+ const clientTag = clientScriptTag(client, nonce);
253
354
 
254
355
  const mergedHead = mergeHeadBlocks(head);
255
356
  // a route-provided <title> replaces the default one
@@ -258,27 +359,29 @@ export function buildShell(ssrHtml: string, stateJson: string, client: string |
258
359
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? '' : `\n ${FAVICON}`;
259
360
  const headTags = mergedHead ? `\n ${mergedHead}` : '';
260
361
  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.
362
+ // js=false (a route exporting csr = false): the document ends at the container - no state
363
+ // script, no inlined bundle, zero JavaScript.
263
364
  const jsTail = js
264
365
  ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
265
366
  : '';
367
+ const open = js ? '<div id="app">' : '';
368
+ const close = js ? '</div>' : '';
369
+ const shellStyles = js ? `\n <style>${STYLES_MIN}</style>` : '';
266
370
 
267
371
  return `<!DOCTYPE html>
268
- <html lang="en">
372
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
269
373
  <head>
270
374
  <meta charset="UTF-8">
271
375
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
272
- ${titleTag}
273
- <style>${STYLES}</style>${styleTag}
376
+ ${titleTag}${shellStyles}${styleTag}
274
377
  </head>
275
378
  <body>
276
- <div id="app">${ssrHtml}</div>${jsTail}
379
+ ${open}${ssrHtml}${close}${jsTail}
277
380
  </body>
278
381
  </html>`;
279
382
  }
280
383
 
281
384
  /** 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);
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);
284
387
  }