@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.10

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.
Files changed (219) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +496 -91
  22. package/dist/dom.d.ts +4 -0
  23. package/dist/dom.js +62 -16
  24. package/dist/effects.js +43 -10
  25. package/dist/events.d.ts +2 -0
  26. package/dist/events.js +18 -0
  27. package/dist/flight-props.d.ts +7 -0
  28. package/dist/flight-props.js +105 -0
  29. package/dist/handler-html.js +4 -4
  30. package/dist/handler-routing.d.ts +2 -23
  31. package/dist/handler-routing.js +9 -190
  32. package/dist/handler-segments.d.ts +6 -0
  33. package/dist/handler-segments.js +18 -4
  34. package/dist/head-tags.d.ts +9 -0
  35. package/dist/head-tags.js +93 -6
  36. package/dist/highlight-bind.js +1 -1
  37. package/dist/highlight.d.ts +3 -2
  38. package/dist/highlight.js +17 -12
  39. package/dist/hints.d.ts +25 -2
  40. package/dist/hints.js +147 -74
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +3 -0
  43. package/dist/island-swap.d.ts +47 -0
  44. package/dist/island-swap.js +635 -0
  45. package/dist/jsx-dev-runtime.d.ts +1 -1
  46. package/dist/jsx-types.d.ts +99 -3
  47. package/dist/krate-core.js +1 -1
  48. package/dist/krate-dev.js +407 -80
  49. package/dist/krate-f-actions.js +1 -1
  50. package/dist/krate-f-classes.js +1 -1
  51. package/dist/krate-f-highlight.js +1 -1
  52. package/dist/krate-f-list.js +1 -1
  53. package/dist/krate-f-navigation.js +1 -1
  54. package/dist/krate-f-router-lite.js +1 -1
  55. package/dist/krate-f-router.js +1 -1
  56. package/dist/krate-features.json +455 -0
  57. package/dist/krate-hydrate-lite.js +5 -5
  58. package/dist/krate-hydrate.js +5 -5
  59. package/dist/krate-island-swap.js +1 -0
  60. package/dist/krate-runtime.js +5 -5
  61. package/dist/krate-suspense.js +1 -1
  62. package/dist/list.d.ts +14 -4
  63. package/dist/list.js +30 -23
  64. package/dist/metadata.js +5 -2
  65. package/dist/navigation-react.d.ts +13 -0
  66. package/dist/navigation-react.js +86 -0
  67. package/dist/navigation.d.ts +19 -0
  68. package/dist/navigation.js +35 -0
  69. package/dist/node-server.js +3 -3
  70. package/dist/og.js +1 -1
  71. package/dist/platform.d.ts +52 -0
  72. package/dist/platform.js +57 -0
  73. package/dist/react-compat.d.ts +39 -0
  74. package/dist/react-compat.js +359 -0
  75. package/dist/react-server.d.ts +63 -0
  76. package/dist/react-server.js +125 -0
  77. package/dist/region-wire.d.ts +10 -0
  78. package/dist/region-wire.js +154 -0
  79. package/dist/request-context.js +1 -1
  80. package/dist/request-extras.d.ts +4 -0
  81. package/dist/request-extras.js +51 -0
  82. package/dist/resp.js +1 -1
  83. package/dist/route-source.d.ts +39 -0
  84. package/dist/route-source.js +532 -0
  85. package/dist/router-lite.js +3 -9
  86. package/dist/router.d.ts +1 -1
  87. package/dist/router.js +675 -100
  88. package/dist/server-handler.d.ts +69 -1
  89. package/dist/server-handler.js +515 -96
  90. package/dist/server-renderer.js +16 -7
  91. package/dist/server.d.ts +73 -16
  92. package/dist/server.js +619 -102
  93. package/dist/sha256.js +9 -9
  94. package/dist/signal.js +47 -20
  95. package/dist/site-config.d.ts +15 -0
  96. package/dist/site-config.js +28 -0
  97. package/dist/slot.d.ts +12 -0
  98. package/dist/slot.js +23 -0
  99. package/dist/ssr-core.d.ts +2 -0
  100. package/dist/ssr-core.js +12 -4
  101. package/dist/suspense.js +34 -2
  102. package/dist/testing.d.ts +62 -0
  103. package/dist/testing.js +90 -0
  104. package/dist/use-id.js +1 -1
  105. package/package.json +28 -3
  106. package/dist/action-context.test.d.ts +0 -1
  107. package/dist/action-context.test.js +0 -72
  108. package/dist/actions.test.d.ts +0 -1
  109. package/dist/actions.test.js +0 -477
  110. package/dist/cache-adapter.test.d.ts +0 -1
  111. package/dist/cache-adapter.test.js +0 -244
  112. package/dist/cache.test.d.ts +0 -1
  113. package/dist/cache.test.js +0 -233
  114. package/dist/class-component.test.d.ts +0 -1
  115. package/dist/class-component.test.js +0 -462
  116. package/dist/class-helpers.test.d.ts +0 -1
  117. package/dist/class-helpers.test.js +0 -169
  118. package/dist/context.test.d.ts +0 -1
  119. package/dist/context.test.js +0 -57
  120. package/dist/derived.test.d.ts +0 -1
  121. package/dist/derived.test.js +0 -140
  122. package/dist/dev-overlay.test.d.ts +0 -1
  123. package/dist/dev-overlay.test.js +0 -152
  124. package/dist/discrete.test.d.ts +0 -1
  125. package/dist/discrete.test.js +0 -100
  126. package/dist/dom.test.d.ts +0 -1
  127. package/dist/dom.test.js +0 -31
  128. package/dist/effect-errors.test.d.ts +0 -1
  129. package/dist/effect-errors.test.js +0 -163
  130. package/dist/effects.test.d.ts +0 -1
  131. package/dist/effects.test.js +0 -485
  132. package/dist/events.test.d.ts +0 -1
  133. package/dist/events.test.js +0 -447
  134. package/dist/handler-html.test.d.ts +0 -1
  135. package/dist/handler-html.test.js +0 -256
  136. package/dist/handler-routing.test.d.ts +0 -1
  137. package/dist/handler-routing.test.js +0 -99
  138. package/dist/handler-segments.test.d.ts +0 -1
  139. package/dist/handler-segments.test.js +0 -217
  140. package/dist/head-tags.test.d.ts +0 -1
  141. package/dist/head-tags.test.js +0 -131
  142. package/dist/highlight-bind.test.d.ts +0 -1
  143. package/dist/highlight-bind.test.js +0 -124
  144. package/dist/highlight.test.d.ts +0 -1
  145. package/dist/highlight.test.js +0 -56
  146. package/dist/lanes.test.d.ts +0 -1
  147. package/dist/lanes.test.js +0 -59
  148. package/dist/list.test.d.ts +0 -1
  149. package/dist/list.test.js +0 -344
  150. package/dist/metadata.test.d.ts +0 -1
  151. package/dist/metadata.test.js +0 -167
  152. package/dist/navigation.test.d.ts +0 -1
  153. package/dist/navigation.test.js +0 -130
  154. package/dist/node-server.test.d.ts +0 -1
  155. package/dist/node-server.test.js +0 -492
  156. package/dist/optimistic-lanes.test.d.ts +0 -1
  157. package/dist/optimistic-lanes.test.js +0 -45
  158. package/dist/patterns.test.d.ts +0 -1
  159. package/dist/patterns.test.js +0 -98
  160. package/dist/portal.test.d.ts +0 -1
  161. package/dist/portal.test.js +0 -99
  162. package/dist/react-effects.test.d.ts +0 -1
  163. package/dist/react-effects.test.js +0 -96
  164. package/dist/react-suspense.test.d.ts +0 -1
  165. package/dist/react-suspense.test.js +0 -194
  166. package/dist/react.test.d.ts +0 -1
  167. package/dist/react.test.js +0 -60
  168. package/dist/react19.test.d.ts +0 -1
  169. package/dist/react19.test.js +0 -176
  170. package/dist/reactivity-core.test.d.ts +0 -1
  171. package/dist/reactivity-core.test.js +0 -152
  172. package/dist/reconcile.test.d.ts +0 -1
  173. package/dist/reconcile.test.js +0 -110
  174. package/dist/refs.test.d.ts +0 -1
  175. package/dist/refs.test.js +0 -257
  176. package/dist/router-layout.test.d.ts +0 -1
  177. package/dist/router-layout.test.js +0 -249
  178. package/dist/router-nav.test.d.ts +0 -1
  179. package/dist/router-nav.test.js +0 -464
  180. package/dist/router-slots.test.d.ts +0 -1
  181. package/dist/router-slots.test.js +0 -144
  182. package/dist/router-speculation.test.d.ts +0 -1
  183. package/dist/router-speculation.test.js +0 -25
  184. package/dist/router-styles.test.d.ts +0 -1
  185. package/dist/router-styles.test.js +0 -98
  186. package/dist/router.test.d.ts +0 -1
  187. package/dist/router.test.js +0 -36
  188. package/dist/server-async.test.d.ts +0 -1
  189. package/dist/server-async.test.js +0 -216
  190. package/dist/server-handler.test.d.ts +0 -1
  191. package/dist/server-handler.test.js +0 -535
  192. package/dist/server-highlight.test.d.ts +0 -1
  193. package/dist/server-highlight.test.js +0 -32
  194. package/dist/server-renderer.test.d.ts +0 -1
  195. package/dist/server-renderer.test.js +0 -266
  196. package/dist/server.test.d.ts +0 -1
  197. package/dist/server.test.js +0 -88
  198. package/dist/sha256.test.d.ts +0 -1
  199. package/dist/sha256.test.js +0 -13
  200. package/dist/signal-lanes.test.d.ts +0 -1
  201. package/dist/signal-lanes.test.js +0 -32
  202. package/dist/signal.test.d.ts +0 -1
  203. package/dist/signal.test.js +0 -68
  204. package/dist/slots.test.d.ts +0 -1
  205. package/dist/slots.test.js +0 -169
  206. package/dist/snapshots.test.d.ts +0 -1
  207. package/dist/snapshots.test.js +0 -208
  208. package/dist/ssr-core-behavior.test.d.ts +0 -1
  209. package/dist/ssr-core-behavior.test.js +0 -620
  210. package/dist/ssr-core.test.d.ts +0 -1
  211. package/dist/ssr-core.test.js +0 -324
  212. package/dist/static-memory.test.d.ts +0 -1
  213. package/dist/static-memory.test.js +0 -26
  214. package/dist/storage.test.d.ts +0 -1
  215. package/dist/storage.test.js +0 -46
  216. package/dist/suspense-actions.test.d.ts +0 -1
  217. package/dist/suspense-actions.test.js +0 -72
  218. package/dist/suspense.test.d.ts +0 -1
  219. package/dist/suspense.test.js +0 -518
package/dist/router.js CHANGED
@@ -5,6 +5,8 @@
5
5
  // place. All router state lives at module scope so `reinitRouter()` (called
6
6
  // by every page's hydration script) only refreshes per-page bindings and never
7
7
  // loses the prefetch cache, saved scroll positions or the in-flight navigation.
8
+ import { basePath, withBase } from './base-path.js';
9
+ import { siteConfig } from './site-config.js';
8
10
  /**
9
11
  * The shared runtime chunk is loaded once and must persist across SPA
10
12
  * navigations. Page-specific hydration scripts, in contrast, must be
@@ -12,15 +14,14 @@
12
14
  * removed before loading a new page and re-appended.
13
15
  */
14
16
  const RUNTIME_CHUNK_RE = /\/chunks\/runtime\.[^/]+\.js$/;
17
+ /**
18
+ * Scripts that stay loaded across navigations: the runtime and the shared
19
+ * component chunks (chunks/c/), which only register the hydration code page
20
+ * scripts call. Each runs once per document.
21
+ */
22
+ const PERSISTENT_SCRIPT_RE = /\/chunks\/(?:runtime\.[^/]+|c\/[^/]+)\.js$/;
15
23
  function runtimeConfig() {
16
- return globalThis.__KRATE_CFG__ || {};
17
- }
18
- /** Normalizes the configured base path to "" or "/prefix" (no trailing slash). */
19
- function basePath() {
20
- const bp = runtimeConfig().basePath || '';
21
- if (!bp || bp === '/')
22
- return '';
23
- return '/' + bp.replace(/^\/+|\/+$/g, '');
24
+ return siteConfig();
24
25
  }
25
26
  /** Strips the base path from a pathname so route comparisons are consistent. */
26
27
  function stripBase(pathname) {
@@ -67,7 +68,7 @@ function resolveSrc(src, baseUrl) {
67
68
  * not stall waiting on the chunk after the HTML swap.
68
69
  */
69
70
  export function pageAssetURLs(html, baseUrl, loaded) {
70
- const doc = new DOMParser().parseFromString(html, 'text/html');
71
+ const doc = typeof html === 'string' ? new DOMParser().parseFromString(html, 'text/html') : html;
71
72
  const out = [];
72
73
  const seen = new Set();
73
74
  const consider = (src) => {
@@ -93,6 +94,45 @@ export function pageAssetURLs(html, baseUrl, loaded) {
93
94
  }
94
95
  // Router state (module scope, survives reinitRouter).
95
96
  let initialized = false;
97
+ // Island bundles carry their own copy of this module, which is never
98
+ // initialized: the page's router registers itself here, and an uninitialized
99
+ // copy hands navigations to it instead of loading a new document.
100
+ const LIVE_ROUTER = Symbol.for('krate.router');
101
+ function liveRouter() {
102
+ if (initialized)
103
+ return null;
104
+ const g = globalThis;
105
+ let r = g[LIVE_ROUTER];
106
+ // The page runtime is loaded but its router has not started yet (a page
107
+ // with islands only, before the runtime starts it): start it here. The
108
+ // check compares krateRouter, not initRouter, so an island's copy does not
109
+ // keep its own (unused) router start code.
110
+ if (!r && typeof document !== 'undefined' && otherRuntime() && typeof g.initRouter === 'function') {
111
+ try {
112
+ g.initRouter();
113
+ }
114
+ catch (err) {
115
+ console.error(err);
116
+ }
117
+ r = g[LIVE_ROUTER];
118
+ }
119
+ return r && r !== krateRouter ? r : null;
120
+ }
121
+ /**
122
+ * The page runtime's navigate when this is an island's copy of the router
123
+ * and the page has no registered router (an older runtime): it still owns
124
+ * the history, so a navigation goes through it before falling back to a
125
+ * full load.
126
+ */
127
+ function pageNavigate() {
128
+ const nav = globalThis.navigate;
129
+ return otherRuntime() && typeof nav === 'function' ? nav : null;
130
+ }
131
+ /** True in a copy of this module other than the one the page runtime exposes. */
132
+ function otherRuntime() {
133
+ const pageRouter = globalThis.krateRouter;
134
+ return !!pageRouter && pageRouter !== krateRouter;
135
+ }
96
136
  let navSeq = 0;
97
137
  let pendingAbort;
98
138
  let keySeq = 0;
@@ -113,13 +153,27 @@ const SCROLL_HISTORY_MAX = 50;
113
153
  const prefetchedAssets = new Set();
114
154
  const PREFETCHED_ASSETS_MAX = 128;
115
155
  const errorPageCache = new Map();
156
+ /**
157
+ * Documents of visited history entries, keyed by history entry key (LRU), so
158
+ * back/forward renders without a request. Cleared by invalidatePrefetchCache().
159
+ */
160
+ const historyDocs = new Map();
161
+ const HISTORY_CACHE_MAX = 10;
162
+ /** Bumped by invalidatePrefetchCache(): a document fetched before it is stale. */
163
+ let cacheGen = 0;
164
+ /** History key of the hard-loaded first entry, until its document is stored. */
165
+ let initialKey = '';
116
166
  let prefetchTimers = new Map();
117
167
  let prefetchObserver = null;
118
168
  let loadingOverlay = [];
169
+ let loadingTimer;
119
170
  /** Output prefix of intercepting-route fragments (see the compiler's parallel.go). */
120
171
  const INTERCEPT_PREFIX = '_krate/i';
121
- const TRANSITION_MS = 150;
122
172
  const PREFETCH_DELAY = 200;
173
+ /** How long a navigation must be pending before the loading.tsx UI shows. */
174
+ const LOADING_DELAY_MS = 100;
175
+ /** Attribute set on <html> while a navigation is loading. */
176
+ const NAVIGATING_ATTR = 'data-krate-navigating';
123
177
  function now() {
124
178
  return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();
125
179
  }
@@ -176,6 +230,9 @@ function snapshot() {
176
230
  }
177
231
  /** Current router state (pathname without base path, search, hash, status). */
178
232
  export function getNavigationState() {
233
+ const live = liveRouter();
234
+ if (live)
235
+ return live.getState();
179
236
  if (typeof location === 'undefined') {
180
237
  return { url: '', pathname: '/', search: '', hash: '', status: 'idle' };
181
238
  }
@@ -198,6 +255,14 @@ function setStatus(next) {
198
255
  if (status === next)
199
256
  return;
200
257
  status = next;
258
+ // Apps style the pending state with html[data-krate-navigating]; the old
259
+ // page stays visible and interactive until the new one is ready.
260
+ try {
261
+ document.documentElement.toggleAttribute(NAVIGATING_ATTR, next === 'loading');
262
+ }
263
+ catch {
264
+ /* ignore */
265
+ }
201
266
  emit();
202
267
  }
203
268
  /**
@@ -207,6 +272,9 @@ function setStatus(next) {
207
272
  * with getNavigationState().
208
273
  */
209
274
  export function subscribeNavigation(fn) {
275
+ const live = liveRouter();
276
+ if (live)
277
+ return live.subscribe(fn);
210
278
  listeners.add(fn);
211
279
  return () => {
212
280
  listeners.delete(fn);
@@ -276,11 +344,66 @@ function cacheTake(key) {
276
344
  * `krate:revalidate` event.
277
345
  */
278
346
  export function invalidatePrefetchCache(url) {
347
+ // A prefetch still in flight started before the data changed: forgetting it
348
+ // keeps its (stale) response out of the cache.
349
+ cacheGen++;
279
350
  if (url === undefined) {
280
351
  prefetchCache.clear();
352
+ prefetchInflight.clear();
353
+ historyDocs.clear();
281
354
  return;
282
355
  }
283
- prefetchCache.delete(cacheKey(url));
356
+ const key = cacheKey(url);
357
+ prefetchCache.delete(key);
358
+ prefetchInflight.delete(key);
359
+ historyDocs.forEach((doc, k) => {
360
+ if (cacheKey(doc.url) === key)
361
+ historyDocs.delete(k);
362
+ });
363
+ }
364
+ function historyPut(key, doc) {
365
+ if (!key)
366
+ return;
367
+ historyDocs.delete(key);
368
+ while (historyDocs.size >= HISTORY_CACHE_MAX) {
369
+ const oldest = historyDocs.keys().next().value;
370
+ if (oldest === undefined)
371
+ break;
372
+ historyDocs.delete(oldest);
373
+ }
374
+ historyDocs.set(key, doc);
375
+ }
376
+ /**
377
+ * The hard-loaded first entry has no document string: fetch it in idle time
378
+ * once the user left it, so going back to it is instant too. A response the
379
+ * server marked no-store is not kept.
380
+ */
381
+ function storeInitialDocument(key, url) {
382
+ if (savingData())
383
+ return;
384
+ const gen = cacheGen;
385
+ idle(() => {
386
+ if (historyDocs.has(key) || gen !== cacheGen)
387
+ return;
388
+ fetch(cacheKey(url), { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
389
+ .then(async (res) => {
390
+ if (!res.ok || /no-store/i.test(res.headers.get('cache-control') || ''))
391
+ return;
392
+ const finalUrl = res.url || cacheKey(url);
393
+ if (pathOf(finalUrl) !== pathOf(url))
394
+ return;
395
+ const ct = res.headers.get('content-type') || '';
396
+ const html = await res.text();
397
+ if (!(isHTMLType(ct) || (ct === '' && looksLikeHTML(html))))
398
+ return;
399
+ if (gen !== cacheGen || historyDocs.has(key) || !initialized)
400
+ return;
401
+ historyPut(key, { html, url, status: res.status });
402
+ })
403
+ .catch(() => {
404
+ /* back falls back to a normal fetch */
405
+ });
406
+ });
284
407
  }
285
408
  function isHTMLType(ct) {
286
409
  return /text\/html|application\/xhtml\+xml/i.test(ct);
@@ -288,16 +411,50 @@ function isHTMLType(ct) {
288
411
  function looksLikeHTML(body) {
289
412
  return /^\s*(<!doctype html|<html|<head|<body)/i.test(body);
290
413
  }
291
- function prefetchAsset(url) {
414
+ function prefetchAsset(url, as = 'script') {
292
415
  if (prefetchedAssets.has(url) || prefetchedAssets.size >= PREFETCHED_ASSETS_MAX)
293
416
  return;
294
417
  prefetchedAssets.add(url);
295
418
  const link = document.createElement('link');
296
419
  link.rel = 'prefetch';
297
- link.as = 'script';
420
+ link.as = as;
298
421
  link.href = url;
299
422
  document.head.appendChild(link);
300
423
  }
424
+ /** Stylesheets of a prefetched document that this document does not have. */
425
+ function newStylesheetURLs(doc, baseUrl) {
426
+ const have = new Set();
427
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => have.add(l.href));
428
+ const out = [];
429
+ doc.querySelectorAll('link[rel="stylesheet"][href]').forEach((l) => {
430
+ try {
431
+ const abs = new URL(l.getAttribute('href'), baseUrl).href;
432
+ if (!have.has(abs) && !out.includes(abs))
433
+ out.push(abs);
434
+ }
435
+ catch {
436
+ /* ignore */
437
+ }
438
+ });
439
+ return out;
440
+ }
441
+ /**
442
+ * The scripts this document already has: its script tags, and every resource
443
+ * it fetched, which includes the island modules an earlier client-side
444
+ * navigation imported and that the current head no longer lists.
445
+ */
446
+ function loadedAssetURLs() {
447
+ const loaded = new Set();
448
+ document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
449
+ try {
450
+ for (const e of performance.getEntriesByType('resource'))
451
+ loaded.add(e.name);
452
+ }
453
+ catch {
454
+ // No resource timing: the script tags are all we know.
455
+ }
456
+ return loaded;
457
+ }
301
458
  function prefetchPage(url) {
302
459
  const key = cacheKey(url);
303
460
  const cached = prefetchCache.get(key);
@@ -318,10 +475,16 @@ function prefetchPage(url) {
318
475
  const html = await res.text();
319
476
  if (!(isHTMLType(ct) || (ct === '' && looksLikeHTML(html))))
320
477
  return;
478
+ // Invalidated while in flight: the response is stale.
479
+ if (prefetchInflight.get(key) !== p)
480
+ return;
321
481
  cachePut(key, { html, url: finalUrl, status: res.status, at: now() });
322
- const loaded = new Set();
323
- document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
324
- for (const asset of pageAssetURLs(html, finalUrl, loaded))
482
+ // Warm the route's stylesheets and scripts too, so the navigation does
483
+ // not wait on them before the swap.
484
+ const doc = new DOMParser().parseFromString(html, 'text/html');
485
+ for (const sheet of newStylesheetURLs(doc, finalUrl))
486
+ prefetchAsset(sheet, 'style');
487
+ for (const asset of pageAssetURLs(doc, finalUrl, loadedAssetURLs()))
325
488
  prefetchAsset(asset);
326
489
  })
327
490
  .catch(() => {
@@ -329,7 +492,8 @@ function prefetchPage(url) {
329
492
  // errors through krate:navigate-error.
330
493
  })
331
494
  .finally(() => {
332
- prefetchInflight.delete(key);
495
+ if (prefetchInflight.get(key) === p)
496
+ prefetchInflight.delete(key);
333
497
  });
334
498
  prefetchInflight.set(key, p);
335
499
  return p;
@@ -360,6 +524,24 @@ function shouldPrefetch(a) {
360
524
  const v = a.getAttribute('data-prefetch');
361
525
  return a.hasAttribute('data-prefetch') && v !== 'false' && v !== '0';
362
526
  }
527
+ /** Most links per page that viewport prefetch will fetch. */
528
+ const VIEWPORT_PREFETCH_MAX = 5;
529
+ let viewportPrefetched = 0;
530
+ /** Whether the connection asks for no speculative traffic (Save-Data, 2g). */
531
+ function savingData() {
532
+ const c = navigator.connection;
533
+ if (!c)
534
+ return false;
535
+ return c.saveData === true || c.effectiveType === 'slow-2g' || c.effectiveType === '2g';
536
+ }
537
+ // Viewport prefetch is opt-in: prefetch="viewport" on the link, or the site-wide
538
+ // `prefetch: "viewport"` default. Everything else prefetches on intent only.
539
+ function wantsViewportPrefetch(a) {
540
+ if (!shouldPrefetch(a))
541
+ return false;
542
+ const v = a.getAttribute('data-prefetch');
543
+ return v === 'viewport' || (runtimeConfig().prefetch === 'viewport' && v !== 'intent');
544
+ }
363
545
  // Above-the-fold/viewport prefetch is deferred to idle time so it never
364
546
  // competes with first paint; hover/focus keeps the 200ms intent debounce.
365
547
  function idle(fn) {
@@ -369,19 +551,27 @@ function idle(fn) {
369
551
  else
370
552
  setTimeout(fn, 50);
371
553
  }
372
- function prefetchHoverHandler(e) {
554
+ /** The prefetchable link an event targets and its absolute URL. */
555
+ function prefetchTarget(e) {
373
556
  const t = e.target;
374
557
  if (!t || typeof t.closest !== 'function')
375
- return;
558
+ return null;
376
559
  const a = t.closest('a[data-prefetch]');
377
- if (!a || !shouldPrefetch(a) || !isLocalLink(a))
378
- return;
560
+ if (!a || !shouldPrefetch(a) || !isLocalLink(a) || savingData())
561
+ return null;
379
562
  const href = a.getAttribute('href');
380
563
  if (!href)
381
- return;
564
+ return null;
382
565
  const url = new URL(href, location.href).href;
383
566
  if (pathOf(url) === renderedPath)
567
+ return null;
568
+ return { a, url };
569
+ }
570
+ function prefetchHoverHandler(e) {
571
+ const hit = prefetchTarget(e);
572
+ if (!hit)
384
573
  return;
574
+ const { a, url } = hit;
385
575
  const existing = prefetchTimers.get(a);
386
576
  if (existing)
387
577
  clearTimeout(existing);
@@ -391,17 +581,36 @@ function prefetchHoverHandler(e) {
391
581
  }, PREFETCH_DELAY);
392
582
  prefetchTimers.set(a, timer);
393
583
  }
584
+ // A press (touch, or a pointer about to click) is a stronger signal than a
585
+ // hover: prefetch right away, so the click finds the document in flight.
586
+ function prefetchPressHandler(e) {
587
+ if (typeof e.button === 'number' && e.button !== 0)
588
+ return;
589
+ const hit = prefetchTarget(e);
590
+ if (!hit)
591
+ return;
592
+ const existing = prefetchTimers.get(hit.a);
593
+ if (existing) {
594
+ clearTimeout(existing);
595
+ prefetchTimers.delete(hit.a);
596
+ }
597
+ void prefetchPage(hit.url);
598
+ }
599
+ const PRESS_EVENTS = ['touchstart', typeof PointerEvent === 'function' ? 'pointerdown' : 'mousedown'];
394
600
  function observePrefetchLinks() {
395
- if (!prefetchObserver)
601
+ viewportPrefetched = 0;
602
+ if (!prefetchObserver || savingData())
396
603
  return;
397
604
  document.querySelectorAll('a[data-prefetch]').forEach((a) => {
398
- if (shouldPrefetch(a))
605
+ if (wantsViewportPrefetch(a))
399
606
  prefetchObserver.observe(a);
400
607
  });
401
608
  }
402
609
  function setupPrefetch() {
403
610
  document.addEventListener('mouseover', prefetchHoverHandler);
404
611
  document.addEventListener('focusin', prefetchHoverHandler);
612
+ for (const name of PRESS_EVENTS)
613
+ document.addEventListener(name, prefetchPressHandler, { passive: true });
405
614
  if (typeof IntersectionObserver !== 'undefined') {
406
615
  prefetchObserver = new IntersectionObserver((entries) => {
407
616
  for (const entry of entries) {
@@ -409,10 +618,12 @@ function setupPrefetch() {
409
618
  continue;
410
619
  const a = entry.target;
411
620
  const href = a.getAttribute('href');
412
- if (href && isLocalLink(a) && shouldPrefetch(a)) {
621
+ if (href && isLocalLink(a) && wantsViewportPrefetch(a) && viewportPrefetched < VIEWPORT_PREFETCH_MAX && !savingData()) {
413
622
  const url = new URL(href, location.href).href;
414
- if (pathOf(url) !== renderedPath)
623
+ if (pathOf(url) !== renderedPath) {
624
+ viewportPrefetched++;
415
625
  idle(() => void prefetchPage(url));
626
+ }
416
627
  }
417
628
  prefetchObserver.unobserve(entry.target);
418
629
  }
@@ -433,23 +644,35 @@ function setupSpeculationRules() {
433
644
  // is used instead of emitting a blocked script.
434
645
  if (document.querySelector('meta[http-equiv="Content-Security-Policy" i]'))
435
646
  return;
647
+ if (savingData())
648
+ return;
436
649
  try {
437
650
  const script = document.createElement('script');
438
651
  script.type = 'speculationrules';
652
+ const bp = basePath();
439
653
  script.textContent = JSON.stringify({
440
654
  prefetch: [
441
655
  {
442
656
  where: {
443
657
  and: [
444
- { href_matches: '/*' },
445
- { not: { href_matches: '/__krate/*' } },
446
- { not: { href_matches: '/api/*' } },
658
+ { href_matches: bp + '/*' },
659
+ { not: { href_matches: bp + '/__krate/*' } },
660
+ { not: { href_matches: bp + '/api/*' } },
447
661
  ],
448
662
  },
449
663
  eagerness: 'moderate',
450
664
  },
451
665
  ],
452
666
  });
667
+ // A CSP sent as a header cannot be read from here: when it blocks the
668
+ // inline script, drop it and leave prefetching to the JS path.
669
+ const onViolation = (e) => {
670
+ if (e && e.blockedURI === 'inline' && String(e.effectiveDirective || e.violatedDirective || '').startsWith('script-src')) {
671
+ script.remove();
672
+ document.removeEventListener('securitypolicyviolation', onViolation);
673
+ }
674
+ };
675
+ document.addEventListener('securitypolicyviolation', onViolation);
453
676
  document.head.appendChild(script);
454
677
  }
455
678
  catch {
@@ -480,33 +703,34 @@ function supportsViewTransitions() {
480
703
  function appRoot(doc) {
481
704
  return (doc.getElementById('root') || doc.body);
482
705
  }
483
- // While a fetch is in flight: overlay the loading.tsx template (if the page
484
- // has one) and, without View Transitions, fade the content out.
706
+ // While a fetch is in flight the old page stays as it is (visible and
707
+ // interactive). A navigation still pending after LOADING_DELAY_MS overlays the
708
+ // loading.tsx template, if the page has one, so a fast response never flashes it.
485
709
  function beginTransition() {
486
- const tpl = document.querySelector('template[data-krate-loading]');
487
- if (tpl && tpl.content && loadingOverlay.length === 0) {
710
+ if (loadingTimer !== undefined)
711
+ clearTimeout(loadingTimer);
712
+ loadingTimer = setTimeout(() => {
713
+ loadingTimer = undefined;
714
+ const tpl = document.querySelector('template[data-krate-loading]');
715
+ if (status !== 'loading' || !tpl || !tpl.content || loadingOverlay.length > 0)
716
+ return;
488
717
  // Non-destructive loading UI: overlay the template without wiping the
489
718
  // live DOM, so the swap still sees the old tree.
490
719
  const frag = tpl.content.cloneNode(true);
491
720
  loadingOverlay = Array.from(frag.childNodes);
492
721
  document.body.appendChild(frag);
493
- }
494
- // Reduced motion: no fade at all (the overlay above is static).
495
- if (!supportsViewTransitions() && !prefersReducedMotion()) {
496
- const el = appRoot(document);
497
- el.style.transition = `opacity ${TRANSITION_MS}ms ease`;
498
- el.style.opacity = '0';
499
- }
722
+ }, LOADING_DELAY_MS);
500
723
  }
501
724
  function endTransition() {
725
+ if (loadingTimer !== undefined) {
726
+ clearTimeout(loadingTimer);
727
+ loadingTimer = undefined;
728
+ }
502
729
  for (const n of loadingOverlay) {
503
730
  if (n.parentNode)
504
731
  n.parentNode.removeChild(n);
505
732
  }
506
733
  loadingOverlay = [];
507
- const el = appRoot(document);
508
- if (el.style.opacity === '0')
509
- el.style.opacity = '';
510
734
  }
511
735
  /**
512
736
  * Apply `data-view-transition="name"` to `view-transition-name` (and
@@ -526,8 +750,30 @@ function applyViewTransitionNames(root) {
526
750
  });
527
751
  }
528
752
  // Document reconciliation
529
- /** How long a navigation waits for new stylesheets before swapping anyway. */
530
- const STYLESHEET_TIMEOUT_MS = 3000;
753
+ /** How long a navigation waits for new stylesheets and scripts before swapping anyway. */
754
+ const ASSET_TIMEOUT_MS = 3000;
755
+ /** Resolves once link has loaded or failed (listen before inserting it). */
756
+ function linkSettled(link) {
757
+ return new Promise((resolve) => {
758
+ const done = () => {
759
+ link.removeEventListener('load', done);
760
+ link.removeEventListener('error', done);
761
+ resolve();
762
+ };
763
+ link.addEventListener('load', done);
764
+ link.addEventListener('error', done);
765
+ });
766
+ }
767
+ /** Resolves once every promise settled, or after ASSET_TIMEOUT_MS. */
768
+ function settledOrTimeout(pending) {
769
+ if (pending.length === 0)
770
+ return Promise.resolve();
771
+ let timer;
772
+ const timeout = new Promise((resolve) => {
773
+ timer = setTimeout(resolve, ASSET_TIMEOUT_MS);
774
+ });
775
+ return Promise.race([Promise.all(pending).then(() => { }), timeout]).then(() => clearTimeout(timer));
776
+ }
531
777
  /**
532
778
  * Diff stylesheet <link>s by absolute URL (base-path and format safe). New
533
779
  * links are inserted at the position they have in the incoming document (before
@@ -566,15 +812,7 @@ function prepareStylesheets(doc, baseUrl) {
566
812
  link.rel = 'stylesheet';
567
813
  link.href = abs;
568
814
  // Listen before insertion so a synchronous settle is not missed.
569
- pending.push(new Promise((resolve) => {
570
- const done = () => {
571
- link.removeEventListener('load', done);
572
- link.removeEventListener('error', done);
573
- resolve();
574
- };
575
- link.addEventListener('load', done);
576
- link.addEventListener('error', done);
577
- }));
815
+ pending.push(linkSettled(link));
578
816
  added.push({ link, media: link.getAttribute('media') });
579
817
  link.media = 'not all';
580
818
  if (prev) {
@@ -591,16 +829,8 @@ function prepareStylesheets(doc, baseUrl) {
591
829
  }
592
830
  prev = el;
593
831
  });
594
- let ready = Promise.resolve();
595
- if (pending.length > 0) {
596
- let timer;
597
- const timeout = new Promise((resolve) => {
598
- timer = setTimeout(resolve, STYLESHEET_TIMEOUT_MS);
599
- });
600
- ready = Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
601
- }
602
832
  return {
603
- ready,
833
+ ready: settledOrTimeout(pending),
604
834
  commit() {
605
835
  for (const { link, media } of added) {
606
836
  if (media === null)
@@ -623,6 +853,36 @@ function reconcileHeadMeta(doc) {
623
853
  document.head.appendChild(document.importNode(el, true));
624
854
  });
625
855
  }
856
+ let docAttrSnap = null;
857
+ function attrsOf(el) {
858
+ const out = {};
859
+ if (el)
860
+ for (const a of Array.from(el.attributes))
861
+ out[a.name] = a.value;
862
+ return out;
863
+ }
864
+ function docAttrsOf(d) {
865
+ return { html: attrsOf(d.documentElement), body: attrsOf(d.body) };
866
+ }
867
+ function reconcileDocAttrs(doc) {
868
+ const prev = docAttrSnap ?? docAttrsOf(document);
869
+ const next = docAttrsOf(doc);
870
+ const apply = (target, before, after) => {
871
+ if (!target)
872
+ return;
873
+ for (const name of new Set([...Object.keys(before), ...Object.keys(after)])) {
874
+ if (before[name] === after[name])
875
+ continue;
876
+ if (after[name] === undefined)
877
+ target.removeAttribute(name);
878
+ else
879
+ target.setAttribute(name, after[name]);
880
+ }
881
+ };
882
+ apply(document.documentElement, prev.html, next.html);
883
+ apply(document.body, prev.body, next.body);
884
+ docAttrSnap = next;
885
+ }
626
886
  function scriptsToLoad(doc, baseUrl) {
627
887
  const keep = new Set();
628
888
  document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
@@ -643,21 +903,88 @@ function scriptsToLoad(doc, baseUrl) {
643
903
  });
644
904
  return out;
645
905
  }
906
+ /**
907
+ * Preloads the incoming page's scripts (and its own modulepreload links) before
908
+ * the swap, so they run from cache right after it instead of leaving the new
909
+ * page un-hydrated while they download. The links request each script the way
910
+ * loadScript does (no crossorigin attribute: a module script fetches in cors
911
+ * mode with same-origin credentials, as modulepreload does; a classic one in
912
+ * no-cors mode, as preload as=script does), so the browser reuses the response.
913
+ */
914
+ function preloadScripts(doc, baseUrl, scripts) {
915
+ const loaded = loadedAssetURLs();
916
+ const links = [];
917
+ const pending = [];
918
+ const add = (href, module, crossOrigin) => {
919
+ if (loaded.has(href))
920
+ return;
921
+ loaded.add(href);
922
+ const link = document.createElement('link');
923
+ if (module)
924
+ link.rel = 'modulepreload';
925
+ else {
926
+ link.rel = 'preload';
927
+ link.as = 'script';
928
+ }
929
+ if (crossOrigin !== null)
930
+ link.setAttribute('crossorigin', crossOrigin);
931
+ link.href = href;
932
+ pending.push(linkSettled(link));
933
+ links.push(link);
934
+ document.head.appendChild(link);
935
+ };
936
+ for (const s of scripts)
937
+ add(s.src, s.module, null);
938
+ doc.querySelectorAll('link[rel="modulepreload"][href]').forEach((l) => {
939
+ try {
940
+ add(resolveSrc(l.getAttribute('href'), baseUrl), true, l.getAttribute('crossorigin'));
941
+ }
942
+ catch {
943
+ /* ignore */
944
+ }
945
+ });
946
+ return {
947
+ ready: settledOrTimeout(pending),
948
+ remove() {
949
+ links.forEach((l) => l.remove());
950
+ },
951
+ };
952
+ }
646
953
  function loadScript(script) {
647
954
  return new Promise((resolve) => {
648
955
  const s = document.createElement('script');
649
956
  s.src = script.src;
650
957
  if (script.module)
651
958
  s.type = 'module';
959
+ // Classic scripts run in document order, as on a full load: a shared
960
+ // component chunk must register before the page script that calls it.
961
+ else
962
+ s.async = false;
652
963
  // Only page scripts are disposable across navigations; the shared runtime
653
- // chunk stays in place.
654
- if (!RUNTIME_CHUNK_RE.test(script.src))
964
+ // and component chunks stay in place.
965
+ if (!PERSISTENT_SCRIPT_RE.test(script.src))
655
966
  s.setAttribute('data-krate-spa', '');
656
967
  s.onload = () => resolve(true);
657
968
  s.onerror = () => resolve(false);
658
969
  document.body.appendChild(s);
659
970
  });
660
971
  }
972
+ // Inline boot scripts (data-krate-boot: the CSS ARIA enhancer and the :has()
973
+ // shim) are emitted into the page that needs them. A soft navigation parses
974
+ // but never runs inline scripts, so each distinct one runs here, once.
975
+ const bootRan = new Set();
976
+ function runBootScripts(root) {
977
+ root.querySelectorAll('script[data-krate-boot]').forEach((s) => {
978
+ const code = s.textContent || '';
979
+ if (!code || bootRan.has(code))
980
+ return;
981
+ bootRan.add(code);
982
+ const el = document.createElement('script');
983
+ el.text = code;
984
+ document.head.appendChild(el);
985
+ el.remove();
986
+ });
987
+ }
661
988
  // Scroll, focus, announcements
662
989
  function hashTarget(hash) {
663
990
  if (!hash || hash === '#')
@@ -698,6 +1025,71 @@ function applyScroll(url, req) {
698
1025
  window.scrollTo(0, 0);
699
1026
  }
700
1027
  let focusedRoot = null;
1028
+ // Attributes that tell a focused control apart from its siblings, in addition
1029
+ // to its tag, when it has no id.
1030
+ const FOCUS_SIG_ATTRS = ['name', 'type', 'role', 'aria-label', 'placeholder', 'data-testid', 'data-slot', 'href'];
1031
+ function focusSignature(el) {
1032
+ let s = el.tagName;
1033
+ for (const a of FOCUS_SIG_ATTRS) {
1034
+ const v = el.getAttribute(a);
1035
+ if (v !== null)
1036
+ s += '\u0000' + a + '=' + v;
1037
+ }
1038
+ return s;
1039
+ }
1040
+ function sameSignature(root, sig, tag) {
1041
+ return Array.from(root.getElementsByTagName(tag)).filter((e) => focusSignature(e) === sig);
1042
+ }
1043
+ /** Whether the swap of plan replaces el (it sits in the swapped region or a swapped slot). */
1044
+ function replacedBySwap(el, root, plan) {
1045
+ if (!root.contains(el))
1046
+ return false;
1047
+ if (!plan.region)
1048
+ return true;
1049
+ const within = (pair) => !!(pair[0].compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) &&
1050
+ !!(pair[1].compareDocumentPosition(el) & Node.DOCUMENT_POSITION_PRECEDING);
1051
+ return within(plan.region.live) || plan.slots.some((sl) => within(sl.live));
1052
+ }
1053
+ function captureFocus(root, plan) {
1054
+ const el = document.activeElement;
1055
+ if (!el || el === document.body || el === root || !replacedBySwap(el, root, plan))
1056
+ return null;
1057
+ const sig = focusSignature(el);
1058
+ const field = el;
1059
+ let start = null;
1060
+ let end = null;
1061
+ try {
1062
+ start = typeof field.selectionStart === 'number' ? field.selectionStart : null;
1063
+ end = typeof field.selectionEnd === 'number' ? field.selectionEnd : null;
1064
+ }
1065
+ catch {
1066
+ /* input types without a selection */
1067
+ }
1068
+ return { id: el.id, sig, index: sameSignature(root, sig, el.tagName).indexOf(el), start, end };
1069
+ }
1070
+ function hasFocusWithin(root) {
1071
+ const a = document.activeElement;
1072
+ return !!a && a !== document.body && a !== root && root.contains(a);
1073
+ }
1074
+ function restoreFocus(root, mark) {
1075
+ const tag = mark.sig.split('\u0000')[0];
1076
+ let el = mark.id ? document.getElementById(mark.id) : null;
1077
+ if (!el || !root.contains(el))
1078
+ el = sameSignature(root, mark.sig, tag)[mark.index] ?? null;
1079
+ if (!el || typeof el.focus !== 'function')
1080
+ return;
1081
+ try {
1082
+ el.focus({ preventScroll: true });
1083
+ const field = el;
1084
+ if (mark.start !== null && mark.end !== null && document.activeElement === el && typeof field.setSelectionRange === 'function') {
1085
+ const n = field.value.length;
1086
+ field.setSelectionRange(Math.min(mark.start, n), Math.min(mark.end, n));
1087
+ }
1088
+ }
1089
+ catch {
1090
+ /* ignore */
1091
+ }
1092
+ }
701
1093
  /** Move focus to the content root after navigation (a11y). */
702
1094
  function focusContent() {
703
1095
  const active = document.activeElement;
@@ -783,8 +1175,18 @@ function fetchErrorPage(path) {
783
1175
  })
784
1176
  .catch(() => null);
785
1177
  }
1178
+ /** The stored document of the history entry a back/forward step restores. */
1179
+ function historyHit(req) {
1180
+ if (req.kind !== 'pop' || !req.restoreKey || req.bypassCache)
1181
+ return undefined;
1182
+ const doc = historyDocs.get(req.restoreKey);
1183
+ return doc && pathOf(doc.url) === pathOf(req.url) ? doc : undefined;
1184
+ }
786
1185
  async function loadDocument(req, signal) {
787
1186
  const key = cacheKey(req.url);
1187
+ const stored = historyHit(req);
1188
+ if (stored)
1189
+ return { ok: true, doc: { html: stored.html, url: req.url, status: stored.status } };
788
1190
  if (!req.bypassCache) {
789
1191
  const inflight = prefetchInflight.get(key);
790
1192
  if (inflight)
@@ -800,6 +1202,10 @@ async function loadDocument(req, signal) {
800
1202
  return { ok: true, doc: { html: hit.html, url: target, status: hit.status } };
801
1203
  }
802
1204
  }
1205
+ // Only a document that has to come from the network can show the loading
1206
+ // UI: a prefetched one (even one still in flight, awaited above) or a stored
1207
+ // history entry is nearly there.
1208
+ beginTransition();
803
1209
  let res;
804
1210
  try {
805
1211
  res = await fetch(key, {
@@ -879,9 +1285,6 @@ async function runNavigation(req) {
879
1285
  const ctrl = new AbortController();
880
1286
  pendingAbort = ctrl;
881
1287
  setStatus('loading');
882
- const hasCached = !req.bypassCache && prefetchCache.has(cacheKey(req.url));
883
- if (!hasCached)
884
- beginTransition();
885
1288
  let result;
886
1289
  try {
887
1290
  result = await loadDocument(req, ctrl.signal);
@@ -906,20 +1309,41 @@ async function commitDocument(loaded, req, seq) {
906
1309
  const url = loaded.url;
907
1310
  const newRoot = appRoot(doc);
908
1311
  const oldRoot = appRoot(document);
909
- // Save the position of the entry we are leaving (pop saves in the handler).
910
- if (req.kind === 'push')
911
- saveScroll(currentKey);
912
- const newChain = readRouteChain(doc);
913
- const plan = planSwap(currentChain, newChain, location.href, url, doc);
914
1312
  // Load the incoming stylesheets before swapping so the new page (and kept
915
- // layouts whose rules live in the per-page sheet) never renders unstyled.
1313
+ // layouts whose rules live in the per-page sheet) never renders unstyled,
1314
+ // and its scripts so it hydrates as soon as it appears.
916
1315
  const sheets = prepareStylesheets(doc, url);
917
- await sheets.ready;
1316
+ const preload = preloadScripts(doc, url, scriptsToLoad(doc, url));
1317
+ await Promise.all([sheets.ready, preload.ready]);
918
1318
  if (seq !== navSeq) {
919
1319
  sheets.abort();
1320
+ preload.remove();
920
1321
  return;
921
1322
  }
1323
+ // Save the position of the entry we are leaving (pop saves in the handler).
1324
+ // The old page stayed scrollable while the new one loaded.
1325
+ const leaving = currentKey;
1326
+ const leavingUrl = location.href;
1327
+ if (req.kind === 'push')
1328
+ saveScroll(currentKey);
1329
+ const newChain = readRouteChain(doc);
1330
+ const plan = planSwap(currentChain, newChain, location.href, url, doc);
1331
+ // A navigation that stays on the page (a query change, router.refresh())
1332
+ // keeps the page's islands mounted and their DOM in place; a control
1333
+ // focused in one of them keeps the focus. When the swap replaces the focused
1334
+ // element, focus moves to the same element in the new DOM.
1335
+ // Compared with the document on screen: on back/forward the location
1336
+ // already shows the target URL.
1337
+ const samePage = pathOf(url).split('?')[0] === docPath.split('?')[0];
1338
+ let focusMark = null;
1339
+ let focused = null;
1340
+ let islandJobs = [];
922
1341
  const mutate = () => {
1342
+ if (samePage)
1343
+ focusMark = captureFocus(oldRoot, plan);
1344
+ const active = document.activeElement;
1345
+ focused = active && active !== document.body && oldRoot.contains(active) ? active : null;
1346
+ const sel = focused ? selectionOf(focused) : null;
923
1347
  const title = doc.querySelector('title');
924
1348
  if (title)
925
1349
  document.title = title.textContent || '';
@@ -928,35 +1352,55 @@ async function commitDocument(loaded, req, seq) {
928
1352
  g.krateDisposeExcept(plan.keep);
929
1353
  else if (typeof g.disposeAll === 'function')
930
1354
  g.disposeAll();
1355
+ // Islands in the new markup that are mounted already stay mounted; a
1356
+ // navigation to another page keeps only those with the same props.
1357
+ const opts = { sameProps: !samePage };
1358
+ // Imported into one fragment, so the nodes keep their siblings (an
1359
+ // island's open and close comments find each other).
1360
+ const imported = (nodes) => {
1361
+ const f = document.createDocumentFragment();
1362
+ for (const n of nodes)
1363
+ f.appendChild(document.importNode(n, true));
1364
+ return Array.from(f.childNodes);
1365
+ };
931
1366
  if (plan.region) {
932
1367
  // Only the deepest boundary that differs is replaced; the kept layouts'
933
1368
  // DOM (and its state, focus and scroll containers) stays in place.
934
1369
  const { live, next } = plan.region;
935
- clearBetween(live[0], live[1]);
936
- const nodes = between(next[0], next[1]).map((n) => document.importNode(n, true));
937
- for (const n of nodes)
938
- live[1].parentNode.insertBefore(n, live[1]);
1370
+ islandJobs = swapNodes(live[0].parentNode, live[0], live[1], imported(between(next[0], next[1])), opts);
939
1371
  for (const sl of plan.slots) {
940
- clearBetween(sl.live[0], sl.live[1]);
941
- for (const n of between(sl.next[0], sl.next[1]))
942
- sl.live[1].parentNode.insertBefore(document.importNode(n, true), sl.live[1]);
1372
+ islandJobs.push(...swapNodes(sl.live[0].parentNode, sl.live[0], sl.live[1], imported(between(sl.next[0], sl.next[1])), opts));
943
1373
  }
944
1374
  syncLoadingTemplate(oldRoot, newRoot);
945
1375
  }
946
1376
  else {
947
- const nodes = Array.from(newRoot.childNodes).map((n) => document.importNode(n, true));
948
- oldRoot.replaceChildren(...nodes);
1377
+ islandJobs = swapNodes(oldRoot, null, null, imported(Array.from(newRoot.childNodes)), opts);
949
1378
  }
950
1379
  currentChain = plan.chain;
951
1380
  // Detached slot content of earlier intercepts belonged to the old page.
1381
+ interceptSnapshots.forEach((snap) => unmountIslands(snap.nodes));
952
1382
  interceptSnapshots.clear();
953
1383
  sheets.commit();
954
1384
  reconcileHeadMeta(doc);
1385
+ reconcileDocAttrs(doc);
955
1386
  applyViewTransitionNames(document);
1387
+ if (focused && focused.isConnected) {
1388
+ // The focused element was kept: it keeps the focus (and its selection)
1389
+ // even when it had to move.
1390
+ if (document.activeElement !== focused)
1391
+ refocus(focused, sel);
1392
+ focusMark = null;
1393
+ }
1394
+ else if (focusMark)
1395
+ restoreFocus(oldRoot, focusMark);
956
1396
  };
957
- await runMutation(mutate);
958
- if (seq !== navSeq)
1397
+ // A View Transition cross-fades a change of page; a refresh or a query
1398
+ // change on the same page (a search box, a revalidation) swaps in place.
1399
+ await runMutation(mutate, req.kind !== 'refresh' && !samePage);
1400
+ if (seq !== navSeq) {
1401
+ preload.remove();
959
1402
  return;
1403
+ }
960
1404
  endTransition();
961
1405
  // History: the DOM now shows the new route, so the URL follows it before
962
1406
  // any page script runs.
@@ -966,6 +1410,7 @@ async function commitDocument(loaded, req, seq) {
966
1410
  }
967
1411
  else if (req.kind === 'replace') {
968
1412
  scrollPositions.delete(currentKey);
1413
+ historyDocs.delete(currentKey);
969
1414
  currentKey = newKey();
970
1415
  history.replaceState(historyEntry(currentKey, req.state), '', url);
971
1416
  }
@@ -976,6 +1421,15 @@ async function commitDocument(loaded, req, seq) {
976
1421
  else if (req.restoreKey) {
977
1422
  currentKey = req.restoreKey;
978
1423
  }
1424
+ if (loaded.status >= 200 && loaded.status < 300)
1425
+ historyPut(currentKey, { html: loaded.html, url: location.href, status: loaded.status });
1426
+ if (req.kind === 'push' && leaving && leaving === initialKey) {
1427
+ initialKey = '';
1428
+ storeInitialDocument(leaving, leavingUrl);
1429
+ }
1430
+ else if (req.kind === 'replace' && leaving === initialKey) {
1431
+ initialKey = '';
1432
+ }
979
1433
  renderedPath = pathOf(location.href);
980
1434
  docPath = renderedPath;
981
1435
  syncParams(doc);
@@ -992,10 +1446,12 @@ async function commitDocument(loaded, req, seq) {
992
1446
  // Page scripts re-run against the new DOM; the hydration code of kept
993
1447
  // layouts is skipped (krateEnterScope) because their bindings are live.
994
1448
  document.querySelectorAll('script[data-krate-spa]').forEach((s) => s.remove());
1449
+ runBootScripts(doc);
995
1450
  const srcs = scriptsToLoad(doc, url);
996
1451
  keepScopes(plan.skip);
997
1452
  const results = await Promise.all(srcs.map(loadScript));
998
1453
  keepScopes([]);
1454
+ preload.remove();
999
1455
  if (seq !== navSeq)
1000
1456
  return;
1001
1457
  if (results.some((ok) => !ok)) {
@@ -1007,14 +1463,76 @@ async function commitDocument(loaded, req, seq) {
1007
1463
  }
1008
1464
  refreshPageBindings();
1009
1465
  dispatch('krate:navigate-end', { url: location.href, status: loaded.status });
1466
+ // An island that rendered its element anew while mounting took the focus
1467
+ // with it; look the element up again once the islands mounted.
1468
+ const mark = focusMark;
1469
+ if (mark && !hasFocusWithin(oldRoot)) {
1470
+ await islandsSettled(islandJobs);
1471
+ if (seq === navSeq && !hasFocusWithin(oldRoot))
1472
+ restoreFocus(oldRoot, mark);
1473
+ }
1474
+ }
1475
+ /** The island-preserving swap (island-swap.ts), which the island loader chunk installs on pages with islands. */
1476
+ function islandSwap() {
1477
+ const s = globalThis.__krateIslandSwap;
1478
+ return s && typeof s.swap === 'function' && typeof s.unmount === 'function' ? s : null;
1479
+ }
1480
+ /**
1481
+ * Replaces the children of parent between start and end (all of them when
1482
+ * both are null) with nodes, keeping the page's mounted islands when the page
1483
+ * has any.
1484
+ */
1485
+ function swapNodes(parent, start, end, nodes, opts) {
1486
+ const s = islandSwap();
1487
+ if (s)
1488
+ return s.swap(parent, start, end, nodes, opts);
1489
+ if (start && end) {
1490
+ clearBetween(start, end);
1491
+ for (const n of nodes)
1492
+ parent.insertBefore(n, end);
1493
+ }
1494
+ else
1495
+ parent.replaceChildren(...nodes);
1496
+ return [];
1497
+ }
1498
+ function unmountIslands(nodes) {
1499
+ const s = islandSwap();
1500
+ if (s)
1501
+ s.unmount(nodes);
1502
+ }
1503
+ /** Waits (at most a few seconds) for the islands the island loader is mounting and for island updates. */
1504
+ function islandsSettled(jobs) {
1505
+ const ready = globalThis.__krateIslandsReady;
1506
+ const all = Promise.all([...jobs, ready && typeof ready.then === 'function' ? ready : null]);
1507
+ return Promise.race([all, new Promise((r) => setTimeout(r, 3000))]);
1508
+ }
1509
+ function selectionOf(el) {
1510
+ const field = el;
1511
+ try {
1512
+ return typeof field.selectionStart === 'number' && typeof field.selectionEnd === 'number' ? [field.selectionStart, field.selectionEnd] : null;
1513
+ }
1514
+ catch {
1515
+ return null;
1516
+ }
1517
+ }
1518
+ function refocus(el, sel) {
1519
+ try {
1520
+ el.focus({ preventScroll: true });
1521
+ if (sel && document.activeElement === el && typeof el.setSelectionRange === 'function') {
1522
+ el.setSelectionRange(sel[0], sel[1]);
1523
+ }
1524
+ }
1525
+ catch {
1526
+ /* ignore */
1527
+ }
1010
1528
  }
1011
1529
  /**
1012
1530
  * Runs the DOM mutation, inside a View Transition when supported. Resolves
1013
1531
  * once the mutation has been applied (the transition's update callback has
1014
1532
  * run), so callers can touch the new DOM, history and focus afterwards.
1015
1533
  */
1016
- function runMutation(mutate) {
1017
- if (!supportsViewTransitions()) {
1534
+ function runMutation(mutate, animate = true) {
1535
+ if (!animate || !supportsViewTransitions()) {
1018
1536
  mutate();
1019
1537
  return Promise.resolve();
1020
1538
  }
@@ -1029,6 +1547,11 @@ function runMutation(mutate) {
1029
1547
  const vt = document.startViewTransition(once);
1030
1548
  if (vt && vt.finished && typeof vt.finished.catch === 'function')
1031
1549
  vt.finished.catch(() => { });
1550
+ // A newer navigation skips this transition; ready then rejects with
1551
+ // "Transition was skipped", which would otherwise surface as an unhandled
1552
+ // rejection on the page.
1553
+ if (vt && vt.ready && typeof vt.ready.catch === 'function')
1554
+ vt.ready.catch(() => { });
1032
1555
  const done = vt && vt.updateCallbackDone;
1033
1556
  if (done && typeof done.then === 'function') {
1034
1557
  return done.then(() => once(), () => once());
@@ -1084,6 +1607,7 @@ function between(start, end) {
1084
1607
  }
1085
1608
  function clearBetween(start, end) {
1086
1609
  const dispose = globalThis.disposeNode;
1610
+ unmountIslands(between(start, end));
1087
1611
  for (const n of between(start, end)) {
1088
1612
  n.parentNode.removeChild(n);
1089
1613
  if (typeof dispose === 'function')
@@ -1419,6 +1943,7 @@ async function runIntercept(req, hit) {
1419
1943
  document.head.appendChild(link);
1420
1944
  });
1421
1945
  setSlotInfo(hit.slot.key, { ...hit.slot, scope: frag.scope, src: 'intercept' });
1946
+ runBootScripts(doc);
1422
1947
  const state = { __krate: '', state: req.state === undefined ? null : req.state, __kint: { key: hit.slot.key, base: docPath } };
1423
1948
  if (req.kind === 'push') {
1424
1949
  currentKey = newKey();
@@ -1477,16 +2002,33 @@ function restoreSnapshot(snap, key) {
1477
2002
  function sameDocument(url) {
1478
2003
  return pathOf(url) === renderedPath;
1479
2004
  }
2005
+ // A newer in-document step (a hash link, or back/forward over a hash entry)
2006
+ // supersedes a page navigation still loading: it must not swap the page in
2007
+ // afterwards.
2008
+ function cancelPending() {
2009
+ if (status !== 'loading')
2010
+ return;
2011
+ navSeq++;
2012
+ if (pendingAbort)
2013
+ pendingAbort.abort();
2014
+ pendingAbort = undefined;
2015
+ endTransition();
2016
+ setStatus('idle');
2017
+ }
1480
2018
  /** In-document navigation: only the hash (or nothing) changes. */
1481
2019
  function hashNavigate(url, req) {
2020
+ cancelPending();
1482
2021
  saveScroll(currentKey);
1483
2022
  if (url !== location.href || req.state !== undefined) {
1484
2023
  if (req.kind === 'replace') {
1485
2024
  history.replaceState(historyEntry(currentKey || newKey(), req.state), '', url);
1486
2025
  }
1487
2026
  else {
2027
+ const prev = historyDocs.get(currentKey);
1488
2028
  currentKey = newKey();
1489
2029
  history.pushState(historyEntry(currentKey, req.state), '', url);
2030
+ if (prev)
2031
+ historyPut(currentKey, { ...prev, url });
1490
2032
  }
1491
2033
  }
1492
2034
  const hash = new URL(url).hash;
@@ -1592,6 +2134,7 @@ function popstateHandler(e) {
1592
2134
  const url = location.href;
1593
2135
  if (pathOf(url) === renderedPath) {
1594
2136
  // Hash-only history step within the rendered document.
2137
+ cancelPending();
1595
2138
  currentKey = key || currentKey;
1596
2139
  const saved = key ? scrollPositions.get(key) : undefined;
1597
2140
  if (saved !== undefined)
@@ -1647,12 +2190,15 @@ function refreshPageBindings() {
1647
2190
  // Mark the page scripts as disposable so they're removed and re-executed
1648
2191
  // against the fresh DOM on the next navigation.
1649
2192
  document.querySelectorAll('script[src]').forEach((s) => {
1650
- if (!RUNTIME_CHUNK_RE.test(s.src))
2193
+ if (!PERSISTENT_SCRIPT_RE.test(s.src))
1651
2194
  s.setAttribute('data-krate-spa', '');
1652
2195
  });
1653
2196
  }
1654
2197
  // Public API
1655
2198
  function refresh() {
2199
+ const live = liveRouter();
2200
+ if (live)
2201
+ return live.refresh();
1656
2202
  if (!initialized || typeof location === 'undefined') {
1657
2203
  if (typeof location !== 'undefined')
1658
2204
  location.reload();
@@ -1669,19 +2215,31 @@ function refresh() {
1669
2215
  }
1670
2216
  function push(url, opts = {}) {
1671
2217
  if (!initialized) {
1672
- if (typeof location !== 'undefined')
1673
- location.assign(url);
2218
+ const live = liveRouter();
2219
+ if (live)
2220
+ return live.push(url, opts);
2221
+ const nav = pageNavigate();
2222
+ if (nav)
2223
+ nav(url, { ...opts, replace: false });
2224
+ else if (typeof location !== 'undefined')
2225
+ location.assign(withBase(url));
1674
2226
  return Promise.resolve();
1675
2227
  }
1676
- return start({ url, kind: 'push', scroll: opts.scroll !== false, state: opts.state });
2228
+ return start({ url: withBase(url), kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1677
2229
  }
1678
2230
  function replace(url, opts = {}) {
1679
2231
  if (!initialized) {
1680
- if (typeof location !== 'undefined')
1681
- location.replace(url);
2232
+ const live = liveRouter();
2233
+ if (live)
2234
+ return live.replace(url, opts);
2235
+ const nav = pageNavigate();
2236
+ if (nav)
2237
+ nav(url, { ...opts, replace: true });
2238
+ else if (typeof location !== 'undefined')
2239
+ location.replace(withBase(url));
1682
2240
  return Promise.resolve();
1683
2241
  }
1684
- return start({ url, kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
2242
+ return start({ url: withBase(url), kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1685
2243
  }
1686
2244
  /**
1687
2245
  * The router API. Every navigation method resolves once the new route's DOM
@@ -1706,11 +2264,14 @@ export const krateRouter = {
1706
2264
  },
1707
2265
  refresh,
1708
2266
  prefetch(url) {
2267
+ const live = liveRouter();
2268
+ if (live)
2269
+ return live.prefetch(url);
1709
2270
  if (!initialized || typeof location === 'undefined')
1710
2271
  return Promise.resolve();
1711
2272
  let u;
1712
2273
  try {
1713
- u = new URL(url, location.href);
2274
+ u = new URL(withBase(url), location.href);
1714
2275
  }
1715
2276
  catch {
1716
2277
  return Promise.resolve();
@@ -1729,15 +2290,15 @@ export const krateRouter = {
1729
2290
  * client-side, true when a full navigation was triggered.
1730
2291
  */
1731
2292
  export function navigate(url, opts = {}) {
1732
- if (initialized) {
2293
+ if (initialized || liveRouter()) {
1733
2294
  void (opts.replace ? replace(url, opts) : push(url, opts));
1734
2295
  return false;
1735
2296
  }
1736
2297
  if (typeof location !== 'undefined') {
1737
2298
  if (opts.replace)
1738
- location.replace(url);
2299
+ location.replace(withBase(url));
1739
2300
  else
1740
- location.assign(url);
2301
+ location.assign(withBase(url));
1741
2302
  }
1742
2303
  return true;
1743
2304
  }
@@ -1749,10 +2310,15 @@ export function initRouter() {
1749
2310
  return;
1750
2311
  }
1751
2312
  initialized = true;
2313
+ globalThis[LIVE_ROUTER] = krateRouter;
2314
+ // The first document ran its own boot scripts.
2315
+ document.querySelectorAll('script[data-krate-boot]').forEach((s) => bootRan.add(s.textContent || ''));
1752
2316
  renderedPath = pathOf(location.href);
1753
2317
  currentChain = readRouteChain(document);
2318
+ docAttrSnap = docAttrsOf(document);
1754
2319
  docPath = renderedPath;
1755
2320
  currentKey = entryKey(history.state) || newKey();
2321
+ initialKey = currentKey;
1756
2322
  if (entryKey(history.state) === undefined) {
1757
2323
  try {
1758
2324
  history.replaceState(historyEntry(currentKey, history.state), '', location.href);
@@ -1789,6 +2355,8 @@ export function destroyRouter() {
1789
2355
  if (!initialized)
1790
2356
  return;
1791
2357
  initialized = false;
2358
+ if (globalThis[LIVE_ROUTER] === krateRouter)
2359
+ delete globalThis[LIVE_ROUTER];
1792
2360
  document.removeEventListener('click', clickHandler);
1793
2361
  document.removeEventListener('submit', submitHandler);
1794
2362
  window.removeEventListener('popstate', popstateHandler);
@@ -1797,6 +2365,8 @@ export function destroyRouter() {
1797
2365
  window.removeEventListener('pageshow', pageshowHandler);
1798
2366
  document.removeEventListener('mouseover', prefetchHoverHandler);
1799
2367
  document.removeEventListener('focusin', prefetchHoverHandler);
2368
+ for (const name of PRESS_EVENTS)
2369
+ document.removeEventListener(name, prefetchPressHandler);
1800
2370
  for (const timer of prefetchTimers.values())
1801
2371
  clearTimeout(timer);
1802
2372
  prefetchTimers = new Map();
@@ -1810,11 +2380,16 @@ export function destroyRouter() {
1810
2380
  navSeq++;
1811
2381
  prefetchCache.clear();
1812
2382
  prefetchInflight.clear();
2383
+ historyDocs.clear();
2384
+ initialKey = '';
2385
+ cacheGen++;
1813
2386
  scrollPositions.clear();
1814
2387
  errorPageCache.clear();
2388
+ bootRan.clear();
1815
2389
  listeners.clear();
1816
2390
  status = 'idle';
1817
- loadingOverlay = [];
2391
+ document.documentElement.removeAttribute(NAVIGATING_ATTR);
2392
+ endTransition();
1818
2393
  currentChain = [];
1819
2394
  interceptSnapshots.clear();
1820
2395
  docPath = '';