akanjs 3.2.0-rc.27 → 3.2.0-rc.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -505,6 +505,18 @@
505
505
 
506
506
  `akan lint`'s `akan.service.call-in-loop` fix and the agent guidelines name `create<Model>Many` as the way to write a set once.
507
507
 
508
+ - ca67c2c: `router.refresh()` in a CSR bundle, which is what a native app runs, no longer reloads the document. It used to call `window.location.reload()`, so the screen went white and the store, scroll position, open modals, form drafts and the agent session were all lost.
509
+
510
+ Now it works the way the web's refresh does.
511
+
512
+ - The page on screen runs its async renders again: every layout and page level, and the root layouts, with fresh fetches.
513
+ - Each level keeps what it drew until its new render settles, so nothing blanks or falls back to `.loading()`. A component that stays in place keeps its state.
514
+ - The route's guards run again. A guard that now refuses moves the router, as it does on a navigation.
515
+ - A level whose new render fails shows the failure notice with a retry in its place. The document is not reloaded.
516
+ - Pages parked in the stack are left as they are.
517
+
518
+ Code that called `router.refresh()` in a CSR app to reset client state should reset that state itself.
519
+
508
520
  - 73f8830: An error an endpoint declares in `errors` and throws with that status under 500 is now logged at debug, as a returned call is, rather than as an ERROR line. A public endpoint that answers a bad token with a declared 404 no longer sends every probe, token scan or mistyped webhook URL to real-error alerts. Undeclared errors, a declared key thrown with another status, and every 5xx still log as errors.
509
521
  - 5691327: `setErrorConstructor` on `FetchClient`, `HttpClient` and `WsClient`, `HttpClientOptions.ErrorCls` and `FetchClient.build`'s `Err` option are deprecated. Every dictionary's `Err` is `akanjs/common`'s `Err`, which a restored error already is, so they change nothing. They keep working. A generated `lib/sig.ts` no longer calls `fetch.setErrorConstructor(Err)`, and a generated `lib/useClient.ts` no longer passes `{ Err: pageProto.Err }`; `akan sync` rewrites both. No upgrade step is needed.
510
522
  - 14134d3: Under `akan start`, a backend replica that crashes while it waits on the builder no longer has that answer handed to the replica respawned in its place, where it could settle the new process's own request of the same id with its predecessor's route, CSR or graph result. The gateway now forgets a replica's open builder requests when it exits, and passes each answer only to the process that asked.
@@ -798,6 +810,14 @@
798
810
  - **A refused head-safe patch runs each `.head()` once.** When a patch is refused after its head resolved, the full render reuses that head. Before, it ran every `.head()` a second time.
799
811
  - **`@akanjs/devkit`: the SSR runtime manifest keeps every client export of the segment outlet module.** Before, it kept only one.
800
812
 
813
+ - 5cd3bc2: Some SSR navigations go to a page under a different layout, such as from an `(app)` group page to an `(auth)` group page. These no longer flash an empty area where the levels below that layout appear. Before, the navigation swapped the screen as soon as the response's first row arrived. A level mounted for the first time then showed its empty Suspense fallback, and React keeps a fallback on screen for at least 300ms, even when the level's content arrives a moment later.
814
+
815
+ Now such a navigation waits up to 150ms for the response to finish before it swaps the screen, and the previous page stays visible during the wait.
816
+
817
+ - If the response finishes in time, the new page appears complete.
818
+ - If it doesn't, the navigation commits at 150ms and the remaining levels fill in as they stream, as before.
819
+ - A navigation between pages under the same layouts doesn't wait, so a `.loading()` page there still shows its loading view right away. Under a different layout, that loading view can now appear up to 150ms later.
820
+
801
821
  - 3537448: A navigation that a newer one overtakes before its page commits now cuts its `/__rsc` request once the response headers are in, so the server stops streaming it and the browser stops reading it. Before, it ran to the end and was only kept from committing. The cut waits for the headers because a session refresh may answer with a rotated single-use refresh token in `Set-Cookie`, and a request aborted before it lands leaves the browser holding the spent token. A refresh, a shallow push and a move back or forward overtake it the same way. A page that has already committed is never cut, so the Suspense content it still streams keeps arriving while the next navigation loads.
802
822
  - a373d51: With partial RSC commit on (`AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`), a page reached by a patch is now replayed from the browser's cache on a revisit, even after a full navigation in between. Before, every full navigation dropped every cached patch, so a section change made every page of the section before it a network fetch again.
803
823
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.27",
3
+ "version": "3.2.0-rc.29",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -31,7 +31,10 @@ const isLineRowTag = (byte: number): boolean => (byte > 64 && byte < 91) || byte
31
31
 
32
32
  const hexDigit = (byte: number): number => (byte > 96 ? byte - 87 : byte - 48);
33
33
 
34
- export type FlightLineRowHandler = (row: Uint8Array, tag: string) => Uint8Array | null;
34
+ export interface FlightLineRowHandler {
35
+ (row: Uint8Array, tag: string): Uint8Array | null;
36
+ end?: () => void;
37
+ }
35
38
 
36
39
  interface FlightRowSink {
37
40
  enqueue(row: Uint8Array, binary?: boolean): void;
@@ -201,11 +204,17 @@ export const mapFlightLineRows = (
201
204
  reader.read(chunk, batch);
202
205
  batch.flush();
203
206
  },
204
- flush: (controller) => reader.end(controller),
207
+ flush: (controller) => {
208
+ reader.end(controller);
209
+ for (const onLineRow of onLineRows) onLineRow.end?.();
210
+ },
205
211
  }),
206
212
  );
207
213
  };
208
214
 
215
+ export const flightRowsEndWatcher = (onEnd: () => void): FlightLineRowHandler =>
216
+ Object.assign((row: Uint8Array) => row, { end: onEnd });
217
+
209
218
  export type FlightRowPass = (...onLineRows: FlightLineRowHandler[]) => ReadableStream<Uint8Array>;
210
219
 
211
220
  export const flightRowPassOf =
@@ -5,7 +5,12 @@ import { AkanError } from "../base/akanError";
5
5
  import { csrLocation } from "../client/csrLocation";
6
6
  import { DictionaryAsset } from "../client/dictionaryAsset";
7
7
  import type {} from "../client/rscNavigation";
8
- import { type FlightLineRowHandler, type FlightRowPass, flightRowPassOf } from "./flightRowReader";
8
+ import {
9
+ type FlightLineRowHandler,
10
+ type FlightRowPass,
11
+ flightRowPassOf,
12
+ flightRowsEndWatcher,
13
+ } from "./flightRowReader";
9
14
  import {
10
15
  AKAN_RSC_DICTIONARY_HEADER,
11
16
  type AkanRouterStateV1,
@@ -37,8 +42,11 @@ import {
37
42
  createAkanSegmentCacheTree,
38
43
  createRscNavigationCacheNode,
39
44
  deleteRscCacheEntryIfCurrent,
45
+ mountsNewRouteLevels,
46
+ NEW_ROUTE_LEVEL_WAIT_MS,
40
47
  observeRscNavigationNode,
41
48
  type RscNavigationCacheNode,
49
+ settledOrAfter,
42
50
  } from "./rscNavigationState";
43
51
  import { RscParkedRedirect } from "./rscParkedRedirect";
44
52
  import { RscScrollRestoration } from "./rscScrollRestoration";
@@ -277,11 +285,18 @@ async function fetchRsc(
277
285
  if (!applies && node && pendingRequest) parkedRedirect.park({ node, location, replace });
278
286
  else navigateAfterRscRedirect(location, replace);
279
287
  };
280
- const thenable = thenableOf(flightRowPassOf(stream, rscRedirectRowGuard({ onRedirect: handleRedirect })));
288
+ let endStream = () => {};
289
+ const streamed = new Promise<void>((resolve) => {
290
+ endStream = resolve;
291
+ });
292
+ const thenable = thenableOf(
293
+ flightRowPassOf(stream, rscRedirectRowGuard({ onRedirect: handleRedirect }), flightRowsEndWatcher(endStream)),
294
+ );
281
295
  const node = createRscNavigationCacheNode({
282
296
  href,
283
297
  thenable,
284
298
  routerState: responseResult.notFound ? null : readAkanRouterStateResponseHeader(res.headers),
299
+ streamed,
285
300
  });
286
301
  nodeRef.current = node;
287
302
  await dictionaryReady;
@@ -597,6 +612,8 @@ function installNavigate(
597
612
  });
598
613
 
599
614
  await nextNode.thenable;
615
+ if (!notFound && mountsNewRouteLevels(currentRouterState, nextNode.routerState))
616
+ await settledOrAfter(nextNode.streamed, NEW_ROUTE_LEVEL_WAIT_MS);
600
617
 
601
618
  const committed = commitLatestRscNavigation({
602
619
  cache: notFound || replayed ? undefined : caches.pages,
@@ -3,6 +3,7 @@ import {
3
3
  type AkanRouterStateV1,
4
4
  type AkanRouteSegmentState,
5
5
  type AkanRscPatchMetadata,
6
+ countCommonRouteSegments,
6
7
  createAkanSegmentOutletKey,
7
8
  } from "./routeState";
8
9
 
@@ -18,6 +19,7 @@ export interface RscNavigationCacheNode<T> {
18
19
  href: string;
19
20
  thenable: T;
20
21
  routerState: AkanRouterStateV1 | null;
22
+ streamed?: PromiseLike<void>;
21
23
  }
22
24
 
23
25
  export interface RscPatchNavigationCacheNode<T> {
@@ -85,8 +87,29 @@ export function createRscNavigationCacheNode<T>({
85
87
  href,
86
88
  thenable,
87
89
  routerState,
90
+ streamed,
88
91
  }: RscNavigationCacheNode<T>): RscNavigationCacheNode<T> {
89
- return { href, thenable, routerState };
92
+ return streamed ? { href, thenable, routerState, streamed } : { href, thenable, routerState };
93
+ }
94
+
95
+ export const NEW_ROUTE_LEVEL_WAIT_MS = 150;
96
+
97
+ export function mountsNewRouteLevels(current: AkanRouterStateV1 | null, next: AkanRouterStateV1 | null): boolean {
98
+ if (!next) return false;
99
+ const kept = current ? countCommonRouteSegments(current.segments, next.segments) : 0;
100
+ return kept < next.segments.length - 1;
101
+ }
102
+
103
+ export function settledOrAfter(promise: PromiseLike<unknown> | undefined, ms: number): Promise<void> {
104
+ if (!promise) return Promise.resolve();
105
+ return new Promise((resolve) => {
106
+ const done = () => {
107
+ clearTimeout(timer);
108
+ resolve();
109
+ };
110
+ const timer = setTimeout(done, ms);
111
+ promise.then(done, done);
112
+ });
90
113
  }
91
114
 
92
115
  export function createRscPatchNavigationCacheNode<T>({
@@ -1,5 +1,9 @@
1
1
  export declare const FLIGHT_LENGTH_PREFIXED_TAGS = "TAOobUSsLlGgMmV";
2
- export type FlightLineRowHandler = (row: Uint8Array, tag: string) => Uint8Array | null;
2
+ export interface FlightLineRowHandler {
3
+ (row: Uint8Array, tag: string): Uint8Array | null;
4
+ end?: () => void;
5
+ }
3
6
  export declare const mapFlightLineRows: (stream: ReadableStream<Uint8Array>, ...onLineRows: FlightLineRowHandler[]) => ReadableStream<Uint8Array>;
7
+ export declare const flightRowsEndWatcher: (onEnd: () => void) => FlightLineRowHandler;
4
8
  export type FlightRowPass = (...onLineRows: FlightLineRowHandler[]) => ReadableStream<Uint8Array>;
5
9
  export declare const flightRowPassOf: (stream: ReadableStream<Uint8Array>, ...firstOnLineRows: FlightLineRowHandler[]) => FlightRowPass;
@@ -10,6 +10,7 @@ export interface RscNavigationCacheNode<T> {
10
10
  href: string;
11
11
  thenable: T;
12
12
  routerState: AkanRouterStateV1 | null;
13
+ streamed?: PromiseLike<void>;
13
14
  }
14
15
  export interface RscPatchNavigationCacheNode<T> {
15
16
  href: string;
@@ -49,7 +50,10 @@ export type RscPatchNavigationCacheResult<T> = {
49
50
  status: "rejected";
50
51
  reason: AkanSegmentPatchFailureReason;
51
52
  };
52
- export declare function createRscNavigationCacheNode<T>({ href, thenable, routerState, }: RscNavigationCacheNode<T>): RscNavigationCacheNode<T>;
53
+ export declare function createRscNavigationCacheNode<T>({ href, thenable, routerState, streamed, }: RscNavigationCacheNode<T>): RscNavigationCacheNode<T>;
54
+ export declare const NEW_ROUTE_LEVEL_WAIT_MS = 150;
55
+ export declare function mountsNewRouteLevels(current: AkanRouterStateV1 | null, next: AkanRouterStateV1 | null): boolean;
56
+ export declare function settledOrAfter(promise: PromiseLike<unknown> | undefined, ms: number): Promise<void>;
53
57
  export declare function createRscPatchNavigationCacheNode<T>({ href, patch, patchedNode, outletKey, headSnapshot, base, }: {
54
58
  href: string;
55
59
  patch: AkanRscPatchMetadata;
@@ -23,5 +23,6 @@ export declare class CsrGuards {
23
23
  /** Whether a verdict for `key` is held or on its way. */
24
24
  static asked(key: string): boolean;
25
25
  static hold(key: string): () => void;
26
+ static expire(location: GuardedLocation): void;
26
27
  }
27
28
  export {};
@@ -0,0 +1,13 @@
1
+ import type { Location } from "akanjs/client";
2
+ interface CsrRefreshRequest {
3
+ epoch: number;
4
+ locationId: string | null;
5
+ }
6
+ export declare class CsrRefresh {
7
+ #private;
8
+ static idOf({ entryId, href }: Pick<Location, "entryId" | "href">): string;
9
+ static request(location: Location): void;
10
+ static subscribe(listener: () => void): () => void;
11
+ static current(): CsrRefreshRequest;
12
+ }
13
+ export {};
@@ -84,6 +84,10 @@ export class CsrGuards {
84
84
  };
85
85
  }
86
86
 
87
+ static expire(location: GuardedLocation) {
88
+ CsrGuards.#forget(CsrGuards.keyOf(location));
89
+ }
90
+
87
91
  static #forget(key: string) {
88
92
  CsrGuards.#runs.delete(key);
89
93
  CsrGuards.#admitted.delete(key);
@@ -1,9 +1,20 @@
1
1
  "use client";
2
2
  import { debugFrame, RouteDefinition, type RouteRender, router, Translator, usePathCtx } from "akanjs/client";
3
3
  import { isThenable, Logger } from "akanjs/common";
4
- import { createContext, createElement, memo, type ReactNode, useContext, useEffect, useRef, useState } from "react";
4
+ import {
5
+ createContext,
6
+ createElement,
7
+ memo,
8
+ type ReactNode,
9
+ useContext,
10
+ useEffect,
11
+ useRef,
12
+ useState,
13
+ useSyncExternalStore,
14
+ } from "react";
5
15
  import { CsrGuards } from "./CsrGuards";
6
16
  import { CsrFrameDump } from "./csrFrameDump";
17
+ import { CsrRefresh } from "./csrRefresh";
7
18
  import { RenderFailure } from "./RenderFailure";
8
19
  import { useFetch } from "./useFetch";
9
20
  import { usePageActivity } from "./usePageActivity";
@@ -27,6 +38,7 @@ interface RenderedRoute {
27
38
  failure: { error: unknown } | null;
28
39
  /** Asked after the layer's last run was refused, so it draws nothing until its own answer arrives. */
29
40
  afterRefusal: boolean;
41
+ refreshEpoch: number;
30
42
  }
31
43
 
32
44
  interface RenderLayerProps {
@@ -49,6 +61,7 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
49
61
  const renderedRef = useRef<RenderedRoute | null>(null);
50
62
  const [, setFailures] = useState(0);
51
63
  const activity = usePageActivity();
64
+ const refresh = useSyncExternalStore(CsrRefresh.subscribe, CsrRefresh.current, CsrRefresh.current);
52
65
 
53
66
  const onScreenRef = useRef(activity === "current");
54
67
  useEffect(() => {
@@ -65,7 +78,7 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
65
78
 
66
79
  const guarded = location && CsrGuards.declared(location) ? location : null;
67
80
  const guardKey = guarded ? CsrGuards.keyOf(guarded) : null;
68
- const locationId = location ? `${location.entryId ?? ""} ${location.href}` : null;
81
+ const locationId = location ? CsrRefresh.idOf(location) : null;
69
82
 
70
83
  const mayAsk = activity !== "hidden" && activity !== "prev";
71
84
  useEffect(() => (guardKey ? CsrGuards.hold(guardKey) : undefined), [guardKey]);
@@ -110,20 +123,17 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
110
123
  )
111
124
  : (guardKey ?? "");
112
125
  const rendered = renderedRef.current;
113
-
114
126
  const returned = activity === "current" && !onScreenRef.current;
115
-
116
- const moved = !!rendered?.refusedAt && rendered.refusedAt !== locationId;
117
-
118
- const lapsed = !isAsyncRender && rendered?.admittedKey === guardKey;
119
-
120
127
  if (
121
- !rendered ||
122
- rendered.render !== routeRender.render ||
123
- rendered.argsKey !== argsKey ||
124
- (returned && rendered.redirected) ||
125
- moved ||
126
- lapsed
128
+ mustRerun(rendered, {
129
+ render: routeRender.render,
130
+ argsKey,
131
+ returned,
132
+ locationId,
133
+ guardKey,
134
+ isAsyncRender,
135
+ refresh,
136
+ })
127
137
  ) {
128
138
  const redirectsBefore = router.redirectCount();
129
139
  const layer = `${routeRender.kind ?? "layout"} ${index} of ${path}`;
@@ -156,6 +166,7 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
156
166
  admittedKey: null,
157
167
  failure: null,
158
168
  afterRefusal: !!rendered?.refusedAt,
169
+ refreshEpoch: refresh.epoch,
159
170
  };
160
171
  if (isThenable(result))
161
172
  (result as Promise<ReactNode>).then(
@@ -208,6 +219,29 @@ export const RenderLayer = memo((props: RenderLayerProps) => {
208
219
  return <layerChildContext.Provider value={children}>{value}</layerChildContext.Provider>;
209
220
  });
210
221
 
222
+ interface LayerRun {
223
+ render: RouteRender["render"];
224
+ argsKey: string;
225
+ returned: boolean;
226
+ locationId: string | null;
227
+ guardKey: string | null;
228
+ isAsyncRender: boolean;
229
+ refresh: ReturnType<typeof CsrRefresh.current>;
230
+ }
231
+
232
+ function mustRerun(rendered: RenderedRoute | null, run: LayerRun): boolean {
233
+ if (!rendered || rendered.render !== run.render || rendered.argsKey !== run.argsKey) return true;
234
+
235
+ if (run.returned && rendered.redirected) return true;
236
+
237
+ if (rendered.refusedAt && rendered.refusedAt !== run.locationId) return true;
238
+
239
+ if (!run.isAsyncRender && rendered.admittedKey === run.guardKey) return true;
240
+
241
+ if (rendered.refreshEpoch === run.refresh.epoch) return false;
242
+ return run.locationId === null || run.refresh.locationId === run.locationId;
243
+ }
244
+
211
245
  function reportFailure(result: ReactNode | Promise<ReactNode>, layer: string): ReactNode | Promise<ReactNode> {
212
246
  if (!isThenable(result)) return result;
213
247
  debugFrame("layer.render", { layer });
@@ -0,0 +1,33 @@
1
+ import type { Location } from "akanjs/client";
2
+ import { CsrGuards } from "./CsrGuards";
3
+
4
+ interface CsrRefreshRequest {
5
+ epoch: number;
6
+ locationId: string | null;
7
+ }
8
+
9
+ export class CsrRefresh {
10
+ static #request: CsrRefreshRequest = { epoch: 0, locationId: null };
11
+ static readonly #listeners = new Set<() => void>();
12
+
13
+ static idOf({ entryId, href }: Pick<Location, "entryId" | "href">): string {
14
+ return `${entryId ?? ""} ${href}`;
15
+ }
16
+
17
+ static request(location: Location) {
18
+ if (CsrGuards.declared(location)) CsrGuards.expire(location);
19
+ CsrRefresh.#request = { epoch: CsrRefresh.#request.epoch + 1, locationId: CsrRefresh.idOf(location) };
20
+ for (const listener of CsrRefresh.#listeners) listener();
21
+ }
22
+
23
+ static subscribe(listener: () => void): () => void {
24
+ CsrRefresh.#listeners.add(listener);
25
+ return () => {
26
+ CsrRefresh.#listeners.delete(listener);
27
+ };
28
+ }
29
+
30
+ static current(): CsrRefreshRequest {
31
+ return CsrRefresh.#request;
32
+ }
33
+ }
@@ -17,6 +17,7 @@ import {
17
17
  } from "akanjs/client";
18
18
  import { isNativeApp, openExternalUrl } from "akanjs/client/native";
19
19
  import { useCallback, useMemo, useState } from "react";
20
+ import { CsrRefresh } from "./csrRefresh";
20
21
  import { useCsrKeyboard } from "./useCsrKeyboard";
21
22
  import { type CsrLocationState, useCsrLocationState } from "./useCsrLocationState";
22
23
  import { type CsrNavigation, useCsrNavigation } from "./useCsrNavigation";
@@ -75,7 +76,9 @@ const useCsrRouter = ({
75
76
  push: forward("push"),
76
77
  replace: forward("replace"),
77
78
  refresh: () => {
78
- csrLocation.reload();
79
+ const location = getCurrentLocation();
80
+ debugFrame("router.refresh", { href: location.href });
81
+ CsrRefresh.request(location);
79
82
  },
80
83
  back: async ({ scrollToTop }: RouteOptions = {}) => {
81
84
  waitingNavigation.current = null;