rosetack 0.1.4 → 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/dist-cli/edge.mjs CHANGED
@@ -43,18 +43,39 @@ if (!__app) {
43
43
  }
44
44
  // Native View Transitions around client-side navigation (progressive:
45
45
  // browsers without the API navigate normally, no polyfill, no CSS required).
46
- function __navigate(pathname) {
47
- const paint = () => start(__app, pathname);
46
+ // F35: stash the CURRENT entry's scroll position into its history state
47
+ // before a new push - the browser only restores scroll on full page loads; a
48
+ // pjax swap would land wherever the swap left it.
49
+ function __saveScroll() {
50
+ try {
51
+ const s = history.state || {};
52
+ history.replaceState(Object.assign({}, s, { __rosetackScroll: window.scrollY }), '');
53
+ } catch (e) { /* history state unavailable (file:// edge): best effort */ }
54
+ }
55
+ function __navigate(pathname, restore) {
56
+ const paint = () => {
57
+ const p = start(__app, pathname);
58
+ if (restore) {
59
+ // back/forward: restore the entry's scroll (top when it has none)
60
+ const s = history.state || {};
61
+ const y = typeof s.__rosetackScroll === 'number' ? s.__rosetackScroll : 0;
62
+ return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
63
+ }
64
+ // a fresh navigation starts at the top, like a full page load
65
+ window.scrollTo(0, 0);
66
+ return p;
67
+ };
48
68
  if (document.startViewTransition) {
49
69
  return document.startViewTransition(paint).updateCallbackDone;
50
70
  }
51
71
  return paint();
52
72
  }
53
- window.addEventListener('popstate', () => __navigate(window.location.pathname));
73
+ window.addEventListener('popstate', () => __navigate(window.location.pathname, true));
54
74
  document.addEventListener('click', (e) => {
55
75
  const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
56
76
  if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
57
77
  e.preventDefault();
78
+ __saveScroll();
58
79
  history.pushState(null, '', a.getAttribute('href'));
59
80
  __navigate(window.location.pathname);
60
81
  }
@@ -161,6 +182,12 @@ function bootstrap() {
161
182
  return BOOTSTRAP_CACHE;
162
183
  }
163
184
  var 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'`;
185
+ var BASELINE_SECURITY_HEADERS = {
186
+ "x-content-type-options": "nosniff",
187
+ "x-frame-options": "DENY",
188
+ "referrer-policy": "strict-origin-when-cross-origin",
189
+ "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=()"
190
+ };
164
191
  var cspCache = null;
165
192
  var EXTERNAL_BOOTSTRAP_CACHE = null;
166
193
  function externalBootstrap() {
@@ -194,7 +221,11 @@ function mintNonce() {
194
221
  return btoa(raw);
195
222
  }
196
223
  function securityHeaders(client, nonce = "") {
197
- if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
224
+ const headers = { ...BASELINE_SECURITY_HEADERS };
225
+ if (nonce) {
226
+ headers["Content-Security-Policy"] = `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}`;
227
+ return headers;
228
+ }
198
229
  if (!cspCache || cspCache.for !== client) {
199
230
  const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(externalBootstrap(), "utf-8").digest("base64")}'`;
200
231
  cspCache = {
@@ -202,7 +233,8 @@ function securityHeaders(client, nonce = "") {
202
233
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`
203
234
  };
204
235
  }
205
- return { "Content-Security-Policy": cspCache.value };
236
+ headers["Content-Security-Policy"] = cspCache.value;
237
+ return headers;
206
238
  }
207
239
  var 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==">';
208
240
  var STYLES = `
@@ -320,6 +352,43 @@ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(),
320
352
  </html>`;
321
353
  }
322
354
 
355
+ // src/cli/shutdown.ts
356
+ var shutdownHooks = [];
357
+ var draining = null;
358
+ globalThis.__rosetackOnShutdown = onShutdown;
359
+ globalThis.__rosetackRunShutdownHooks = runShutdownHooks;
360
+ function onShutdown(name, fn) {
361
+ const hook = { name, fn };
362
+ shutdownHooks.push(hook);
363
+ return () => {
364
+ const at = shutdownHooks.indexOf(hook);
365
+ if (at !== -1) shutdownHooks.splice(at, 1);
366
+ };
367
+ }
368
+ function runShutdownHooks(reason) {
369
+ if (draining) return draining;
370
+ draining = (async () => {
371
+ const results = [];
372
+ for (const hook of shutdownHooks.slice()) {
373
+ try {
374
+ await hook.fn();
375
+ results.push({ name: hook.name, ok: true });
376
+ } catch (err) {
377
+ const message = err instanceof Error ? err.message : String(err);
378
+ results.push({ name: hook.name, ok: false, error: message });
379
+ console.error(`[rosetack] shutdown hook ${hook.name} failed (${reason}):`, message);
380
+ }
381
+ }
382
+ return results;
383
+ })().finally(() => {
384
+ draining = null;
385
+ });
386
+ return draining;
387
+ }
388
+ function shutdownHookCount() {
389
+ return shutdownHooks.length;
390
+ }
391
+
323
392
  // src/cli/edge.ts
324
393
  function crossSiteWrite(request) {
325
394
  const m = request.method;
@@ -375,7 +444,8 @@ async function createEdgeHandler(outDir, preloaded) {
375
444
  }
376
445
  const pageHeaders = (pathname, nonce = "") => {
377
446
  const headers = {};
378
- if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
447
+ for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
448
+ if (!headers["cache-control"]) headers["cache-control"] = "no-cache";
379
449
  const own = mod.headersFor?.(pathname);
380
450
  if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
381
451
  return headers;
@@ -399,11 +469,18 @@ async function createEdgeHandler(outDir, preloaded) {
399
469
  if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
400
470
  }
401
471
  if (mod.isApi(pathname)) {
472
+ if (request.method !== "GET") {
473
+ const fn = mod.invalidateRenderCache;
474
+ if (typeof fn === "function") fn();
475
+ }
402
476
  const apiRes = await mod.handleApi(request.method, pathname, request);
403
477
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
404
478
  }
405
479
  const form = request.method === "POST" ? await request.formData() : void 0;
406
- if (form) mod.invalidateRenderCache?.();
480
+ if (form) {
481
+ const fn = mod.invalidateRenderCache;
482
+ if (typeof fn === "function") fn();
483
+ }
407
484
  if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
408
485
  const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
409
486
  const streamed = new Response(null, {
@@ -439,5 +516,8 @@ async function createEdgeHandler(outDir, preloaded) {
439
516
  };
440
517
  }
441
518
  export {
442
- createEdgeHandler
519
+ createEdgeHandler,
520
+ onShutdown,
521
+ runShutdownHooks,
522
+ shutdownHookCount
443
523
  };