rosetack 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,324 @@
1
+ (globalThis as any).__rosetack_SKIP_MINIFY = true;
2
+
3
+ import http from 'node:http';
4
+ import { Readable } from 'node:stream';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import zlib from 'node:zlib';
8
+ import { createHash } from 'node:crypto';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { createEdgeHandler } from './edge.ts';
11
+
12
+ const dist = fileURLToPath(new URL('./', import.meta.url));
13
+ const port = Number(process.env.PORT || 8080);
14
+ let handle: ((request: Request) => Promise<Response>) | null = null;
15
+ let mod: any = null;
16
+ let warmList: string[] = [];
17
+
18
+ const earlyHintLinks: string[] = (() => {
19
+ try {
20
+ const html = fs.readFileSync(path.join(dist, 'index.html'), 'utf8');
21
+ const links: string[] = [];
22
+ for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
23
+ const v = `<${m[1]}>; rel=preload; as=script`;
24
+ if (!links.includes(v)) links.push(v);
25
+ }
26
+ for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
27
+ const href = /href="([^"]+)"/.exec(m[0])?.[1];
28
+ if (href) { const v = `<${href}>; rel=preload; as=style`; if (!links.includes(v)) links.push(v); }
29
+ }
30
+ for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
31
+ const v = `<${m[1]}>; rel=preload; as=style`;
32
+ if (!links.includes(v)) links.push(v);
33
+ }
34
+ return links;
35
+ } catch { return []; }
36
+ })();
37
+
38
+ const ready = createEdgeHandler(dist).then(async (h) => {
39
+ handle = h;
40
+ try {
41
+ mod = await import(new URL('./server.js', import.meta.url).href);
42
+ warmList = ['/', ...((mod.dynamicRoutes as string[]) || []).filter((r: string) => !r.includes(':'))];
43
+ } catch { /* warm list stays just the home route */ }
44
+ });
45
+
46
+ const hotCache = new Map<string, { raw: Buffer; br: Buffer; gzip: Buffer; headers: Record<string, string>; etag: string; fetchedAt: number; refreshing?: boolean }>();
47
+ const HOT_TTL = 10_000;
48
+
49
+ function fnv(s: string): string {
50
+ let h = 0x811c9dc5;
51
+ for (let i = 0; i < s.length; i++) {
52
+ h ^= s.charCodeAt(i);
53
+ h = (h * 0x01000193) >>> 0;
54
+ }
55
+ return h.toString(16);
56
+ }
57
+
58
+ async function refetchHot(pathname: string, cookieHeader: string): Promise<void> {
59
+ const headers: Record<string, string> = { 'user-agent': 'rosetack-hot' };
60
+ if (cookieHeader) headers.cookie = cookieHeader;
61
+ const response = await handle!(new Request('http://localhost' + pathname, { headers }));
62
+ const csp = response.headers.get('content-security-policy') || '';
63
+ const key = pathname + '|' + fnv(cookieHeader);
64
+ if (response.status !== 200 || csp.includes('nonce-')) {
65
+ hotCache.delete(key);
66
+ return;
67
+ }
68
+ const head: Record<string, string> = {};
69
+ response.headers.forEach((v, k) => { if (k !== 'content-length' && k !== 'date' && k !== 'content-encoding') head[k] = v; });
70
+ const raw = Buffer.from(await response.arrayBuffer());
71
+ const compressed = raw.length > 1024;
72
+ hotCache.set(key, {
73
+ raw,
74
+ br: compressed ? zlib.brotliCompressSync(raw) : raw,
75
+ gzip: compressed ? zlib.gzipSync(raw, { level: 9 }) : raw,
76
+ compressed,
77
+ headers: head,
78
+ etag: `W/"${raw.length}-${fnv(cookieHeader)}"`,
79
+ fetchedAt: Date.now(),
80
+ });
81
+ }
82
+
83
+ function warmHot(pathname: string, cookieHeader: string): void {
84
+ refetchHot(pathname, cookieHeader)
85
+ .catch(() => {
86
+ const e = hotCache.get(pathname + '|' + fnv(cookieHeader));
87
+ if (e) { e.refreshing = false; e.fetchedAt = Date.now() - HOT_TTL + 2000; }
88
+ })
89
+ .finally(() => {
90
+ const e = hotCache.get(pathname + '|' + fnv(cookieHeader));
91
+ if (e) e.refreshing = false;
92
+ });
93
+ }
94
+
95
+ function tryHot(req: http.IncomingMessage, res: http.ServerResponse): boolean {
96
+ if (req.method !== 'GET') return false;
97
+ const q = req.url || '/';
98
+ const qm = q.indexOf('?');
99
+ if (qm >= 0) return false;
100
+ const cookieHeader = String(req.headers.cookie || '');
101
+ const key = q + '|' + fnv(cookieHeader);
102
+ const entry = hotCache.get(key);
103
+ if (!entry) return false;
104
+ const age = Date.now() - entry.fetchedAt;
105
+ if (age > HOT_TTL && !entry.refreshing) {
106
+ entry.refreshing = true;
107
+ warmHot(q, cookieHeader);
108
+ }
109
+ res.statusCode = 200;
110
+ for (const k in entry.headers) res.setHeader(k, entry.headers[k]);
111
+ res.setHeader('ETag', entry.etag);
112
+ if (req.headers['if-none-match'] === entry.etag) {
113
+ res.statusCode = 304;
114
+ res.end();
115
+ return true;
116
+ }
117
+ const compressed = (entry as any).compressed !== false;
118
+ const accept = String(req.headers['accept-encoding'] || '');
119
+ const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
120
+ if (enc) {
121
+ res.setHeader('Content-Encoding', enc);
122
+ res.end(enc === 'br' ? entry.br : entry.gzip);
123
+ } else {
124
+ res.end(entry.raw);
125
+ }
126
+ return true;
127
+ }
128
+
129
+ function fillHot(pathname: string, cookieHeader: string, response: Response): void {
130
+ const csp = response.headers.get('content-security-policy') || '';
131
+ if (response.status !== 200 || csp.includes('nonce-')) return;
132
+ const head: Record<string, string> = {};
133
+ response.headers.forEach((v, k) => { if (k !== 'content-length' && k !== 'date' && k !== 'content-encoding') head[k] = v; });
134
+ response.arrayBuffer().then((ab) => {
135
+ const raw = Buffer.from(ab);
136
+ hotCache.set(pathname + '|' + fnv(cookieHeader), {
137
+ raw,
138
+ compressed: raw.length > 1024,
139
+ br: raw.length > 1024 ? zlib.brotliCompressSync(raw) : raw,
140
+ gzip: raw.length > 1024 ? zlib.gzipSync(raw, { level: 9 }) : raw,
141
+ headers: head,
142
+ etag: `W/"${raw.length}-${fnv(cookieHeader)}"`,
143
+ fetchedAt: Date.now(),
144
+ });
145
+ }).catch(() => {});
146
+ }
147
+
148
+ const fileCache = new Map<string, { raw: Buffer; br: Buffer; gzip: Buffer; etag: string; mtimeMs: number }>();
149
+ const TYPES: Record<string, string> = {
150
+ '.html': 'text/html; charset=utf-8',
151
+ '.js': 'application/javascript; charset=utf-8',
152
+ '.css': 'text/css; charset=utf-8',
153
+ '.json': 'application/json; charset=utf-8',
154
+ '.svg': 'image/svg+xml',
155
+ '.png': 'image/png',
156
+ '.jpg': 'image/jpeg',
157
+ '.webp': 'image/webp',
158
+ '.ico': 'image/x-icon',
159
+ '.woff2': 'font/woff2',
160
+ '.txt': 'text/plain; charset=utf-8',
161
+ '.xml': 'application/xml',
162
+ '.webmanifest': 'application/manifest+json',
163
+ };
164
+
165
+ try {
166
+ const raw = fs.readFileSync(new URL('../.env', import.meta.url), 'utf-8');
167
+ for (const line of raw.split(/\r?\n/)) {
168
+ const t = line.trim();
169
+ if (!t || t.startsWith('#')) continue;
170
+ const eq = t.indexOf('=');
171
+ if (eq <= 0) continue;
172
+ const k = t.slice(0, eq).trim();
173
+ let v = t.slice(eq + 1).trim();
174
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
175
+ if (!(k in process.env)) process.env[k] = v;
176
+ }
177
+ } catch { /* no .env: fine */ }
178
+ const REVALIDATE_TOKEN = process.env.rosetack_REVALIDATE_TOKEN || '';
179
+ let revalidateMod: any = null;
180
+
181
+ function handleRevalidate(req: http.IncomingMessage, res: http.ServerResponse): boolean {
182
+ if (req.method !== 'POST' || !req.url!.startsWith('/__rosetack/revalidate')) return false;
183
+ if (!REVALIDATE_TOKEN) { res.statusCode = 404; res.end(); return true; }
184
+ if (req.headers['x-rosetack-token'] !== REVALIDATE_TOKEN) {
185
+ res.statusCode = 403; res.setHeader('content-type', 'application/json');
186
+ res.end(JSON.stringify({ error: 'invalid token' })); return true;
187
+ }
188
+ let body = '';
189
+ req.on('data', (c) => { body += c; if (body.length > 1e6) req.destroy(); });
190
+ req.on('end', () => {
191
+ try {
192
+ if (!revalidateMod) revalidateMod = mod;
193
+ const payload = JSON.parse(body || '{}');
194
+ if (payload.all) {
195
+ revalidateMod.invalidateRenderCache();
196
+ res.end(JSON.stringify({ revalidated: true, scope: 'all' }));
197
+ } else {
198
+ let n = 0;
199
+ for (const p of payload.paths || []) n += revalidateMod.invalidatePath(String(p));
200
+ res.end(JSON.stringify({ revalidated: true, paths: (payload.paths || []).length, dropped: n }));
201
+ }
202
+ } catch (e: any) {
203
+ res.statusCode = 400; res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
204
+ }
205
+ });
206
+ return true;
207
+ }
208
+
209
+ function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, rawUrl: string): boolean {
210
+ let pathname: string;
211
+ try {
212
+ pathname = decodeURIComponent(new URL('http://localhost' + rawUrl).pathname);
213
+ } catch {
214
+ return false;
215
+ }
216
+ if (pathname.includes('\0') || pathname.includes('..')) return false;
217
+ const filePath = path.join(dist, pathname);
218
+ if (!filePath.startsWith(dist)) return false;
219
+ let st: fs.Stats;
220
+ try {
221
+ st = fs.statSync(filePath);
222
+ if (!st.isFile()) return false;
223
+ } catch {
224
+ return false;
225
+ }
226
+ const ext = path.extname(filePath).toLowerCase();
227
+ if (!TYPES[ext]) return false;
228
+ let entry = fileCache.get(filePath);
229
+ if (!entry || entry.mtimeMs !== st.mtimeMs) {
230
+ const raw = fs.readFileSync(filePath);
231
+ entry = {
232
+ raw,
233
+ compressed: raw.length > 1024,
234
+ br: raw.length > 1024 ? zlib.brotliCompressSync(raw) : raw,
235
+ gzip: raw.length > 1024 ? zlib.gzipSync(raw, { level: 9 }) : raw,
236
+ etag: `W/"${st.size}-${st.mtimeMs}"`,
237
+ mtimeMs: st.mtimeMs,
238
+ };
239
+ fileCache.set(filePath, entry);
240
+ if (fileCache.size > 500) fileCache.delete(fileCache.keys().next().value as string);
241
+ }
242
+ res.statusCode = 200;
243
+ res.setHeader('Content-Type', TYPES[ext]);
244
+ res.setHeader('ETag', entry.etag);
245
+ res.setHeader('Vary', 'Accept-Encoding');
246
+ const isEntryDoc = pathname === '/' || pathname.endsWith('/') || TYPES[ext].startsWith('text/html');
247
+ res.setHeader('Cache-Control', isEntryDoc ? 'public, max-age=0, must-revalidate' : 'public, max-age=3600');
248
+ if (req.headers['if-none-match'] === entry.etag) {
249
+ res.statusCode = 304;
250
+ res.end();
251
+ return true;
252
+ }
253
+ const compressed = (entry as any).compressed !== false;
254
+ const accept = String(req.headers['accept-encoding'] || '');
255
+ const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
256
+ if (enc) {
257
+ res.setHeader('Content-Encoding', enc);
258
+ res.end(enc === 'br' ? entry.br : entry.gzip);
259
+ } else {
260
+ res.end(entry.raw);
261
+ }
262
+ return true;
263
+ }
264
+
265
+ http.createServer(async (req, res) => {
266
+ try {
267
+ await ready;
268
+ if (handleRevalidate(req, res)) return;
269
+ if (hotCache.size > 0 && tryHot(req, res)) return;
270
+ if (req.method === 'GET' && !req.headers.cookie && hotCache.size === 0) {
271
+ for (const r of warmList) warmHot(r, '');
272
+ }
273
+ if (hotCache.size > 0 && tryHot(req, res)) return;
274
+ if (req.method === 'GET' || req.method === 'HEAD') {
275
+ if (serveStatic(req, res, req.url || '/')) return;
276
+ }
277
+ const url = 'http://' + (req.headers.host || `localhost:${port}`) + (req.url || '/');
278
+ const init: RequestInit = { method: req.method, headers: req.headers as any };
279
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
280
+ (init as any).body = Readable.toWeb(req) as any;
281
+ (init as any).duplex = 'half';
282
+ }
283
+ const cookieHeader = String(req.headers.cookie || '');
284
+ if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
285
+ try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
286
+ }
287
+ const response = await handle!(new Request(url, init));
288
+ if (req.method === 'GET') fillHot(req.url || '/', cookieHeader, response.clone());
289
+ res.statusCode = response.status;
290
+ response.headers.forEach((v, k) => res.setHeader(k, v));
291
+ const htmlDoc = (response.headers.get('content-type') ?? '').startsWith('text/html');
292
+ const accept = String(req.headers['accept-encoding'] ?? '');
293
+ if (response.body && htmlDoc && (accept.includes('br') || accept.includes('gzip'))) {
294
+ const raw = Buffer.from(await response.arrayBuffer());
295
+ const etag = 'W/"' + createHash('sha1').update(raw).digest('base64url').slice(0, 24) + '"';
296
+ if (req.method === 'GET' && req.headers['if-none-match'] === etag) {
297
+ res.statusCode = 304;
298
+ res.end();
299
+ return;
300
+ }
301
+ res.setHeader('ETag', etag);
302
+ res.setHeader('Content-Length', String(raw.length));
303
+ if (accept.includes('br')) {
304
+ res.setHeader('Content-Encoding', 'br');
305
+ res.end(zlib.brotliCompressSync(raw));
306
+ } else {
307
+ res.setHeader('Content-Encoding', 'gzip');
308
+ res.end(zlib.gzipSync(raw));
309
+ }
310
+ } else if (response.body) {
311
+ Readable.fromWeb(response.body as any).pipe(res);
312
+ } else {
313
+ res.end();
314
+ }
315
+ } catch (err) {
316
+ if (!res.headersSent) {
317
+ res.statusCode = 500;
318
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
319
+ }
320
+ res.end('server error');
321
+ }
322
+ }).listen(port, () => {
323
+ console.log(`🌹 RoseTack prod server on http://localhost:${port}`);
324
+ });
package/src/cli/prompt.ts CHANGED
@@ -1,17 +1,4 @@
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
- */
1
+ // The canonical .rose authoring contract, printed by `rosetack prompt`.
15
2
  export const AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
16
3
 
17
4
  rosetack is a zero-hydration web framework: a .rose file compiles to a server
@@ -56,6 +43,9 @@ Rules the compiler enforces (breaking one fails the build):
56
43
  type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
57
44
  - $state / $data declarations are top-level statements. The declared name IS the
58
45
  getter: write count() in the template and the script, never bare count.
46
+ $persist is $state backed by localStorage: let theme = $persist('light') —
47
+ the value survives reloads (SSR renders the initial; the client re-seeds
48
+ from storage at boot).
59
49
  - A route param (pages/blog/[id].rose) is read as state too: declare it
60
50
  (\`let id = $state('1')\`) and read id() - the server overwrites the default
61
51
  with the URL's value, and export const params = { id: [...] } bakes those
@@ -64,9 +54,36 @@ Rules the compiler enforces (breaking one fails the build):
64
54
  synchronously inside its parent. Fetch in the page or the middleware and pass
65
55
  the value down as a prop.
66
56
  - 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}.
57
+ trusted-HTML escape hatch - use it only for content you control. {@const name
58
+ = expr} is a template-level binding: it evaluates once and is visible to every
59
+ expression that follows in the same scope (use it to name a computed value
60
+ inside {#each} without re-evaluating, or to shorten a long expression).
61
+ - Blocks: {#if cond}...{:else if cond2}...{:else}...{/if},
62
+ {#each items as item, i}...{:else}...{/each} (i is the zero-based index, the
63
+ {:else} renders when the list is empty, and the item may be a DESTRUCTURING
64
+ pattern - {#each items as {name, price}} or {#each entries as [k, v]} - the
65
+ body then reads the properties/elements directly),
66
+ {#key expr}...{/key} (re-creates the
67
+ body whenever expr changes), {#boundary}...{:fallback}...{/boundary} (the
68
+ fallback renders on a throw; {$boundaryError()?.message} reads the caught
69
+ error), {#island name="x"}...{/island} (partial hydration) and
70
+ {#defer}...{/defer} (progressive render; hold=N keeps the skeleton up at
71
+ least N ms). {:else} / {:else if} must sit inside an {#if} block.
72
+ - Two-way binding: <input bind:value={q}> / <input type="checkbox"
73
+ bind:checked={on}> / <select bind:value={s}>. Numeric inputs coerce through
74
+ valueAsNumber. Radio groups: <input type="radio" value="free"
75
+ bind:group={plan}> - the group state holds the selected value and every
76
+ radio's checked state follows it. bind:this={ref} captures the ELEMENT into
77
+ a $state slot (declare it: let ref = $state(null)) - call ref().focus() or
78
+ measure it after mount. A bind:* name must be a $state declaration.
79
+ - Conditional attributes: class:NAME={expr} and style:PROP={expr} merge with
80
+ the tag's static class/style into one reactive attribute.
81
+ - Boolean attributes (checked/disabled/...) are presence-correct: a false
82
+ expression omits the attribute entirely.
83
+ - use:NAME attaches a registered element action: directives.NAME = (el, param)
84
+ => { ...; return { update: (p) => ..., destroy: () => ... } } (or return a
85
+ cleanup function). A reactive param: use:tooltip={text} - the action's
86
+ update half re-runs when text changes; the param arrives JSON-parsed.
70
87
  - A <slot> with attributes is a named slot and must declare its name:
71
88
  <slot name="row" item={post} />. A named slot must be a DIRECT child of the
72
89
  component tag - never inside another element or an {#if}/{#each} block.
@@ -81,8 +98,19 @@ Rules the compiler enforces (breaking one fails the build):
81
98
 
82
99
  ## Events and server actions
83
100
 
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)}.
101
+ - on:EVENT={handler} wires a client event - ANY event, not just click. The
102
+ handler is a named function from the script or an inline arrow:
103
+ on:click={() => $setState('n', n() + 1)}, on:keydown={noteKey}.
104
+ click/input/change/submit ride one delegated listener per event type; every
105
+ other event (keydown, focus, scroll, mouseenter, ...) is bound directly on
106
+ the element by wire(), so no handler is ever silently dead. |window /
107
+ |document move the binding onto the global instead (Escape closes the modal,
108
+ scroll, resize) - one target per handler.
109
+ Modifiers ride the event: on:submit|preventDefault={save} (supported:
110
+ |preventDefault, |stopPropagation, |self - only when the event target IS the
111
+ bound element, |once - unbind after the first run). capture/passive are NOT
112
+ supported: they are listener options and one delegated listener per event
113
+ type cannot carry per-element options.
86
114
  - A server action is an exported async function. Call it from a native form
87
115
  (method="POST", no JS needed - progressive enhancement) or from any event
88
116
  (on:click={like} - one POST, in-place adopt). Its return value is an
package/src/cli/shell.ts CHANGED
@@ -45,7 +45,7 @@ export function getStyles(): string {
45
45
  }
46
46
  }
47
47
 
48
- const BOOTSTRAP = esbuild.transformSync(`
48
+ const BOOTSTRAP_SOURCE = `
49
49
  // shell = false: the document's SSR content sits directly in <body> - no
50
50
  // #app wrapper, no demo styles, so a real theme's CSS owns the document from
51
51
  // the first byte (and a JS-less visitor never sees either). The bundle still
@@ -168,13 +168,46 @@ if (__state.__notFound) {
168
168
  } else {
169
169
  start(__app, window.location.pathname);
170
170
  }
171
- `, { minify: true }).code;
171
+ `;
172
+ let BOOTSTRAP_CACHE: string | null = null;
173
+ function bootstrap(): string {
174
+ if (BOOTSTRAP_CACHE === null) {
175
+ if ((globalThis as any).__rosetack_SKIP_MINIFY) {
176
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
177
+ } else {
178
+ try {
179
+ BOOTSTRAP_CACHE = esbuild.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
180
+ } catch {
181
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
182
+ }
183
+ }
184
+ }
185
+ return BOOTSTRAP_CACHE;
186
+ }
172
187
 
173
188
  const CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
174
189
  let cspCache: { for: string | null; value: string } | null = null;
175
- const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm, prefetchStats } from '/client.js';\n${BOOTSTRAP}`;
190
+ let EXTERNAL_BOOTSTRAP_CACHE: string | null = null;
191
+ function externalBootstrap(): string {
192
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `\nimport { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';\n${bootstrap()}`;
193
+ return EXTERNAL_BOOTSTRAP_CACHE;
194
+ }
176
195
  function inlineScript(client: string): string {
177
- return `\n${client}\n${BOOTSTRAP}`;
196
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
197
+ let body = client;
198
+ let aliases = "";
199
+ if (m) {
200
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
201
+ aliases = m[1]
202
+ .split(",")
203
+ .map((pair) => {
204
+ const parts = pair.split(" as ").map((x) => x.trim());
205
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
206
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
207
+ })
208
+ .join("");
209
+ }
210
+ return `\n${body}\n${aliases}\n${bootstrap()}`;
178
211
  }
179
212
  /**
180
213
  * A fresh CSP nonce: 128 bits from the platform RNG, base64 - the syntax the
@@ -213,7 +246,7 @@ export function securityHeaders(client: string | null, nonce = ''): Record<strin
213
246
  if (!cspCache || cspCache.for !== client) {
214
247
  const scriptSrc = client
215
248
  ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
216
- : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
249
+ : `'self' 'sha256-${createHash('sha256').update(externalBootstrap(), 'utf-8').digest('base64')}'`;
217
250
  cspCache = {
218
251
  for: client,
219
252
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`,
@@ -310,7 +343,7 @@ export function clientScriptTag(client: string | null, nonce = ''): string {
310
343
  const n = nonce ? ` nonce="${nonce}"` : '';
311
344
  return client
312
345
  ? `<script type="module"${n}>${inlineScript(client)}</script>`
313
- : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
346
+ : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${externalBootstrap()}</script>`;
314
347
  }
315
348
 
316
349
  /**