rosetack 0.1.3 → 0.1.5

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.
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
@@ -67,18 +67,39 @@ if (!__app) {
67
67
  }
68
68
  // Native View Transitions around client-side navigation (progressive:
69
69
  // browsers without the API navigate normally, no polyfill, no CSS required).
70
- function __navigate(pathname) {
71
- const paint = () => start(__app, pathname);
70
+ // F35: stash the CURRENT entry's scroll position into its history state
71
+ // before a new push - the browser only restores scroll on full page loads; a
72
+ // pjax swap would land wherever the swap left it.
73
+ function __saveScroll() {
74
+ try {
75
+ const s = history.state || {};
76
+ history.replaceState(Object.assign({}, s, { __rosetackScroll: window.scrollY }), '');
77
+ } catch (e) { /* history state unavailable (file:// edge): best effort */ }
78
+ }
79
+ function __navigate(pathname, restore) {
80
+ const paint = () => {
81
+ const p = start(__app, pathname);
82
+ if (restore) {
83
+ // back/forward: restore the entry's scroll (top when it has none)
84
+ const s = history.state || {};
85
+ const y = typeof s.__rosetackScroll === 'number' ? s.__rosetackScroll : 0;
86
+ return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
87
+ }
88
+ // a fresh navigation starts at the top, like a full page load
89
+ window.scrollTo(0, 0);
90
+ return p;
91
+ };
72
92
  if (document.startViewTransition) {
73
93
  return document.startViewTransition(paint).updateCallbackDone;
74
94
  }
75
95
  return paint();
76
96
  }
77
- window.addEventListener('popstate', () => __navigate(window.location.pathname));
97
+ window.addEventListener('popstate', () => __navigate(window.location.pathname, true));
78
98
  document.addEventListener('click', (e) => {
79
99
  const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
80
100
  if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
81
101
  e.preventDefault();
102
+ __saveScroll();
82
103
  history.pushState(null, '', a.getAttribute('href'));
83
104
  __navigate(window.location.pathname);
84
105
  }
@@ -168,13 +189,55 @@ if (__state.__notFound) {
168
189
  } else {
169
190
  start(__app, window.location.pathname);
170
191
  }
171
- `, { minify: true }).code;
192
+ `;
193
+ let BOOTSTRAP_CACHE: string | null = null;
194
+ function bootstrap(): string {
195
+ if (BOOTSTRAP_CACHE === null) {
196
+ if ((globalThis as any).__rosetack_SKIP_MINIFY) {
197
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
198
+ } else {
199
+ try {
200
+ BOOTSTRAP_CACHE = esbuild.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
201
+ } catch {
202
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
203
+ }
204
+ }
205
+ }
206
+ return BOOTSTRAP_CACHE;
207
+ }
172
208
 
173
209
  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'`;
210
+
211
+
212
+ const BASELINE_SECURITY_HEADERS: Record<string, string> = {
213
+ 'x-content-type-options': 'nosniff',
214
+ 'x-frame-options': 'DENY',
215
+ 'referrer-policy': 'strict-origin-when-cross-origin',
216
+ 'permissions-policy': 'accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), fullscreen=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), serial=(), usb=(), xr-spatial-tracking=()',
217
+ };
218
+
174
219
  let cspCache: { for: string | null; value: string } | null = null;
175
- const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm, prefetchStats } from '/client.js';\n${BOOTSTRAP}`;
220
+ let EXTERNAL_BOOTSTRAP_CACHE: string | null = null;
221
+ function externalBootstrap(): string {
222
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `\nimport { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';\n${bootstrap()}`;
223
+ return EXTERNAL_BOOTSTRAP_CACHE;
224
+ }
176
225
  function inlineScript(client: string): string {
177
- return `\n${client}\n${BOOTSTRAP}`;
226
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
227
+ let body = client;
228
+ let aliases = "";
229
+ if (m) {
230
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
231
+ aliases = m[1]
232
+ .split(",")
233
+ .map((pair) => {
234
+ const parts = pair.split(" as ").map((x) => x.trim());
235
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
236
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
237
+ })
238
+ .join("");
239
+ }
240
+ return `\n${body}\n${aliases}\n${bootstrap()}`;
178
241
  }
179
242
  /**
180
243
  * A fresh CSP nonce: 128 bits from the platform RNG, base64 - the syntax the
@@ -209,17 +272,22 @@ export function mintNonce(): string {
209
272
  * the route opts into, per route, not a framework default.
210
273
  */
211
274
  export function securityHeaders(client: string | null, nonce = ''): Record<string, string> {
212
- if (nonce) return { 'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
275
+ const headers: Record<string, string> = { ...BASELINE_SECURITY_HEADERS };
276
+ if (nonce) {
277
+ headers['Content-Security-Policy'] = `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}`;
278
+ return headers;
279
+ }
213
280
  if (!cspCache || cspCache.for !== client) {
214
281
  const scriptSrc = client
215
282
  ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
216
- : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
283
+ : `'self' 'sha256-${createHash('sha256').update(externalBootstrap(), 'utf-8').digest('base64')}'`;
217
284
  cspCache = {
218
285
  for: client,
219
286
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`,
220
287
  };
221
288
  }
222
- return { 'Content-Security-Policy': cspCache.value };
289
+ headers['Content-Security-Policy'] = cspCache.value;
290
+ return headers;
223
291
  }
224
292
 
225
293
  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==">';
@@ -310,7 +378,7 @@ export function clientScriptTag(client: string | null, nonce = ''): string {
310
378
  const n = nonce ? ` nonce="${nonce}"` : '';
311
379
  return client
312
380
  ? `<script type="module"${n}>${inlineScript(client)}</script>`
313
- : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
381
+ : `<script type="module"${n} src="/client.js"></script>\n<script type="module"${n}>${externalBootstrap()}</script>`;
314
382
  }
315
383
 
316
384
  /**
@@ -0,0 +1,54 @@
1
+
2
+
3
+ type ShutdownHook = {
4
+ name: string;
5
+ fn: () => void | Promise<void>;
6
+ };
7
+
8
+ type HookResult = { name: string; ok: boolean; error?: string };
9
+
10
+ const shutdownHooks: ShutdownHook[] = [];
11
+
12
+
13
+ let draining: Promise<HookResult[]> | null = null;
14
+
15
+ (globalThis as unknown as { __rosetackOnShutdown?: typeof onShutdown }).__rosetackOnShutdown =
16
+ onShutdown;
17
+ (globalThis as unknown as { __rosetackRunShutdownHooks?: typeof runShutdownHooks }).__rosetackRunShutdownHooks =
18
+ runShutdownHooks;
19
+
20
+ /** Returns an unregister function - a hot-swapped client must drop its old hook. */
21
+ export function onShutdown(name: string, fn: () => void | Promise<void>): () => void {
22
+ const hook: ShutdownHook = { name, fn };
23
+ shutdownHooks.push(hook);
24
+ return () => {
25
+ const at = shutdownHooks.indexOf(hook);
26
+ if (at !== -1) shutdownHooks.splice(at, 1);
27
+ };
28
+ }
29
+
30
+ /** Never rejects; a throwing hook is reported and the rest still run. */
31
+ export function runShutdownHooks(reason: string): Promise<HookResult[]> {
32
+ if (draining) return draining;
33
+ draining = (async () => {
34
+ const results: HookResult[] = [];
35
+ for (const hook of shutdownHooks.slice()) {
36
+ try {
37
+ await hook.fn();
38
+ results.push({ name: hook.name, ok: true });
39
+ } catch (err) {
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ results.push({ name: hook.name, ok: false, error: message });
42
+ console.error(`[rosetack] shutdown hook ${hook.name} failed (${reason}):`, message);
43
+ }
44
+ }
45
+ return results;
46
+ })().finally(() => {
47
+ draining = null;
48
+ });
49
+ return draining;
50
+ }
51
+
52
+ export function shutdownHookCount(): number {
53
+ return shutdownHooks.length;
54
+ }