@ivogt/rsc-router 0.0.0-experimental.1
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/README.md +19 -0
- package/package.json +131 -0
- package/src/__mocks__/version.ts +6 -0
- package/src/__tests__/route-definition.test.ts +63 -0
- package/src/browser/event-controller.ts +876 -0
- package/src/browser/index.ts +18 -0
- package/src/browser/link-interceptor.ts +121 -0
- package/src/browser/lru-cache.ts +69 -0
- package/src/browser/merge-segment-loaders.ts +126 -0
- package/src/browser/navigation-bridge.ts +891 -0
- package/src/browser/navigation-client.ts +155 -0
- package/src/browser/navigation-store.ts +823 -0
- package/src/browser/partial-update.ts +545 -0
- package/src/browser/react/Link.tsx +248 -0
- package/src/browser/react/NavigationProvider.tsx +228 -0
- package/src/browser/react/ScrollRestoration.tsx +94 -0
- package/src/browser/react/context.ts +53 -0
- package/src/browser/react/index.ts +52 -0
- package/src/browser/react/location-state-shared.ts +120 -0
- package/src/browser/react/location-state.ts +62 -0
- package/src/browser/react/use-action.ts +240 -0
- package/src/browser/react/use-client-cache.ts +56 -0
- package/src/browser/react/use-handle.ts +178 -0
- package/src/browser/react/use-link-status.ts +134 -0
- package/src/browser/react/use-navigation.ts +150 -0
- package/src/browser/react/use-segments.ts +188 -0
- package/src/browser/request-controller.ts +149 -0
- package/src/browser/rsc-router.tsx +310 -0
- package/src/browser/scroll-restoration.ts +324 -0
- package/src/browser/server-action-bridge.ts +747 -0
- package/src/browser/shallow.ts +35 -0
- package/src/browser/types.ts +443 -0
- package/src/cache/__tests__/memory-segment-store.test.ts +487 -0
- package/src/cache/__tests__/memory-store.test.ts +484 -0
- package/src/cache/cache-scope.ts +565 -0
- package/src/cache/cf/__tests__/cf-cache-store.test.ts +361 -0
- package/src/cache/cf/cf-cache-store.ts +274 -0
- package/src/cache/cf/index.ts +19 -0
- package/src/cache/index.ts +52 -0
- package/src/cache/memory-segment-store.ts +150 -0
- package/src/cache/memory-store.ts +253 -0
- package/src/cache/types.ts +366 -0
- package/src/client.rsc.tsx +88 -0
- package/src/client.tsx +609 -0
- package/src/components/DefaultDocument.tsx +20 -0
- package/src/default-error-boundary.tsx +88 -0
- package/src/deps/browser.ts +8 -0
- package/src/deps/html-stream-client.ts +2 -0
- package/src/deps/html-stream-server.ts +2 -0
- package/src/deps/rsc.ts +10 -0
- package/src/deps/ssr.ts +2 -0
- package/src/errors.ts +259 -0
- package/src/handle.ts +120 -0
- package/src/handles/MetaTags.tsx +178 -0
- package/src/handles/index.ts +6 -0
- package/src/handles/meta.ts +247 -0
- package/src/href-client.ts +128 -0
- package/src/href.ts +139 -0
- package/src/index.rsc.ts +69 -0
- package/src/index.ts +84 -0
- package/src/loader.rsc.ts +204 -0
- package/src/loader.ts +47 -0
- package/src/network-error-thrower.tsx +21 -0
- package/src/outlet-context.ts +15 -0
- package/src/root-error-boundary.tsx +277 -0
- package/src/route-content-wrapper.tsx +198 -0
- package/src/route-definition.ts +1333 -0
- package/src/route-map-builder.ts +140 -0
- package/src/route-types.ts +148 -0
- package/src/route-utils.ts +89 -0
- package/src/router/__tests__/match-context.test.ts +104 -0
- package/src/router/__tests__/match-pipelines.test.ts +537 -0
- package/src/router/__tests__/match-result.test.ts +566 -0
- package/src/router/__tests__/on-error.test.ts +935 -0
- package/src/router/__tests__/pattern-matching.test.ts +577 -0
- package/src/router/error-handling.ts +287 -0
- package/src/router/handler-context.ts +60 -0
- package/src/router/loader-resolution.ts +326 -0
- package/src/router/manifest.ts +116 -0
- package/src/router/match-context.ts +261 -0
- package/src/router/match-middleware/background-revalidation.ts +236 -0
- package/src/router/match-middleware/cache-lookup.ts +261 -0
- package/src/router/match-middleware/cache-store.ts +250 -0
- package/src/router/match-middleware/index.ts +81 -0
- package/src/router/match-middleware/intercept-resolution.ts +268 -0
- package/src/router/match-middleware/segment-resolution.ts +174 -0
- package/src/router/match-pipelines.ts +214 -0
- package/src/router/match-result.ts +212 -0
- package/src/router/metrics.ts +62 -0
- package/src/router/middleware.test.ts +1355 -0
- package/src/router/middleware.ts +748 -0
- package/src/router/pattern-matching.ts +271 -0
- package/src/router/revalidation.ts +190 -0
- package/src/router/router-context.ts +299 -0
- package/src/router/types.ts +96 -0
- package/src/router.ts +3484 -0
- package/src/rsc/__tests__/helpers.test.ts +175 -0
- package/src/rsc/handler.ts +942 -0
- package/src/rsc/helpers.ts +64 -0
- package/src/rsc/index.ts +56 -0
- package/src/rsc/nonce.ts +18 -0
- package/src/rsc/types.ts +225 -0
- package/src/segment-system.tsx +405 -0
- package/src/server/__tests__/request-context.test.ts +171 -0
- package/src/server/context.ts +340 -0
- package/src/server/handle-store.ts +230 -0
- package/src/server/loader-registry.ts +174 -0
- package/src/server/request-context.ts +470 -0
- package/src/server/root-layout.tsx +10 -0
- package/src/server/tsconfig.json +14 -0
- package/src/server.ts +126 -0
- package/src/ssr/__tests__/ssr-handler.test.tsx +188 -0
- package/src/ssr/index.tsx +215 -0
- package/src/types.ts +1473 -0
- package/src/use-loader.tsx +346 -0
- package/src/vite/__tests__/expose-loader-id.test.ts +117 -0
- package/src/vite/expose-action-id.ts +344 -0
- package/src/vite/expose-handle-id.ts +209 -0
- package/src/vite/expose-loader-id.ts +357 -0
- package/src/vite/expose-location-state-id.ts +177 -0
- package/src/vite/index.ts +608 -0
- package/src/vite/version.d.ts +12 -0
- package/src/vite/virtual-entries.ts +109 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import type { ReactNode } from "react";
|
|
3
|
+
import type { PartialCacheOptions, ErrorBoundaryHandler, Handler, LoaderDefinition, MiddlewareFn, NotFoundBoundaryHandler, ShouldRevalidateFn } from "../types";
|
|
4
|
+
import { invariant } from "../errors";
|
|
5
|
+
|
|
6
|
+
// ============================================================================
|
|
7
|
+
// Performance Metrics Types
|
|
8
|
+
// ============================================================================
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Performance metric entry for a single measured operation
|
|
12
|
+
*/
|
|
13
|
+
export interface PerformanceMetric {
|
|
14
|
+
label: string; // e.g., "route-matching", "loader:UserLoader"
|
|
15
|
+
duration: number; // milliseconds
|
|
16
|
+
startTime: number; // relative to request start
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Request-scoped metrics store
|
|
21
|
+
*/
|
|
22
|
+
export interface MetricsStore {
|
|
23
|
+
enabled: boolean;
|
|
24
|
+
requestStart: number;
|
|
25
|
+
metrics: PerformanceMetric[];
|
|
26
|
+
}
|
|
27
|
+
// ============================================================================
|
|
28
|
+
// RSC Router Context
|
|
29
|
+
// ============================================================================
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Cache configuration for an entry
|
|
33
|
+
* When set, this entry and its children will use this cache config
|
|
34
|
+
* unless overridden by a nested cache() call.
|
|
35
|
+
*/
|
|
36
|
+
export type EntryCacheConfig = {
|
|
37
|
+
/** Cache options (false means caching disabled for this entry) - ttl is optional, uses defaults */
|
|
38
|
+
options: PartialCacheOptions | false;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Entry data structure for manifest
|
|
43
|
+
*/
|
|
44
|
+
export type EntryPropCommon = {
|
|
45
|
+
id: string;
|
|
46
|
+
shortCode: string; // Short identifier for network efficiency (e.g., "L0", "P1", "R2")
|
|
47
|
+
parent: EntryData | null;
|
|
48
|
+
/** Cache configuration for this entry (set by cache() DSL) */
|
|
49
|
+
cache?: EntryCacheConfig;
|
|
50
|
+
};
|
|
51
|
+
export type EntryPropDatas = {
|
|
52
|
+
middleware: MiddlewareFn<any, any>[];
|
|
53
|
+
revalidate: ShouldRevalidateFn<any, any>[];
|
|
54
|
+
errorBoundary: (ReactNode | ErrorBoundaryHandler)[];
|
|
55
|
+
notFoundBoundary: (ReactNode | NotFoundBoundaryHandler)[];
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Loader entry stored in EntryData
|
|
59
|
+
* Contains the loader definition and its revalidation rules
|
|
60
|
+
*/
|
|
61
|
+
export type LoaderEntry = {
|
|
62
|
+
loader: LoaderDefinition<any>;
|
|
63
|
+
revalidate: ShouldRevalidateFn<any, any>[];
|
|
64
|
+
/** Cache config for this specific loader (loaders are NOT cached by default) */
|
|
65
|
+
cache?: EntryCacheConfig;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Segments state for intercept context
|
|
70
|
+
* Matches the structure from useSegments() for consistency
|
|
71
|
+
*/
|
|
72
|
+
export type InterceptSegmentsState = {
|
|
73
|
+
/** URL path segments (e.g., /shop/products/123 → ["shop", "products", "123"]) */
|
|
74
|
+
path: readonly string[];
|
|
75
|
+
/** Matched segment IDs in order (layouts and routes only, e.g., ["L0", "L0L1", "L0L1R0"]) */
|
|
76
|
+
ids: readonly string[];
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Context passed to intercept selector functions (when())
|
|
81
|
+
* Contains navigation context to determine if interception should occur.
|
|
82
|
+
*
|
|
83
|
+
* Note: when() is evaluated during route matching, BEFORE middleware runs.
|
|
84
|
+
* So ctx.get()/ctx.use() are not available, but env (platform bindings) is.
|
|
85
|
+
*/
|
|
86
|
+
export type InterceptSelectorContext<TEnv = any> = {
|
|
87
|
+
from: URL; // Source URL (where user is coming from)
|
|
88
|
+
to: URL; // Destination URL (where user is navigating to)
|
|
89
|
+
params: Record<string, string>; // Matched route params
|
|
90
|
+
request: Request; // The HTTP request object
|
|
91
|
+
env: TEnv; // Platform bindings (Cloudflare env, etc.)
|
|
92
|
+
segments: InterceptSegmentsState; // Client's current segments (where navigating FROM)
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Selector function for conditional interception
|
|
97
|
+
* Returns true to intercept, false to skip and fall through to route handler
|
|
98
|
+
*/
|
|
99
|
+
export type InterceptWhenFn<TEnv = any> = (ctx: InterceptSelectorContext<TEnv>) => boolean;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Intercept entry stored in EntryData
|
|
103
|
+
* Contains the slot name, route to intercept, and handler
|
|
104
|
+
*/
|
|
105
|
+
export type InterceptEntry = {
|
|
106
|
+
slotName: `@${string}`; // e.g., "@modal"
|
|
107
|
+
routeName: string; // e.g., "card"
|
|
108
|
+
handler: ReactNode | Handler<any, any>;
|
|
109
|
+
middleware: MiddlewareFn<any, any>[];
|
|
110
|
+
revalidate: ShouldRevalidateFn<any, any>[];
|
|
111
|
+
errorBoundary: (ReactNode | ErrorBoundaryHandler)[];
|
|
112
|
+
notFoundBoundary: (ReactNode | NotFoundBoundaryHandler)[];
|
|
113
|
+
loader: LoaderEntry[];
|
|
114
|
+
loading?: ReactNode | false;
|
|
115
|
+
layout?: ReactNode | Handler<any, any>; // Wrapper layout with <Outlet /> for content
|
|
116
|
+
when: InterceptWhenFn[]; // Selector conditions - all must return true to intercept
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export type EntryPropSegments = {
|
|
120
|
+
loader: LoaderEntry[];
|
|
121
|
+
layout: EntryData[];
|
|
122
|
+
parallel: EntryData[]; // type: "parallel" entries with their own loaders/revalidate/loading
|
|
123
|
+
intercept: InterceptEntry[]; // intercept definitions for soft navigation
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
export type EntryData =
|
|
127
|
+
| ({
|
|
128
|
+
type: "route";
|
|
129
|
+
handler: Handler<any, any>;
|
|
130
|
+
loading?: ReactNode | false;
|
|
131
|
+
} & EntryPropCommon &
|
|
132
|
+
EntryPropDatas &
|
|
133
|
+
EntryPropSegments)
|
|
134
|
+
| ({
|
|
135
|
+
type: "layout";
|
|
136
|
+
handler: ReactNode | Handler<any, any>;
|
|
137
|
+
loading?: ReactNode | false;
|
|
138
|
+
} & EntryPropCommon &
|
|
139
|
+
EntryPropDatas &
|
|
140
|
+
EntryPropSegments)
|
|
141
|
+
| ({
|
|
142
|
+
type: "parallel";
|
|
143
|
+
handler: Record<`@${string}`, Handler<any, any> | ReactNode>;
|
|
144
|
+
loading?: ReactNode | false;
|
|
145
|
+
} & EntryPropCommon &
|
|
146
|
+
EntryPropDatas &
|
|
147
|
+
EntryPropSegments)
|
|
148
|
+
| ({
|
|
149
|
+
type: "cache";
|
|
150
|
+
/** Cache entries create cache boundaries and render like layouts (with Outlet) */
|
|
151
|
+
handler: ReactNode | Handler<any, any>;
|
|
152
|
+
loading?: ReactNode | false;
|
|
153
|
+
} & EntryPropCommon &
|
|
154
|
+
EntryPropDatas &
|
|
155
|
+
EntryPropSegments);
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Context stored in AsyncLocalStorage
|
|
159
|
+
*/
|
|
160
|
+
interface HelperContext {
|
|
161
|
+
manifest: Map<string, EntryData>;
|
|
162
|
+
namespace: string;
|
|
163
|
+
parent: EntryData | null;
|
|
164
|
+
counters: Record<string, number>;
|
|
165
|
+
forRoute?: string;
|
|
166
|
+
mountIndex?: number;
|
|
167
|
+
metrics?: MetricsStore;
|
|
168
|
+
/** True when rendering for SSR (document requests) */
|
|
169
|
+
isSSR?: boolean;
|
|
170
|
+
}
|
|
171
|
+
export const RSCRouterContext: AsyncLocalStorage<HelperContext> =
|
|
172
|
+
new AsyncLocalStorage<HelperContext>();
|
|
173
|
+
|
|
174
|
+
export const getContext = (): {
|
|
175
|
+
context: AsyncLocalStorage<HelperContext>;
|
|
176
|
+
getStore: () => HelperContext;
|
|
177
|
+
getParent: () => EntryData | null;
|
|
178
|
+
getOrCreateStore: (forRoute?: string) => HelperContext;
|
|
179
|
+
getNextIndex: (
|
|
180
|
+
type: (string & {}) | "layout" | "parallel" | "middleware" | "revalidate"
|
|
181
|
+
) => string;
|
|
182
|
+
getShortCode: (
|
|
183
|
+
type: "layout" | "parallel" | "route" | "loader" | "cache"
|
|
184
|
+
) => string;
|
|
185
|
+
run: <T>(
|
|
186
|
+
namespace: string,
|
|
187
|
+
parent: EntryData | null,
|
|
188
|
+
callback: (...args: any[]) => T
|
|
189
|
+
) => T;
|
|
190
|
+
runWithStore: <T>(
|
|
191
|
+
store: HelperContext,
|
|
192
|
+
namespace: string,
|
|
193
|
+
parent: EntryData | null,
|
|
194
|
+
callback: (...args: any[]) => T
|
|
195
|
+
) => T;
|
|
196
|
+
} => {
|
|
197
|
+
const context = RSCRouterContext;
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
context,
|
|
201
|
+
getOrCreateStore: (forRoute?: string): HelperContext => {
|
|
202
|
+
let store = RSCRouterContext.getStore();
|
|
203
|
+
if (!store) {
|
|
204
|
+
store = {
|
|
205
|
+
manifest: new Map<string, EntryData>(),
|
|
206
|
+
namespace: "",
|
|
207
|
+
parent: null,
|
|
208
|
+
forRoute,
|
|
209
|
+
counters: {},
|
|
210
|
+
} satisfies HelperContext;
|
|
211
|
+
}
|
|
212
|
+
return store;
|
|
213
|
+
},
|
|
214
|
+
getStore: (): HelperContext => {
|
|
215
|
+
const store = context.getStore();
|
|
216
|
+
if (!store) {
|
|
217
|
+
throw new Error(
|
|
218
|
+
"RSC Router context store is not available. Make sure to run within RSC Router context."
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
return store;
|
|
222
|
+
},
|
|
223
|
+
getParent: (): EntryData | null => {
|
|
224
|
+
const store = context.getStore();
|
|
225
|
+
if (!store) {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return store.parent;
|
|
230
|
+
},
|
|
231
|
+
getNextIndex: (
|
|
232
|
+
type: (string & {}) | "layout" | "parallel" | "middleware" | "revalidate"
|
|
233
|
+
) => {
|
|
234
|
+
const store = context.getStore();
|
|
235
|
+
invariant(store, "No context RSCRouterContext available");
|
|
236
|
+
store.counters[type] ??= 0;
|
|
237
|
+
const index = store.counters[type];
|
|
238
|
+
store.counters[type] = index + 1;
|
|
239
|
+
return `$${type}.${index}`;
|
|
240
|
+
},
|
|
241
|
+
getShortCode: (type: "layout" | "parallel" | "route" | "loader" | "cache") => {
|
|
242
|
+
const store = context.getStore();
|
|
243
|
+
invariant(store, "No context RSCRouterContext available");
|
|
244
|
+
|
|
245
|
+
const parent = store.parent;
|
|
246
|
+
const prefix = type === "layout" ? "L" : type === "parallel" ? "P" : type === "loader" ? "D" : type === "cache" ? "C" : "R";
|
|
247
|
+
const mountPrefix = store.mountIndex !== undefined ? `M${store.mountIndex}` : "";
|
|
248
|
+
|
|
249
|
+
if (!parent) {
|
|
250
|
+
// Root entry: prefix with mount index and use mount-scoped counter
|
|
251
|
+
const counterKey = mountPrefix ? `${mountPrefix}_root_${type}` : `root_${type}`;
|
|
252
|
+
store.counters[counterKey] ??= 0;
|
|
253
|
+
const index = store.counters[counterKey];
|
|
254
|
+
store.counters[counterKey] = index + 1;
|
|
255
|
+
return `${mountPrefix}${prefix}${index}`;
|
|
256
|
+
} else {
|
|
257
|
+
// Child entry: use parent-scoped counter (parent already has M prefix)
|
|
258
|
+
const counterKey = `${parent.shortCode}_${type}`;
|
|
259
|
+
store.counters[counterKey] ??= 0;
|
|
260
|
+
const index = store.counters[counterKey];
|
|
261
|
+
store.counters[counterKey] = index + 1;
|
|
262
|
+
return `${parent.shortCode}${prefix}${index}`;
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
runWithStore: <T>(
|
|
266
|
+
store: HelperContext,
|
|
267
|
+
namespace: string,
|
|
268
|
+
parent: EntryData | null,
|
|
269
|
+
callback: (...args: any[]) => T
|
|
270
|
+
): T => {
|
|
271
|
+
return context.run(
|
|
272
|
+
{
|
|
273
|
+
manifest: store.manifest,
|
|
274
|
+
namespace,
|
|
275
|
+
parent: parent || null,
|
|
276
|
+
counters: store.counters,
|
|
277
|
+
forRoute: store.forRoute,
|
|
278
|
+
mountIndex: store.mountIndex,
|
|
279
|
+
metrics: store.metrics,
|
|
280
|
+
isSSR: store.isSSR,
|
|
281
|
+
},
|
|
282
|
+
callback
|
|
283
|
+
);
|
|
284
|
+
},
|
|
285
|
+
run: <T>(
|
|
286
|
+
namespace: string,
|
|
287
|
+
parent: EntryData | null,
|
|
288
|
+
callback: (...args: any[]) => T
|
|
289
|
+
) => {
|
|
290
|
+
const store = context.getStore();
|
|
291
|
+
// Preserve parent counters to ensure globally unique shortCodes
|
|
292
|
+
const counters = store?.counters || {};
|
|
293
|
+
const manifest = store ? store.manifest : new Map<string, EntryData>();
|
|
294
|
+
return context.run(
|
|
295
|
+
{
|
|
296
|
+
manifest,
|
|
297
|
+
namespace,
|
|
298
|
+
parent: parent || null,
|
|
299
|
+
counters,
|
|
300
|
+
forRoute: store?.forRoute,
|
|
301
|
+
mountIndex: store?.mountIndex,
|
|
302
|
+
metrics: store?.metrics,
|
|
303
|
+
isSSR: store?.isSSR,
|
|
304
|
+
},
|
|
305
|
+
callback
|
|
306
|
+
);
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
// ============================================================================
|
|
312
|
+
// Performance Metrics Helpers
|
|
313
|
+
// ============================================================================
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Track performance of a code block (no-op if metrics not enabled)
|
|
317
|
+
* Returns a done() callback to mark completion and record duration
|
|
318
|
+
*
|
|
319
|
+
* @example
|
|
320
|
+
* ```typescript
|
|
321
|
+
* const done = track("route-matching");
|
|
322
|
+
* // ... do work ...
|
|
323
|
+
* done(); // Records duration
|
|
324
|
+
* ```
|
|
325
|
+
*/
|
|
326
|
+
export function track(label: string): () => void {
|
|
327
|
+
const store = RSCRouterContext.getStore();
|
|
328
|
+
|
|
329
|
+
// No-op if context unavailable or metrics not enabled
|
|
330
|
+
if (!store?.metrics?.enabled) {
|
|
331
|
+
return () => {};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const startTime = performance.now() - store.metrics.requestStart;
|
|
335
|
+
|
|
336
|
+
return () => {
|
|
337
|
+
const duration = performance.now() - store.metrics!.requestStart - startTime;
|
|
338
|
+
store.metrics!.metrics.push({ label, duration, startTime });
|
|
339
|
+
};
|
|
340
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Handle data structure: handleName -> segmentId -> entries[]
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* {
|
|
7
|
+
* "breadcrumbs": {
|
|
8
|
+
* "$root.layout": [{ label: "Home", href: "/" }],
|
|
9
|
+
* "shop.layout": [{ label: "Shop", href: "/shop" }],
|
|
10
|
+
* }
|
|
11
|
+
* }
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export type HandleData = Record<string, Record<string, unknown[]>>;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Deep clone handle data to create a snapshot.
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
function cloneHandleData(data: HandleData): HandleData {
|
|
21
|
+
const clone: HandleData = {};
|
|
22
|
+
for (const handleName in data) {
|
|
23
|
+
clone[handleName] = {};
|
|
24
|
+
for (const segmentId in data[handleName]) {
|
|
25
|
+
clone[handleName][segmentId] = [...data[handleName][segmentId]];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return clone;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* HandleStore tracks pending handler promises and stores handle data.
|
|
33
|
+
*
|
|
34
|
+
* Combines two responsibilities:
|
|
35
|
+
* 1. Promise tracking - know when all handlers have resolved
|
|
36
|
+
* 2. Data storage - collect handle data pushed by handlers
|
|
37
|
+
* 3. Streaming - emit handle data via async iterator on each push
|
|
38
|
+
*/
|
|
39
|
+
export interface HandleStore {
|
|
40
|
+
/**
|
|
41
|
+
* Track a handler promise (non-blocking).
|
|
42
|
+
* Returns the promise unchanged - just registers it for tracking.
|
|
43
|
+
*/
|
|
44
|
+
track<T>(promise: Promise<T>): Promise<T>;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Promise that resolves when all tracked handlers have settled.
|
|
48
|
+
* Does not reject - uses Promise.allSettled internally.
|
|
49
|
+
*/
|
|
50
|
+
readonly settled: Promise<void>;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Push handle data for a specific handle and segment.
|
|
54
|
+
* Multiple pushes to the same handle/segment accumulate in an array.
|
|
55
|
+
* Each push triggers an emission on the stream.
|
|
56
|
+
*/
|
|
57
|
+
push(handleName: string, segmentId: string, data: unknown): void;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Get all collected handle data after all handlers have settled.
|
|
61
|
+
* Returns a promise that waits for `settled`, then returns the data.
|
|
62
|
+
* The data may contain unresolved promises which RSC will stream.
|
|
63
|
+
* @deprecated Use stream() for progressive updates
|
|
64
|
+
*/
|
|
65
|
+
getData(): Promise<HandleData>;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Get an async iterator that yields handle data on each push.
|
|
69
|
+
* The iterator completes when all handlers have settled.
|
|
70
|
+
* Each yield contains the full accumulated state (not just the delta).
|
|
71
|
+
*/
|
|
72
|
+
stream(): AsyncGenerator<HandleData, void, unknown>;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Get handle data for a specific segment (for caching).
|
|
76
|
+
* Returns data in format: { handleName: [values...] }
|
|
77
|
+
*/
|
|
78
|
+
getDataForSegment(segmentId: string): Record<string, unknown[]>;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Replay cached handle data back into the store (for cache hits).
|
|
82
|
+
* Used to restore handle data when serving cached segments.
|
|
83
|
+
*/
|
|
84
|
+
replaySegmentData(segmentId: string, segmentHandles: Record<string, unknown[]>): void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Create a new HandleStore instance.
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```ts
|
|
92
|
+
* const handleStore = createHandleStore();
|
|
93
|
+
*
|
|
94
|
+
* // In router - track without awaiting
|
|
95
|
+
* const component = handleStore.track(entry.handler(context));
|
|
96
|
+
*
|
|
97
|
+
* // In handler - push handle data (value, promise, or async callback result)
|
|
98
|
+
* handleStore.push("breadcrumbs", segmentId, { label: "Home", href: "/" });
|
|
99
|
+
* handleStore.push("meta", segmentId, fetchMetaAsync()); // promise
|
|
100
|
+
*
|
|
101
|
+
* // Stream handle data progressively
|
|
102
|
+
* for await (const handles of handleStore.stream()) {
|
|
103
|
+
* console.log("Handle update:", handles);
|
|
104
|
+
* }
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
export function createHandleStore(): HandleStore {
|
|
108
|
+
const pending: Promise<unknown>[] = [];
|
|
109
|
+
const data: HandleData = {};
|
|
110
|
+
|
|
111
|
+
// Queue for pending emissions and resolver for waiting consumer
|
|
112
|
+
let pendingEmissions: HandleData[] = [];
|
|
113
|
+
let emissionResolver: (() => void) | null = null;
|
|
114
|
+
let completed = false;
|
|
115
|
+
|
|
116
|
+
// Signal that a new emission is available
|
|
117
|
+
function signalEmission() {
|
|
118
|
+
if (emissionResolver) {
|
|
119
|
+
const resolver = emissionResolver;
|
|
120
|
+
emissionResolver = null;
|
|
121
|
+
resolver();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Wait for the next emission or completion
|
|
126
|
+
function waitForEmission(): Promise<void> {
|
|
127
|
+
if (pendingEmissions.length > 0 || completed) {
|
|
128
|
+
return Promise.resolve();
|
|
129
|
+
}
|
|
130
|
+
return new Promise((resolve) => {
|
|
131
|
+
emissionResolver = resolve;
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
track<T>(promise: Promise<T>): Promise<T> {
|
|
137
|
+
pending.push(promise);
|
|
138
|
+
return promise;
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
get settled(): Promise<void> {
|
|
142
|
+
if (pending.length === 0) {
|
|
143
|
+
return Promise.resolve();
|
|
144
|
+
}
|
|
145
|
+
return Promise.allSettled(pending).then(() => {});
|
|
146
|
+
},
|
|
147
|
+
|
|
148
|
+
push(handleName: string, segmentId: string, value: unknown): void {
|
|
149
|
+
if (!data[handleName]) {
|
|
150
|
+
data[handleName] = {};
|
|
151
|
+
}
|
|
152
|
+
if (!data[handleName][segmentId]) {
|
|
153
|
+
data[handleName][segmentId] = [];
|
|
154
|
+
}
|
|
155
|
+
data[handleName][segmentId].push(value);
|
|
156
|
+
|
|
157
|
+
// Queue a snapshot for emission
|
|
158
|
+
pendingEmissions.push(cloneHandleData(data));
|
|
159
|
+
signalEmission();
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
getData(): Promise<HandleData> {
|
|
163
|
+
return this.settled.then(() => data);
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
async *stream(): AsyncGenerator<HandleData, void, unknown> {
|
|
167
|
+
// Set up completion handler
|
|
168
|
+
this.settled.then(() => {
|
|
169
|
+
completed = true;
|
|
170
|
+
signalEmission();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
// Initial small delay to batch rapid synchronous pushes
|
|
174
|
+
// This allows multiple handles pushing in quick succession to be batched
|
|
175
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
176
|
+
|
|
177
|
+
// If we already have data, yield the accumulated state
|
|
178
|
+
if (Object.keys(data).length > 0) {
|
|
179
|
+
// Clear pending emissions since we're yielding current state
|
|
180
|
+
pendingEmissions = [];
|
|
181
|
+
yield cloneHandleData(data);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Continue streaming on each push
|
|
185
|
+
while (!completed) {
|
|
186
|
+
await waitForEmission();
|
|
187
|
+
|
|
188
|
+
// Yield all pending emissions (yield latest only)
|
|
189
|
+
if (pendingEmissions.length > 0) {
|
|
190
|
+
// Skip intermediate states, yield the latest
|
|
191
|
+
const latest = pendingEmissions[pendingEmissions.length - 1];
|
|
192
|
+
pendingEmissions = [];
|
|
193
|
+
yield latest;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Final yield only if there are pending emissions that weren't yielded
|
|
198
|
+
// (handles that pushed after our last yield but before completion)
|
|
199
|
+
if (pendingEmissions.length > 0) {
|
|
200
|
+
yield cloneHandleData(data);
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
|
|
204
|
+
getDataForSegment(segmentId: string): Record<string, unknown[]> {
|
|
205
|
+
const result: Record<string, unknown[]> = {};
|
|
206
|
+
for (const handleName in data) {
|
|
207
|
+
if (data[handleName][segmentId]) {
|
|
208
|
+
result[handleName] = [...data[handleName][segmentId]];
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return result;
|
|
212
|
+
},
|
|
213
|
+
|
|
214
|
+
replaySegmentData(segmentId: string, segmentHandles: Record<string, unknown[]>): void {
|
|
215
|
+
for (const handleName in segmentHandles) {
|
|
216
|
+
if (!data[handleName]) {
|
|
217
|
+
data[handleName] = {};
|
|
218
|
+
}
|
|
219
|
+
if (!data[handleName][segmentId]) {
|
|
220
|
+
data[handleName][segmentId] = [];
|
|
221
|
+
}
|
|
222
|
+
// Append replayed data
|
|
223
|
+
data[handleName][segmentId].push(...segmentHandles[handleName]);
|
|
224
|
+
}
|
|
225
|
+
// Trigger emission for streaming
|
|
226
|
+
pendingEmissions.push(cloneHandleData(data));
|
|
227
|
+
signalEmission();
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
}
|