rosetack 0.0.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.
@@ -0,0 +1,337 @@
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
+ */
9
+
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ import * as esbuild from 'esbuild';
13
+ import { createHash } from 'crypto';
14
+
15
+ const OUT_DIR = path.join(process.cwd(), 'dist');
16
+
17
+ let clientCache: { mtimeMs: number; source: string } | null = null;
18
+
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
+ let splitMode = false;
22
+ export function setBundleMode(mode: string): void {
23
+ splitMode = mode === 'split';
24
+ }
25
+
26
+ /** Read dist/client.js with an mtime-based cache (dev server rebuilds it). */
27
+ export function getClientSource(): string | null {
28
+ if (splitMode) return null; // mode B: the document references /client.js
29
+ const file = path.join(OUT_DIR, 'client.js');
30
+ try {
31
+ const st = fs.statSync(file);
32
+ if (!clientCache || clientCache.mtimeMs !== st.mtimeMs) {
33
+ clientCache = { mtimeMs: st.mtimeMs, source: fs.readFileSync(file, 'utf-8') };
34
+ }
35
+ return clientCache.source;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ let styleCache: { mtimeMs: number; source: string } | null = null;
42
+
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
+ */
48
+ export function getStyles(): string {
49
+ const file = path.join(OUT_DIR, 'styles.css');
50
+ try {
51
+ const st = fs.statSync(file);
52
+ if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
53
+ styleCache = { mtimeMs: st.mtimeMs, source: fs.readFileSync(file, 'utf-8') };
54
+ }
55
+ return styleCache.source;
56
+ } catch {
57
+ return '';
58
+ }
59
+ }
60
+
61
+ // Bootstrap appended after the inlined bundle: client-side navigation. Distinct names avoid
62
+ // any collision with minified bundle identifiers.
63
+ const BOOTSTRAP = esbuild.transformSync(`
64
+ const __app = document.getElementById('app');
65
+ // Native View Transitions around client-side navigation (progressive:
66
+ // browsers without the API navigate normally, no polyfill, no CSS required).
67
+ function __navigate(pathname) {
68
+ const paint = () => start(__app, pathname);
69
+ if (document.startViewTransition) {
70
+ return document.startViewTransition(paint).updateCallbackDone;
71
+ }
72
+ return paint();
73
+ }
74
+ window.addEventListener('popstate', () => __navigate(window.location.pathname));
75
+ document.addEventListener('click', (e) => {
76
+ const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
77
+ if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
78
+ e.preventDefault();
79
+ history.pushState(null, '', a.getAttribute('href'));
80
+ __navigate(window.location.pathname);
81
+ }
82
+ });
83
+ // Prefetch the target route's full render (including $data) on hover, keyboard
84
+ // focus, or touch - the click that follows paints from cache: no await, no
85
+ // request. Other frameworks prefetch data only; rosetack prefetches the render
86
+ // because the inlined bundle already contains every route.
87
+ function __prefetchHandler(e) {
88
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
89
+ if (a && prefetch) prefetch(a.getAttribute('href'), 'hover');
90
+ }
91
+ document.addEventListener('mouseover', __prefetchHandler);
92
+ document.addEventListener('focusin', __prefetchHandler);
93
+ document.addEventListener('touchstart', __prefetchHandler, { passive: true });
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
+ // APIs are feature-detected; without them the hover/focus/touch path above
97
+ // still covers every link.
98
+ if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
99
+ const io = new IntersectionObserver((entries) => {
100
+ for (const e of entries) {
101
+ if (!e.isIntersecting) continue;
102
+ io.unobserve(e.target); // one-shot per element; fresh links re-observe after nav
103
+ requestIdleCallback(() => prefetch(e.target.getAttribute('href'), 'viewport'));
104
+ }
105
+ });
106
+ // observing an already-observed element is a no-op, so re-sweeping is cheap
107
+ const observeLinks = () => {
108
+ for (const a of document.querySelectorAll('a[href^="/"]')) io.observe(a);
109
+ };
110
+ observeLinks();
111
+ // navigation swaps the container's innerHTML: re-observe the fresh links
112
+ const __rawNav = __navigate;
113
+ __navigate = (p) => __rawNav(p).then(observeLinks, () => {});
114
+ }
115
+ // Progressive-enhancement forms: <form method="POST"> backed by a server
116
+ // action. With JS the submit is intercepted and handed to postForm (one
117
+ // request, in-place adopt). Without JS the browser performs the native POST
118
+ // and the server re-renders the page: the same form works with JavaScript
119
+ // disabled, which Server Actions in other frameworks do not.
120
+ document.addEventListener('submit', (e) => {
121
+ const f = e.target;
122
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
123
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
124
+ e.preventDefault();
125
+ postForm(new FormData(f));
126
+ });
127
+ // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
128
+ // If the document was rendered for a DIFFERENT route (a static-file server's
129
+ // SPA fallback serves index.html for unknown paths), adopt nothing - let the
130
+ // client router render the requested route from scratch.
131
+ const __st = document.getElementById('__rosetack_state');
132
+ const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
133
+ if (__state.__route === window.location.pathname) {
134
+ start(__app, window.location.pathname, true);
135
+ } else {
136
+ start(__app, window.location.pathname);
137
+ }
138
+ `, { minify: true }).code;
139
+
140
+ // The document inlines its entire runtime, so rosetack can ship a STRICT content security
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'`;
143
+ let cspCache: { for: string | null; value: string } | null = null;
144
+ // The exact bytes between the external bootstrap's script tags - the single source of truth
145
+ // shared by the tag and the CSP hash …
146
+ const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm } from '/client.js';\n${BOOTSTRAP}`;
147
+ // The exact bytes between the module script's tags - the single source of truth shared by
148
+ // the tag and the CSP hash, so the policy can never drift from what actually ships.
149
+ function inlineScript(client: string): string {
150
+ return `\n${client}\n${BOOTSTRAP}`;
151
+ }
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}` };
186
+ if (!cspCache || cspCache.for !== client) {
187
+ // client === null: split mode (or the edge without a built client.js). 'self' covers
188
+ // the external modules and chunks, the hash covers the inline bootstrap …
189
+ const scriptSrc = client
190
+ ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
191
+ : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
192
+ cspCache = {
193
+ for: client,
194
+ value: `script-src ${scriptSrc}; ${CSP_TAIL}`,
195
+ };
196
+ }
197
+ return { 'Content-Security-Policy': cspCache.value };
198
+ }
199
+
200
+ // An inline SVG favicon (the rose). Without it every browser requests /favicon.ico on every
201
+ // page load - one wasted request per visit.
202
+ 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==">';
203
+
204
+ // Shared by the buffered shell and the streaming shell-open so both produce
205
+ // byte-identical static markup.
206
+ const STYLES = `
207
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
208
+ button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
209
+ a { color: #e91e63; text-decoration: none; font-weight: bold; }
210
+ a:hover { text-decoration: underline; }
211
+ nav a { margin-right: 1rem; }
212
+ .rh { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; border-bottom: 2px solid #e91e63; margin-bottom: 1.5rem; padding-bottom: 0.75rem; }
213
+ .rb { font-size: 1.6rem; }
214
+ .rbrand { display: inline-flex; align-items: center; gap: 0.5em; }
215
+ .rlogo { height: 1em; width: 1em; vertical-align: -0.08em; margin-right: 0.2em; }
216
+ @media (max-width: 640px) {
217
+ .rh { flex-direction: column; align-items: flex-start; gap: 0.75rem; }
218
+ nav a:last-child { margin-right: 0; }
219
+ }
220
+ .rn { display: inline-block; margin-left: 1.5rem; }
221
+ .rf { margin-top: 2rem; color: #888; font-size: 0.85rem; }
222
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
223
+ `;
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
+
231
+ /**
232
+ * Merge the route chain's <head> blocks (document order: page first, then its
233
+ * layouts) into one clean <head> fragment. First occurrence wins per key, so a
234
+ * page overrides its layouts - matching the client's reverse-order applyHead.
235
+ */
236
+ function mergeHeadBlocks(blocks: string[]): string {
237
+ const byKey = new Map<string, string>();
238
+ const order: string[] = [];
239
+ // first occurrence wins: blocks arrive page-first (a page renders inside its
240
+ // layouts' <slot/>), so the page's title/meta override the layouts'
241
+ const put = (key: string, html: string) => {
242
+ if (!byKey.has(key)) {
243
+ byKey.set(key, html);
244
+ order.push(key);
245
+ }
246
+ };
247
+ for (const block of blocks) {
248
+ // title carries content, so it needs its own pattern
249
+ for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put('title', m[0]);
250
+ for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
251
+ const tag = m[1].toLowerCase();
252
+ const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
253
+ const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
254
+ // keyed tags carry their key (must match HEAD_ATTR in the runtime) so the client
255
+ // adopts these SSR-injected elements in place on the first navigation instead of …
256
+ const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
257
+ put(key, marked);
258
+ }
259
+ }
260
+ return order.map((k) => byKey.get(k)!).join('\n ');
261
+ }
262
+
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}"` : '';
273
+ return client
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>`;
276
+ }
277
+
278
+ /**
279
+ * The static half of the document for streaming SSR: everything up to (and
280
+ * including) the open `<div id="app">`. No route tags - the route's <head>
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.
287
+ */
288
+ export function shellOpen(styles: string = getStyles(), lang = 'en', dir = ''): string {
289
+ const styleTag = styles ? `\n <style>${styles}</style>` : '';
290
+ return `<!DOCTYPE html>
291
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
292
+ <head>
293
+ <meta charset="UTF-8">
294
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
295
+ <title>RoseTack</title>
296
+ <style>${STYLES_MIN}</style>${styleTag}
297
+ ${FAVICON}
298
+ </head>
299
+ <body>
300
+ <div id="app">`;
301
+ }
302
+
303
+ /** Build the document from an explicit client source (edge runtimes have no fs). */
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);
306
+
307
+ const mergedHead = mergeHeadBlocks(head);
308
+ // a route-provided <title> replaces the default one
309
+ const titleTag = /<title>/i.test(mergedHead) ? '' : '<title>RoseTack</title>';
310
+ // a route-provided icon replaces the inline favicon
311
+ const iconTag = /rel=["']?icon/i.test(mergedHead) ? '' : `\n ${FAVICON}`;
312
+ const headTags = mergedHead ? `\n ${mergedHead}` : '';
313
+ const styleTag = styles ? `\n <style>${styles}</style>` : '';
314
+ // js=false (a route exporting csr = false): the document ends at the container - no state
315
+ // script, no inlined bundle, zero JavaScript.
316
+ const jsTail = js
317
+ ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
318
+ : '';
319
+
320
+ return `<!DOCTYPE html>
321
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
322
+ <head>
323
+ <meta charset="UTF-8">
324
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
325
+ ${titleTag}
326
+ <style>${STYLES_MIN}</style>${styleTag}
327
+ </head>
328
+ <body>
329
+ <div id="app">${ssrHtml}</div>${jsTail}
330
+ </body>
331
+ </html>`;
332
+ }
333
+
334
+ /** Node entry: reads dist/client.js from disk (mtime-cached). */
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);
337
+ }