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/dist-cli/edge.mjs CHANGED
@@ -21,7 +21,7 @@ function getStyles() {
21
21
  return "";
22
22
  }
23
23
  }
24
- var BOOTSTRAP = esbuild.transformSync(`
24
+ var BOOTSTRAP_SOURCE = `
25
25
  // shell = false: the document's SSR content sits directly in <body> - no
26
26
  // #app wrapper, no demo styles, so a real theme's CSS owns the document from
27
27
  // the first byte (and a JS-less visitor never sees either). The bundle still
@@ -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
  }
@@ -144,16 +165,53 @@ if (__state.__notFound) {
144
165
  } else {
145
166
  start(__app, window.location.pathname);
146
167
  }
147
- `, { minify: true }).code;
168
+ `;
169
+ var BOOTSTRAP_CACHE = null;
170
+ function bootstrap() {
171
+ if (BOOTSTRAP_CACHE === null) {
172
+ if (globalThis.__rosetack_SKIP_MINIFY) {
173
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
174
+ } else {
175
+ try {
176
+ BOOTSTRAP_CACHE = esbuild.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
177
+ } catch {
178
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
179
+ }
180
+ }
181
+ }
182
+ return BOOTSTRAP_CACHE;
183
+ }
148
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
+ };
149
191
  var cspCache = null;
150
- var EXTERNAL_BOOTSTRAP = `
151
- import { start, prefetch, postForm, prefetchStats } from '/client.js';
152
- ${BOOTSTRAP}`;
192
+ var EXTERNAL_BOOTSTRAP_CACHE = null;
193
+ function externalBootstrap() {
194
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `
195
+ import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';
196
+ ${bootstrap()}`;
197
+ return EXTERNAL_BOOTSTRAP_CACHE;
198
+ }
153
199
  function inlineScript(client) {
200
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
201
+ let body = client;
202
+ let aliases = "";
203
+ if (m) {
204
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
205
+ aliases = m[1].split(",").map((pair) => {
206
+ const parts = pair.split(" as ").map((x) => x.trim());
207
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
208
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
209
+ }).join("");
210
+ }
154
211
  return `
155
- ${client}
156
- ${BOOTSTRAP}`;
212
+ ${body}
213
+ ${aliases}
214
+ ${bootstrap()}`;
157
215
  }
158
216
  function mintNonce() {
159
217
  const bytes = new Uint8Array(16);
@@ -163,15 +221,20 @@ function mintNonce() {
163
221
  return btoa(raw);
164
222
  }
165
223
  function securityHeaders(client, nonce = "") {
166
- 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
+ }
167
229
  if (!cspCache || cspCache.for !== client) {
168
- const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(EXTERNAL_BOOTSTRAP, "utf-8").digest("base64")}'`;
230
+ const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(externalBootstrap(), "utf-8").digest("base64")}'`;
169
231
  cspCache = {
170
232
  for: client,
171
233
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`
172
234
  };
173
235
  }
174
- return { "Content-Security-Policy": cspCache.value };
236
+ headers["Content-Security-Policy"] = cspCache.value;
237
+ return headers;
175
238
  }
176
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==">';
177
240
  var STYLES = `
@@ -230,7 +293,7 @@ function mergeHeadBlocks(blocks) {
230
293
  function clientScriptTag(client, nonce = "") {
231
294
  const n = nonce ? ` nonce="${nonce}"` : "";
232
295
  return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
233
- <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
296
+ <script type="module"${n}>${externalBootstrap()}</script>`;
234
297
  }
235
298
  function shellOpen(styles = getStyles(), lang = "en", dir = "", shell = true) {
236
299
  const styleTag = styles ? `
@@ -289,6 +352,43 @@ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(),
289
352
  </html>`;
290
353
  }
291
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
+
292
392
  // src/cli/edge.ts
293
393
  function crossSiteWrite(request) {
294
394
  const m = request.method;
@@ -322,6 +422,7 @@ async function createEdgeHandler(outDir, preloaded) {
322
422
  client = null;
323
423
  }
324
424
  }
425
+ if (client && client.includes("chunks/")) client = null;
325
426
  if (preloaded && "styles" in preloaded) {
326
427
  styles = preloaded.styles ?? "";
327
428
  } else {
@@ -343,7 +444,8 @@ async function createEdgeHandler(outDir, preloaded) {
343
444
  }
344
445
  const pageHeaders = (pathname, nonce = "") => {
345
446
  const headers = {};
346
- 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";
347
449
  const own = mod.headersFor?.(pathname);
348
450
  if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
349
451
  return headers;
@@ -367,10 +469,18 @@ async function createEdgeHandler(outDir, preloaded) {
367
469
  if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
368
470
  }
369
471
  if (mod.isApi(pathname)) {
472
+ if (request.method !== "GET") {
473
+ const fn = mod.invalidateRenderCache;
474
+ if (typeof fn === "function") fn();
475
+ }
370
476
  const apiRes = await mod.handleApi(request.method, pathname, request);
371
477
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
372
478
  }
373
479
  const form = request.method === "POST" ? await request.formData() : void 0;
480
+ if (form) {
481
+ const fn = mod.invalidateRenderCache;
482
+ if (typeof fn === "function") fn();
483
+ }
374
484
  if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
375
485
  const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
376
486
  const streamed = new Response(null, {
@@ -393,7 +503,9 @@ async function createEdgeHandler(outDir, preloaded) {
393
503
  });
394
504
  return new Response(stream, { status: head.status, headers: head.headers });
395
505
  }
396
- const page = await mod.renderPage(pathname, form);
506
+ const cookieHeader = request.headers.get("cookie") || "";
507
+ const memoHit = !form && mod.isCachedRoute?.(pathname) ? mod.peekRenderCache?.(pathname, cookieHeader) : null;
508
+ const page = memoHit ?? (mod.renderPageCached && !form ? await mod.renderPageCached(pathname, cookieHeader) : await mod.renderPage(pathname, form));
397
509
  const nonce = mod.cspNonce?.(pathname) ? mintNonce() : "";
398
510
  const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
399
511
  const buffered = new Response(html, {
@@ -404,5 +516,8 @@ async function createEdgeHandler(outDir, preloaded) {
404
516
  };
405
517
  }
406
518
  export {
407
- createEdgeHandler
519
+ createEdgeHandler,
520
+ onShutdown,
521
+ runShutdownHooks,
522
+ shutdownHookCount
408
523
  };