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
@@ -50,30 +50,17 @@ import {
50
50
  shouldStoreRouteCache,
51
51
  } from "./cachePolicy";
52
52
  import { FallbackHead } from "./fallbackHead";
53
- import {
54
- createAkanLocaleAlternateHeadSnapshot,
55
- mergeAkanHeadSnapshots,
56
- renderAkanHeadSnapshot,
57
- resolveHeadResult,
58
- } from "./head";
53
+ import { resolveHeadResult } from "./head";
59
54
  import { LogForwarder } from "./logging/logForwarder";
60
55
  import { ProcessMetricsCollector } from "./processMetricsCollector";
61
- import { RouteElementComposer, type RouteNotFoundInPlace } from "./routeElementComposer";
56
+ import { type AdmittedNotFoundFallback, RouteElementComposer, type RouteNotFoundInPlace } from "./routeElementComposer";
62
57
  import { RouteShellGate } from "./routeShellGate";
63
- import {
64
- type AkanRscPatchDecision,
65
- createAkanRouterState,
66
- encodeAkanHeadSnapshot,
67
- encodeAkanRouterState,
68
- encodeAkanRscPatchSegmentPath,
69
- isAkanRscPartialCommitEnabled,
70
- readAkanRouterStateRequest,
71
- resolveAkanRscPartialDecision,
72
- resolveAkanRscPatchDecision,
73
- } from "./routeState";
58
+ import { encodeAkanRouterState, isAkanRscPartialCommitEnabled } from "./routeState";
74
59
  import { type PagesContext, RouteTreeBuilder } from "./routeTreeBuilder";
75
60
  import { concatBytes, encodeAkanRedirectDigest } from "./rscHttp";
76
61
  import { RscPagePrompts } from "./rscPagePrompts";
62
+ import { type ResolvedRouteHead, type RouteHeadSnapshots, RscPatchPlanner } from "./rscPatchPlanner";
63
+ import { AkanRouteHeadReference } from "./rscSegmentOutletReference";
77
64
  import {
78
65
  type CachedRscResult,
79
66
  createCachedRscPatchMetadata,
@@ -81,8 +68,8 @@ import {
81
68
  invalidateCachedRscResults,
82
69
  isCachedRscPatchMetadataCompatible,
83
70
  replayCachedRscResult,
84
- resolveAkanRscHeadSafePatchDecision,
85
71
  resolveRscWorkerPatchCacheEntry,
72
+ rscWorkerTraceBaseOf,
86
73
  shouldCollectRscWorkerRenderChunks,
87
74
  shouldStoreRscWorkerPatchResult,
88
75
  shouldUseRscWorkerFullResultCache,
@@ -111,6 +98,7 @@ interface RenderMsg {
111
98
  method?: string;
112
99
  headers?: Record<string, string>;
113
100
  clientManifest?: ClientManifest;
101
+ prefetch?: boolean;
114
102
  }
115
103
  interface CancelMsg {
116
104
  type: "cancel";
@@ -185,12 +173,6 @@ interface FlightRenderResult {
185
173
  /** Well above any sensible TTL: this reclaims a cache nobody is reading, not tracks expiry closely. */
186
174
  const RESULT_CACHE_SWEEP_INTERVAL_MS = 60_000;
187
175
 
188
- function hashRscTraceCacheKey(cacheKey: string): string {
189
- let hash = 5381;
190
- for (let index = 0; index < cacheKey.length; index += 1) hash = (hash * 33) ^ cacheKey.charCodeAt(index);
191
- return (hash >>> 0).toString(36);
192
- }
193
-
194
176
  interface RscRendererStats {
195
177
  renderCount: number;
196
178
  inFlightRenderCount: number;
@@ -281,6 +263,14 @@ export class RscRenderer {
281
263
  run: (request, routeId, fn) => this.#runWithRequest(request, routeId, fn),
282
264
  defaultLocale: () => this.#i18n.defaultLocale,
283
265
  });
266
+ readonly #patchPlanner = new RscPatchPlanner({
267
+ logger: this.#logger,
268
+ routes: () => this.#pathRoutes,
269
+ buildId: () => this.#pagesBundleBuildId,
270
+ basePathOf: (url) => this.#getBasePath(url),
271
+ localeAlternatesOf: (url) => this.#getLocaleAlternateLanguages(url),
272
+ defaultHead: () => this.#renderDefaultHead(),
273
+ });
284
274
 
285
275
  constructor() {
286
276
  if (typeof process.send !== "function") {
@@ -507,74 +497,40 @@ export class RscRenderer {
507
497
  );
508
498
  else this.#logger.verbose(`render[${requestId}] no route matched pathname=${urlObj.pathname} — rendering 404`);
509
499
  const beforeLoadedKeys = RouteTreeBuilder.getCacheStats().loadedModuleKeys;
500
+ const searchParams = parseSearchParams(urlObj.search);
501
+ const fallbackMatch = match ? null : RouteTreeBuilder.matchFallback(urlObj.pathname, this.#fallbackRoutes);
502
+ const notFoundFallback = await RouteElementComposer.admitNotFoundFallback(fallbackMatch, searchParams);
503
+ const verdict =
504
+ msg.prefetch && (await RouteElementComposer.prefetchVerdict(match, notFoundFallback, searchParams));
505
+ if (verdict === "refused") {
506
+ this.#send({ type: "meta", requestId, status: 204 });
507
+ this.#send({ type: "end", requestId });
508
+ return;
509
+ }
510
+ const admitted = verdict === "admitted";
510
511
  const cacheDecision = match ? this.#getResultCacheEntry(request, urlObj) : { entry: null };
511
512
  const cacheEntry = cacheDecision.entry;
512
- const targetRouterState = match
513
- ? createAkanRouterState({
514
- pathRoute: match.pathRoute,
515
- href: urlObj.href,
516
- buildId: this.#pagesBundleBuildId,
517
- })
518
- : null;
519
- const searchParams = parseSearchParams(urlObj.search);
520
- const currentRouterState = readAkanRouterStateRequest(request.headers);
521
- const partialDecision = targetRouterState
522
- ? resolveAkanRscPartialDecision({
523
- currentState: currentRouterState.state,
524
- currentRoute: currentRouterState.currentRoute,
525
- targetState: targetRouterState,
526
- })
527
- : { status: "full" as const, reason: "missing-route", commonPrefixLength: 0 };
528
- const patchDecision: AkanRscPatchDecision =
529
- targetRouterState && match
530
- ? resolveAkanRscPatchDecision({
531
- currentState: currentRouterState.state,
532
- targetState: targetRouterState,
533
- partialDecision,
534
- })
535
- : { status: "full" as const, reason: partialDecision.reason, commonPrefixLength: 0 };
536
-
537
- let admitted = false;
538
- const safePatchDecision = match
539
- ? await this.#resolveHeadSafePatchDecision(match.pathRoute, patchDecision, async () => {
540
- await RouteElementComposer.admit({ pathRoute: match.pathRoute, params: match.params, searchParams });
541
- admitted = true;
542
- return await this.#resolveRouteHeadSnapshot(urlObj, match, searchParams);
543
- })
544
- : patchDecision;
513
+ const {
514
+ targetRouterState,
515
+ currentRouterState,
516
+ decision: safePatchDecision,
517
+ admittedHead,
518
+ } = await this.#patchPlanner.plan({ request, url: urlObj, match, searchParams, admitted });
545
519
  const patchCacheEntry = resolveRscWorkerPatchCacheEntry({
546
520
  cacheEntry,
547
521
  targetRouterState,
548
522
  safePatchDecision,
549
523
  partialCommitEnabled: isAkanRscPartialCommitEnabled(),
550
524
  });
551
- const createTraceBase = (
552
- decision: AkanRscPatchDecision,
553
- cacheKey = cacheEntry?.key,
554
- routeState = targetRouterState,
555
- ) => ({
525
+ const createTraceBase = rscWorkerTraceBaseOf({
556
526
  navId: requestId,
557
527
  pathname: urlObj.pathname,
558
528
  routeId,
559
- partial: decision.status,
560
- partialReason: decision.reason ?? currentRouterState.reason,
561
- partialCommonPrefixLength: decision.commonPrefixLength,
562
- ...(decision.patch
563
- ? {
564
- patchStartIndex: decision.patch.patchStartIndex,
565
- patchSegmentPath: encodeAkanRscPatchSegmentPath(decision.patch.segmentPath),
566
- patchStartSegment: decision.patch.patchStartSegmentKey,
567
- patchHeadSafe: decision.patch.headSafe,
568
- patchHeadSnapshot: decision.patch.headSnapshot
569
- ? (encodeAkanHeadSnapshot(decision.patch.headSnapshot) ?? undefined)
570
- : undefined,
571
- }
572
- : {}),
573
- ...(routeState ? { routeState: encodeAkanRouterState(routeState) } : {}),
574
- ...(cacheKey ? { cacheKeyHash: hashRscTraceCacheKey(cacheKey) } : {}),
575
- ...(cacheDecision.reason ? { cacheReason: cacheDecision.reason } : {}),
529
+ routerStateReason: currentRouterState.reason,
530
+ cacheKey: cacheEntry?.key,
531
+ cacheReason: cacheDecision.reason,
532
+ routeState: targetRouterState,
576
533
  });
577
- const traceBase = createTraceBase(safePatchDecision, patchCacheEntry?.key ?? cacheEntry?.key);
578
534
  const cachedPatch = patchCacheEntry ? this.#getCached(this.#patchResultCache, patchCacheEntry.key) : null;
579
535
  if (
580
536
  cachedPatch?.patch &&
@@ -592,7 +548,7 @@ export class RscRenderer {
592
548
  const cachedTraceBase = createTraceBase(
593
549
  cachedPatchDecision,
594
550
  patchCacheEntry.key,
595
- cachedPatch.patch.targetRouterState,
551
+ RscPatchPlanner.routeStateWith(cachedPatch.patch.targetRouterState, admittedHead?.snapshots?.layoutsKey),
596
552
  );
597
553
  await this.#replayCached(requestId, routeId, startedAt, cachedPatch, {
598
554
  ...cachedTraceBase,
@@ -607,6 +563,11 @@ export class RscRenderer {
607
563
  ? this.#getCached(this.#resultCache, cacheEntry.key)
608
564
  : null;
609
565
  if (cached) {
566
+ const traceBase = createTraceBase(
567
+ safePatchDecision,
568
+ patchCacheEntry?.key ?? cacheEntry?.key,
569
+ RscPatchPlanner.routeStateWith(targetRouterState, cached.routeHeadKey),
570
+ );
610
571
  await this.#replayCached(requestId, routeId, startedAt, cached, {
611
572
  ...traceBase,
612
573
  cache: "hit",
@@ -623,6 +584,7 @@ export class RscRenderer {
623
584
  return;
624
585
  }
625
586
  let element: ReactNode;
587
+ let routeHead: ResolvedRouteHead | undefined;
626
588
  let effectivePatchDecision = safePatchDecision;
627
589
  const notFoundProbe = { hit: false };
628
590
  const notFound = this.#notFoundInPlace(urlObj, notFoundProbe);
@@ -634,7 +596,7 @@ export class RscRenderer {
634
596
  safePatchDecision.patch.patchStartIndex,
635
597
  searchParams,
636
598
  notFound,
637
- { guarded: admitted },
599
+ { guarded: admitted || !!admittedHead },
638
600
  );
639
601
  if (suffixElement === null) {
640
602
  effectivePatchDecision = {
@@ -642,11 +604,23 @@ export class RscRenderer {
642
604
  reason: "suffix-compose-fallback",
643
605
  commonPrefixLength: safePatchDecision.commonPrefixLength,
644
606
  };
645
- element = await this.#renderMatched(urlObj, match, searchParams, notFound, { guarded: true, gate });
646
- } else element = suffixElement;
607
+ ({ element, head: routeHead } = await this.#renderMatched(urlObj, match, searchParams, notFound, {
608
+ guarded: true,
609
+ head: admittedHead,
610
+ gate,
611
+ }));
612
+ } else {
613
+ element = suffixElement;
614
+ routeHead = admittedHead;
615
+ }
647
616
  } else if (match)
648
- element = await this.#renderMatched(urlObj, match, searchParams, notFound, { guarded: admitted, gate });
649
- else element = await this.#renderNotFound(urlObj, gate);
617
+ ({ element, head: routeHead } = await this.#renderMatched(urlObj, match, searchParams, notFound, {
618
+ guarded: admitted || !!admittedHead,
619
+ head: admittedHead,
620
+ gate,
621
+ }));
622
+ else element = await this.#renderNotFound(urlObj, notFoundFallback, gate);
623
+ const routeHeadKey = routeHead?.snapshots?.layoutsKey;
650
624
  const traceCacheKey =
651
625
  effectivePatchDecision.status === "patch" ? (patchCacheEntry?.key ?? cacheEntry?.key) : cacheEntry?.key;
652
626
  const ssrBlocking = getRequestFrameState<PageState>()?.ssr === "block";
@@ -655,6 +629,11 @@ export class RscRenderer {
655
629
  cache: cacheEntry ? "miss" : "bypass",
656
630
  ssrBlocking,
657
631
  };
632
+
633
+ const renderedRouteState = RscPatchPlanner.routeStateWith(targetRouterState, routeHeadKey);
634
+ const renderedTrace = renderedRouteState
635
+ ? { ...trace, routeState: encodeAkanRouterState(renderedRouteState) }
636
+ : trace;
658
637
  this.#logger.verbose(`render[${requestId}] starting Flight stream`);
659
638
  const result = await this.#renderFlightElement(element, msg.clientManifest ?? this.#clientManifest, {
660
639
  requestId,
@@ -664,7 +643,7 @@ export class RscRenderer {
664
643
  patchCacheEntry,
665
644
  }),
666
645
  status: match ? undefined : 404,
667
- trace,
646
+ trace: renderedTrace,
668
647
  notFoundProbe,
669
648
  gate,
670
649
  onComplete: ({ chunks, bytes, chunksCount, control, lateControlSent }) => {
@@ -685,6 +664,7 @@ export class RscRenderer {
685
664
  theme: getRequestTheme(),
686
665
  ssrBlocking,
687
666
  cacheState,
667
+ routeHeadKey,
688
668
  });
689
669
  if (
690
670
  shouldStoreRscWorkerPatchResult({
@@ -921,7 +901,7 @@ export class RscRenderer {
921
901
  controlRef.current = { type: "not-found" };
922
902
  return error.digest;
923
903
  }
924
- controlRef.current = { type: "error", error };
904
+ if (!RouteElementComposer.streamed(error)) controlRef.current = { type: "error", error };
925
905
  return this.#reportRenderError(error, options.trace?.pathname);
926
906
  },
927
907
  });
@@ -1219,26 +1199,6 @@ export class RscRenderer {
1219
1199
  this.#send({ type: "not-found", requestId });
1220
1200
  }
1221
1201
 
1222
- async #resolveHeadSafePatchDecision(
1223
- pathRoute: PathRoute,
1224
- patchDecision: AkanRscPatchDecision,
1225
- resolveHeadSnapshot: () => Promise<ResolvedHead["headSnapshot"]>,
1226
- ): Promise<AkanRscPatchDecision> {
1227
- if (patchDecision.status !== "patch" || !patchDecision.patch) {
1228
- return patchDecision;
1229
- }
1230
- if (!isAkanRscPartialCommitEnabled()) {
1231
- return { status: "full", reason: "guard-disabled", commonPrefixLength: patchDecision.commonPrefixLength };
1232
- }
1233
- const pageConfig = await pathRoute.renderPage.getPageConfig?.();
1234
- return resolveAkanRscHeadSafePatchDecision({
1235
- partialCommitEnabled: true,
1236
- patchDecision,
1237
- pageConfig,
1238
- headSnapshot: pageConfig?.rscPatchHeadSafe === true ? await resolveHeadSnapshot() : undefined,
1239
- });
1240
- }
1241
-
1242
1202
  #recordRouteStats(routeId: string, flightBytes: number, durationMs: number): void {
1243
1203
  const current = this.#routeStats.get(routeId) ?? { routeId, count: 0, flightBytes: 0, totalDurationMs: 0 };
1244
1204
  current.count += 1;
@@ -1407,8 +1367,8 @@ export class RscRenderer {
1407
1367
  match: { pathRoute: PathRoute; params: Record<string, string> },
1408
1368
  searchParams: Record<string, string | string[]>,
1409
1369
  notFound: RouteNotFoundInPlace,
1410
- { guarded = false, gate }: { guarded?: boolean; gate?: RouteShellGate } = {},
1411
- ): Promise<ReactNode> {
1370
+ { guarded = false, head, gate }: { guarded?: boolean; head?: ResolvedRouteHead; gate?: RouteShellGate } = {},
1371
+ ): Promise<{ element: ReactNode; head: ResolvedRouteHead }> {
1412
1372
  this.#logger.verbose(
1413
1373
  `composing route element pathname=${url.pathname} search=${url.search || "(none)"} params=${JSON.stringify(match.params)}`,
1414
1374
  );
@@ -1426,11 +1386,7 @@ export class RscRenderer {
1426
1386
 
1427
1387
  const themeColorTheme = untrackedCookies().get("theme")?.value ?? rootTheme;
1428
1388
  const manifestLink = await this.#renderManifestLink(url, rootLayouts);
1429
- const routeHead = await RouteElementComposer.resolveHeadWithSnapshot({
1430
- pathRoute,
1431
- params: match.params,
1432
- searchParams,
1433
- });
1389
+ const routeHead = head ?? (await this.#patchPlanner.resolveHead(url, pathRoute, match.params, searchParams));
1434
1390
  const fallbackHead = new FallbackHead();
1435
1391
  const body = RouteElementComposer.compose({
1436
1392
  pathRoute,
@@ -1441,7 +1397,12 @@ export class RscRenderer {
1441
1397
  gate,
1442
1398
  });
1443
1399
  const renderHead = async (tags: ReactNode[] | null) => {
1444
- if (!tags) return this.#renderHeadTags(url, { manifestLink, routeHead });
1400
+ if (!tags)
1401
+ return this.#renderHeadTags(url, {
1402
+ manifestLink,
1403
+ routeHead: routeHead.layers.head,
1404
+ snapshots: routeHead.snapshots,
1405
+ });
1445
1406
  const layoutsHead = await RscRenderer.#resolveFallbackHead({
1446
1407
  kind: "not-found",
1447
1408
  route: pathRoute,
@@ -1451,7 +1412,7 @@ export class RscRenderer {
1451
1412
  return this.#renderHeadTags(url, { manifestLink, routeHead: layoutsHead, noindex: true, tags });
1452
1413
  };
1453
1414
 
1454
- return (
1415
+ const element = (
1455
1416
  <html lang={match.params.lang ?? this.#i18n.defaultLocale} suppressHydrationWarning>
1456
1417
  <head key="head">
1457
1418
  <meta key="charset" charSet="utf-8" />
@@ -1470,6 +1431,7 @@ export class RscRenderer {
1470
1431
  </body>
1471
1432
  </html>
1472
1433
  );
1434
+ return { element, head: routeHead };
1473
1435
  }
1474
1436
 
1475
1437
  async #renderMatchedSuffix(
@@ -1500,19 +1462,18 @@ export class RscRenderer {
1500
1462
  });
1501
1463
  }
1502
1464
 
1503
- async #renderNotFound(url: URL, gate?: RouteShellGate): Promise<ReactNode> {
1504
- const matchedFallback = RouteTreeBuilder.matchFallback(url.pathname, this.#fallbackRoutes);
1505
- if (matchedFallback) {
1506
- const searchParams = parseSearchParams(url.search);
1507
- const route = await RouteElementComposer.admittedFallbackOf(matchedFallback.fallbackRoute, {
1508
- params: matchedFallback.params,
1509
- searchParams,
1510
- });
1465
+ async #renderNotFound(
1466
+ url: URL,
1467
+ notFoundFallback: AdmittedNotFoundFallback | null,
1468
+ gate?: RouteShellGate,
1469
+ ): Promise<ReactNode> {
1470
+ if (notFoundFallback) {
1471
+ const { route, params, searchParams } = notFoundFallback;
1511
1472
  try {
1512
1473
  const fallback = await this.#renderFallbackDocument({
1513
1474
  kind: "not-found",
1514
1475
  route,
1515
- params: matchedFallback.params,
1476
+ params,
1516
1477
  searchParams,
1517
1478
  pathname: url.pathname,
1518
1479
  url,
@@ -1591,18 +1552,33 @@ export class RscRenderer {
1591
1552
  {
1592
1553
  manifestLink,
1593
1554
  routeHead,
1555
+ snapshots,
1594
1556
  noindex = false,
1595
1557
  tags = null,
1596
- }: { manifestLink: ReactNode; routeHead: ResolvedHead; noindex?: boolean; tags?: ReactNode[] | null },
1558
+ }: {
1559
+ manifestLink: ReactNode;
1560
+ routeHead: ResolvedHead;
1561
+ snapshots?: RouteHeadSnapshots;
1562
+ noindex?: boolean;
1563
+ tags?: ReactNode[] | null;
1564
+ },
1597
1565
  ): ReactNode {
1598
- const routeHeadSnapshot = this.#createRouteHeadSnapshot(url, routeHead);
1599
- const head = routeHeadSnapshot
1600
- ? renderAkanHeadSnapshot(routeHeadSnapshot)
1601
- : (routeHead.node ?? this.#renderDefaultHead());
1566
+ if (snapshots) {
1567
+ const ownsManifest = [...snapshots.layouts.nodes, ...snapshots.page.nodes].some(
1568
+ (node) => RouteHead.keyOf(node.tag, node.attrs ?? {}) === "link:manifest",
1569
+ );
1570
+ return (
1571
+ <>
1572
+ {ownsManifest ? null : manifestLink}
1573
+ <AkanRouteHeadReference layouts={snapshots.layouts} page={snapshots.page} />
1574
+ </>
1575
+ );
1576
+ }
1577
+ const head = routeHead.node ?? this.#renderDefaultHead();
1602
1578
  return (
1603
1579
  <>
1604
1580
  {RouteHead.mergeNodes([manifestLink, head, noindex ? RouteHead.noindexOver(head) : null, tags])}
1605
- {routeHeadSnapshot ? null : this.#renderLocaleAlternates(url)}
1581
+ {this.#renderLocaleAlternates(url)}
1606
1582
  </>
1607
1583
  );
1608
1584
  }
@@ -1619,27 +1595,6 @@ export class RscRenderer {
1619
1595
  });
1620
1596
  }
1621
1597
 
1622
- async #resolveRouteHeadSnapshot(
1623
- url: URL,
1624
- match: { pathRoute: PathRoute; params: Record<string, string> },
1625
- searchParams: Record<string, string | string[]>,
1626
- ): Promise<ResolvedHead["headSnapshot"]> {
1627
- const routeHead = await RouteElementComposer.resolveHeadWithSnapshot({
1628
- pathRoute: match.pathRoute,
1629
- params: match.params,
1630
- searchParams,
1631
- });
1632
- return this.#createRouteHeadSnapshot(url, routeHead);
1633
- }
1634
-
1635
- #createRouteHeadSnapshot(url: URL, routeHead: ResolvedHead): ResolvedHead["headSnapshot"] {
1636
- if (!routeHead.headSnapshot) return undefined;
1637
- return mergeAkanHeadSnapshots(
1638
- routeHead.headSnapshot,
1639
- createAkanLocaleAlternateHeadSnapshot(this.#getLocaleAlternateLanguages(url)),
1640
- );
1641
- }
1642
-
1643
1598
  #getLocaleAlternateLanguages(url: URL): Record<string, string> {
1644
1599
  const languages: Record<string, string> = {};
1645
1600
  const publicUrl = RscRenderer.#getPublicRequestUrl(url);
@@ -13,6 +13,8 @@ import {
13
13
  type AkanRscPatchDecision,
14
14
  type AkanRscPatchMetadata,
15
15
  encodeAkanHeadSnapshot,
16
+ encodeAkanRouterState,
17
+ encodeAkanRscPatchSegmentPath,
16
18
  isAkanHeadSnapshotV1,
17
19
  } from "./routeState";
18
20
  import type { RscTraceMetadata } from "./ssrTypes";
@@ -29,6 +31,8 @@ export interface CachedRscResult {
29
31
  ssrBlocking?: boolean;
30
32
  cacheState: RouteCacheRenderState;
31
33
  patch?: CachedRscPatchMetadata;
34
+ /** Key of the layouts' head the page renders in its route head, named in the router state a replay sends. */
35
+ routeHeadKey?: string;
32
36
  }
33
37
 
34
38
  export interface CachedRscPatchMetadata {
@@ -42,6 +46,47 @@ export interface RscPatchCacheKeyInput {
42
46
  patch: AkanRscPatchMetadata;
43
47
  }
44
48
 
49
+ export interface RscWorkerTraceContext {
50
+ navId: string;
51
+ pathname: string;
52
+ routeId: string;
53
+ routerStateReason?: string;
54
+ cacheKey?: string;
55
+ cacheReason?: string;
56
+ routeState: AkanRouterStateV1 | null;
57
+ }
58
+
59
+ function hashRscTraceCacheKey(cacheKey: string): string {
60
+ let hash = 5381;
61
+ for (let index = 0; index < cacheKey.length; index += 1) hash = (hash * 33) ^ cacheKey.charCodeAt(index);
62
+ return (hash >>> 0).toString(36);
63
+ }
64
+
65
+ export function rscWorkerTraceBaseOf(context: RscWorkerTraceContext) {
66
+ return (decision: AkanRscPatchDecision, cacheKey = context.cacheKey, routeState = context.routeState) => ({
67
+ navId: context.navId,
68
+ pathname: context.pathname,
69
+ routeId: context.routeId,
70
+ partial: decision.status,
71
+ partialReason: decision.reason ?? context.routerStateReason,
72
+ partialCommonPrefixLength: decision.commonPrefixLength,
73
+ ...(decision.patch
74
+ ? {
75
+ patchStartIndex: decision.patch.patchStartIndex,
76
+ patchSegmentPath: encodeAkanRscPatchSegmentPath(decision.patch.segmentPath),
77
+ patchStartSegment: decision.patch.patchStartSegmentKey,
78
+ patchHeadSafe: decision.patch.headSafe,
79
+ patchHeadSnapshot: decision.patch.headSnapshot
80
+ ? (encodeAkanHeadSnapshot(decision.patch.headSnapshot) ?? undefined)
81
+ : undefined,
82
+ }
83
+ : {}),
84
+ ...(routeState ? { routeState: encodeAkanRouterState(routeState) } : {}),
85
+ ...(cacheKey ? { cacheKeyHash: hashRscTraceCacheKey(cacheKey) } : {}),
86
+ ...(context.cacheReason ? { cacheReason: context.cacheReason } : {}),
87
+ });
88
+ }
89
+
45
90
  export function createRscPatchCacheEntry({ baseEntry, targetRouterState, patch }: RscPatchCacheKeyInput) {
46
91
  const key = [
47
92
  "patch-v1",
@@ -226,16 +271,27 @@ export function resolveAkanRscHeadSafePatchDecision({
226
271
  partialCommitEnabled,
227
272
  patchDecision,
228
273
  pageConfig,
274
+ routeHeadMounted = true,
275
+ frameChange,
229
276
  headSnapshot,
277
+ layoutsHeadChanged = false,
230
278
  }: {
231
279
  partialCommitEnabled: boolean;
232
280
  patchDecision: AkanRscPatchDecision;
233
281
  pageConfig?: PageConfig;
282
+ /** Whether the page the patch leaves from shows its head through `AkanRouteHead`, the only head a patch can swap. */
283
+ routeHeadMounted?: boolean;
284
+ frameChange?: "params-changed" | "layouts-changed" | "page-state-changed" | "frame-unknown";
234
285
  headSnapshot?: AkanHeadSnapshotV1;
286
+ /** Whether the target's layouts head differs from the one the page left from shows, which a patch would keep. */
287
+ layoutsHeadChanged?: boolean;
235
288
  }): AkanRscPatchDecision {
236
289
  if (!partialCommitEnabled || patchDecision.status !== "patch" || !patchDecision.patch) return patchDecision;
237
290
  if (pageConfig?.rscPatchHeadSafe !== true) return fullDecision("head-unsafe", patchDecision);
291
+ if (!routeHeadMounted) return fullDecision("head-unmounted", patchDecision);
292
+ if (frameChange) return fullDecision(frameChange, patchDecision);
238
293
  if (!headSnapshot) return fullDecision("head-missing", patchDecision);
294
+ if (layoutsHeadChanged) return fullDecision("layouts-head-changed", patchDecision);
239
295
  if (!isAkanHeadSnapshotV1(headSnapshot)) return fullDecision("head-invalid", patchDecision);
240
296
  if (!encodeAkanHeadSnapshot(headSnapshot)) return fullDecision("head-too-large", patchDecision);
241
297
  return { ...patchDecision, patch: { ...patchDecision.patch, headSafe: true, headSnapshot } };
@@ -14,7 +14,7 @@ import type { ClientManifest } from "./artifact";
14
14
  import type { RouteCacheInvalidation, RouteCacheRenderState } from "./cachePolicy";
15
15
  import { ChildOutputReader } from "./logging/childOutputReader";
16
16
  import { MemoryLimit } from "./memoryLimit";
17
- import type { RscTraceMetadata, SsrLateControl } from "./ssrTypes";
17
+ import type { RscRenderOptions, RscTraceMetadata, SsrLateControl } from "./ssrTypes";
18
18
  import type { BaseBuildArtifact, CssAsset } from "./types";
19
19
 
20
20
  const DEFAULT_RSC_HOST_MAX_PENDING_CHUNKS = 256;
@@ -465,15 +465,12 @@ export class RscWorker {
465
465
  this.#proc = this.#spawn();
466
466
  }
467
467
 
468
- renderWithMeta(
469
- req: Request,
470
- options: { clientManifest?: ClientManifest; signal?: AbortSignal; clientIp?: string | null } = {},
471
- ): Promise<RscRenderResult> {
468
+ renderWithMeta(req: Request, options: RscRenderOptions = {}): Promise<RscRenderResult> {
472
469
  const requestId = crypto.randomUUID();
473
470
  return createRscHostRenderStream({
474
471
  setPending: (pending) => this.#pending.set(requestId, pending),
475
472
  deletePending: () => this.#pending.delete(requestId),
476
- sendRenderOrQueue: () => this.#sendRenderOrQueue(requestId, req, options.clientManifest, options.clientIp),
473
+ sendRenderOrQueue: () => this.#sendRenderOrQueue(requestId, req, options),
477
474
  cancelRender: () => this.#cancelRender(requestId),
478
475
  signal: options.signal,
479
476
  onPendingChunkOverflow: () => {
@@ -899,12 +896,13 @@ export class RscWorker {
899
896
  return headers;
900
897
  }
901
898
 
902
- #sendRenderOrQueue(requestId: string, req: Request, clientManifest?: ClientManifest, clientIp?: string | null): void {
899
+ #sendRenderOrQueue(requestId: string, req: Request, { clientManifest, clientIp, prefetch }: RscRenderOptions): void {
903
900
  const send = () => {
904
901
  if (!this.#pending.has(requestId)) return;
905
902
  try {
906
903
  const headers = RscWorker.workerHeaders(req, clientIp);
907
- this.#proc.send({ type: "render", requestId, url: req.url, method: req.method, headers, clientManifest });
904
+ const { url, method } = req;
905
+ this.#proc.send({ type: "render", requestId, url, method, headers, clientManifest, prefetch });
908
906
  } catch (err) {
909
907
  this.#resolvePending(requestId, (p) =>
910
908
  p.onError(`rsc worker send failed: ${err instanceof Error ? err.message : String(err)}`),
@@ -1,4 +1,5 @@
1
1
  import type { AkanRequestStore, AkanTheme } from "akanjs/fetch";
2
+ import type { ClientManifest } from "./artifact";
2
3
  import type { ModulePreloadPlan } from "./artifact/modulePreloadPlan";
3
4
 
4
5
  export interface SsrManifestEntry {
@@ -49,6 +50,14 @@ export interface RscTraceMetadata {
49
50
  ssrBlocking?: boolean;
50
51
  }
51
52
 
53
+ export interface RscRenderOptions {
54
+ clientManifest?: ClientManifest;
55
+ signal?: AbortSignal;
56
+ clientIp?: string | null;
57
+ /** A Link prefetch through `/__rsc`, never taken from a header a document request could carry. */
58
+ prefetch?: boolean;
59
+ }
60
+
52
61
  export interface SsrFromRscInput {
53
62
  request?: Request;
54
63
  requestStore?: AkanRequestStore;