akanjs 3.2.0-rc.7 → 3.2.0-rc.9

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 (97) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/common/failureCode.ts +18 -0
  3. package/common/index.ts +3 -0
  4. package/common/mcpFailure.ts +9 -0
  5. package/common/restartSchedule.ts +55 -0
  6. package/fetch/client/httpClient.ts +12 -2
  7. package/package.json +1 -1
  8. package/server/akanApp.ts +21 -21
  9. package/server/mcp/McpDispatcher.ts +20 -5
  10. package/server/mcp/McpPages.ts +21 -6
  11. package/server/mcp/McpRouter.ts +51 -22
  12. package/server/rscClient.tsx +62 -76
  13. package/server/rscClientChunks.ts +29 -0
  14. package/server/rscClientFetch.ts +6 -1
  15. package/server/rscInlineStream.ts +34 -0
  16. package/server/rscNavigationState.ts +21 -1
  17. package/server/rscPrefetchCache.ts +27 -17
  18. package/server/rscWorkerHost.ts +9 -13
  19. package/service/documentStoreError.ts +16 -0
  20. package/service/index.ts +3 -0
  21. package/service/injectError.ts +5 -0
  22. package/service/injectInfo.ts +28 -17
  23. package/service/insightQueryError.ts +19 -0
  24. package/service/liveSyncHub.ts +5 -2
  25. package/service/predefinedAdaptor/anthropicLlm.ts +2 -0
  26. package/service/predefinedAdaptor/cache.adaptor.ts +3 -2
  27. package/service/predefinedAdaptor/compress.adaptor.ts +5 -1
  28. package/service/predefinedAdaptor/database.adaptor.ts +3 -1
  29. package/service/predefinedAdaptor/documentTransfer.ts +2 -1
  30. package/service/predefinedAdaptor/insightQuery.ts +35 -11
  31. package/service/predefinedAdaptor/llm.adaptor.ts +2 -0
  32. package/service/predefinedAdaptor/openaiDialect.ts +2 -0
  33. package/service/predefinedAdaptor/searchIndex.ts +5 -1
  34. package/service/predefinedAdaptor/sql/PostgresInsightSession.ts +15 -5
  35. package/service/predefinedAdaptor/sql/QueryCompiler.ts +29 -13
  36. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +20 -8
  37. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +45 -94
  38. package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +2 -1
  39. package/service/predefinedAdaptor/sql/UpdateCompiler.ts +6 -2
  40. package/service/predefinedAdaptor/sql/fieldValues.ts +74 -0
  41. package/service/predefinedAdaptor/sql/search/fts5.ts +4 -1
  42. package/service/predefinedAdaptor/sql/search/postgres.ts +6 -2
  43. package/service/predefinedAdaptor/sql/values.ts +8 -4
  44. package/service/predefinedAdaptor/storage.adaptor.ts +7 -3
  45. package/service/serve.ts +3 -2
  46. package/service/serviceModule.ts +2 -2
  47. package/signal/SignalFailure.ts +8 -1
  48. package/signal/endpointErrorContract.ts +9 -2
  49. package/signal/endpointInfo.ts +6 -5
  50. package/signal/exception.ts +1 -0
  51. package/signal/index.ts +2 -0
  52. package/signal/internalInfo.ts +6 -4
  53. package/signal/mcp/Msg.ts +23 -10
  54. package/signal/mcp/index.ts +1 -0
  55. package/signal/mcp/promptError.ts +9 -0
  56. package/signal/middleware.ts +5 -5
  57. package/signal/serializer/fetch.serializer.ts +2 -1
  58. package/signal/signalContext.ts +15 -16
  59. package/signal/signalContractError.ts +10 -0
  60. package/signal/signalDeclarationError.ts +13 -0
  61. package/signal/signalRegistry.ts +3 -1
  62. package/signal/slice.ts +2 -1
  63. package/signal/sliceInfo.ts +12 -9
  64. package/types/common/failureCode.d.ts +6 -0
  65. package/types/common/index.d.ts +3 -0
  66. package/types/common/mcpFailure.d.ts +6 -0
  67. package/types/common/restartSchedule.d.ts +16 -0
  68. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  69. package/types/server/mcp/McpPages.d.ts +2 -1
  70. package/types/server/rscClient.d.ts +0 -5
  71. package/types/server/rscClientChunks.d.ts +6 -0
  72. package/types/server/rscClientFetch.d.ts +1 -1
  73. package/types/server/rscInlineStream.d.ts +9 -0
  74. package/types/server/rscNavigationState.d.ts +8 -3
  75. package/types/server/rscPrefetchCache.d.ts +7 -6
  76. package/types/service/documentStoreError.d.ts +7 -0
  77. package/types/service/index.d.ts +3 -0
  78. package/types/service/injectError.d.ts +4 -0
  79. package/types/service/insightQueryError.d.ts +9 -0
  80. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +2 -0
  81. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +0 -5
  82. package/types/service/predefinedAdaptor/sql/fieldValues.d.ts +5 -0
  83. package/types/service/serviceModule.d.ts +1 -1
  84. package/types/signal/SignalFailure.d.ts +1 -0
  85. package/types/signal/exception.d.ts +1 -0
  86. package/types/signal/index.d.ts +2 -0
  87. package/types/signal/mcp/index.d.ts +1 -0
  88. package/types/signal/mcp/promptError.d.ts +5 -0
  89. package/types/signal/signalContractError.d.ts +4 -0
  90. package/types/signal/signalDeclarationError.d.ts +4 -0
  91. package/types/vendor/use-agentic/types.d.ts +5 -0
  92. package/vendor/use-agentic/CHANGELOG.md +24 -0
  93. package/vendor/use-agentic/ToolRunner.ts +18 -3
  94. package/vendor/use-agentic/WIRE.md +5 -0
  95. package/vendor/use-agentic/types.ts +5 -0
  96. package/webkit/McpAppAgent.ts +8 -3
  97. package/webkit/McpAppFetchBridge.ts +9 -5
@@ -1,5 +1,5 @@
1
- import { type BackendEnv, getEnv } from "akanjs/base";
2
- import { Logger } from "akanjs/common";
1
+ import { AkanError, type BackendEnv, getEnv } from "akanjs/base";
2
+ import { Logger, MCP_FAILURE_META, type McpFailure } from "akanjs/common";
3
3
  import { DictionaryLookup } from "akanjs/dictionary";
4
4
  import { CacheAdaptorRole, type InjectRegistry, type LiveRegistry } from "akanjs/service";
5
5
  import {
@@ -286,7 +286,7 @@ export class McpRouter {
286
286
  McpRouter.logger.error(
287
287
  `MCP ${method} failed: ${error instanceof Error ? (error.stack ?? error.message) : error}`,
288
288
  );
289
- return McpRouter.#error(id, McpErrorCode.internal, "Internal server error.");
289
+ return McpRouter.#error(id, McpErrorCode.internal, "Internal server error.", McpRouter.#coded("internalError"));
290
290
  }
291
291
  }
292
292
 
@@ -437,6 +437,7 @@ export class McpRouter {
437
437
  : `Too many calls in flight: at most ${this.#limiter.concurrent} at once. Retry in ${seconds}s.`;
438
438
  return {
439
439
  refused: McpRouter.#error(call.id, McpErrorCode.rateLimited, message, {
440
+ ...McpRouter.#coded(AkanError.codeOfStatus(429)),
440
441
  status: 429,
441
442
  headers: { "retry-after": String(seconds) },
442
443
  }),
@@ -447,13 +448,20 @@ export class McpRouter {
447
448
  let streaming = false;
448
449
  try {
449
450
  const name = call.params.name;
450
- if (typeof name !== "string") return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing tool name.");
451
+ if (typeof name !== "string")
452
+ return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing tool name.", McpRouter.#invalid);
451
453
 
452
454
  const exposed = document.isAppOnly(name) && !call.ui ? undefined : document.findTool(name);
453
455
 
454
- if (!exposed) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown tool: ${name}.`);
456
+ if (!exposed)
457
+ return McpRouter.#error(
458
+ call.id,
459
+ McpErrorCode.invalidParams,
460
+ `Unknown tool: ${name}.`,
461
+ McpRouter.#coded("unknownTool"),
462
+ );
455
463
  const args = McpRouter.#arguments(call.params);
456
- if (!args) return McpRouter.#error(call.id, McpErrorCode.invalidParams, McpRouter.#badArguments);
464
+ if (!args) return McpRouter.#badArgumentsError(call.id);
457
465
  const progressToken = McpRouter.#progressToken(call);
458
466
  const option = { forView: this.#pages.forView(call.ui, McpRouter.#meta(call.params)) };
459
467
  if (progressToken === undefined)
@@ -510,7 +518,7 @@ export class McpRouter {
510
518
 
511
519
  stream.write(
512
520
  "error" in outcome
513
- ? McpRouter.#errorBody(call.id, McpErrorCode.internal, "Internal server error.")
521
+ ? McpRouter.#errorBody(call.id, McpErrorCode.internal, "Internal server error.", { code: "internalError" })
514
522
  : this.#envelope(call, outcome.result),
515
523
  );
516
524
  } finally {
@@ -520,6 +528,16 @@ export class McpRouter {
520
528
 
521
529
  static readonly #badArguments = "`arguments` must be an object of named values.";
522
530
 
531
+ static #coded(code: string) {
532
+ return { data: { code } };
533
+ }
534
+
535
+ static readonly #invalid = McpRouter.#coded("invalidArgument");
536
+
537
+ static #badArgumentsError(id: string | number | null) {
538
+ return McpRouter.#error(id, McpErrorCode.invalidParams, McpRouter.#badArguments, McpRouter.#invalid);
539
+ }
540
+
523
541
  static #arguments(params: Record<string, unknown>) {
524
542
  const args = params.arguments;
525
543
  if (args === undefined || args === null) return {};
@@ -546,37 +564,45 @@ export class McpRouter {
546
564
 
547
565
  async #pageToolCall(call: McpCall, document: McpDocument, entry: PagePromptEntry) {
548
566
  const outcome = await this.#pages.toolCall(call, document, entry, McpRouter.#arguments(call.params));
549
- if ("badArguments" in outcome)
550
- return McpRouter.#error(call.id, McpErrorCode.invalidParams, McpRouter.#badArguments);
567
+ if ("badArguments" in outcome) return McpRouter.#badArgumentsError(call.id);
551
568
  return this.#result(call, outcome.result);
552
569
  }
553
570
 
554
571
  async #promptsGet(call: McpCall, document: McpDocument) {
555
572
  const name = call.params.name;
556
- if (typeof name !== "string") return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing prompt name.");
573
+ if (typeof name !== "string")
574
+ return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing prompt name.", McpRouter.#invalid);
575
+ const unknown = McpRouter.#coded("unknownPrompt");
557
576
  const entry = await this.#pages.prompt(name);
558
- if (!entry) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown prompt: ${name}.`);
577
+ if (!entry) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown prompt: ${name}.`, unknown);
559
578
  const page = await this.#pages.run(call, document, entry, McpRouter.#arguments(call.params));
560
- if ("badArguments" in page) return McpRouter.#error(call.id, McpErrorCode.invalidParams, McpRouter.#badArguments);
561
- if ("refusal" in page) return McpRouter.#error(call.id, McpErrorCode.invalidParams, page.refusal);
579
+ if ("badArguments" in page) return McpRouter.#badArgumentsError(call.id);
580
+ if ("refusal" in page)
581
+ return McpRouter.#error(call.id, McpErrorCode.invalidParams, page.refusal, McpRouter.#coded(page.failure.code));
562
582
  return this.#result(call, { description: entry.description, messages: page.messages });
563
583
  }
564
584
 
565
585
  async #resourcesRead(call: McpCall, document: McpDocument) {
566
586
  const uri = call.params.uri;
567
- if (typeof uri !== "string") return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing resource uri.");
587
+ if (typeof uri !== "string")
588
+ return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing resource uri.", McpRouter.#invalid);
589
+ const unknown = McpRouter.#coded("unknownResource");
568
590
  if (this.#apps && uri.startsWith(McpApps.scheme)) {
569
591
  const contents = await this.#apps.read(uri, this.#auth.publicOrigin(call.req));
570
- if (!contents) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}.`);
592
+ if (!contents) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}.`, unknown);
571
593
  return this.#result(call, { contents: [contents] });
572
594
  }
573
595
  const resolved = document.resolveResource(uri);
574
- if (!resolved) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}.`);
596
+ if (!resolved) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}.`, unknown);
575
597
  const result = await this.#dispatcher.call(resolved.exposed, resolved.args, call.req);
576
598
  const [first] = result.content;
577
599
  const firstText = first?.type === "text" ? first.text : undefined;
578
600
 
579
- if (result.isError) return McpRouter.#error(call.id, McpErrorCode.invalidParams, firstText ?? "Read failed.");
601
+ if (result.isError) {
602
+ const failure = result._meta?.[MCP_FAILURE_META] as McpFailure | undefined;
603
+ const code = failure?.code ?? AkanError.codeOfStatus(500);
604
+ return McpRouter.#error(call.id, McpErrorCode.invalidParams, firstText ?? "Read failed.", McpRouter.#coded(code));
605
+ }
580
606
 
581
607
  const text =
582
608
  result.structuredContent === undefined ? (firstText ?? "null") : JSON.stringify(result.structuredContent);
@@ -631,11 +657,14 @@ export class McpRouter {
631
657
 
632
658
  #envelope(call: McpCall, result: object, cache?: McpCacheHint) {
633
659
 
634
- const meta =
635
- call.era === "modern"
636
- ? { resultType: "complete", _meta: { [MCP_META_SERVER_INFO]: this.#serverInfo() }, ...cache }
637
- : {};
638
- return { jsonrpc: "2.0", id: call.id, result: { ...meta, ...result } } satisfies McpJsonRpcResponse;
660
+ const own = (result as { _meta?: Record<string, unknown> })._meta;
661
+ if (call.era !== "modern") return { jsonrpc: "2.0", id: call.id, result } satisfies McpJsonRpcResponse;
662
+ const _meta = { [MCP_META_SERVER_INFO]: this.#serverInfo(), ...own };
663
+ return {
664
+ jsonrpc: "2.0",
665
+ id: call.id,
666
+ result: { resultType: "complete", ...cache, ...result, _meta },
667
+ } satisfies McpJsonRpcResponse;
639
668
  }
640
669
 
641
670
  static #page<T>(items: T[], cursor: unknown, size: number) {
@@ -21,8 +21,11 @@ import {
21
21
  claimChunkReload,
22
22
  isBuildBundle,
23
23
  isLinkFailure,
24
+ lazyLinkFailureKeyOf,
24
25
  navigationOfChunk,
26
+ noteChunkLoadFailure,
25
27
  recordChunksOf,
28
+ reportingRootErrors,
26
29
  } from "./rscClientChunks";
27
30
  import { fetchRscNavigationResponse, fetchRscPrefetchResponse } from "./rscClientFetch";
28
31
  import { validateRscPatchForGuardedCommit } from "./rscClientPatch";
@@ -33,6 +36,7 @@ import {
33
36
  rollbackPreparedAkanHeadSnapshotPatch,
34
37
  } from "./rscHeadPatch";
35
38
  import { getRscPayloadStream, guardRscRedirectRows, type RscRedirectRow } from "./rscHttp";
39
+ import { createInitialRscStream } from "./rscInlineStream";
36
40
  import {
37
41
  type AkanSegmentCacheNode,
38
42
  commitLatestRscNavigation,
@@ -40,6 +44,7 @@ import {
40
44
  createRscNavigationCacheNode,
41
45
  createRscPatchNavigationCacheNode,
42
46
  deleteRscCacheEntryIfCurrent,
47
+ forgetRscPatchesOfLostBases,
43
48
  observeRscNavigationNode,
44
49
  type RscNavigationCacheNode,
45
50
  type RscPatchNavigationCacheNode,
@@ -51,26 +56,12 @@ import { RscPrefetchCache } from "./rscPrefetchCache";
51
56
  import { RscScrollRestoration } from "./rscScrollRestoration";
52
57
  import { commitAkanSegmentOutletPatch, resetAkanSegmentOutletPatches } from "./rscSegmentOutlet";
53
58
 
54
- type InlineRscChunk = [1, string] | [3, string];
55
-
56
59
  declare global {
57
- var __RSC_CHUNKS__: InlineRscChunk[] | undefined;
58
- var __RSC_CLOSED__: boolean | undefined;
59
- var __RSC_PUSH__: ((type: InlineRscChunk[0], data: string) => void) | undefined;
60
- var __RSC_CLOSE__: (() => void) | undefined;
61
60
  var __AKAN_RSC_INITIAL_STATE__: string | undefined;
62
61
  var __AKAN_DICT_URL__: string | undefined;
63
62
  var __webpack_chunk_load__: ((chunkId: string) => Promise<unknown>) | undefined;
64
63
  }
65
64
 
66
- function decodeInlineRscChunk([type, data]: InlineRscChunk): Uint8Array {
67
- if (type === 1) return new TextEncoder().encode(data);
68
- const binary = atob(data);
69
- const bytes = new Uint8Array(binary.length);
70
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
71
- return bytes;
72
- }
73
-
74
65
  type RscThenable = Promise<ReactNode> & {
75
66
  status?: "pending" | "fulfilled" | "rejected";
76
67
  value?: ReactNode;
@@ -107,24 +98,6 @@ class RscRouteNotFound extends Error {
107
98
  }
108
99
  }
109
100
 
110
- function createInitialRscStream(): ReadableStream<Uint8Array> {
111
- return new ReadableStream<Uint8Array>({
112
- start(controller) {
113
- const queued = globalThis.__RSC_CHUNKS__ ?? [];
114
- for (const chunk of queued) controller.enqueue(decodeInlineRscChunk(chunk));
115
- globalThis.__RSC_CHUNKS__ = [];
116
-
117
- if (globalThis.__RSC_CLOSED__) {
118
- controller.close();
119
- return;
120
- }
121
-
122
- globalThis.__RSC_PUSH__ = (type, data) => controller.enqueue(decodeInlineRscChunk([type, data]));
123
- globalThis.__RSC_CLOSE__ = () => controller.close();
124
- },
125
- });
126
- }
127
-
128
101
  function normalizeHref(href: string): string {
129
102
  return new URL(href, window.location.origin).href;
130
103
  }
@@ -350,7 +323,12 @@ const readAuthCookies = () =>
350
323
  .join("; ");
351
324
  const rscCache = new Map<string, RscCacheNode>();
352
325
  const rscPatchCache = new Map<string, RscPatchNavigationCacheNode<RscThenable>>();
353
- const rscPrefetchCache = new RscPrefetchCache({ fetchResponse: fetchRscPrefetchResponse });
326
+
327
+ const prefetchBase = () => (isAkanRscPartialCommitEnabled() ? currentFullNode : null);
328
+ const rscPrefetchCache = new RscPrefetchCache<RscCacheNode | null>({
329
+ fetchResponse: (href, signal) => fetchRscPrefetchResponse(href, signal, currentRouterState),
330
+ baseOf: prefetchBase,
331
+ });
354
332
 
355
333
  StaleReads.subscribe(() => rscPrefetchCache.clear());
356
334
  const initialThenable = createRscThenable(createInitialRscStream());
@@ -418,6 +396,7 @@ if (loadChunk)
418
396
  globalThis.__webpack_chunk_load__ = (chunkId) => {
419
397
  const loading = loadChunk(chunkId);
420
398
  const navigation = navigationOfChunk(chunkId);
399
+ loading.catch(noteChunkLoadFailure);
421
400
  if (navigation) loading.catch((error: unknown) => loadDocumentForChunkFailure(chunkId, navigation, error));
422
401
  return loading;
423
402
  };
@@ -433,21 +412,28 @@ function loadDocumentForChunkFailure(chunkId: string, navigation: ChunkNavigatio
433
412
  else hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
434
413
  }
435
414
 
415
+ function loadDocumentForLazyChunkFailure(error: unknown): void {
416
+ const leaving =
417
+ !!pendingRequest && pendingRequest.navId !== refreshNavId && pendingRequest.target !== pageKeyOf(renderedHref);
418
+ if (shownNode === initialNode || leaving || documentNavigationFallbackInFlight || !isBuildBundle()) return;
419
+ const key = lazyLinkFailureKeyOf(error);
420
+ if (key && navigator.onLine && claimChunkReload(key))
421
+ hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
422
+ }
423
+
436
424
  globalThis.__AKAN_RSC_IS_FROM_CACHE__ = () => currentCommitFromCache;
437
425
 
438
426
  function rememberCommittedRouteState(node: RscCacheNode): void {
439
- rscPatchCache.clear();
427
+ currentFullNode = node;
440
428
  shownNode = node;
441
429
  parkedRedirect.clear();
442
- if (!node.routerState) return;
430
+ forgetRscPatchesOfLostBases(rscPatchCache, rscCache, node);
443
431
  currentRouterState = node.routerState;
444
432
  currentSegmentTree = createAkanSegmentCacheTree(node);
445
- currentFullNode = node;
446
433
  currentCommitKind = "full";
447
434
  }
448
435
 
449
436
  function forgetCommittedRouteState(): void {
450
- rscPatchCache.clear();
451
437
  shownNode = null;
452
438
  parkedRedirect.clear();
453
439
  currentRouterState = null;
@@ -485,6 +471,34 @@ function replayedPageOf(target: string): RscCacheNode | undefined {
485
471
  return node;
486
472
  }
487
473
 
474
+ const cachedPatchReplayOf = (node: RscPatchNavigationCacheNode<RscThenable>, navId?: number) =>
475
+ resolveCachedRscPatchNavigation({
476
+ currentTree: currentSegmentTree,
477
+ currentBase: currentFullNode,
478
+ node,
479
+ partialCommitEnabled: isAkanRscPartialCommitEnabled(),
480
+ navId,
481
+ getCurrentNavId: () => navigationSeq,
482
+ });
483
+
484
+ function replayCachedPatch(target: string, navId: number, replace?: boolean, requestScroll?: () => void): boolean {
485
+ const cachedPatch = rscPatchCache.get(target);
486
+ if (!cachedPatch) return false;
487
+ const patchResult = cachedPatchReplayOf(cachedPatch, navId);
488
+ if (patchResult.status === "patched") {
489
+ const { tree, patchedNode, outletKey, headSnapshot } = patchResult;
490
+ const patch = { type: "patched" as const, tree, patchedNode, patch: cachedPatch.patch, outletKey, headSnapshot };
491
+ if (commitRscPatchNavigation({ target, patch, replace, requestScroll })) {
492
+ currentCommitFromCache = true;
493
+ rememberPatchedRouteState(tree, patchedNode);
494
+ rememberRscCacheNode(rscPatchCache, cachedPatch, MAX_RSC_CACHE_ENTRIES);
495
+ return true;
496
+ }
497
+ }
498
+ rscPatchCache.delete(target);
499
+ return false;
500
+ }
501
+
488
502
  const isConstrainedNetwork = () => {
489
503
  const connection = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } })
490
504
  .connection;
@@ -499,8 +513,10 @@ globalThis.__AKAN_RSC_PREFETCH__ = (href, priority) => {
499
513
  if (new URL(target).origin !== window.location.origin || pendingRequest?.target === key) return none;
500
514
 
501
515
  const authCookies = readAuthCookies();
502
- if (authCookies === cachedAuthCookies && cachedPageOf(target)) return none;
503
- return rscPrefetchCache.request(key, authCookies, priority);
516
+ const cachedPatch = rscPatchCache.get(target);
517
+ const replayable = cachedPageOf(target) || (!!cachedPatch && cachedPatchReplayOf(cachedPatch).status === "patched");
518
+ if (authCookies === cachedAuthCookies && replayable) return none;
519
+ return rscPrefetchCache.request(key, authCookies, priority, prefetchBase());
504
520
  };
505
521
 
506
522
  function Root(): ReactNode {
@@ -614,41 +630,8 @@ function Root(): ReactNode {
614
630
  let notFound = false;
615
631
  let servedFromCache = !!nextNode;
616
632
  if (!nextNode) {
617
- const cachedPatch = rscPatchCache.get(target);
618
- if (cachedPatch) {
619
- const patchResult = resolveCachedRscPatchNavigation({
620
- currentTree: currentSegmentTree,
621
- node: cachedPatch,
622
- partialCommitEnabled: isAkanRscPartialCommitEnabled(),
623
- navId,
624
- getCurrentNavId: () => navigationSeq,
625
- });
626
- if (patchResult.status === "patched") {
627
- const replayedPatch = {
628
- type: "patched" as const,
629
- tree: patchResult.tree,
630
- patchedNode: patchResult.patchedNode,
631
- patch: cachedPatch.patch,
632
- outletKey: patchResult.outletKey,
633
- headSnapshot: patchResult.headSnapshot,
634
- };
635
- if (
636
- commitRscPatchNavigation({
637
- target,
638
- patch: replayedPatch,
639
- replace: options.replace,
640
- requestScroll,
641
- })
642
- ) {
643
- currentCommitFromCache = true;
644
- rememberPatchedRouteState(patchResult.tree, patchResult.patchedNode);
645
- rememberRscCacheNode(rscPatchCache, cachedPatch, MAX_RSC_CACHE_ENTRIES);
646
- return;
647
- }
648
- }
649
- rscPatchCache.delete(target);
650
- }
651
- const taken = rscPrefetchCache.take(pageKeyOf(target), cachedAuthCookies, signal);
633
+ if (replayCachedPatch(target, navId, options.replace, requestScroll)) return;
634
+ const taken = rscPrefetchCache.take(pageKeyOf(target), cachedAuthCookies, signal, prefetchBase());
652
635
  const prefetched = (await taken?.response) ?? undefined;
653
636
  if (signal.aborted) return;
654
637
  servedFromCache = !!prefetched && !taken?.fresh;
@@ -671,7 +654,7 @@ function Root(): ReactNode {
671
654
  requestScroll,
672
655
  })
673
656
  ) {
674
- currentCommitFromCache = false;
657
+ currentCommitFromCache = servedFromCache;
675
658
  rememberPatchedRouteState(fetched.tree, fetched.patchedNode);
676
659
  const patchCacheNode = createRscPatchNavigationCacheNode({
677
660
  href: target,
@@ -679,6 +662,7 @@ function Root(): ReactNode {
679
662
  patchedNode: fetched.patchedNode,
680
663
  outletKey: fetched.outletKey,
681
664
  headSnapshot: fetched.headSnapshot,
665
+ base: currentFullNode,
682
666
  });
683
667
  if (patchCacheNode) rememberRscCacheNode(rscPatchCache, patchCacheNode, MAX_RSC_CACHE_ENTRIES);
684
668
  return;
@@ -770,8 +754,10 @@ window.addEventListener("popstate", (event) => {
770
754
  }, 0);
771
755
  });
772
756
 
757
+ window.addEventListener("unhandledrejection", (event) => loadDocumentForLazyChunkFailure(event.reason));
758
+ const rootOptions = isBuildBundle() ? reportingRootErrors(loadDocumentForLazyChunkFailure) : undefined;
773
759
  const hydrate = () => {
774
- hydrateRoot(document, createElement(Root));
760
+ hydrateRoot(document, createElement(Root), rootOptions);
775
761
  scrollRestoration.restoreDocumentLoad();
776
762
  };
777
763
 
@@ -41,6 +41,35 @@ const linkFailure =
41
41
  export const isLinkFailure = (error: unknown): boolean =>
42
42
  (error instanceof SyntaxError || error instanceof TypeError) && linkFailure.test(error.message);
43
43
 
44
+ const chunkLoadFailures = new WeakSet<object>();
45
+ export const noteChunkLoadFailure = (error: unknown): void => {
46
+ if (typeof error === "object" && error !== null) chunkLoadFailures.add(error);
47
+ };
48
+
49
+ export const lazyLinkFailureKeyOf = (error: unknown): string | null =>
50
+ error instanceof Error && isLinkFailure(error) && !chunkLoadFailures.has(error) ? `import() ${error.message}` : null;
51
+
52
+ const reportGlobalError = (error: unknown): void => {
53
+ if (typeof reportError === "function") {
54
+ reportError(error);
55
+ return;
56
+ }
57
+ const message = error instanceof Error ? error.message : String(error);
58
+ if (window.dispatchEvent(new ErrorEvent("error", { bubbles: true, cancelable: true, message, error })))
59
+ console.error(error);
60
+ };
61
+
62
+ export const reportingRootErrors = (onError: (error: unknown) => void) => ({
63
+ onCaughtError: (error: unknown) => {
64
+ console.error(error);
65
+ onError(error);
66
+ },
67
+ onUncaughtError: (error: unknown) => {
68
+ reportGlobalError(error);
69
+ onError(error);
70
+ },
71
+ });
72
+
44
73
  const chunkReloadsKey = "akan.rsc.chunkReloads";
45
74
  export function claimChunkReload(chunkId: string): boolean {
46
75
  try {
@@ -45,9 +45,14 @@ const fetchKeepingHeaders = async (endpoint: URL, init: RequestInit, signal: Abo
45
45
  return response;
46
46
  };
47
47
 
48
- export const fetchRscPrefetchResponse = (href: string, signal: AbortSignal) => {
48
+ export const fetchRscPrefetchResponse = (
49
+ href: string,
50
+ signal: AbortSignal,
51
+ currentRouterState: AkanRouterStateV1 | null = null,
52
+ ) => {
49
53
  const headers = rscRequestHeaders();
50
54
  headers.set(AKAN_RSC_PREFETCH_HEADER, "1");
55
+ if (isAkanRscPartialCommitEnabled()) appendAkanRouterStateRequestHeaders(headers, currentRouterState);
51
56
  return fetchKeepingHeaders(rscEndpointOf(href), { headers, credentials: "same-origin", cache: "no-store" }, signal);
52
57
  };
53
58
 
@@ -0,0 +1,34 @@
1
+ type InlineRscChunk = [1, string] | [3, string];
2
+
3
+ declare global {
4
+ var __RSC_CHUNKS__: InlineRscChunk[] | undefined;
5
+ var __RSC_CLOSED__: boolean | undefined;
6
+ var __RSC_PUSH__: ((type: InlineRscChunk[0], data: string) => void) | undefined;
7
+ var __RSC_CLOSE__: (() => void) | undefined;
8
+ }
9
+
10
+ function decodeInlineRscChunk([type, data]: InlineRscChunk): Uint8Array {
11
+ if (type === 1) return new TextEncoder().encode(data);
12
+ const binary = atob(data);
13
+ const bytes = new Uint8Array(binary.length);
14
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
15
+ return bytes;
16
+ }
17
+
18
+ export function createInitialRscStream(): ReadableStream<Uint8Array> {
19
+ return new ReadableStream<Uint8Array>({
20
+ start(controller) {
21
+ const queued = globalThis.__RSC_CHUNKS__ ?? [];
22
+ for (const chunk of queued) controller.enqueue(decodeInlineRscChunk(chunk));
23
+ globalThis.__RSC_CHUNKS__ = [];
24
+
25
+ if (globalThis.__RSC_CLOSED__) {
26
+ controller.close();
27
+ return;
28
+ }
29
+
30
+ globalThis.__RSC_PUSH__ = (type, data) => controller.enqueue(decodeInlineRscChunk([type, data]));
31
+ globalThis.__RSC_CLOSE__ = () => controller.close();
32
+ },
33
+ });
34
+ }
@@ -27,6 +27,8 @@ export interface RscPatchNavigationCacheNode<T> {
27
27
  patch: AkanRscPatchMetadata;
28
28
  outletKey: string;
29
29
  headSnapshot: AkanHeadSnapshotV1;
30
+ /** The full commit whose layouts the patch went under; it keeps them, so it applies under that very commit only. */
31
+ base: RscNavigationCacheNode<T>;
30
32
  }
31
33
 
32
34
  export interface AkanSegmentCacheNode<T> {
@@ -39,6 +41,7 @@ export interface AkanSegmentCacheNode<T> {
39
41
 
40
42
  export type AkanSegmentPatchFailureReason =
41
43
  | "missing-current-tree"
44
+ | "base-changed"
42
45
  | "segment-path-mismatch"
43
46
  | "stale"
44
47
  | "unsupported-suffix"
@@ -92,14 +95,16 @@ export function createRscPatchNavigationCacheNode<T>({
92
95
  patchedNode,
93
96
  outletKey,
94
97
  headSnapshot,
98
+ base,
95
99
  }: {
96
100
  href: string;
97
101
  patch: AkanRscPatchMetadata;
98
102
  patchedNode: AkanSegmentCacheNode<T>;
99
103
  outletKey: string;
100
104
  headSnapshot: AkanHeadSnapshotV1;
105
+ base: RscNavigationCacheNode<T> | null;
101
106
  }): RscPatchNavigationCacheNode<T> | null {
102
- if (!patchedNode.thenable) return null;
107
+ if (!patchedNode.thenable || !base) return null;
103
108
  return {
104
109
  href,
105
110
  thenable: patchedNode.thenable,
@@ -107,9 +112,21 @@ export function createRscPatchNavigationCacheNode<T>({
107
112
  patch,
108
113
  outletKey,
109
114
  headSnapshot,
115
+ base,
110
116
  };
111
117
  }
112
118
 
119
+ export function forgetRscPatchesOfLostBases<T>(
120
+ patchCache: RscNavigationCache<RscPatchNavigationCacheNode<T>>,
121
+ fullCache: RscNavigationCache<RscNavigationCacheNode<T>>,
122
+ currentBase: RscNavigationCacheNode<T> | null,
123
+ ): void {
124
+ for (const href of [...patchCache.keys()]) {
125
+ const base = patchCache.get(href)?.base;
126
+ if (base && base !== currentBase && fullCache.get(base.href) !== base) patchCache.delete(href);
127
+ }
128
+ }
129
+
113
130
  export function createAkanSegmentCacheTree<T>(node: RscNavigationCacheNode<T>): AkanSegmentCacheNode<T> | null {
114
131
  const routerState = node.routerState;
115
132
  if (!routerState || routerState.segments.length === 0) return null;
@@ -221,18 +238,21 @@ export function rememberRscCacheNode<N extends { href: string }>(
221
238
 
222
239
  export function resolveCachedRscPatchNavigation<T>({
223
240
  currentTree,
241
+ currentBase,
224
242
  node,
225
243
  partialCommitEnabled,
226
244
  navId,
227
245
  getCurrentNavId,
228
246
  }: {
229
247
  currentTree: AkanSegmentCacheNode<T> | null;
248
+ currentBase: RscNavigationCacheNode<T> | null;
230
249
  node: RscPatchNavigationCacheNode<T>;
231
250
  partialCommitEnabled: boolean;
232
251
  navId?: number;
233
252
  getCurrentNavId?: () => number;
234
253
  }): RscPatchNavigationCacheResult<T> {
235
254
  if (!partialCommitEnabled) return { status: "rejected", reason: "guard-disabled" };
255
+ if (node.base !== currentBase) return { status: "rejected", reason: "base-changed" };
236
256
  const patchResult = applyAkanSegmentCachePatch({
237
257
  currentTree,
238
258
  targetRouterState: node.routerState,