akanjs 3.2.0-rc.2 → 3.2.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +105 -1
  3. package/client/csrTypes.ts +13 -1
  4. package/client/frameConfig.ts +4 -2
  5. package/client/route/RouteHead.ts +11 -2
  6. package/client/router.ts +8 -4
  7. package/client/rscNavigation.ts +2 -3
  8. package/client/rscRoutePatch.ts +42 -0
  9. package/common/akanGraph.ts +1 -1
  10. package/common/types.ts +5 -0
  11. package/dictionary/base.dictionary.ts +1 -0
  12. package/fetch/client/fetchClient.ts +11 -16
  13. package/fetch/client/fetchHandle.ts +11 -1
  14. package/fetch/client/inflightQueries.ts +17 -0
  15. package/fetch/index.ts +1 -0
  16. package/fetch/staleReads.ts +27 -0
  17. package/fetch/streamedRead.ts +23 -0
  18. package/package.json +1 -1
  19. package/server/akanServer.ts +1 -1
  20. package/server/artifact/builderRpc.ts +22 -7
  21. package/server/artifact/ipcTypes.ts +9 -3
  22. package/server/devtools/README.md +4 -3
  23. package/server/devtools/devtoolsRouter.ts +9 -5
  24. package/server/devtools/studio/studioRoute.ts +18 -11
  25. package/server/head.tsx +4 -19
  26. package/server/routeElementComposer.tsx +86 -3
  27. package/server/routeState.ts +5 -1
  28. package/server/routeTreeBuilder.ts +1 -0
  29. package/server/rscClient.tsx +118 -21
  30. package/server/rscClientChunks.ts +62 -0
  31. package/server/rscClientFetch.ts +6 -1
  32. package/server/rscHeadPatch.ts +17 -56
  33. package/server/rscParkedRedirect.ts +23 -0
  34. package/server/rscPatchPlanner.ts +220 -0
  35. package/server/rscPrefetchCache.ts +39 -17
  36. package/server/rscResponse.ts +78 -0
  37. package/server/rscSegmentOutlet.tsx +24 -5
  38. package/server/rscSegmentOutletReference.ts +10 -12
  39. package/server/rscWorker.tsx +109 -154
  40. package/server/rscWorkerCache.ts +56 -0
  41. package/server/rscWorkerHost.ts +6 -8
  42. package/server/ssrTypes.ts +9 -0
  43. package/server/webRouter.ts +12 -89
  44. package/store/action.ts +282 -299
  45. package/store/actionErrorKey.ts +9 -0
  46. package/store/draftFlush.ts +5 -0
  47. package/store/draftStore.ts +2 -0
  48. package/store/formDrafts.ts +115 -0
  49. package/store/modelListPatch.ts +53 -0
  50. package/store/modelWriteGuard.ts +91 -0
  51. package/store/rootStore.ts +2 -0
  52. package/store/storeInstance.ts +9 -10
  53. package/store/uploadPoll.ts +52 -0
  54. package/store/withSelector.ts +6 -4
  55. package/types/client/csrTypes.d.ts +13 -1
  56. package/types/client/route/RouteHead.d.ts +5 -1
  57. package/types/client/router.d.ts +3 -2
  58. package/types/client/rscNavigation.d.ts +2 -2
  59. package/types/client/rscRoutePatch.d.ts +22 -0
  60. package/types/common/akanGraph.d.ts +1 -1
  61. package/types/common/types.d.ts +5 -0
  62. package/types/dictionary/base.dictionary.d.ts +1 -1
  63. package/types/dictionary/dictionary.d.ts +8 -8
  64. package/types/fetch/client/fetchHandle.d.ts +1 -0
  65. package/types/fetch/client/inflightQueries.d.ts +2 -0
  66. package/types/fetch/index.d.ts +1 -0
  67. package/types/fetch/staleReads.d.ts +8 -0
  68. package/types/fetch/streamedRead.d.ts +8 -0
  69. package/types/server/artifact/builderRpc.d.ts +8 -0
  70. package/types/server/artifact/ipcTypes.d.ts +8 -0
  71. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  72. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  73. package/types/server/head.d.ts +2 -2
  74. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  75. package/types/server/routeElementComposer.d.ts +24 -1
  76. package/types/server/routeState.d.ts +2 -0
  77. package/types/server/rscClient.d.ts +1 -0
  78. package/types/server/rscClientChunks.d.ts +10 -0
  79. package/types/server/rscHeadPatch.d.ts +5 -4
  80. package/types/server/rscParkedRedirect.d.ts +12 -0
  81. package/types/server/rscPatchPlanner.d.ts +49 -0
  82. package/types/server/rscPrefetchCache.d.ts +2 -2
  83. package/types/server/rscResponse.d.ts +9 -0
  84. package/types/server/rscSegmentOutlet.d.ts +5 -0
  85. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  86. package/types/server/rscWorkerCache.d.ts +33 -1
  87. package/types/server/rscWorkerHost.d.ts +2 -6
  88. package/types/server/ssrTypes.d.ts +8 -0
  89. package/types/server/webRouter.d.ts +1 -7
  90. package/types/store/action.d.ts +10 -6
  91. package/types/store/actionErrorKey.d.ts +1 -0
  92. package/types/store/baseSt.d.ts +1 -295
  93. package/types/store/draftFlush.d.ts +4 -0
  94. package/types/store/formDrafts.d.ts +21 -0
  95. package/types/store/modelListPatch.d.ts +34 -0
  96. package/types/store/modelWriteGuard.d.ts +45 -0
  97. package/types/store/rootStore.d.ts +6 -0
  98. package/types/store/uploadPoll.d.ts +16 -0
  99. package/types/store/withSelector.d.ts +1 -1
  100. package/types/ui/Link/inputModality.d.ts +5 -0
  101. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  102. package/types/ui/Load/Edit_Client.d.ts +2 -0
  103. package/types/ui/Load/Pagination.d.ts +4 -1
  104. package/types/ui/Load/Stream.d.ts +7 -1
  105. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  106. package/types/ui/Load/Units.d.ts +2 -0
  107. package/types/ui/Load/View.d.ts +2 -0
  108. package/types/webkit/nativeCore.d.ts +1 -0
  109. package/types/webkit/nativePurchase.d.ts +2 -1
  110. package/types/webkit/useFrameRuntime.d.ts +1 -0
  111. package/types/webkit/useGeoLocation.d.ts +1 -1
  112. package/types/webkit/usePurchase.d.ts +1 -1
  113. package/types/webkit/useTransitionStore.d.ts +1 -0
  114. package/ui/Button.tsx +1 -0
  115. package/ui/Link/inputModality.ts +21 -0
  116. package/ui/Link/prefetchIntent.ts +7 -25
  117. package/ui/Link/viewportPrefetch.ts +30 -0
  118. package/ui/Load/Edit_Client.tsx +7 -1
  119. package/ui/Load/Pagination.tsx +10 -2
  120. package/ui/Load/Stream.tsx +24 -4
  121. package/ui/Load/StreamBoundary.tsx +70 -0
  122. package/ui/Load/Units.tsx +3 -0
  123. package/ui/Load/View.tsx +3 -0
  124. package/ui/System/Client.tsx +28 -7
  125. package/webkit/nativeCore.ts +1 -0
  126. package/webkit/nativePurchase.ts +6 -3
  127. package/webkit/useCamera.tsx +22 -21
  128. package/webkit/useGeoLocation.tsx +4 -1
  129. package/webkit/usePurchase.tsx +4 -2
  130. package/webkit/useTransitionStore.ts +13 -0
@@ -6,6 +6,7 @@ import { DictionaryAsset } from "../client/dictionaryAsset";
6
6
  import type {} from "../client/rscNavigation";
7
7
  import { isAuthTokenKey } from "../common/authCookie";
8
8
  import { CookieJar } from "../common/cookieJar";
9
+ import { StaleReads } from "../fetch/staleReads";
9
10
  import {
10
11
  AKAN_RSC_DICTIONARY_HEADER,
11
12
  type AkanHeadSnapshotV1,
@@ -15,6 +16,14 @@ import {
15
16
  isAkanRscPartialCommitEnabled,
16
17
  readAkanRouterStateResponseHeader,
17
18
  } from "./routeState";
19
+ import {
20
+ type ChunkNavigation,
21
+ claimChunkReload,
22
+ isBuildBundle,
23
+ isLinkFailure,
24
+ navigationOfChunk,
25
+ recordChunksOf,
26
+ } from "./rscClientChunks";
18
27
  import { fetchRscNavigationResponse, fetchRscPrefetchResponse } from "./rscClientFetch";
19
28
  import { validateRscPatchForGuardedCommit } from "./rscClientPatch";
20
29
  import {
@@ -37,6 +46,7 @@ import {
37
46
  rememberRscCacheNode,
38
47
  resolveCachedRscPatchNavigation,
39
48
  } from "./rscNavigationState";
49
+ import { RscParkedRedirect } from "./rscParkedRedirect";
40
50
  import { RscPrefetchCache } from "./rscPrefetchCache";
41
51
  import { RscScrollRestoration } from "./rscScrollRestoration";
42
52
  import { commitAkanSegmentOutletPatch, resetAkanSegmentOutletPatches } from "./rscSegmentOutlet";
@@ -50,6 +60,7 @@ declare global {
50
60
  var __RSC_CLOSE__: (() => void) | undefined;
51
61
  var __AKAN_RSC_INITIAL_STATE__: string | undefined;
52
62
  var __AKAN_DICT_URL__: string | undefined;
63
+ var __webpack_chunk_load__: ((chunkId: string) => Promise<unknown>) | undefined;
53
64
  }
54
65
 
55
66
  function decodeInlineRscChunk([type, data]: InlineRscChunk): Uint8Array {
@@ -138,11 +149,17 @@ function createRscThenable(stream: ReadableStream<Uint8Array>): RscThenable {
138
149
  return trackRscThenable(createFromReadableStream<ReactNode>(stream) as RscThenable);
139
150
  }
140
151
 
152
+ window.addEventListener("pageshow", (event) => {
153
+ if (event.persisted) documentNavigationFallbackInFlight = false;
154
+ });
155
+
141
156
  function hardNavigateAfterRscFailure(target: string, replace = false, error?: unknown): void {
142
157
  if (documentNavigationFallbackInFlight) return;
143
158
  documentNavigationFallbackInFlight = true;
144
159
  console.warn(`[rscClient] RSC navigation failed, falling back to document navigation: ${String(error)}`);
145
- if (replace) window.location.replace(target);
160
+
161
+ if (normalizeHref(target) === normalizeHref(window.location.href)) window.location.reload();
162
+ else if (replace) window.location.replace(target);
146
163
  else window.location.assign(target);
147
164
  }
148
165
 
@@ -171,7 +188,7 @@ function commitRscPatchNavigation({
171
188
  }): boolean {
172
189
  const patchThenable = patch.patchedNode.thenable;
173
190
  if (!patchThenable) throw new Error("[rscClient] validated RSC patch is missing a thenable");
174
- const preparedHeadPatch = prepareAkanHeadSnapshotPatch(patch.headSnapshot);
191
+ const preparedHeadPatch = prepareAkanHeadSnapshotPatch(patch.headSnapshot, target);
175
192
  if (!preparedHeadPatch) return false;
176
193
 
177
194
  let outletCommitted = false;
@@ -186,6 +203,8 @@ function commitRscPatchNavigation({
186
203
  return;
187
204
  }
188
205
  commitHistory(target, replace);
206
+ shownNode = null;
207
+ parkedRedirect.clear();
189
208
  requestScroll?.();
190
209
  } catch {
191
210
  if (headApplied) rollbackPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
@@ -236,6 +255,12 @@ async function fetchRsc(
236
255
  } = {},
237
256
  ): Promise<RscFetchResult> {
238
257
  const shouldApplyNavigation = options.shouldApplyNavigation ?? (() => true);
258
+ const navigation =
259
+ options.navId === undefined
260
+ ? undefined
261
+ : { navId: options.navId, href, replace: options.replaceOnRedirect ?? (() => true) };
262
+ const thenableOf = (stream: ReadableStream<Uint8Array>) =>
263
+ createRscThenable(navigation ? recordChunksOf(stream, navigation) : stream);
239
264
  const responseResult = await fetchRscNavigationResponse(href, {
240
265
  buildId: options.buildId,
241
266
  currentRouterState,
@@ -246,6 +271,8 @@ async function fetchRsc(
246
271
  signal: options.signal,
247
272
  prefetched: options.prefetched,
248
273
  });
274
+ if (responseResult.type === "not-found" && shouldApplyNavigation())
275
+ parkedRedirect.resume(stillOnItsEntry, navigateAfterRscRedirect);
249
276
  if (responseResult.type === "redirected" || responseResult.type === "not-found") return responseResult;
250
277
 
251
278
  const dictionaryReady = DictionaryAsset.load(responseResult.response.headers.get(AKAN_RSC_DICTIONARY_HEADER));
@@ -257,7 +284,7 @@ async function fetchRsc(
257
284
  response: responseResult.response,
258
285
  patch: responseResult.patch,
259
286
  href,
260
- createThenable: createRscThenable,
287
+ createThenable: thenableOf,
261
288
  navId: options.navId,
262
289
  getCurrentNavId: () => navigationSeq,
263
290
  getHeadSnapshotPatchFailureReason: getAkanHeadSnapshotPatchFailureReason,
@@ -286,15 +313,20 @@ async function fetchRsc(
286
313
  if (!stream) throw new Error(`[rscClient] RSC fetch failed ${res.status} ${res.statusText}`);
287
314
  const nodeRef: { current?: RscCacheNode } = {};
288
315
  const handleRedirect = (redirect: RscRedirectRow) => {
289
- if (!shouldApplyNavigation()) return;
316
+ const node = nodeRef.current;
317
+ if (node) deleteRscCacheEntryIfCurrent(rscCache, href, node);
318
+ const applies = shouldApplyNavigation();
319
+
320
+ if (!applies && node !== shownNode) return;
290
321
  const location = redirect.location ? normalizeHref(redirect.location) : href;
291
- if (nodeRef.current) deleteRscCacheEntryIfCurrent(rscCache, href, nodeRef.current);
292
- navigateAfterRscRedirect(location, redirect.method !== "push" && (options.replaceOnRedirect?.() ?? true));
322
+ const replace = redirect.method !== "push" && (options.replaceOnRedirect?.() ?? true);
323
+ if (!applies && node && pendingRequest) parkedRedirect.park({ node, location, replace });
324
+ else navigateAfterRscRedirect(location, replace);
293
325
  };
294
326
  const guardedStream = guardRscRedirectRows(stream, {
295
327
  onRedirect: handleRedirect,
296
328
  });
297
- const thenable = createRscThenable(guardedStream);
329
+ const thenable = thenableOf(guardedStream);
298
330
  const node = createRscNavigationCacheNode({
299
331
  href,
300
332
  thenable,
@@ -319,6 +351,8 @@ const readAuthCookies = () =>
319
351
  const rscCache = new Map<string, RscCacheNode>();
320
352
  const rscPatchCache = new Map<string, RscPatchNavigationCacheNode<RscThenable>>();
321
353
  const rscPrefetchCache = new RscPrefetchCache({ fetchResponse: fetchRscPrefetchResponse });
354
+
355
+ StaleReads.subscribe(() => rscPrefetchCache.clear());
322
356
  const initialThenable = createRscThenable(createInitialRscStream());
323
357
  const initialRouterState = decodeAkanRouterState(globalThis.__AKAN_RSC_INITIAL_STATE__);
324
358
  const initialNode = createRscNavigationCacheNode({
@@ -330,19 +364,46 @@ rscCache.set(initialNode.href, initialNode);
330
364
  let currentRouterState: AkanRouterStateV1 | null = initialRouterState;
331
365
  let currentSegmentTree: RscSegmentCacheNode | null = createAkanSegmentCacheTree(initialNode);
332
366
  let currentFullNode: RscCacheNode | null = initialNode;
367
+ let shownNode: RscCacheNode | null = initialNode;
368
+ const parkedRedirect = new RscParkedRedirect<RscCacheNode>();
333
369
  let currentCommitKind: "full" | "patch" = "full";
334
370
  let currentCommitFromCache = false;
335
371
  let navigationSeq = 0;
336
372
  let pendingRequest: { navId: number; controller: AbortController; target: string } | null = null;
373
+ let latestPageNavId = 0;
337
374
  let cachedAuthCookies = readAuthCookies();
338
375
 
376
+ const stillOnItsEntry = (node: RscCacheNode) => {
377
+ const entry = (window.history.state as { __akanRouter?: { shallow?: boolean; rendered?: string } } | null)
378
+ ?.__akanRouter;
379
+ const here = normalizeHref(window.location.href);
380
+ return node === shownNode && pageKeyOf(node.href) === withoutHash(entry?.shallow ? entry.rendered : here);
381
+ };
382
+
339
383
  function supersedeNavigation(): number {
340
384
  pendingRequest?.controller.abort();
341
385
  pendingRequest = null;
342
386
  return ++navigationSeq;
343
387
  }
344
388
 
389
+ function supersedeForPageNavigation(): number {
390
+ documentNavigationFallbackInFlight = false;
391
+ return supersedeNavigation();
392
+ }
393
+
394
+ let refreshNavId: number | undefined;
395
+ function supersedeForRefresh(): number {
396
+ refreshNavId = supersedeNavigation();
397
+ return refreshNavId;
398
+ }
399
+
400
+ function supersedeKeepingPage(): void {
401
+ supersedeNavigation();
402
+ parkedRedirect.resume(stillOnItsEntry, navigateAfterRscRedirect);
403
+ }
404
+
345
405
  function requestSignalOf(navId: number, target: string): AbortSignal {
406
+ latestPageNavId = navId;
346
407
  const controller = new AbortController();
347
408
  pendingRequest = { navId, controller, target: pageKeyOf(target) };
348
409
  return controller.signal;
@@ -352,10 +413,32 @@ function settleRequestOf(navId: number): void {
352
413
  if (pendingRequest?.navId === navId) pendingRequest = null;
353
414
  }
354
415
 
416
+ const loadChunk = globalThis.__webpack_chunk_load__;
417
+ if (loadChunk)
418
+ globalThis.__webpack_chunk_load__ = (chunkId) => {
419
+ const loading = loadChunk(chunkId);
420
+ const navigation = navigationOfChunk(chunkId);
421
+ if (navigation) loading.catch((error: unknown) => loadDocumentForChunkFailure(chunkId, navigation, error));
422
+ return loading;
423
+ };
424
+
425
+ function loadDocumentForChunkFailure(chunkId: string, navigation: ChunkNavigation, error: unknown): void {
426
+ if (documentNavigationFallbackInFlight || !isBuildBundle()) return;
427
+ const showsItsPage = navigation.navId === refreshNavId || pageKeyOf(renderedHref) === pageKeyOf(navigation.href);
428
+ const pending = pendingRequest?.navId === navigation.navId && !showsItsPage;
429
+ const onScreen = navigation.navId === latestPageNavId && showsItsPage;
430
+ if (!pending && !(onScreen && navigator.onLine && isLinkFailure(error))) return;
431
+ if (!claimChunkReload(chunkId)) return;
432
+ if (pending) hardNavigateAfterRscFailure(navigation.href, navigation.replace(), error);
433
+ else hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
434
+ }
435
+
355
436
  globalThis.__AKAN_RSC_IS_FROM_CACHE__ = () => currentCommitFromCache;
356
437
 
357
438
  function rememberCommittedRouteState(node: RscCacheNode): void {
358
439
  rscPatchCache.clear();
440
+ shownNode = node;
441
+ parkedRedirect.clear();
359
442
  if (!node.routerState) return;
360
443
  currentRouterState = node.routerState;
361
444
  currentSegmentTree = createAkanSegmentCacheTree(node);
@@ -365,6 +448,8 @@ function rememberCommittedRouteState(node: RscCacheNode): void {
365
448
 
366
449
  function forgetCommittedRouteState(): void {
367
450
  rscPatchCache.clear();
451
+ shownNode = null;
452
+ parkedRedirect.clear();
368
453
  currentRouterState = null;
369
454
  currentSegmentTree = null;
370
455
  currentFullNode = null;
@@ -389,6 +474,17 @@ function forgetPagesOfAnotherAccount(): void {
389
474
  currentSegmentTree = null;
390
475
  }
391
476
 
477
+ function cachedPageOf(target: string): RscCacheNode | undefined {
478
+ const key = pageKeyOf(target);
479
+ return rscCache.get(target) ?? [...rscCache.values()].findLast((node) => pageKeyOf(node.href) === key);
480
+ }
481
+
482
+ function replayedPageOf(target: string): RscCacheNode | undefined {
483
+ const node = cachedPageOf(target);
484
+ if (node) rememberRscCacheNode(rscCache, node, MAX_RSC_CACHE_ENTRIES);
485
+ return node;
486
+ }
487
+
392
488
  const isConstrainedNetwork = () => {
393
489
  const connection = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } })
394
490
  .connection;
@@ -396,14 +492,15 @@ const isConstrainedNetwork = () => {
396
492
  };
397
493
 
398
494
  globalThis.__AKAN_RSC_PREFETCH__ = (href, priority) => {
399
- if (isConstrainedNetwork()) return;
495
+ const none = () => undefined;
496
+ if (isConstrainedNetwork()) return none;
400
497
  const target = normalizeHref(href);
401
498
  const key = pageKeyOf(target);
402
- if (new URL(target).origin !== window.location.origin || pendingRequest?.target === key) return;
499
+ if (new URL(target).origin !== window.location.origin || pendingRequest?.target === key) return none;
403
500
 
404
501
  const authCookies = readAuthCookies();
405
- if (authCookies === cachedAuthCookies && rscCache.has(target)) return;
406
- rscPrefetchCache.request(key, authCookies, priority);
502
+ if (authCookies === cachedAuthCookies && cachedPageOf(target)) return none;
503
+ return rscPrefetchCache.request(key, authCookies, priority);
407
504
  };
408
505
 
409
506
  function Root(): ReactNode {
@@ -427,19 +524,19 @@ function Root(): ReactNode {
427
524
  if (!currentFullNode) return;
428
525
  const currentFullState = currentFullNode.routerState;
429
526
  const canRestoreFullNode =
430
- currentFullNode.href === href &&
527
+ pageKeyOf(currentFullNode.href) === pageKeyOf(href) &&
431
528
  ((!currentFullState && !currentRouterState) ||
432
529
  (currentFullState !== null &&
433
530
  currentRouterState !== null &&
434
531
  currentFullState.routeId === currentRouterState.routeId));
435
532
  if (canRestoreFullNode) {
436
533
  resetAkanSegmentOutletPatches();
437
- rscCache.set(href, currentFullNode);
534
+ rscCache.set(currentFullNode.href, currentFullNode);
438
535
  }
439
536
  };
440
537
 
441
538
  globalThis.__AKAN_RSC_REFRESH__ = async (options = {}) => {
442
- const navId = supersedeNavigation();
539
+ const navId = supersedeForRefresh();
443
540
  const target = normalizeHref(window.location.href);
444
541
  rscCache.clear();
445
542
  rscPatchCache.clear();
@@ -497,12 +594,12 @@ function Root(): ReactNode {
497
594
 
498
595
  globalThis.__AKAN_RSC_NAVIGATE__ = async (href, options = {}) => {
499
596
  if (options.shallow && navigateShallow(normalizeHref(href), options.replace)) {
500
- supersedeNavigation();
597
+ supersedeKeepingPage();
501
598
  return;
502
599
  }
503
600
  forgetPagesOfAnotherAccount();
504
601
  rscPrefetchCache.prune();
505
- const navId = supersedeNavigation();
602
+ const navId = supersedeForPageNavigation();
506
603
  const target = normalizeHref(href);
507
604
  const signal = requestSignalOf(navId, target);
508
605
 
@@ -512,7 +609,8 @@ function Root(): ReactNode {
512
609
  const hash = options.scrollY === undefined ? new URL(target).hash : "";
513
610
  const requestScroll = scrollY === undefined ? undefined : () => setScrollRequest({ scrollY, hash });
514
611
  try {
515
- let nextNode = rscCache.get(target);
612
+ const replayed = replayedPageOf(target);
613
+ let nextNode = replayed;
516
614
  let notFound = false;
517
615
  let servedFromCache = !!nextNode;
518
616
  if (!nextNode) {
@@ -602,8 +700,6 @@ function Root(): ReactNode {
602
700
  nextNode = fetched.node;
603
701
  notFound = !!fetched.notFound;
604
702
  }
605
- } else {
606
- rememberRscCacheNode(rscCache, nextNode, MAX_RSC_CACHE_ENTRIES);
607
703
  }
608
704
  observeRscNavigationNode({
609
705
  cache: rscCache,
@@ -615,8 +711,9 @@ function Root(): ReactNode {
615
711
  });
616
712
 
617
713
  await nextNode.thenable;
714
+
618
715
  const committed = commitLatestRscNavigation({
619
- cache: notFound ? undefined : rscCache,
716
+ cache: notFound || replayed ? undefined : rscCache,
620
717
  href: target,
621
718
  thenable: nextNode,
622
719
  maxEntries: MAX_RSC_CACHE_ENTRIES,
@@ -663,7 +760,7 @@ window.addEventListener("popstate", (event) => {
663
760
  ?.catch((error: unknown) => hardNavigateAfterRscFailure(window.location.href, true, error));
664
761
  else {
665
762
 
666
- supersedeNavigation();
763
+ supersedeKeepingPage();
667
764
  if (scrollY !== undefined) scrollRestoration.scrollTo(scrollY);
668
765
  }
669
766
  window.setTimeout(() => {
@@ -0,0 +1,62 @@
1
+ import { mapFlightLineRows } from "./flightRowReader";
2
+
3
+ export interface ChunkNavigation {
4
+ navId: number;
5
+ href: string;
6
+ replace: () => boolean;
7
+ }
8
+
9
+ const chunkNavigations = new Map<string, ChunkNavigation>();
10
+ const quotedString = /"([^"\\]*)"/g;
11
+ const maxScriptRowBytes = 1024;
12
+ const rowDecoder = new TextDecoder();
13
+
14
+ export function recordChunksOf(
15
+ stream: ReadableStream<Uint8Array>,
16
+ navigation: ChunkNavigation,
17
+ ): ReadableStream<Uint8Array> {
18
+
19
+ const scriptRows = new Map<string, string>();
20
+ return mapFlightLineRows(stream, (row, tag) => {
21
+ if (tag !== "I" && (tag !== "" || row.byteLength > maxScriptRowBytes)) return row;
22
+ const text = rowDecoder.decode(row);
23
+ const colon = text.indexOf(":");
24
+ const value = text.slice(colon + 1 + tag.length).trimEnd();
25
+ if (tag === "") {
26
+ if (value.startsWith('"') && value.endsWith('.js"')) scriptRows.set(text.slice(0, colon), value.slice(1, -1));
27
+ return row;
28
+ }
29
+ for (const [, named] of value.matchAll(quotedString)) {
30
+ const chunkId = (named.startsWith("$") ? scriptRows.get(named.slice(1)) : undefined) ?? named;
31
+ if (chunkId.endsWith(".js")) chunkNavigations.set(chunkId, navigation);
32
+ }
33
+ return row;
34
+ });
35
+ }
36
+
37
+ export const navigationOfChunk = (chunkId: string): ChunkNavigation | undefined => chunkNavigations.get(chunkId);
38
+
39
+ const linkFailure =
40
+ /does not provide an export named|doesn't provide an export named|import not found|Importing binding name|Failed to resolve module specifier|was a bare specifier|does not resolve to a valid URL/;
41
+ export const isLinkFailure = (error: unknown): boolean =>
42
+ (error instanceof SyntaxError || error instanceof TypeError) && linkFailure.test(error.message);
43
+
44
+ const chunkReloadsKey = "akan.rsc.chunkReloads";
45
+ export function claimChunkReload(chunkId: string): boolean {
46
+ try {
47
+ const reloaded = JSON.parse(sessionStorage.getItem(chunkReloadsKey) ?? "[]") as string[];
48
+ if (reloaded.includes(chunkId)) return false;
49
+ sessionStorage.setItem(chunkReloadsKey, JSON.stringify([...reloaded, chunkId].slice(-32)));
50
+ return true;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ export const isBuildBundle = (): boolean => {
57
+ try {
58
+ return process.env.AKAN_BUNDLE_COMMAND === "build";
59
+ } catch {
60
+ return false;
61
+ }
62
+ };
@@ -5,6 +5,7 @@ import {
5
5
  type AkanRouterStateV1,
6
6
  type AkanRscPatchMetadata,
7
7
  appendAkanRouterStateRequestHeaders,
8
+ isAkanRscPartialCommitEnabled,
8
9
  readAkanRscPatchMetadataResponseHeaders,
9
10
  } from "./routeState";
10
11
 
@@ -21,6 +22,9 @@ const rscEndpointOf = (href: string, buildId?: number) => {
21
22
  return endpoint;
22
23
  };
23
24
 
25
+ const sentRouterStateOf = (state: AkanRouterStateV1 | null) =>
26
+ state?.headKey && !isAkanRscPartialCommitEnabled() ? { ...state, headKey: undefined } : state;
27
+
24
28
  const rscRequestHeaders = () => {
25
29
  const headers = new Headers({ Accept: "text/x-component", "Cache-Control": "no-cache" });
26
30
  const importMapKey = (globalThis as { __AKAN_IMPORT_MAP_KEY__?: string }).__AKAN_IMPORT_MAP_KEY__;
@@ -62,7 +66,8 @@ export async function fetchRscNavigationResponse(
62
66
  ): Promise<RscClientFetchResponseResult> {
63
67
  const shouldApplyNavigation = options.shouldApplyNavigation ?? (() => true);
64
68
  const headers = rscRequestHeaders();
65
- if (options.sendRouterState !== false) appendAkanRouterStateRequestHeaders(headers, options.currentRouterState);
69
+ if (options.sendRouterState !== false)
70
+ appendAkanRouterStateRequestHeaders(headers, sentRouterStateOf(options.currentRouterState));
66
71
  const response =
67
72
  options.prefetched ??
68
73
  (await fetchKeepingHeaders(
@@ -1,31 +1,17 @@
1
- import type { AkanHeadSnapshotNode, AkanHeadSnapshotV1 } from "./routeState";
1
+ import { hasRscRouteHead, type RscRoutePatch, readRscRoutePatch, writeRscRoutePatch } from "../client/rscRoutePatch";
2
+ import type { AkanHeadSnapshotV1 } from "./routeState";
2
3
  import type { AkanSegmentPatchFailureReason } from "./rscNavigationState";
3
4
 
4
- const AKAN_ROUTE_HEAD_SELECTOR = '[data-akan-head="route"]';
5
-
6
5
  export interface PreparedAkanHeadSnapshotPatch {
7
- existing: HTMLElement[];
8
- replacement: HTMLElement[];
9
- }
10
-
11
- function createHeadElement(node: AkanHeadSnapshotNode, index: number): HTMLElement {
12
- const element = document.createElement(node.tag);
13
- element.setAttribute("data-akan-head", "route");
14
- element.setAttribute("data-akan-head-key", `${node.tag}:${index}`);
15
- for (const [key, value] of Object.entries(node.attrs ?? {})) {
16
- element.setAttribute(key, value);
17
- }
18
- if (node.tag === "title") element.textContent = node.text ?? "";
19
- return element;
6
+ previous: RscRoutePatch | null;
7
+ next: RscRoutePatch;
20
8
  }
21
9
 
22
10
  export function getAkanHeadSnapshotPatchFailureReason(
23
11
  snapshot: AkanHeadSnapshotV1,
24
12
  ): Extract<AkanSegmentPatchFailureReason, "head-missing" | "head-invalid"> | null {
25
- if (typeof document === "undefined" || !document.head) return "head-invalid";
26
- const existing = document.head.querySelector(AKAN_ROUTE_HEAD_SELECTOR);
27
- if (!existing) return "head-missing";
28
13
  if (!Array.isArray(snapshot.nodes)) return "head-invalid";
14
+ if (!hasRscRouteHead()) return "head-missing";
29
15
  return null;
30
16
  }
31
17
 
@@ -33,50 +19,25 @@ export function canApplyAkanHeadSnapshotPatch(snapshot: AkanHeadSnapshotV1): boo
33
19
  return getAkanHeadSnapshotPatchFailureReason(snapshot) === null;
34
20
  }
35
21
 
36
- export function prepareAkanHeadSnapshotPatch(snapshot: AkanHeadSnapshotV1): PreparedAkanHeadSnapshotPatch | null {
37
- try {
38
- if (getAkanHeadSnapshotPatchFailureReason(snapshot)) return null;
39
- const existing = [...document.head.querySelectorAll<HTMLElement>(AKAN_ROUTE_HEAD_SELECTOR)];
40
- if (!existing[0]) return null;
41
- return {
42
- existing,
43
- replacement: snapshot.nodes.map((node, index) => createHeadElement(node, index)),
44
- };
45
- } catch {
46
- return null;
47
- }
22
+ export function prepareAkanHeadSnapshotPatch(
23
+ snapshot: AkanHeadSnapshotV1,
24
+ href: string,
25
+ ): PreparedAkanHeadSnapshotPatch | null {
26
+ if (getAkanHeadSnapshotPatchFailureReason(snapshot)) return null;
27
+ return { previous: readRscRoutePatch(), next: { href, head: snapshot } };
48
28
  }
49
29
 
50
30
  export function commitPreparedAkanHeadSnapshotPatch(prepared: PreparedAkanHeadSnapshotPatch): boolean {
51
- try {
52
-
53
- const inHead = prepared.existing.filter((node) => node.parentNode === document.head);
54
- const anchor = inHead[0];
55
- if (!anchor) return false;
56
- const fragment = document.createDocumentFragment();
57
- for (const node of prepared.replacement) fragment.appendChild(node);
58
- document.head.insertBefore(fragment, anchor);
59
- for (const node of inHead) node.remove();
60
- return true;
61
- } catch {
62
- return false;
63
- }
31
+ if (!hasRscRouteHead()) return false;
32
+ writeRscRoutePatch(prepared.next);
33
+ return true;
64
34
  }
65
35
 
66
36
  export function rollbackPreparedAkanHeadSnapshotPatch(prepared: PreparedAkanHeadSnapshotPatch): void {
67
- try {
68
- const anchor = prepared.replacement.find((node) => node.parentNode === document.head) ?? null;
69
- if (anchor) {
70
- const fragment = document.createDocumentFragment();
71
- for (const node of prepared.existing) if (!node.parentNode) fragment.appendChild(node);
72
- document.head.insertBefore(fragment, anchor);
73
- }
74
- for (const node of prepared.replacement) if (node.parentNode === document.head) node.remove();
75
- } catch {
76
- }
37
+ writeRscRoutePatch(prepared.previous);
77
38
  }
78
39
 
79
- export function applyAkanHeadSnapshotPatch(snapshot: AkanHeadSnapshotV1): boolean {
80
- const prepared = prepareAkanHeadSnapshotPatch(snapshot);
40
+ export function applyAkanHeadSnapshotPatch(snapshot: AkanHeadSnapshotV1, href: string): boolean {
41
+ const prepared = prepareAkanHeadSnapshotPatch(snapshot, href);
81
42
  return prepared ? commitPreparedAkanHeadSnapshotPatch(prepared) : false;
82
43
  }
@@ -0,0 +1,23 @@
1
+ interface ParkedRedirect<Node> {
2
+ node: Node;
3
+ location: string;
4
+ replace: boolean;
5
+ }
6
+
7
+ export class RscParkedRedirect<Node> {
8
+ #parked: ParkedRedirect<Node> | null = null;
9
+
10
+ park(redirect: ParkedRedirect<Node>): void {
11
+ this.#parked = redirect;
12
+ }
13
+
14
+ clear(): void {
15
+ this.#parked = null;
16
+ }
17
+
18
+ resume(stillShown: (node: Node) => boolean, navigate: (location: string, replace: boolean) => void): void {
19
+ const parked = this.#parked;
20
+ this.#parked = null;
21
+ if (parked && stillShown(parked.node)) navigate(parked.location, parked.replace);
22
+ }
23
+ }