@rangojs/router 0.0.0-experimental.10
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/CLAUDE.md +43 -0
- package/README.md +19 -0
- package/dist/bin/rango.js +227 -0
- package/dist/vite/index.js +3039 -0
- package/package.json +171 -0
- package/skills/caching/SKILL.md +191 -0
- package/skills/debug-manifest/SKILL.md +108 -0
- package/skills/document-cache/SKILL.md +180 -0
- package/skills/fonts/SKILL.md +165 -0
- package/skills/hooks/SKILL.md +442 -0
- package/skills/intercept/SKILL.md +190 -0
- package/skills/layout/SKILL.md +213 -0
- package/skills/links/SKILL.md +180 -0
- package/skills/loader/SKILL.md +246 -0
- package/skills/middleware/SKILL.md +202 -0
- package/skills/mime-routes/SKILL.md +124 -0
- package/skills/parallel/SKILL.md +228 -0
- package/skills/prerender/SKILL.md +283 -0
- package/skills/rango/SKILL.md +54 -0
- package/skills/response-routes/SKILL.md +358 -0
- package/skills/route/SKILL.md +173 -0
- package/skills/router-setup/SKILL.md +346 -0
- package/skills/tailwind/SKILL.md +129 -0
- package/skills/theme/SKILL.md +78 -0
- package/skills/typesafety/SKILL.md +394 -0
- package/src/__internal.ts +175 -0
- package/src/bin/rango.ts +24 -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 +913 -0
- package/src/browser/navigation-client.ts +165 -0
- package/src/browser/navigation-store.ts +823 -0
- package/src/browser/partial-update.ts +600 -0
- package/src/browser/react/Link.tsx +248 -0
- package/src/browser/react/NavigationProvider.tsx +346 -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/mount-context.ts +32 -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 +203 -0
- package/src/browser/react/use-href.tsx +40 -0
- package/src/browser/react/use-link-status.ts +134 -0
- package/src/browser/react/use-mount.ts +31 -0
- package/src/browser/react/use-navigation.ts +140 -0
- package/src/browser/react/use-segments.ts +188 -0
- package/src/browser/request-controller.ts +164 -0
- package/src/browser/rsc-router.tsx +352 -0
- package/src/browser/scroll-restoration.ts +324 -0
- package/src/browser/segment-structure-assert.ts +67 -0
- package/src/browser/server-action-bridge.ts +762 -0
- package/src/browser/shallow.ts +35 -0
- package/src/browser/types.ts +478 -0
- package/src/build/generate-manifest.ts +377 -0
- package/src/build/generate-route-types.ts +828 -0
- package/src/build/index.ts +36 -0
- package/src/build/route-trie.ts +239 -0
- package/src/cache/cache-scope.ts +563 -0
- package/src/cache/cf/cf-cache-store.ts +428 -0
- package/src/cache/cf/index.ts +19 -0
- package/src/cache/document-cache.ts +340 -0
- package/src/cache/index.ts +58 -0
- package/src/cache/memory-segment-store.ts +150 -0
- package/src/cache/memory-store.ts +253 -0
- package/src/cache/types.ts +392 -0
- package/src/client.rsc.tsx +83 -0
- package/src/client.tsx +643 -0
- package/src/component-utils.ts +76 -0
- package/src/components/DefaultDocument.tsx +23 -0
- package/src/debug.ts +233 -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 +295 -0
- package/src/handle.ts +130 -0
- package/src/handles/MetaTags.tsx +193 -0
- package/src/handles/index.ts +6 -0
- package/src/handles/meta.ts +247 -0
- package/src/host/cookie-handler.ts +159 -0
- package/src/host/errors.ts +97 -0
- package/src/host/index.ts +56 -0
- package/src/host/pattern-matcher.ts +214 -0
- package/src/host/router.ts +330 -0
- package/src/host/testing.ts +79 -0
- package/src/host/types.ts +138 -0
- package/src/host/utils.ts +25 -0
- package/src/href-client.ts +202 -0
- package/src/href-context.ts +33 -0
- package/src/index.rsc.ts +121 -0
- package/src/index.ts +165 -0
- package/src/loader.rsc.ts +207 -0
- package/src/loader.ts +47 -0
- package/src/network-error-thrower.tsx +21 -0
- package/src/outlet-context.ts +15 -0
- package/src/prerender/param-hash.ts +35 -0
- package/src/prerender/store.ts +40 -0
- package/src/prerender.ts +156 -0
- package/src/reverse.ts +267 -0
- package/src/root-error-boundary.tsx +277 -0
- package/src/route-content-wrapper.tsx +193 -0
- package/src/route-definition.ts +1431 -0
- package/src/route-map-builder.ts +242 -0
- package/src/route-types.ts +220 -0
- package/src/router/error-handling.ts +287 -0
- package/src/router/handler-context.ts +158 -0
- package/src/router/intercept-resolution.ts +387 -0
- package/src/router/loader-resolution.ts +327 -0
- package/src/router/manifest.ts +216 -0
- package/src/router/match-api.ts +621 -0
- package/src/router/match-context.ts +264 -0
- package/src/router/match-middleware/background-revalidation.ts +236 -0
- package/src/router/match-middleware/cache-lookup.ts +382 -0
- package/src/router/match-middleware/cache-store.ts +276 -0
- package/src/router/match-middleware/index.ts +81 -0
- package/src/router/match-middleware/intercept-resolution.ts +281 -0
- package/src/router/match-middleware/segment-resolution.ts +184 -0
- package/src/router/match-pipelines.ts +214 -0
- package/src/router/match-result.ts +213 -0
- package/src/router/metrics.ts +62 -0
- package/src/router/middleware.ts +791 -0
- package/src/router/pattern-matching.ts +407 -0
- package/src/router/revalidation.ts +190 -0
- package/src/router/router-context.ts +301 -0
- package/src/router/segment-resolution.ts +1315 -0
- package/src/router/trie-matching.ts +172 -0
- package/src/router/types.ts +163 -0
- package/src/router.gen.ts +6 -0
- package/src/router.ts +2423 -0
- package/src/rsc/handler.ts +1443 -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 +236 -0
- package/src/segment-system.tsx +442 -0
- package/src/server/context.ts +466 -0
- package/src/server/handle-store.ts +229 -0
- package/src/server/loader-registry.ts +174 -0
- package/src/server/request-context.ts +554 -0
- package/src/server/root-layout.tsx +10 -0
- package/src/server/tsconfig.json +14 -0
- package/src/server.ts +171 -0
- package/src/ssr/index.tsx +296 -0
- package/src/theme/ThemeProvider.tsx +291 -0
- package/src/theme/ThemeScript.tsx +61 -0
- package/src/theme/constants.ts +59 -0
- package/src/theme/index.ts +58 -0
- package/src/theme/theme-context.ts +70 -0
- package/src/theme/theme-script.ts +152 -0
- package/src/theme/types.ts +182 -0
- package/src/theme/use-theme.ts +44 -0
- package/src/types.ts +1757 -0
- package/src/urls.gen.ts +8 -0
- package/src/urls.ts +1282 -0
- package/src/use-loader.tsx +346 -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 +426 -0
- package/src/vite/expose-location-state-id.ts +177 -0
- package/src/vite/expose-prerender-handler-id.ts +429 -0
- package/src/vite/index.ts +2068 -0
- package/src/vite/package-resolution.ts +125 -0
- package/src/vite/version.d.ts +12 -0
- package/src/vite/virtual-entries.ts +114 -0
package/src/router.ts
ADDED
|
@@ -0,0 +1,2423 @@
|
|
|
1
|
+
import type { ComponentType } from "react";
|
|
2
|
+
import { type ReactNode } from "react";
|
|
3
|
+
import { createCacheScope } from "./cache/cache-scope.js";
|
|
4
|
+
import type { SegmentCacheStore } from "./cache/types.js";
|
|
5
|
+
import { assertClientComponent } from "./component-utils.js";
|
|
6
|
+
import { DefaultDocument } from "./components/DefaultDocument.js";
|
|
7
|
+
import {
|
|
8
|
+
sanitizeError,
|
|
9
|
+
} from "./errors";
|
|
10
|
+
import { serializeManifest, type SerializedManifest } from "./debug.js";
|
|
11
|
+
import {
|
|
12
|
+
createReverse,
|
|
13
|
+
type ReverseFunction,
|
|
14
|
+
type PrefixRoutePatterns,
|
|
15
|
+
} from "./reverse.js";
|
|
16
|
+
import {
|
|
17
|
+
registerRouteMap,
|
|
18
|
+
getPrecomputedEntries,
|
|
19
|
+
getRouteTrie,
|
|
20
|
+
} from "./route-map-builder.js";
|
|
21
|
+
import { tryTrieMatch } from "./router/trie-matching.js";
|
|
22
|
+
import {
|
|
23
|
+
createRouteHelpers,
|
|
24
|
+
type RouteHandlers,
|
|
25
|
+
} from "./route-definition.js";
|
|
26
|
+
import MapRootLayout from "./server/root-layout.js";
|
|
27
|
+
import type { AllUseItems, IncludeItem } from "./route-types.js";
|
|
28
|
+
import type { UrlPatterns } from "./urls.js";
|
|
29
|
+
import {
|
|
30
|
+
EntryData,
|
|
31
|
+
InterceptEntry,
|
|
32
|
+
InterceptSelectorContext,
|
|
33
|
+
getContext,
|
|
34
|
+
RSCRouterContext,
|
|
35
|
+
runWithPrefixes,
|
|
36
|
+
type MetricsStore,
|
|
37
|
+
} from "./server/context";
|
|
38
|
+
import { createHandleStore, type HandleStore } from "./server/handle-store.js";
|
|
39
|
+
import { getRequestContext } from "./server/request-context.js";
|
|
40
|
+
import type {
|
|
41
|
+
ErrorBoundaryHandler,
|
|
42
|
+
ErrorInfo,
|
|
43
|
+
ErrorPhase,
|
|
44
|
+
HandlerContext,
|
|
45
|
+
LoaderDataResult,
|
|
46
|
+
MatchResult,
|
|
47
|
+
NotFoundBoundaryHandler,
|
|
48
|
+
OnErrorCallback,
|
|
49
|
+
ResolvedRouteMap,
|
|
50
|
+
RouteDefinition,
|
|
51
|
+
RouteEntry,
|
|
52
|
+
TrailingSlashMode,
|
|
53
|
+
} from "./types";
|
|
54
|
+
import type {
|
|
55
|
+
NonceProvider,
|
|
56
|
+
} from "./rsc/types.js";
|
|
57
|
+
import type { ExecutionContext } from "./server/request-context.js";
|
|
58
|
+
|
|
59
|
+
// Extracted router utilities
|
|
60
|
+
import {
|
|
61
|
+
createErrorInfo,
|
|
62
|
+
findNearestErrorBoundary as findErrorBoundary,
|
|
63
|
+
findNearestNotFoundBoundary as findNotFoundBoundary,
|
|
64
|
+
invokeOnError,
|
|
65
|
+
} from "./router/error-handling.js";
|
|
66
|
+
|
|
67
|
+
// Extracted segment resolution functions
|
|
68
|
+
import {
|
|
69
|
+
resolveAllSegments as _resolveAllSegments,
|
|
70
|
+
resolveLoadersOnly as _resolveLoadersOnly,
|
|
71
|
+
resolveLoadersOnlyWithRevalidation as _resolveLoadersOnlyWithRevalidation,
|
|
72
|
+
buildEntryRevalidateMap as _buildEntryRevalidateMap,
|
|
73
|
+
resolveAllSegmentsWithRevalidation as _resolveAllSegmentsWithRevalidation,
|
|
74
|
+
} from "./router/segment-resolution.js";
|
|
75
|
+
|
|
76
|
+
// Extracted intercept resolution functions
|
|
77
|
+
import {
|
|
78
|
+
findInterceptForRoute as _findInterceptForRoute,
|
|
79
|
+
resolveInterceptEntry as _resolveInterceptEntry,
|
|
80
|
+
resolveInterceptLoadersOnly as _resolveInterceptLoadersOnly,
|
|
81
|
+
} from "./router/intercept-resolution.js";
|
|
82
|
+
|
|
83
|
+
// Extracted match API functions
|
|
84
|
+
import {
|
|
85
|
+
createMatchContextForFull as _createMatchContextForFull,
|
|
86
|
+
createMatchContextForPartial as _createMatchContextForPartial,
|
|
87
|
+
matchError as _matchError,
|
|
88
|
+
} from "./router/match-api.js";
|
|
89
|
+
|
|
90
|
+
import type { SegmentResolutionDeps, MatchApiDeps } from "./router/types.js";
|
|
91
|
+
import { createHandlerContext } from "./router/handler-context.js";
|
|
92
|
+
import {
|
|
93
|
+
setupLoaderAccess,
|
|
94
|
+
setupLoaderAccessSilent,
|
|
95
|
+
wrapLoaderWithErrorHandling,
|
|
96
|
+
} from "./router/loader-resolution.js";
|
|
97
|
+
import { loadManifest } from "./router/manifest.js";
|
|
98
|
+
import {
|
|
99
|
+
createMetricsStore,
|
|
100
|
+
} from "./router/metrics.js";
|
|
101
|
+
import {
|
|
102
|
+
collectRouteMiddleware,
|
|
103
|
+
parsePattern,
|
|
104
|
+
type MiddlewareEntry,
|
|
105
|
+
type MiddlewareFn,
|
|
106
|
+
} from "./router/middleware.js";
|
|
107
|
+
import {
|
|
108
|
+
extractStaticPrefix,
|
|
109
|
+
findMatch as findRouteMatch,
|
|
110
|
+
isLazyEvaluationNeeded,
|
|
111
|
+
traverseBack,
|
|
112
|
+
type RouteMatchResult,
|
|
113
|
+
} from "./router/pattern-matching.js";
|
|
114
|
+
import { evaluateRevalidation } from "./router/revalidation.js";
|
|
115
|
+
import {
|
|
116
|
+
type RouterContext,
|
|
117
|
+
runWithRouterContext,
|
|
118
|
+
} from "./router/router-context.js";
|
|
119
|
+
import {
|
|
120
|
+
type ActionContext,
|
|
121
|
+
type MatchContext,
|
|
122
|
+
createPipelineState,
|
|
123
|
+
} from "./router/match-context.js";
|
|
124
|
+
import { createMatchPartialPipeline } from "./router/match-pipelines.js";
|
|
125
|
+
import { collectMatchResult } from "./router/match-result.js";
|
|
126
|
+
import { resolveThemeConfig } from "./theme/constants.js";
|
|
127
|
+
|
|
128
|
+
// Response type -> MIME type used for Accept header matching
|
|
129
|
+
const RESPONSE_TYPE_MIME: Record<string, string> = {
|
|
130
|
+
json: "application/json",
|
|
131
|
+
text: "text/plain",
|
|
132
|
+
xml: "application/xml",
|
|
133
|
+
html: "text/html",
|
|
134
|
+
md: "text/markdown",
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
// Reverse lookup: MIME type -> response type tag (e.g. "text/html" -> "html")
|
|
138
|
+
const MIME_RESPONSE_TYPE: Record<string, string> = Object.fromEntries(
|
|
139
|
+
Object.entries(RESPONSE_TYPE_MIME).map(([tag, mime]) => [mime, tag]),
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
interface AcceptEntry {
|
|
143
|
+
mime: string;
|
|
144
|
+
q: number;
|
|
145
|
+
order: number;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Parse an Accept header into a sorted array of MIME entries.
|
|
150
|
+
* Respects q-values (default 1.0) and uses client order as tiebreaker
|
|
151
|
+
* when q-values are equal (matching Express/Hono behavior).
|
|
152
|
+
*/
|
|
153
|
+
function parseAcceptTypes(accept: string): AcceptEntry[] {
|
|
154
|
+
const entries: AcceptEntry[] = [];
|
|
155
|
+
const parts = accept.split(",");
|
|
156
|
+
for (let i = 0; i < parts.length; i++) {
|
|
157
|
+
const part = parts[i]!;
|
|
158
|
+
const segments = part.split(";");
|
|
159
|
+
const mime = segments[0]!.trim();
|
|
160
|
+
if (!mime) continue;
|
|
161
|
+
let q = 1.0;
|
|
162
|
+
for (let j = 1; j < segments.length; j++) {
|
|
163
|
+
const param = segments[j]!.trim();
|
|
164
|
+
if (param.startsWith("q=")) {
|
|
165
|
+
q = Math.max(0, Math.min(1, Number(param.slice(2)) || 0));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
entries.push({ mime, q, order: i });
|
|
169
|
+
}
|
|
170
|
+
// Sort: highest q first, then lowest client order first (stable)
|
|
171
|
+
entries.sort((a, b) => b.q - a.q || a.order - b.order);
|
|
172
|
+
return entries;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Sentinel response type for RSC routes in negotiation candidates
|
|
176
|
+
const RSC_RESPONSE_TYPE = "__rsc__";
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Pick the best negotiate variant by walking the client's sorted Accept list.
|
|
180
|
+
* For each accepted MIME type (in q-value/order priority), check if any
|
|
181
|
+
* candidate serves that type. Wildcards (*\/*) match the first candidate.
|
|
182
|
+
* Falls back to the first candidate if nothing matches.
|
|
183
|
+
*/
|
|
184
|
+
function pickNegotiateVariant(
|
|
185
|
+
acceptEntries: AcceptEntry[],
|
|
186
|
+
candidates: Array<{ routeKey: string; responseType: string }>,
|
|
187
|
+
): { routeKey: string; responseType: string } {
|
|
188
|
+
// Build a MIME -> candidate lookup for O(1) matching
|
|
189
|
+
const byCandidateMime = new Map<string, { routeKey: string; responseType: string }>();
|
|
190
|
+
for (const c of candidates) {
|
|
191
|
+
const mime = c.responseType === RSC_RESPONSE_TYPE ? "text/html" : RESPONSE_TYPE_MIME[c.responseType];
|
|
192
|
+
if (mime && !byCandidateMime.has(mime)) {
|
|
193
|
+
byCandidateMime.set(mime, c);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
for (const entry of acceptEntries) {
|
|
198
|
+
if (entry.q === 0) continue;
|
|
199
|
+
// Wildcard matches first candidate
|
|
200
|
+
if (entry.mime === "*/*") return candidates[0]!;
|
|
201
|
+
// Type wildcard (e.g. "text/*") — match first candidate with that type
|
|
202
|
+
if (entry.mime.endsWith("/*")) {
|
|
203
|
+
const typePrefix = entry.mime.slice(0, entry.mime.indexOf("/"));
|
|
204
|
+
for (const [mime, candidate] of byCandidateMime) {
|
|
205
|
+
if (mime.startsWith(typePrefix + "/")) return candidate;
|
|
206
|
+
}
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const match = byCandidateMime.get(entry.mime);
|
|
210
|
+
if (match) return match;
|
|
211
|
+
}
|
|
212
|
+
// No match — use first candidate as default
|
|
213
|
+
return candidates[0]!;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Props passed to the root layout component
|
|
218
|
+
*/
|
|
219
|
+
export interface RootLayoutProps {
|
|
220
|
+
children: ReactNode;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Router configuration options
|
|
225
|
+
*/
|
|
226
|
+
/**
|
|
227
|
+
* Brand marker for identifying router instances at build time.
|
|
228
|
+
* Used by the Vite plugin to auto-discover routers from module exports.
|
|
229
|
+
*/
|
|
230
|
+
export const RSC_ROUTER_BRAND: "__rsc_router__" = "__rsc_router__";
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Global registry of all router instances created via createRouter().
|
|
234
|
+
* Each router is keyed by its id (auto-generated or user-provided).
|
|
235
|
+
* Used by the Vite plugin at build time to discover routers and extract
|
|
236
|
+
* manifests, prefix trees, and pre-render candidates.
|
|
237
|
+
*/
|
|
238
|
+
export const RouterRegistry: Map<string, RSCRouter<any, any>> = new Map();
|
|
239
|
+
|
|
240
|
+
let routerAutoId = 0;
|
|
241
|
+
|
|
242
|
+
export interface RSCRouterOptions<TEnv = any> {
|
|
243
|
+
/**
|
|
244
|
+
* Unique identifier for this router instance.
|
|
245
|
+
* Used to namespace static output files and route maps.
|
|
246
|
+
* Auto-generated if not provided.
|
|
247
|
+
*/
|
|
248
|
+
id?: string;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Enable performance metrics collection
|
|
252
|
+
* When enabled, metrics are output to console and available via Server-Timing header
|
|
253
|
+
*/
|
|
254
|
+
debugPerformance?: boolean;
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Allow the `?__debug_manifest` query parameter to return route manifest data as JSON.
|
|
258
|
+
* In development mode this is always enabled regardless of this setting.
|
|
259
|
+
* Defaults to true. Set to false to disable in production.
|
|
260
|
+
* @internal
|
|
261
|
+
*/
|
|
262
|
+
allowDebugManifest?: boolean;
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Document component that wraps the entire application.
|
|
266
|
+
*
|
|
267
|
+
* This component provides the HTML structure for your app and wraps
|
|
268
|
+
* both normal route content AND error states, preventing the app shell
|
|
269
|
+
* from unmounting during errors (avoids FOUC).
|
|
270
|
+
*
|
|
271
|
+
* Must be a client component ("use client") that accepts { children }.
|
|
272
|
+
*
|
|
273
|
+
* If not provided, a default document with basic HTML structure is used:
|
|
274
|
+
* `<html><head><meta charset/viewport></head><body>{children}</body></html>`
|
|
275
|
+
*
|
|
276
|
+
* @example
|
|
277
|
+
* ```typescript
|
|
278
|
+
* // components/Document.tsx
|
|
279
|
+
* "use client";
|
|
280
|
+
* export function Document({ children }: { children: ReactNode }) {
|
|
281
|
+
* return (
|
|
282
|
+
* <html lang="en">
|
|
283
|
+
* <head>
|
|
284
|
+
* <link rel="stylesheet" href="/styles.css" />
|
|
285
|
+
* </head>
|
|
286
|
+
* <body>
|
|
287
|
+
* <nav>...</nav>
|
|
288
|
+
* {children}
|
|
289
|
+
* </body>
|
|
290
|
+
* </html>
|
|
291
|
+
* );
|
|
292
|
+
* }
|
|
293
|
+
*
|
|
294
|
+
* // router.tsx
|
|
295
|
+
* const router = createRouter<AppEnv>({
|
|
296
|
+
* document: Document,
|
|
297
|
+
* });
|
|
298
|
+
* ```
|
|
299
|
+
*/
|
|
300
|
+
document?: ComponentType<RootLayoutProps>;
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Default error boundary fallback used when no error boundary is defined in the route tree
|
|
304
|
+
* If not provided, errors will propagate and crash the request
|
|
305
|
+
*/
|
|
306
|
+
defaultErrorBoundary?: ReactNode | ErrorBoundaryHandler;
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Default not-found boundary fallback used when no notFoundBoundary is defined in the route tree
|
|
310
|
+
* If not provided, DataNotFoundError will be treated as a regular error
|
|
311
|
+
*/
|
|
312
|
+
defaultNotFoundBoundary?: ReactNode | NotFoundBoundaryHandler;
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Component to render when no route matches the requested URL.
|
|
316
|
+
*
|
|
317
|
+
* This is rendered within your document/app shell with a 404 status code.
|
|
318
|
+
* Use this for a custom 404 page that maintains your app's look and feel.
|
|
319
|
+
*
|
|
320
|
+
* If not provided, a default "Page not found" component is rendered.
|
|
321
|
+
*
|
|
322
|
+
* Can be a static ReactNode or a function receiving the pathname.
|
|
323
|
+
*
|
|
324
|
+
* @example
|
|
325
|
+
* ```typescript
|
|
326
|
+
* // Simple static component
|
|
327
|
+
* const router = createRouter<AppEnv>({
|
|
328
|
+
* document: Document,
|
|
329
|
+
* notFound: <NotFound404 />,
|
|
330
|
+
* });
|
|
331
|
+
*
|
|
332
|
+
* // Dynamic component with pathname
|
|
333
|
+
* const router = createRouter<AppEnv>({
|
|
334
|
+
* document: Document,
|
|
335
|
+
* notFound: ({ pathname }) => (
|
|
336
|
+
* <div>
|
|
337
|
+
* <h1>404 - Not Found</h1>
|
|
338
|
+
* <p>No page exists at {pathname}</p>
|
|
339
|
+
* <a href="/">Go home</a>
|
|
340
|
+
* </div>
|
|
341
|
+
* ),
|
|
342
|
+
* });
|
|
343
|
+
* ```
|
|
344
|
+
*/
|
|
345
|
+
notFound?: ReactNode | ((props: { pathname: string }) => ReactNode);
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Callback invoked when an error occurs during request handling.
|
|
349
|
+
*
|
|
350
|
+
* This callback is for notification/logging purposes - it cannot modify
|
|
351
|
+
* the error handling flow. Use errorBoundary() in route definitions to
|
|
352
|
+
* customize error UI.
|
|
353
|
+
*
|
|
354
|
+
* The callback receives comprehensive context about the error including:
|
|
355
|
+
* - The error itself
|
|
356
|
+
* - Phase where it occurred (routing, middleware, loader, handler, etc.)
|
|
357
|
+
* - Request info (URL, method, params)
|
|
358
|
+
* - Route info (routeKey, segmentId)
|
|
359
|
+
* - Environment/bindings
|
|
360
|
+
* - Duration from request start
|
|
361
|
+
*
|
|
362
|
+
* @example
|
|
363
|
+
* ```typescript
|
|
364
|
+
* const router = createRouter<AppEnv>({
|
|
365
|
+
* onError: (context) => {
|
|
366
|
+
* // Send to error tracking service
|
|
367
|
+
* Sentry.captureException(context.error, {
|
|
368
|
+
* tags: {
|
|
369
|
+
* phase: context.phase,
|
|
370
|
+
* route: context.routeKey,
|
|
371
|
+
* },
|
|
372
|
+
* extra: {
|
|
373
|
+
* url: context.url.toString(),
|
|
374
|
+
* params: context.params,
|
|
375
|
+
* duration: context.duration,
|
|
376
|
+
* },
|
|
377
|
+
* });
|
|
378
|
+
* },
|
|
379
|
+
* });
|
|
380
|
+
* ```
|
|
381
|
+
*/
|
|
382
|
+
onError?: OnErrorCallback<TEnv>;
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Cache store for segment caching.
|
|
386
|
+
*
|
|
387
|
+
* When provided, enables route-level caching via cache() boundaries.
|
|
388
|
+
* The store handles persistence (memory, KV, Redis, etc.).
|
|
389
|
+
*
|
|
390
|
+
* Can be a static config or a function receiving env for runtime bindings.
|
|
391
|
+
*
|
|
392
|
+
* @example Static config
|
|
393
|
+
* ```typescript
|
|
394
|
+
* import { MemorySegmentCacheStore } from "rsc-router/rsc";
|
|
395
|
+
*
|
|
396
|
+
* const router = createRouter({
|
|
397
|
+
* cache: {
|
|
398
|
+
* store: new MemorySegmentCacheStore({ defaults: { ttl: 60 } }),
|
|
399
|
+
* },
|
|
400
|
+
* });
|
|
401
|
+
* ```
|
|
402
|
+
*
|
|
403
|
+
* @example Dynamic config with env (e.g., Cloudflare Workers with ExecutionContext)
|
|
404
|
+
* ```typescript
|
|
405
|
+
* const router = createRouter<AppEnv>({
|
|
406
|
+
* cache: (env) => ({
|
|
407
|
+
* store: new CFCacheStore({
|
|
408
|
+
* defaults: { ttl: 60 },
|
|
409
|
+
* ctx: env.ctx, // ExecutionContext for non-blocking writes
|
|
410
|
+
* }),
|
|
411
|
+
* }),
|
|
412
|
+
* });
|
|
413
|
+
* ```
|
|
414
|
+
*/
|
|
415
|
+
cache?:
|
|
416
|
+
| { store: SegmentCacheStore; enabled?: boolean }
|
|
417
|
+
| ((env: TEnv & { ctx?: ExecutionContext }) => {
|
|
418
|
+
store: SegmentCacheStore;
|
|
419
|
+
enabled?: boolean;
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Theme configuration for automatic theme management.
|
|
424
|
+
*
|
|
425
|
+
* When provided, enables:
|
|
426
|
+
* - ctx.theme and ctx.setTheme() in route handlers
|
|
427
|
+
* - useTheme() hook for client components
|
|
428
|
+
* - FOUC prevention via inline script in MetaTags
|
|
429
|
+
* - Automatic ThemeProvider wrapping in NavigationProvider
|
|
430
|
+
*
|
|
431
|
+
* @example
|
|
432
|
+
* ```typescript
|
|
433
|
+
* const router = createRouter<AppEnv>({
|
|
434
|
+
* theme: {
|
|
435
|
+
* defaultTheme: "system",
|
|
436
|
+
* themes: ["light", "dark"],
|
|
437
|
+
* }
|
|
438
|
+
* });
|
|
439
|
+
*
|
|
440
|
+
* // In route handler:
|
|
441
|
+
* route("settings", (ctx) => {
|
|
442
|
+
* const theme = ctx.theme; // "light" | "dark" | "system"
|
|
443
|
+
* ctx.setTheme("dark"); // Sets cookie
|
|
444
|
+
* return <SettingsPage />;
|
|
445
|
+
* });
|
|
446
|
+
*
|
|
447
|
+
* // In client component:
|
|
448
|
+
* import { useTheme } from "@rangojs/router/theme";
|
|
449
|
+
*
|
|
450
|
+
* function ThemeToggle() {
|
|
451
|
+
* const { theme, setTheme, themes } = useTheme();
|
|
452
|
+
* return <select value={theme} onChange={e => setTheme(e.target.value)}>
|
|
453
|
+
* {themes.map(t => <option key={t}>{t}</option>)}
|
|
454
|
+
* </select>;
|
|
455
|
+
* }
|
|
456
|
+
* ```
|
|
457
|
+
*
|
|
458
|
+
* Use `theme: true` to enable with all defaults.
|
|
459
|
+
*/
|
|
460
|
+
theme?: import("./theme/types.js").ThemeConfig | true;
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* URL patterns to register with the router.
|
|
464
|
+
*
|
|
465
|
+
* Alternative to calling `.routes()` method - allows passing patterns
|
|
466
|
+
* directly in the config for a more concise setup.
|
|
467
|
+
*
|
|
468
|
+
* @example
|
|
469
|
+
* ```typescript
|
|
470
|
+
* import { urls } from "@rangojs/router/server";
|
|
471
|
+
*
|
|
472
|
+
* const urlpatterns = urls(({ path, layout }) => [
|
|
473
|
+
* path("/", HomePage, { name: "home" }),
|
|
474
|
+
* path("/about", AboutPage, { name: "about" }),
|
|
475
|
+
* ]);
|
|
476
|
+
*
|
|
477
|
+
* const router = createRouter<AppEnv>({
|
|
478
|
+
* document: Document,
|
|
479
|
+
* urls: urlpatterns,
|
|
480
|
+
* });
|
|
481
|
+
* ```
|
|
482
|
+
*/
|
|
483
|
+
urls?: UrlPatterns<TEnv, any>;
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Nonce provider for Content Security Policy (CSP).
|
|
487
|
+
*
|
|
488
|
+
* Can be:
|
|
489
|
+
* - A function that returns a nonce string
|
|
490
|
+
* - A function that returns `true` to auto-generate a nonce
|
|
491
|
+
* - Undefined to disable nonce (default)
|
|
492
|
+
*
|
|
493
|
+
* The nonce will be applied to inline scripts injected by the RSC payload.
|
|
494
|
+
* It's also available to middleware via `ctx.get('nonce')`.
|
|
495
|
+
*
|
|
496
|
+
* @example Auto-generate nonce
|
|
497
|
+
* ```tsx
|
|
498
|
+
* createRouter({
|
|
499
|
+
* nonce: () => true,
|
|
500
|
+
* });
|
|
501
|
+
* ```
|
|
502
|
+
*
|
|
503
|
+
* @example Custom nonce from request context
|
|
504
|
+
* ```tsx
|
|
505
|
+
* createRouter({
|
|
506
|
+
* nonce: (request, env) => env.nonce,
|
|
507
|
+
* });
|
|
508
|
+
* ```
|
|
509
|
+
*/
|
|
510
|
+
nonce?: NonceProvider<TEnv>;
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* RSC version string included in metadata.
|
|
514
|
+
* The browser sends this back on partial requests to detect version mismatches.
|
|
515
|
+
*
|
|
516
|
+
* Defaults to the auto-generated VERSION from `@rangojs/router:version` virtual module.
|
|
517
|
+
* Only set this if you need a custom versioning strategy.
|
|
518
|
+
*
|
|
519
|
+
* @default VERSION from @rangojs/router:version
|
|
520
|
+
*/
|
|
521
|
+
version?: string;
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Enable connection warmup to keep TCP+TLS alive after idle periods.
|
|
525
|
+
*
|
|
526
|
+
* When enabled, the client sends a HEAD request after the user returns
|
|
527
|
+
* from an idle period (60s+), prewarming the TLS connection before
|
|
528
|
+
* the next navigation.
|
|
529
|
+
*
|
|
530
|
+
* @default true
|
|
531
|
+
*/
|
|
532
|
+
warmup?: boolean;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Merge route patterns with response types into a single route map.
|
|
537
|
+
* Routes with response types get { path, response } objects; others stay as strings.
|
|
538
|
+
*/
|
|
539
|
+
type MergeRoutesWithResponses<
|
|
540
|
+
TRoutes extends Record<string, string>,
|
|
541
|
+
TResponses,
|
|
542
|
+
> = {
|
|
543
|
+
[K in keyof TRoutes]: K extends keyof NonNullable<TResponses>
|
|
544
|
+
? unknown extends NonNullable<TResponses>[K]
|
|
545
|
+
? TRoutes[K] // RSC route — TData defaults to unknown, keep as plain string
|
|
546
|
+
: { readonly path: TRoutes[K]; readonly response: NonNullable<TResponses>[K] }
|
|
547
|
+
: TRoutes[K]
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Extract the URL pattern from a route entry (string or { path, response } object)
|
|
552
|
+
*/
|
|
553
|
+
type PatternOfEntry<V> =
|
|
554
|
+
V extends string ? V
|
|
555
|
+
: V extends { readonly path: infer P extends string } ? P
|
|
556
|
+
: never;
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Type-level detection of conflicting route keys.
|
|
560
|
+
* Extracts keys that exist in both TExisting and TNew but with different URL patterns.
|
|
561
|
+
* Returns `never` if no conflicts exist.
|
|
562
|
+
* Compares patterns (not full entries) to handle both string and { path, response } values.
|
|
563
|
+
*
|
|
564
|
+
* @example
|
|
565
|
+
* ```typescript
|
|
566
|
+
* ConflictingKeys<{ a: "/a" }, { a: "/b" }> // "a" (conflict - same key, different URLs)
|
|
567
|
+
* ConflictingKeys<{ a: "/a" }, { a: "/a" }> // never (no conflict - same key and URL)
|
|
568
|
+
* ConflictingKeys<{ a: "/a" }, { b: "/b" }> // never (no conflict - different keys)
|
|
569
|
+
* ```
|
|
570
|
+
*/
|
|
571
|
+
type ConflictingKeys<
|
|
572
|
+
TExisting extends Record<string, unknown>,
|
|
573
|
+
TNew extends Record<string, unknown>,
|
|
574
|
+
> = {
|
|
575
|
+
[K in keyof TExisting & keyof TNew]: PatternOfEntry<TExisting[K]> extends PatternOfEntry<TNew[K]>
|
|
576
|
+
? PatternOfEntry<TNew[K]> extends PatternOfEntry<TExisting[K]>
|
|
577
|
+
? never // Same pattern, no conflict
|
|
578
|
+
: K // Different patterns, conflict
|
|
579
|
+
: K; // Different patterns, conflict
|
|
580
|
+
}[keyof TExisting & keyof TNew];
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Error type returned when route keys conflict.
|
|
584
|
+
* Methods require an impossible `never` parameter so TypeScript errors at the call site.
|
|
585
|
+
*/
|
|
586
|
+
type RouteConflictError<TConflicts extends string> = {
|
|
587
|
+
__error: `Route key conflict! Key "${TConflicts}" already exists with a different URL pattern.`;
|
|
588
|
+
hint: "Route keys must be globally unique. Use prefixed names like 'blog.index' instead of 'index'.";
|
|
589
|
+
conflictingKeys: TConflicts;
|
|
590
|
+
// These methods require `never` so calling them produces an error at the call site
|
|
591
|
+
routes: (
|
|
592
|
+
__conflict: `Fix route key conflict: "${TConflicts}" is already defined with a different URL pattern`,
|
|
593
|
+
) => never;
|
|
594
|
+
map: (
|
|
595
|
+
__conflict: `Fix route key conflict: "${TConflicts}" is already defined with a different URL pattern`,
|
|
596
|
+
) => never;
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Simplified route helpers for inline route definitions.
|
|
601
|
+
* Uses TRoutes (Record<string, string>) instead of RouteDefinition.
|
|
602
|
+
*
|
|
603
|
+
* Note: Some helpers use `any` for context types as a trade-off for simpler usage.
|
|
604
|
+
* The main type safety is in the `route` helper which enforces valid route names.
|
|
605
|
+
* For full type safety, use the standard map() API with separate handler files.
|
|
606
|
+
*/
|
|
607
|
+
type InlineRouteHelpers<TRoutes extends Record<string, string>, TEnv> = {
|
|
608
|
+
/**
|
|
609
|
+
* Define a route handler for a specific route pattern
|
|
610
|
+
*/
|
|
611
|
+
route: <K extends keyof TRoutes & string>(
|
|
612
|
+
name: K,
|
|
613
|
+
handler:
|
|
614
|
+
| ((ctx: HandlerContext<{}, TEnv>) => ReactNode | Promise<ReactNode>)
|
|
615
|
+
| ReactNode,
|
|
616
|
+
) => AllUseItems;
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Define a layout that wraps child routes
|
|
620
|
+
*/
|
|
621
|
+
layout: (
|
|
622
|
+
component:
|
|
623
|
+
| ReactNode
|
|
624
|
+
| ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>),
|
|
625
|
+
use?: () => AllUseItems[],
|
|
626
|
+
) => AllUseItems;
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Define parallel routes
|
|
630
|
+
*/
|
|
631
|
+
parallel: (
|
|
632
|
+
slots: Record<
|
|
633
|
+
`@${string}`,
|
|
634
|
+
| ReactNode
|
|
635
|
+
| ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>)
|
|
636
|
+
>,
|
|
637
|
+
use?: () => AllUseItems[],
|
|
638
|
+
) => AllUseItems;
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Define route middleware
|
|
642
|
+
*/
|
|
643
|
+
middleware: (
|
|
644
|
+
fn: (ctx: any, next: () => Promise<void>) => Promise<void>,
|
|
645
|
+
) => AllUseItems;
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Define revalidation handlers
|
|
649
|
+
*/
|
|
650
|
+
revalidate: (fn: (ctx: any) => boolean | Promise<boolean>) => AllUseItems;
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Define data loaders
|
|
654
|
+
*/
|
|
655
|
+
loader: (loader: any, use?: () => AllUseItems[]) => AllUseItems;
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Define loading states
|
|
659
|
+
*/
|
|
660
|
+
loading: (component: ReactNode) => AllUseItems;
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Define error boundaries
|
|
664
|
+
*/
|
|
665
|
+
errorBoundary: (
|
|
666
|
+
handler: ReactNode | ((props: { error: Error }) => ReactNode),
|
|
667
|
+
) => AllUseItems;
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Define not found boundaries
|
|
671
|
+
*/
|
|
672
|
+
notFoundBoundary: (
|
|
673
|
+
handler: ReactNode | ((props: { pathname: string }) => ReactNode),
|
|
674
|
+
) => AllUseItems;
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
* Define intercept routes
|
|
678
|
+
*/
|
|
679
|
+
intercept: (
|
|
680
|
+
name: string,
|
|
681
|
+
handler:
|
|
682
|
+
| ReactNode
|
|
683
|
+
| ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>),
|
|
684
|
+
use?: () => AllUseItems[],
|
|
685
|
+
) => AllUseItems;
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Define when conditions for intercepts
|
|
689
|
+
*/
|
|
690
|
+
when: (condition: (ctx: any) => boolean | Promise<boolean>) => AllUseItems;
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* Define cache configuration
|
|
694
|
+
*/
|
|
695
|
+
cache: (
|
|
696
|
+
config: { ttl?: number; swr?: number } | false,
|
|
697
|
+
use?: () => AllUseItems[],
|
|
698
|
+
) => AllUseItems;
|
|
699
|
+
};
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* Router builder for chaining .use() and .map()
|
|
703
|
+
* TRoutes accumulates all registered route types through the chain
|
|
704
|
+
* TLocalRoutes contains the routes for the current .routes() call (for inline handler typing)
|
|
705
|
+
*/
|
|
706
|
+
interface RouteBuilder<
|
|
707
|
+
T extends RouteDefinition,
|
|
708
|
+
TEnv,
|
|
709
|
+
TRoutes extends Record<string, unknown>,
|
|
710
|
+
TLocalRoutes extends Record<string, string> = Record<string, string>,
|
|
711
|
+
> {
|
|
712
|
+
/**
|
|
713
|
+
* Add middleware scoped to this mount
|
|
714
|
+
* Called between .routes() and .map()
|
|
715
|
+
*
|
|
716
|
+
* @example
|
|
717
|
+
* ```typescript
|
|
718
|
+
* .routes("/admin", adminRoutes)
|
|
719
|
+
* .use(authMiddleware) // All of /admin/*
|
|
720
|
+
* .use("/danger/*", superAuth) // Only /admin/danger/*
|
|
721
|
+
* .map(() => import("./admin"))
|
|
722
|
+
* ```
|
|
723
|
+
*/
|
|
724
|
+
use(
|
|
725
|
+
patternOrMiddleware: string | MiddlewareFn<TEnv>,
|
|
726
|
+
middleware?: MiddlewareFn<TEnv>,
|
|
727
|
+
): RouteBuilder<T, TEnv, TRoutes, TLocalRoutes>;
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Map routes to handlers
|
|
731
|
+
*
|
|
732
|
+
* Supports two patterns:
|
|
733
|
+
*
|
|
734
|
+
* 1. Lazy loading (code-split):
|
|
735
|
+
* ```typescript
|
|
736
|
+
* .routes(homeRoutes)
|
|
737
|
+
* .map(() => import("./handlers/home"))
|
|
738
|
+
* ```
|
|
739
|
+
*
|
|
740
|
+
* 2. Inline definition:
|
|
741
|
+
* ```typescript
|
|
742
|
+
* .routes({ index: "/", about: "/about" })
|
|
743
|
+
* .map(({ route }) => [
|
|
744
|
+
* route("index", () => <HomePage />),
|
|
745
|
+
* route("about", () => <AboutPage />),
|
|
746
|
+
* ])
|
|
747
|
+
* ```
|
|
748
|
+
*/
|
|
749
|
+
// Inline definition overload - handler receives helpers (must be first for correct inference)
|
|
750
|
+
// Uses TLocalRoutes so route names don't need the prefix
|
|
751
|
+
map<
|
|
752
|
+
H extends (
|
|
753
|
+
helpers: InlineRouteHelpers<TLocalRoutes, TEnv>,
|
|
754
|
+
) => Array<AllUseItems>,
|
|
755
|
+
>(
|
|
756
|
+
handler: H,
|
|
757
|
+
): RSCRouter<TEnv, TRoutes>;
|
|
758
|
+
// Lazy loading overload - verifies imported handlers match route definition
|
|
759
|
+
map(
|
|
760
|
+
handler: () =>
|
|
761
|
+
| Array<AllUseItems>
|
|
762
|
+
| Promise<{ default: RouteHandlers<TLocalRoutes> }>
|
|
763
|
+
| Promise<RouteHandlers<TLocalRoutes>>,
|
|
764
|
+
): RSCRouter<TEnv, TRoutes>;
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Accumulated route map for typeof extraction
|
|
768
|
+
* Used for module augmentation: `type AppRoutes = typeof _router.routeMap`
|
|
769
|
+
*/
|
|
770
|
+
readonly routeMap: TRoutes;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* RSC Router interface
|
|
775
|
+
* TRoutes accumulates all registered route types through the builder chain
|
|
776
|
+
*/
|
|
777
|
+
export interface RSCRouter<
|
|
778
|
+
TEnv = any,
|
|
779
|
+
TRoutes extends Record<string, unknown> = Record<string, string>,
|
|
780
|
+
> {
|
|
781
|
+
/**
|
|
782
|
+
* Brand marker for build-time discovery.
|
|
783
|
+
* The Vite plugin uses this to identify router instances in module exports.
|
|
784
|
+
*/
|
|
785
|
+
readonly __brand: typeof RSC_ROUTER_BRAND;
|
|
786
|
+
|
|
787
|
+
/**
|
|
788
|
+
* Unique identifier for this router instance.
|
|
789
|
+
* Used to namespace static output and isolate route maps between routers.
|
|
790
|
+
*/
|
|
791
|
+
readonly id: string;
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* Register routes with a prefix
|
|
795
|
+
* Route keys stay unchanged, only URL patterns get the prefix applied.
|
|
796
|
+
* This enables composable route modules that work regardless of mount point.
|
|
797
|
+
*
|
|
798
|
+
* @throws Compile-time error if route keys conflict with previously registered routes
|
|
799
|
+
*/
|
|
800
|
+
routes<const TPrefix extends string, const T extends Record<string, string>>(
|
|
801
|
+
prefix: TPrefix,
|
|
802
|
+
routes: T,
|
|
803
|
+
): ConflictingKeys<TRoutes, PrefixRoutePatterns<T, TPrefix>> extends never
|
|
804
|
+
? RouteBuilder<
|
|
805
|
+
RouteDefinition,
|
|
806
|
+
TEnv,
|
|
807
|
+
TRoutes & PrefixRoutePatterns<T, TPrefix>,
|
|
808
|
+
T
|
|
809
|
+
>
|
|
810
|
+
: RouteConflictError<
|
|
811
|
+
ConflictingKeys<TRoutes, PrefixRoutePatterns<T, TPrefix>> & string
|
|
812
|
+
>;
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* Register routes without a prefix
|
|
816
|
+
* Route types are accumulated through the chain
|
|
817
|
+
*
|
|
818
|
+
* @throws Compile-time error if route keys conflict with previously registered routes
|
|
819
|
+
*/
|
|
820
|
+
routes<const T extends Record<string, string>>(
|
|
821
|
+
routes: T,
|
|
822
|
+
): ConflictingKeys<TRoutes, T> extends never
|
|
823
|
+
? RouteBuilder<RouteDefinition, TEnv, TRoutes & T, T>
|
|
824
|
+
: RouteConflictError<ConflictingKeys<TRoutes, T> & string>;
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Register routes using Django-style URL patterns
|
|
828
|
+
* This is the new API for @rangojs/router - call once with urls() result
|
|
829
|
+
*
|
|
830
|
+
* @example
|
|
831
|
+
* ```typescript
|
|
832
|
+
* createRouter({})
|
|
833
|
+
* .routes(urlpatterns) // Single call with urls() result
|
|
834
|
+
* ```
|
|
835
|
+
*/
|
|
836
|
+
routes<T extends UrlPatterns<TEnv, any>>(
|
|
837
|
+
patterns: T,
|
|
838
|
+
): RSCRouter<
|
|
839
|
+
TEnv,
|
|
840
|
+
TRoutes &
|
|
841
|
+
(NonNullable<T["_routes"]> extends Record<string, string>
|
|
842
|
+
? MergeRoutesWithResponses<NonNullable<T["_routes"]>, T["_responses"]>
|
|
843
|
+
: Record<string, string>)
|
|
844
|
+
>;
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* Add global middleware that runs on all routes
|
|
848
|
+
* Position matters: middleware before any .routes() is global
|
|
849
|
+
*
|
|
850
|
+
* @example
|
|
851
|
+
* ```typescript
|
|
852
|
+
* createRouter({ document: RootLayout })
|
|
853
|
+
* .use(loggerMiddleware) // All routes
|
|
854
|
+
* .use("/api/*", rateLimiter) // Pattern match
|
|
855
|
+
* .routes(homeRoutes)
|
|
856
|
+
* .map(() => import("./home"))
|
|
857
|
+
* ```
|
|
858
|
+
*/
|
|
859
|
+
use(
|
|
860
|
+
patternOrMiddleware: string | MiddlewareFn<TEnv>,
|
|
861
|
+
middleware?: MiddlewareFn<TEnv>,
|
|
862
|
+
): RSCRouter<TEnv, TRoutes>;
|
|
863
|
+
|
|
864
|
+
/**
|
|
865
|
+
* Type-safe URL builder for registered routes
|
|
866
|
+
* Types are inferred from the accumulated route registrations
|
|
867
|
+
* Route keys stay unchanged regardless of mount prefix.
|
|
868
|
+
*
|
|
869
|
+
* @example
|
|
870
|
+
* ```typescript
|
|
871
|
+
* // Given: .routes("/shop", { cart: "/cart", detail: "/product/:slug" })
|
|
872
|
+
* router.reverse("cart"); // "/shop/cart"
|
|
873
|
+
* router.reverse("detail", { slug: "widget" }); // "/shop/product/widget"
|
|
874
|
+
* ```
|
|
875
|
+
*/
|
|
876
|
+
reverse: ReverseFunction<TRoutes>;
|
|
877
|
+
|
|
878
|
+
/**
|
|
879
|
+
* Accumulated route map for typeof extraction
|
|
880
|
+
* Used for module augmentation: `type AppRoutes = typeof _router.routeMap`
|
|
881
|
+
*
|
|
882
|
+
* @example
|
|
883
|
+
* ```typescript
|
|
884
|
+
* const _router = createRouter<AppEnv>()
|
|
885
|
+
* .routes(homeRoutes).map(() => import('./home'))
|
|
886
|
+
* .routes('/shop', shopRoutes).map(() => import('./shop'));
|
|
887
|
+
*
|
|
888
|
+
* type AppRoutes = typeof _router.routeMap;
|
|
889
|
+
*
|
|
890
|
+
* declare global {
|
|
891
|
+
* namespace RSCRouter {
|
|
892
|
+
* interface RegisteredRoutes extends AppRoutes {}
|
|
893
|
+
* }
|
|
894
|
+
* }
|
|
895
|
+
* ```
|
|
896
|
+
*/
|
|
897
|
+
readonly routeMap: TRoutes;
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Root layout component that wraps the entire application
|
|
901
|
+
* Access this to pass to renderSegments
|
|
902
|
+
*/
|
|
903
|
+
readonly rootLayout?: ComponentType<RootLayoutProps>;
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* Error callback for monitoring/alerting
|
|
907
|
+
* Called when errors occur in loaders, actions, or routes
|
|
908
|
+
*/
|
|
909
|
+
readonly onError?: RSCRouterOptions<TEnv>["onError"];
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* Cache configuration (for internal use by RSC handler)
|
|
913
|
+
*/
|
|
914
|
+
readonly cache?: RSCRouterOptions<TEnv>["cache"];
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Not found component to render when no route matches (for internal use by RSC handler)
|
|
918
|
+
*/
|
|
919
|
+
readonly notFound?: RSCRouterOptions<TEnv>["notFound"];
|
|
920
|
+
|
|
921
|
+
/**
|
|
922
|
+
* Resolved theme configuration (null if theme not enabled)
|
|
923
|
+
* Used by NavigationProvider to include ThemeProvider and by MetaTags to render theme script
|
|
924
|
+
*/
|
|
925
|
+
readonly themeConfig: import("./theme/types.js").ResolvedThemeConfig | null;
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* Whether connection warmup is enabled.
|
|
929
|
+
* When true, the client sends HEAD /?_rsc_warmup after idle periods
|
|
930
|
+
* and the server responds with 204 No Content.
|
|
931
|
+
*/
|
|
932
|
+
readonly warmupEnabled: boolean;
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* Whether ?__debug_manifest is allowed in production.
|
|
936
|
+
* Always enabled in development.
|
|
937
|
+
* @internal
|
|
938
|
+
*/
|
|
939
|
+
readonly allowDebugManifest: boolean;
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* App-level middleware entries (for internal use by RSC handler)
|
|
943
|
+
* These wrap the entire request/response cycle
|
|
944
|
+
*/
|
|
945
|
+
readonly middleware: MiddlewareEntry<TEnv>[];
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* Nonce provider for CSP (for internal use by createHandler)
|
|
949
|
+
*/
|
|
950
|
+
readonly nonce?: NonceProvider<TEnv>;
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* RSC version string (for internal use by createHandler)
|
|
954
|
+
*/
|
|
955
|
+
readonly version?: string;
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* URL patterns reference for build-time manifest generation
|
|
959
|
+
* @internal
|
|
960
|
+
*/
|
|
961
|
+
readonly urlpatterns?: UrlPatterns<TEnv, any>;
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* Source file path where createRouter() was called.
|
|
965
|
+
* Set via Error.stack parsing at construction time.
|
|
966
|
+
* Used by the Vite plugin to write per-router named-routes.gen.ts files.
|
|
967
|
+
* @internal
|
|
968
|
+
*/
|
|
969
|
+
readonly __sourceFile?: string;
|
|
970
|
+
|
|
971
|
+
match(request: Request, context: TEnv): Promise<MatchResult>;
|
|
972
|
+
|
|
973
|
+
/**
|
|
974
|
+
* Preview match - returns route middleware without segment resolution.
|
|
975
|
+
* Also returns responseType and handler for response routes (non-RSC short-circuit).
|
|
976
|
+
*/
|
|
977
|
+
previewMatch(
|
|
978
|
+
request: Request,
|
|
979
|
+
context: TEnv,
|
|
980
|
+
): Promise<{
|
|
981
|
+
routeMiddleware?: Array<{
|
|
982
|
+
handler: import("./router/middleware.js").MiddlewareFn;
|
|
983
|
+
params: Record<string, string>;
|
|
984
|
+
}>;
|
|
985
|
+
responseType?: string;
|
|
986
|
+
handler?: Function;
|
|
987
|
+
params?: Record<string, string>;
|
|
988
|
+
negotiated?: boolean;
|
|
989
|
+
} | null>;
|
|
990
|
+
|
|
991
|
+
matchPartial(
|
|
992
|
+
request: Request,
|
|
993
|
+
context: TEnv,
|
|
994
|
+
actionContext?: {
|
|
995
|
+
actionId?: string;
|
|
996
|
+
actionUrl?: URL;
|
|
997
|
+
actionResult?: any;
|
|
998
|
+
formData?: FormData;
|
|
999
|
+
},
|
|
1000
|
+
): Promise<MatchResult | null>;
|
|
1001
|
+
|
|
1002
|
+
/**
|
|
1003
|
+
* Match an error to the nearest error boundary and return error segments
|
|
1004
|
+
*
|
|
1005
|
+
* Used when an action or other operation fails and we need to render
|
|
1006
|
+
* the error boundary UI. Finds the nearest errorBoundary in the route tree
|
|
1007
|
+
* for the current URL and renders it with the error info.
|
|
1008
|
+
*
|
|
1009
|
+
* @param request - The current request (used to match the route)
|
|
1010
|
+
* @param context - Environment context
|
|
1011
|
+
* @param error - The error that occurred
|
|
1012
|
+
* @param segmentType - Type of segment where error occurred (default: "route")
|
|
1013
|
+
* @returns MatchResult with error segment, or null if no error boundary found
|
|
1014
|
+
*/
|
|
1015
|
+
matchError(
|
|
1016
|
+
request: Request,
|
|
1017
|
+
context: TEnv,
|
|
1018
|
+
error: unknown,
|
|
1019
|
+
segmentType?: ErrorInfo["segmentType"],
|
|
1020
|
+
): Promise<MatchResult | null>;
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* @internal
|
|
1024
|
+
* Debug utility to serialize the manifest for inspection
|
|
1025
|
+
* Returns a JSON-friendly representation of all routes and layouts
|
|
1026
|
+
*/
|
|
1027
|
+
debugManifest(): Promise<SerializedManifest>;
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* Handle an RSC request.
|
|
1031
|
+
*
|
|
1032
|
+
* Uses the router's configuration (nonce, version, cache) automatically.
|
|
1033
|
+
* The handler is lazily created on first call.
|
|
1034
|
+
*
|
|
1035
|
+
* @example Cloudflare Workers
|
|
1036
|
+
* ```tsx
|
|
1037
|
+
* import { router } from "./router";
|
|
1038
|
+
*
|
|
1039
|
+
* export default { fetch: router.fetch };
|
|
1040
|
+
* ```
|
|
1041
|
+
*
|
|
1042
|
+
* @example Direct export
|
|
1043
|
+
* ```tsx
|
|
1044
|
+
* const router = createRouter({
|
|
1045
|
+
* document: Document,
|
|
1046
|
+
* urls: urlpatterns,
|
|
1047
|
+
* nonce: () => true,
|
|
1048
|
+
* });
|
|
1049
|
+
*
|
|
1050
|
+
* export const fetch = router.fetch;
|
|
1051
|
+
* ```
|
|
1052
|
+
*/
|
|
1053
|
+
fetch(
|
|
1054
|
+
request: Request,
|
|
1055
|
+
env: TEnv & { ctx?: ExecutionContext },
|
|
1056
|
+
): Promise<Response>;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/**
|
|
1060
|
+
* Create an RSC router with generic context type
|
|
1061
|
+
* Route types are accumulated automatically through the builder chain
|
|
1062
|
+
*
|
|
1063
|
+
* @example
|
|
1064
|
+
* ```typescript
|
|
1065
|
+
* interface AppContext {
|
|
1066
|
+
* db: Database;
|
|
1067
|
+
* user?: User;
|
|
1068
|
+
* }
|
|
1069
|
+
*
|
|
1070
|
+
* const router = createRouter<AppContext>({
|
|
1071
|
+
* debugPerformance: true // Enable metrics
|
|
1072
|
+
* });
|
|
1073
|
+
*
|
|
1074
|
+
* // Route types accumulate through the chain - no module augmentation needed!
|
|
1075
|
+
* // Keys stay unchanged, only URL patterns get the prefix
|
|
1076
|
+
* router
|
|
1077
|
+
* .routes(homeRoutes) // accumulates homeRoutes
|
|
1078
|
+
* .map(() => import('./home'))
|
|
1079
|
+
* .routes('/shop', shopRoutes) // accumulates shopRoutes with prefixed URLs
|
|
1080
|
+
* .map(() => import('./shop'));
|
|
1081
|
+
*
|
|
1082
|
+
* // router.reverse now has type-safe autocomplete for all registered routes
|
|
1083
|
+
* // Given shopRoutes = { cart: "/cart" }, reverse uses original key:
|
|
1084
|
+
* router.reverse("cart"); // "/shop/cart"
|
|
1085
|
+
* ```
|
|
1086
|
+
*/
|
|
1087
|
+
|
|
1088
|
+
export function createRouter<TEnv = any>(
|
|
1089
|
+
options: RSCRouterOptions<TEnv> = {},
|
|
1090
|
+
): RSCRouter<TEnv, {}> {
|
|
1091
|
+
const {
|
|
1092
|
+
id: userProvidedId,
|
|
1093
|
+
debugPerformance = false,
|
|
1094
|
+
document: documentOption,
|
|
1095
|
+
defaultErrorBoundary,
|
|
1096
|
+
defaultNotFoundBoundary,
|
|
1097
|
+
notFound,
|
|
1098
|
+
onError,
|
|
1099
|
+
cache,
|
|
1100
|
+
theme: themeOption,
|
|
1101
|
+
urls: urlsOption,
|
|
1102
|
+
nonce,
|
|
1103
|
+
version,
|
|
1104
|
+
warmup: warmupOption,
|
|
1105
|
+
allowDebugManifest: allowDebugManifestOption = true,
|
|
1106
|
+
} = options;
|
|
1107
|
+
|
|
1108
|
+
const routerId = userProvidedId ?? `router_${routerAutoId++}`;
|
|
1109
|
+
|
|
1110
|
+
// Capture the source file that called createRouter() via stack trace parsing.
|
|
1111
|
+
// Used by the Vite plugin to write per-router named-routes.gen.ts files.
|
|
1112
|
+
let __sourceFile: string | undefined;
|
|
1113
|
+
try {
|
|
1114
|
+
const stack = new Error().stack;
|
|
1115
|
+
if (stack) {
|
|
1116
|
+
const lines = stack.split("\n");
|
|
1117
|
+
for (const line of lines) {
|
|
1118
|
+
const match = line.match(/\((.+?\.(ts|tsx|js|jsx)):\d+:\d+\)/);
|
|
1119
|
+
if (match && !match[1].includes("/router.ts") && !match[1].includes("@rangojs/router")) {
|
|
1120
|
+
__sourceFile = match[1];
|
|
1121
|
+
break;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
} catch {}
|
|
1126
|
+
|
|
1127
|
+
// Resolve warmup enabled flag (default: true)
|
|
1128
|
+
const warmupEnabled = warmupOption !== false;
|
|
1129
|
+
|
|
1130
|
+
// Resolve theme config (null if theme not enabled)
|
|
1131
|
+
const resolvedThemeConfig = themeOption
|
|
1132
|
+
? resolveThemeConfig(themeOption)
|
|
1133
|
+
: null;
|
|
1134
|
+
|
|
1135
|
+
/**
|
|
1136
|
+
* Wrapper for invokeOnError that binds the router's onError callback.
|
|
1137
|
+
* Uses the shared utility from router/error-handling.ts for consistent behavior.
|
|
1138
|
+
*/
|
|
1139
|
+
function callOnError(
|
|
1140
|
+
error: unknown,
|
|
1141
|
+
phase: ErrorPhase,
|
|
1142
|
+
context: Parameters<typeof invokeOnError<TEnv>>[3],
|
|
1143
|
+
): void {
|
|
1144
|
+
invokeOnError(onError, error, phase, context, "Router");
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
// Validate document is a client component
|
|
1148
|
+
if (documentOption !== undefined) {
|
|
1149
|
+
assertClientComponent(documentOption, "document");
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
// Use default document if none provided (keeps internal name as rootLayout)
|
|
1153
|
+
const rootLayout = documentOption ?? DefaultDocument;
|
|
1154
|
+
const routesEntries: RouteEntry<TEnv>[] = [];
|
|
1155
|
+
let mountIndex = 0;
|
|
1156
|
+
|
|
1157
|
+
// Store reference to urlpatterns for runtime manifest generation
|
|
1158
|
+
let storedUrlPatterns: UrlPatterns<TEnv, any> | null = null;
|
|
1159
|
+
|
|
1160
|
+
// Global middleware storage
|
|
1161
|
+
const globalMiddleware: MiddlewareEntry<TEnv>[] = [];
|
|
1162
|
+
|
|
1163
|
+
// Helper to add middleware entry
|
|
1164
|
+
function addMiddleware(
|
|
1165
|
+
patternOrMiddleware: string | MiddlewareFn<TEnv>,
|
|
1166
|
+
middleware?: MiddlewareFn<TEnv>,
|
|
1167
|
+
mountPrefix: string | null = null,
|
|
1168
|
+
): void {
|
|
1169
|
+
let pattern: string | null = null;
|
|
1170
|
+
let handler: MiddlewareFn<TEnv>;
|
|
1171
|
+
|
|
1172
|
+
if (typeof patternOrMiddleware === "string") {
|
|
1173
|
+
// Pattern + middleware
|
|
1174
|
+
pattern = patternOrMiddleware;
|
|
1175
|
+
if (!middleware) {
|
|
1176
|
+
throw new Error(
|
|
1177
|
+
"Middleware function required when pattern is provided",
|
|
1178
|
+
);
|
|
1179
|
+
}
|
|
1180
|
+
handler = middleware;
|
|
1181
|
+
} else {
|
|
1182
|
+
// Just middleware (no pattern)
|
|
1183
|
+
handler = patternOrMiddleware;
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
// If mount-scoped, prepend mount prefix to pattern
|
|
1187
|
+
let fullPattern = pattern;
|
|
1188
|
+
if (mountPrefix && pattern) {
|
|
1189
|
+
// e.g., mountPrefix="/blog", pattern="/admin/*" → "/blog/admin/*"
|
|
1190
|
+
fullPattern =
|
|
1191
|
+
pattern === "*" ? `${mountPrefix}/*` : `${mountPrefix}${pattern}`;
|
|
1192
|
+
} else if (mountPrefix && !pattern) {
|
|
1193
|
+
// Mount-scoped middleware without pattern applies to all of mount
|
|
1194
|
+
fullPattern = `${mountPrefix}/*`;
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// Parse pattern into regex
|
|
1198
|
+
let regex: RegExp | null = null;
|
|
1199
|
+
let paramNames: string[] = [];
|
|
1200
|
+
if (fullPattern) {
|
|
1201
|
+
const parsed = parsePattern(fullPattern);
|
|
1202
|
+
regex = parsed.regex;
|
|
1203
|
+
paramNames = parsed.paramNames;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
globalMiddleware.push({
|
|
1207
|
+
pattern: fullPattern,
|
|
1208
|
+
regex,
|
|
1209
|
+
paramNames,
|
|
1210
|
+
handler,
|
|
1211
|
+
mountPrefix,
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// Track all registered routes with their prefixes for reverse()
|
|
1216
|
+
const mergedRouteMap: Record<string, string> = {};
|
|
1217
|
+
|
|
1218
|
+
// Build a Map from precomputed entries for O(1) lookup by staticPrefix.
|
|
1219
|
+
// The array is set at import time (from the virtual module) before createRouter runs.
|
|
1220
|
+
const precomputedEntriesRaw = getPrecomputedEntries();
|
|
1221
|
+
const precomputedByPrefix: Map<string, Record<string, string>> | null =
|
|
1222
|
+
precomputedEntriesRaw
|
|
1223
|
+
? new Map(precomputedEntriesRaw.map((e) => [e.staticPrefix, e.routes]))
|
|
1224
|
+
: null;
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
// Wrapper to pass debugPerformance to external createMetricsStore
|
|
1228
|
+
const getMetricsStore = () => createMetricsStore(debugPerformance);
|
|
1229
|
+
|
|
1230
|
+
// Wrapper to pass defaults to error/notFound boundary finders
|
|
1231
|
+
const findNearestErrorBoundary = (entry: EntryData | null) =>
|
|
1232
|
+
findErrorBoundary(entry, defaultErrorBoundary);
|
|
1233
|
+
|
|
1234
|
+
const findNearestNotFoundBoundary = (entry: EntryData | null) =>
|
|
1235
|
+
findNotFoundBoundary(entry, defaultNotFoundBoundary);
|
|
1236
|
+
|
|
1237
|
+
// Helper to get handleStore from request context
|
|
1238
|
+
const getHandleStore = (): HandleStore | undefined => {
|
|
1239
|
+
return getRequestContext()?._handleStore;
|
|
1240
|
+
};
|
|
1241
|
+
|
|
1242
|
+
// Track a pending handler promise (non-blocking)
|
|
1243
|
+
const trackHandler = <T>(promise: Promise<T>): Promise<T> => {
|
|
1244
|
+
const store = getHandleStore();
|
|
1245
|
+
return store ? store.track(promise) : promise;
|
|
1246
|
+
};
|
|
1247
|
+
|
|
1248
|
+
// Wrapper for wrapLoaderWithErrorHandling that uses router's error boundary finder
|
|
1249
|
+
// Includes onError callback for loader error notification
|
|
1250
|
+
function wrapLoaderPromise<T>(
|
|
1251
|
+
promise: Promise<T>,
|
|
1252
|
+
entry: EntryData,
|
|
1253
|
+
segmentId: string,
|
|
1254
|
+
pathname: string,
|
|
1255
|
+
errorContext?: {
|
|
1256
|
+
request: Request;
|
|
1257
|
+
url: URL;
|
|
1258
|
+
routeKey?: string;
|
|
1259
|
+
params?: Record<string, string>;
|
|
1260
|
+
env?: TEnv;
|
|
1261
|
+
isPartial?: boolean;
|
|
1262
|
+
requestStartTime?: number;
|
|
1263
|
+
},
|
|
1264
|
+
): Promise<LoaderDataResult<T>> {
|
|
1265
|
+
return wrapLoaderWithErrorHandling(
|
|
1266
|
+
promise,
|
|
1267
|
+
entry,
|
|
1268
|
+
segmentId,
|
|
1269
|
+
pathname,
|
|
1270
|
+
findNearestErrorBoundary,
|
|
1271
|
+
createErrorInfo,
|
|
1272
|
+
// Invoke onError when loader fails
|
|
1273
|
+
errorContext
|
|
1274
|
+
? (error, ctx) => {
|
|
1275
|
+
callOnError(error, "loader", {
|
|
1276
|
+
request: errorContext.request,
|
|
1277
|
+
url: errorContext.url,
|
|
1278
|
+
routeKey: errorContext.routeKey,
|
|
1279
|
+
params: errorContext.params,
|
|
1280
|
+
segmentId: ctx.segmentId,
|
|
1281
|
+
segmentType: "loader",
|
|
1282
|
+
loaderName: ctx.loaderName,
|
|
1283
|
+
env: errorContext.env,
|
|
1284
|
+
isPartial: errorContext.isPartial,
|
|
1285
|
+
handledByBoundary: ctx.handledByBoundary,
|
|
1286
|
+
requestStartTime: errorContext.requestStartTime,
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
: undefined,
|
|
1290
|
+
);
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// Dependencies object for extracted segment resolution functions.
|
|
1294
|
+
// Captures closure-bound helpers from createRouter.
|
|
1295
|
+
const segmentDeps: SegmentResolutionDeps<TEnv> = {
|
|
1296
|
+
wrapLoaderPromise,
|
|
1297
|
+
trackHandler,
|
|
1298
|
+
findNearestErrorBoundary,
|
|
1299
|
+
findNearestNotFoundBoundary,
|
|
1300
|
+
callOnError,
|
|
1301
|
+
};
|
|
1302
|
+
|
|
1303
|
+
// Match API dependencies
|
|
1304
|
+
const matchApiDeps: MatchApiDeps<TEnv> = {
|
|
1305
|
+
findMatch: (pathname: string, ms?: any) => findMatch(pathname, ms),
|
|
1306
|
+
getMetricsStore,
|
|
1307
|
+
findInterceptForRoute: (routeKey, parentEntry, selectorContext, isAction) =>
|
|
1308
|
+
findInterceptForRoute(routeKey, parentEntry, selectorContext, isAction),
|
|
1309
|
+
callOnError,
|
|
1310
|
+
findNearestErrorBoundary,
|
|
1311
|
+
};
|
|
1312
|
+
|
|
1313
|
+
// Thin wrappers that bind the deps to extracted functions.
|
|
1314
|
+
// These maintain the same signatures as the original inline functions
|
|
1315
|
+
// so that RouterContext and call sites don't need to change.
|
|
1316
|
+
|
|
1317
|
+
function resolveAllSegments(
|
|
1318
|
+
entries: EntryData[],
|
|
1319
|
+
routeKey: string,
|
|
1320
|
+
params: Record<string, string>,
|
|
1321
|
+
context: HandlerContext<any, TEnv>,
|
|
1322
|
+
loaderPromises: Map<string, Promise<any>>,
|
|
1323
|
+
) {
|
|
1324
|
+
return _resolveAllSegments(entries, routeKey, params, context, loaderPromises, segmentDeps);
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
function resolveLoadersOnly(
|
|
1328
|
+
entries: EntryData[],
|
|
1329
|
+
context: HandlerContext<any, TEnv>,
|
|
1330
|
+
) {
|
|
1331
|
+
return _resolveLoadersOnly(entries, context, segmentDeps);
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
function resolveLoadersOnlyWithRevalidation(
|
|
1335
|
+
entries: EntryData[],
|
|
1336
|
+
context: HandlerContext<any, TEnv>,
|
|
1337
|
+
clientSegmentIds: Set<string>,
|
|
1338
|
+
prevParams: Record<string, string>,
|
|
1339
|
+
request: Request,
|
|
1340
|
+
prevUrl: URL,
|
|
1341
|
+
nextUrl: URL,
|
|
1342
|
+
routeKey: string,
|
|
1343
|
+
actionContext?: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData },
|
|
1344
|
+
) {
|
|
1345
|
+
return _resolveLoadersOnlyWithRevalidation(
|
|
1346
|
+
entries, context, clientSegmentIds, prevParams, request,
|
|
1347
|
+
prevUrl, nextUrl, routeKey, segmentDeps, actionContext,
|
|
1348
|
+
);
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
function buildEntryRevalidateMap(entries: EntryData[]) {
|
|
1352
|
+
return _buildEntryRevalidateMap(entries);
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
function resolveAllSegmentsWithRevalidation(
|
|
1356
|
+
entries: EntryData[],
|
|
1357
|
+
routeKey: string,
|
|
1358
|
+
params: Record<string, string>,
|
|
1359
|
+
context: HandlerContext<any, TEnv>,
|
|
1360
|
+
clientSegmentSet: Set<string>,
|
|
1361
|
+
prevParams: Record<string, string>,
|
|
1362
|
+
request: Request,
|
|
1363
|
+
prevUrl: URL,
|
|
1364
|
+
nextUrl: URL,
|
|
1365
|
+
loaderPromises: Map<string, Promise<any>>,
|
|
1366
|
+
actionContext: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData } | undefined,
|
|
1367
|
+
interceptResult: { intercept: InterceptEntry; entry: EntryData } | null,
|
|
1368
|
+
localRouteName: string,
|
|
1369
|
+
pathname: string,
|
|
1370
|
+
) {
|
|
1371
|
+
return _resolveAllSegmentsWithRevalidation(
|
|
1372
|
+
entries, routeKey, params, context, clientSegmentSet, prevParams, request,
|
|
1373
|
+
prevUrl, nextUrl, loaderPromises, actionContext, interceptResult,
|
|
1374
|
+
localRouteName, pathname, segmentDeps,
|
|
1375
|
+
);
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
function findInterceptForRoute(
|
|
1379
|
+
targetRouteKey: string,
|
|
1380
|
+
fromEntry: EntryData | null,
|
|
1381
|
+
selectorContext: InterceptSelectorContext | null = null,
|
|
1382
|
+
isAction: boolean = false,
|
|
1383
|
+
) {
|
|
1384
|
+
return _findInterceptForRoute(targetRouteKey, fromEntry, selectorContext, isAction);
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
function resolveInterceptEntry(
|
|
1388
|
+
interceptEntry: InterceptEntry,
|
|
1389
|
+
parentEntry: EntryData,
|
|
1390
|
+
params: Record<string, string>,
|
|
1391
|
+
context: HandlerContext<any, TEnv>,
|
|
1392
|
+
belongsToRoute: boolean = true,
|
|
1393
|
+
revalidationContext?: any,
|
|
1394
|
+
) {
|
|
1395
|
+
return _resolveInterceptEntry(
|
|
1396
|
+
interceptEntry, parentEntry, params, context, belongsToRoute,
|
|
1397
|
+
segmentDeps, revalidationContext,
|
|
1398
|
+
);
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
function resolveInterceptLoadersOnly(
|
|
1402
|
+
interceptEntry: InterceptEntry,
|
|
1403
|
+
parentEntry: EntryData,
|
|
1404
|
+
params: Record<string, string>,
|
|
1405
|
+
context: HandlerContext<any, TEnv>,
|
|
1406
|
+
belongsToRoute: boolean = true,
|
|
1407
|
+
revalidationContext: any,
|
|
1408
|
+
) {
|
|
1409
|
+
return _resolveInterceptLoadersOnly(
|
|
1410
|
+
interceptEntry, parentEntry, params, context, belongsToRoute,
|
|
1411
|
+
segmentDeps, revalidationContext,
|
|
1412
|
+
);
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// Detect lazy includes in handler result and create placeholder entries
|
|
1416
|
+
// Lazy includes are IncludeItem with lazy: true and _lazyContext
|
|
1417
|
+
// Moved to outer scope so it can be reused by evaluateLazyEntry for nested includes
|
|
1418
|
+
function findLazyIncludes(items: AllUseItems[]): Array<{
|
|
1419
|
+
prefix: string;
|
|
1420
|
+
patterns: UrlPatterns<TEnv>;
|
|
1421
|
+
context: {
|
|
1422
|
+
urlPrefix: string;
|
|
1423
|
+
namePrefix: string | undefined;
|
|
1424
|
+
parent: unknown;
|
|
1425
|
+
};
|
|
1426
|
+
}> {
|
|
1427
|
+
const lazyItems: Array<{
|
|
1428
|
+
prefix: string;
|
|
1429
|
+
patterns: UrlPatterns<TEnv>;
|
|
1430
|
+
context: {
|
|
1431
|
+
urlPrefix: string;
|
|
1432
|
+
namePrefix: string | undefined;
|
|
1433
|
+
parent: unknown;
|
|
1434
|
+
};
|
|
1435
|
+
}> = [];
|
|
1436
|
+
|
|
1437
|
+
for (const item of items) {
|
|
1438
|
+
if (!item) continue;
|
|
1439
|
+
if (item.type === "include") {
|
|
1440
|
+
const includeItem = item as IncludeItem;
|
|
1441
|
+
if (includeItem.lazy === true && includeItem._lazyContext) {
|
|
1442
|
+
lazyItems.push({
|
|
1443
|
+
prefix: includeItem.prefix,
|
|
1444
|
+
patterns: includeItem.patterns as UrlPatterns<TEnv>,
|
|
1445
|
+
context: includeItem._lazyContext,
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
// Recursively check nested items (in layouts, etc.)
|
|
1450
|
+
if ((item as any).uses && Array.isArray((item as any).uses)) {
|
|
1451
|
+
lazyItems.push(...findLazyIncludes((item as any).uses));
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
return lazyItems;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
/**
|
|
1459
|
+
* Evaluate a lazy entry's patterns and populate its routes
|
|
1460
|
+
* This runs the lazy patterns handler and updates the entry in-place
|
|
1461
|
+
* Also detects nested lazy includes and registers them as new entries
|
|
1462
|
+
*/
|
|
1463
|
+
function evaluateLazyEntry(entry: RouteEntry<TEnv>): void {
|
|
1464
|
+
if (!entry.lazy || entry.lazyEvaluated || !entry.lazyPatterns) {
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// Check for pre-computed routes from build-time data.
|
|
1469
|
+
// Only leaf nodes (no nested includes) are precomputed, so entries with
|
|
1470
|
+
// nested lazy includes fall through to the handler below.
|
|
1471
|
+
if (precomputedByPrefix) {
|
|
1472
|
+
const routes = precomputedByPrefix.get(entry.staticPrefix);
|
|
1473
|
+
if (routes) {
|
|
1474
|
+
entry.lazyEvaluated = true;
|
|
1475
|
+
entry.routes = routes as ResolvedRouteMap<any>;
|
|
1476
|
+
for (const [name, pattern] of Object.entries(routes)) {
|
|
1477
|
+
mergedRouteMap[name] = pattern;
|
|
1478
|
+
}
|
|
1479
|
+
registerRouteMap(mergedRouteMap);
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
// Mark as evaluated immediately to prevent concurrent evaluation.
|
|
1485
|
+
// JS is single-threaded but handlers.handler() could theoretically yield,
|
|
1486
|
+
// and the while-loop in findMatch retries after evaluation.
|
|
1487
|
+
entry.lazyEvaluated = true;
|
|
1488
|
+
|
|
1489
|
+
const lazyPatterns = entry.lazyPatterns as UrlPatterns<TEnv>;
|
|
1490
|
+
const lazyContext = entry.lazyContext;
|
|
1491
|
+
|
|
1492
|
+
// Create a new context for evaluating the lazy patterns
|
|
1493
|
+
const manifest = new Map<string, EntryData>();
|
|
1494
|
+
const patterns = new Map<string, string>();
|
|
1495
|
+
const patternsByPrefix = new Map<string, Map<string, string>>();
|
|
1496
|
+
const trailingSlashMap = new Map<string, TrailingSlashMode>();
|
|
1497
|
+
|
|
1498
|
+
// Capture the handler result to detect nested lazy includes
|
|
1499
|
+
let handlerResult: AllUseItems[] = [];
|
|
1500
|
+
|
|
1501
|
+
RSCRouterContext.run(
|
|
1502
|
+
{
|
|
1503
|
+
manifest,
|
|
1504
|
+
patterns,
|
|
1505
|
+
patternsByPrefix,
|
|
1506
|
+
trailingSlash: trailingSlashMap,
|
|
1507
|
+
namespace: "lazy",
|
|
1508
|
+
parent: (lazyContext?.parent as EntryData | null) ?? null,
|
|
1509
|
+
counters: {},
|
|
1510
|
+
},
|
|
1511
|
+
() => {
|
|
1512
|
+
// Run the lazy patterns handler with the original context prefixes
|
|
1513
|
+
// The prefix comes from the IncludeItem stored in lazyPatterns
|
|
1514
|
+
const includePrefix = (entry as any)._lazyPrefix || "";
|
|
1515
|
+
const fullPrefix = (lazyContext?.urlPrefix || "") + includePrefix;
|
|
1516
|
+
|
|
1517
|
+
if (fullPrefix || lazyContext?.namePrefix) {
|
|
1518
|
+
runWithPrefixes(fullPrefix, lazyContext?.namePrefix, () => {
|
|
1519
|
+
handlerResult = lazyPatterns.handler() as AllUseItems[];
|
|
1520
|
+
});
|
|
1521
|
+
} else {
|
|
1522
|
+
handlerResult = lazyPatterns.handler() as AllUseItems[];
|
|
1523
|
+
}
|
|
1524
|
+
},
|
|
1525
|
+
);
|
|
1526
|
+
|
|
1527
|
+
// Populate the entry's routes from the patterns
|
|
1528
|
+
const routesObject: Record<string, string> = {};
|
|
1529
|
+
for (const [name, pattern] of patterns.entries()) {
|
|
1530
|
+
routesObject[name] = pattern;
|
|
1531
|
+
// Also add to merged route map for reverse() support
|
|
1532
|
+
const existingPattern = mergedRouteMap[name];
|
|
1533
|
+
if (existingPattern !== undefined && existingPattern !== pattern) {
|
|
1534
|
+
console.warn(
|
|
1535
|
+
`[@rangojs/router] Route name conflict: "${name}" already maps to "${existingPattern}", ` +
|
|
1536
|
+
`overwriting with "${pattern}" (from lazy include). Use unique route names to avoid this.`,
|
|
1537
|
+
);
|
|
1538
|
+
}
|
|
1539
|
+
mergedRouteMap[name] = pattern;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
// Update the entry in-place
|
|
1543
|
+
entry.routes = routesObject as ResolvedRouteMap<any>;
|
|
1544
|
+
|
|
1545
|
+
// Note: Do NOT clear lazyPatterns/lazyContext here.
|
|
1546
|
+
// loadManifest() needs them on every request to re-run the handler
|
|
1547
|
+
// in the correct AsyncLocalStorage context (Store.manifest).
|
|
1548
|
+
|
|
1549
|
+
// Update trailing slash config if available
|
|
1550
|
+
if (trailingSlashMap.size > 0) {
|
|
1551
|
+
entry.trailingSlash = Object.fromEntries(trailingSlashMap);
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// Detect nested lazy includes and register them as new entries
|
|
1555
|
+
const nestedLazyIncludes = findLazyIncludes(handlerResult);
|
|
1556
|
+
for (const lazyInclude of nestedLazyIncludes) {
|
|
1557
|
+
// Compute the full URL prefix (combining parent prefix if any)
|
|
1558
|
+
const fullPrefix = lazyInclude.context.urlPrefix
|
|
1559
|
+
? lazyInclude.context.urlPrefix + lazyInclude.prefix
|
|
1560
|
+
: lazyInclude.prefix;
|
|
1561
|
+
|
|
1562
|
+
const nestedEntry: RouteEntry<TEnv> & { _lazyPrefix?: string } = {
|
|
1563
|
+
prefix: "",
|
|
1564
|
+
staticPrefix: extractStaticPrefix(fullPrefix),
|
|
1565
|
+
routes: {} as ResolvedRouteMap<any>, // Empty until first match
|
|
1566
|
+
trailingSlash: entry.trailingSlash,
|
|
1567
|
+
handler: (lazyInclude.patterns as UrlPatterns<TEnv>).handler,
|
|
1568
|
+
mountIndex: entry.mountIndex,
|
|
1569
|
+
// Lazy evaluation fields
|
|
1570
|
+
lazy: true,
|
|
1571
|
+
lazyPatterns: lazyInclude.patterns,
|
|
1572
|
+
lazyContext: lazyInclude.context,
|
|
1573
|
+
lazyEvaluated: false,
|
|
1574
|
+
// Store the include prefix for evaluation
|
|
1575
|
+
_lazyPrefix: lazyInclude.prefix,
|
|
1576
|
+
};
|
|
1577
|
+
// Insert nested lazy entry before any entry whose staticPrefix is a
|
|
1578
|
+
// prefix of (but shorter than) this lazy entry's staticPrefix.
|
|
1579
|
+
// This ensures more specific lazy includes are matched before
|
|
1580
|
+
// less specific eager entries (e.g., "/href/nested" before "/href/:id").
|
|
1581
|
+
const nestedPrefix = nestedEntry.staticPrefix;
|
|
1582
|
+
let insertIndex = routesEntries.length;
|
|
1583
|
+
if (nestedPrefix) {
|
|
1584
|
+
for (let i = 0; i < routesEntries.length; i++) {
|
|
1585
|
+
const existing = routesEntries[i]!;
|
|
1586
|
+
if (
|
|
1587
|
+
nestedPrefix.startsWith(existing.staticPrefix) &&
|
|
1588
|
+
nestedPrefix.length > existing.staticPrefix.length
|
|
1589
|
+
) {
|
|
1590
|
+
insertIndex = i;
|
|
1591
|
+
break;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
routesEntries.splice(insertIndex, 0, nestedEntry);
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
// Re-register route map for runtime reverse() usage
|
|
1599
|
+
registerRouteMap(mergedRouteMap);
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
// Single-entry cache for findMatch to avoid redundant matching within the same request.
|
|
1603
|
+
// previewMatch and match both call findMatch with the same pathname — this ensures
|
|
1604
|
+
// the route matching work (which may check thousands of routes) only happens once.
|
|
1605
|
+
let lastFindMatchPathname: string | null = null;
|
|
1606
|
+
let lastFindMatchResult: RouteMatchResult<TEnv> | null = null;
|
|
1607
|
+
|
|
1608
|
+
// Wrapper for findMatch that uses routesEntries
|
|
1609
|
+
// Handles lazy evaluation by evaluating lazy entries on first match.
|
|
1610
|
+
// Phase 1: try O(path_length) trie match.
|
|
1611
|
+
// Phase 2: fall back to regex iteration.
|
|
1612
|
+
function findMatch(
|
|
1613
|
+
pathname: string,
|
|
1614
|
+
ms?: MetricsStore,
|
|
1615
|
+
): RouteMatchResult<TEnv> | null {
|
|
1616
|
+
// Return cached result if same pathname (avoids double-match per request)
|
|
1617
|
+
if (lastFindMatchPathname === pathname) {
|
|
1618
|
+
return lastFindMatchResult;
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
// Helper to push sub-metrics
|
|
1622
|
+
const pushMetric = ms
|
|
1623
|
+
? (label: string, start: number) => {
|
|
1624
|
+
ms.metrics.push({
|
|
1625
|
+
label,
|
|
1626
|
+
duration: performance.now() - start,
|
|
1627
|
+
startTime: start - ms.requestStart,
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
: undefined;
|
|
1631
|
+
|
|
1632
|
+
// Phase 1: Try trie match (O(path_length))
|
|
1633
|
+
const routeTrie = getRouteTrie();
|
|
1634
|
+
if (routeTrie) {
|
|
1635
|
+
const trieStart = performance.now();
|
|
1636
|
+
const trieResult = tryTrieMatch(routeTrie, pathname);
|
|
1637
|
+
pushMetric?.("match:trie", trieStart);
|
|
1638
|
+
|
|
1639
|
+
if (trieResult) {
|
|
1640
|
+
// Find the RouteEntry that contains this route.
|
|
1641
|
+
// Multiple entries can share the same staticPrefix (e.g., several
|
|
1642
|
+
// include("/", patterns) calls all produce staticPrefix=""). Evaluate
|
|
1643
|
+
// each candidate and pick the one whose routes include the matched key.
|
|
1644
|
+
const entryStart = performance.now();
|
|
1645
|
+
let entry: RouteEntry<TEnv> | undefined;
|
|
1646
|
+
let fallbackEntry: RouteEntry<TEnv> | undefined;
|
|
1647
|
+
|
|
1648
|
+
for (const e of routesEntries) {
|
|
1649
|
+
if (e.staticPrefix !== trieResult.sp) continue;
|
|
1650
|
+
if (!fallbackEntry) fallbackEntry = e;
|
|
1651
|
+
evaluateLazyEntry(e);
|
|
1652
|
+
if (
|
|
1653
|
+
e.routes &&
|
|
1654
|
+
trieResult.routeKey in (e.routes as Record<string, unknown>)
|
|
1655
|
+
) {
|
|
1656
|
+
entry = e;
|
|
1657
|
+
break;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
// If no entry had the route in its routes map, use the first matching
|
|
1662
|
+
// entry as fallback (handles main entry with inline routes not yet
|
|
1663
|
+
// reflected in its routes object).
|
|
1664
|
+
if (!entry) entry = fallbackEntry;
|
|
1665
|
+
|
|
1666
|
+
// If entry not found (nested include not yet discovered), evaluate parent
|
|
1667
|
+
if (!entry) {
|
|
1668
|
+
const parent = routesEntries.find(
|
|
1669
|
+
(e) =>
|
|
1670
|
+
trieResult.sp.startsWith(e.staticPrefix) &&
|
|
1671
|
+
e.staticPrefix !== trieResult.sp,
|
|
1672
|
+
);
|
|
1673
|
+
if (parent) {
|
|
1674
|
+
const lazyStart = performance.now();
|
|
1675
|
+
evaluateLazyEntry(parent);
|
|
1676
|
+
pushMetric?.("match:lazy-eval", lazyStart);
|
|
1677
|
+
}
|
|
1678
|
+
entry = routesEntries.find((e) => e.staticPrefix === trieResult.sp);
|
|
1679
|
+
}
|
|
1680
|
+
pushMetric?.("match:entry-resolve", entryStart);
|
|
1681
|
+
|
|
1682
|
+
if (entry) {
|
|
1683
|
+
lastFindMatchPathname = pathname;
|
|
1684
|
+
lastFindMatchResult = {
|
|
1685
|
+
entry,
|
|
1686
|
+
routeKey: trieResult.routeKey,
|
|
1687
|
+
params: trieResult.params,
|
|
1688
|
+
optionalParams: new Set(trieResult.optionalParams || []),
|
|
1689
|
+
redirectTo: trieResult.redirectTo,
|
|
1690
|
+
ancestry: trieResult.ancestry,
|
|
1691
|
+
...(trieResult.pr ? { pr: true } : {}),
|
|
1692
|
+
...(trieResult.pt ? { pt: true } : {}),
|
|
1693
|
+
...(trieResult.responseType ? { responseType: trieResult.responseType } : {}),
|
|
1694
|
+
...(trieResult.negotiateVariants ? { negotiateVariants: trieResult.negotiateVariants } : {}),
|
|
1695
|
+
...(trieResult.rscFirst ? { rscFirst: true } : {}),
|
|
1696
|
+
};
|
|
1697
|
+
return lastFindMatchResult;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
// Phase 2: Fall back to existing matching (regex iteration)
|
|
1703
|
+
const regexStart = performance.now();
|
|
1704
|
+
let result = findRouteMatch(pathname, routesEntries);
|
|
1705
|
+
|
|
1706
|
+
// If we hit a lazy entry that needs evaluation, evaluate and retry.
|
|
1707
|
+
// Cap iterations to prevent infinite loops from pathological nesting.
|
|
1708
|
+
const MAX_LAZY_ITERATIONS = 100;
|
|
1709
|
+
let iterations = 0;
|
|
1710
|
+
while (isLazyEvaluationNeeded(result)) {
|
|
1711
|
+
if (++iterations > MAX_LAZY_ITERATIONS) {
|
|
1712
|
+
console.error(
|
|
1713
|
+
`[@rangojs/router] Exceeded ${MAX_LAZY_ITERATIONS} lazy evaluation iterations ` +
|
|
1714
|
+
`for pathname "${pathname}". This likely indicates circular lazy includes.`,
|
|
1715
|
+
);
|
|
1716
|
+
lastFindMatchPathname = pathname;
|
|
1717
|
+
lastFindMatchResult = null;
|
|
1718
|
+
return null;
|
|
1719
|
+
}
|
|
1720
|
+
evaluateLazyEntry(result.lazyEntry);
|
|
1721
|
+
result = findRouteMatch(pathname, routesEntries);
|
|
1722
|
+
}
|
|
1723
|
+
pushMetric?.("match:regex-fallback", regexStart);
|
|
1724
|
+
|
|
1725
|
+
lastFindMatchPathname = pathname;
|
|
1726
|
+
lastFindMatchResult = result;
|
|
1727
|
+
return result;
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
|
|
1731
|
+
/**
|
|
1732
|
+
* Match request and return segments (document/SSR requests)
|
|
1733
|
+
*
|
|
1734
|
+
* Uses generator middleware pipeline for clean separation of concerns:
|
|
1735
|
+
* - cache-lookup: Check cache first
|
|
1736
|
+
* - segment-resolution: Resolve segments on cache miss
|
|
1737
|
+
* - cache-store: Store results in cache
|
|
1738
|
+
* - background-revalidation: SWR revalidation
|
|
1739
|
+
*/
|
|
1740
|
+
async function match(request: Request, env: TEnv): Promise<MatchResult> {
|
|
1741
|
+
// Build RouterContext with all closure functions needed by middleware
|
|
1742
|
+
const routerCtx: RouterContext<TEnv> = {
|
|
1743
|
+
findMatch,
|
|
1744
|
+
loadManifest,
|
|
1745
|
+
traverseBack,
|
|
1746
|
+
createHandlerContext,
|
|
1747
|
+
setupLoaderAccess,
|
|
1748
|
+
setupLoaderAccessSilent,
|
|
1749
|
+
getContext,
|
|
1750
|
+
getMetricsStore,
|
|
1751
|
+
createCacheScope,
|
|
1752
|
+
findInterceptForRoute,
|
|
1753
|
+
resolveAllSegmentsWithRevalidation,
|
|
1754
|
+
resolveInterceptEntry,
|
|
1755
|
+
evaluateRevalidation,
|
|
1756
|
+
getRequestContext,
|
|
1757
|
+
resolveAllSegments,
|
|
1758
|
+
createHandleStore,
|
|
1759
|
+
buildEntryRevalidateMap,
|
|
1760
|
+
resolveLoadersOnlyWithRevalidation,
|
|
1761
|
+
resolveInterceptLoadersOnly,
|
|
1762
|
+
resolveLoadersOnly,
|
|
1763
|
+
};
|
|
1764
|
+
|
|
1765
|
+
return runWithRouterContext(routerCtx, async () => {
|
|
1766
|
+
const result = await createMatchContextForFull(request, env);
|
|
1767
|
+
|
|
1768
|
+
// Handle redirect case
|
|
1769
|
+
if ("type" in result && result.type === "redirect") {
|
|
1770
|
+
return {
|
|
1771
|
+
segments: [],
|
|
1772
|
+
matched: [],
|
|
1773
|
+
diff: [],
|
|
1774
|
+
params: {},
|
|
1775
|
+
redirect: result.redirectUrl,
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
const ctx = result as MatchContext<TEnv>;
|
|
1780
|
+
|
|
1781
|
+
try {
|
|
1782
|
+
const state = createPipelineState();
|
|
1783
|
+
const pipeline = createMatchPartialPipeline(ctx, state);
|
|
1784
|
+
return await collectMatchResult(pipeline, ctx, state);
|
|
1785
|
+
} catch (error) {
|
|
1786
|
+
if (error instanceof Response) throw error;
|
|
1787
|
+
// Report unhandled errors during full match pipeline
|
|
1788
|
+
callOnError(error, "routing", {
|
|
1789
|
+
request,
|
|
1790
|
+
url: ctx.url,
|
|
1791
|
+
env,
|
|
1792
|
+
isPartial: false,
|
|
1793
|
+
handledByBoundary: false,
|
|
1794
|
+
});
|
|
1795
|
+
throw sanitizeError(error);
|
|
1796
|
+
}
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
async function matchError(
|
|
1801
|
+
request: Request,
|
|
1802
|
+
_context: TEnv,
|
|
1803
|
+
error: unknown,
|
|
1804
|
+
segmentType: ErrorInfo["segmentType"] = "route",
|
|
1805
|
+
): Promise<MatchResult | null> {
|
|
1806
|
+
return _matchError(request, _context, error, matchApiDeps, defaultErrorBoundary, segmentType);
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
|
|
1810
|
+
async function createMatchContextForFull(
|
|
1811
|
+
request: Request,
|
|
1812
|
+
env: TEnv,
|
|
1813
|
+
) {
|
|
1814
|
+
return _createMatchContextForFull(request, env, matchApiDeps, findInterceptForRoute);
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
async function createMatchContextForPartial(
|
|
1818
|
+
request: Request,
|
|
1819
|
+
env: TEnv,
|
|
1820
|
+
actionContext?: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData },
|
|
1821
|
+
) {
|
|
1822
|
+
return _createMatchContextForPartial(request, env, matchApiDeps, findInterceptForRoute, actionContext);
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
/**
|
|
1826
|
+
* Match partial request with revalidation
|
|
1827
|
+
*
|
|
1828
|
+
* Uses generator middleware pipeline for clean separation of concerns:
|
|
1829
|
+
* - cache-lookup: Check cache first
|
|
1830
|
+
* - segment-resolution: Resolve segments on cache miss
|
|
1831
|
+
* - intercept-resolution: Handle intercept routes
|
|
1832
|
+
* - cache-store: Store results in cache
|
|
1833
|
+
* - background-revalidation: SWR revalidation
|
|
1834
|
+
*/
|
|
1835
|
+
async function matchPartial(
|
|
1836
|
+
request: Request,
|
|
1837
|
+
context: TEnv,
|
|
1838
|
+
actionContext?: ActionContext,
|
|
1839
|
+
): Promise<MatchResult | null> {
|
|
1840
|
+
// Build RouterContext with all closure functions needed by middleware
|
|
1841
|
+
const routerCtx: RouterContext<TEnv> = {
|
|
1842
|
+
findMatch,
|
|
1843
|
+
loadManifest,
|
|
1844
|
+
traverseBack,
|
|
1845
|
+
createHandlerContext,
|
|
1846
|
+
setupLoaderAccess,
|
|
1847
|
+
setupLoaderAccessSilent,
|
|
1848
|
+
getContext,
|
|
1849
|
+
getMetricsStore,
|
|
1850
|
+
createCacheScope,
|
|
1851
|
+
findInterceptForRoute,
|
|
1852
|
+
resolveAllSegmentsWithRevalidation,
|
|
1853
|
+
resolveInterceptEntry,
|
|
1854
|
+
evaluateRevalidation,
|
|
1855
|
+
getRequestContext,
|
|
1856
|
+
resolveAllSegments,
|
|
1857
|
+
createHandleStore,
|
|
1858
|
+
buildEntryRevalidateMap,
|
|
1859
|
+
resolveLoadersOnlyWithRevalidation,
|
|
1860
|
+
resolveInterceptLoadersOnly,
|
|
1861
|
+
};
|
|
1862
|
+
|
|
1863
|
+
return runWithRouterContext(routerCtx, async () => {
|
|
1864
|
+
const ctx = await createMatchContextForPartial(
|
|
1865
|
+
request,
|
|
1866
|
+
context,
|
|
1867
|
+
actionContext,
|
|
1868
|
+
);
|
|
1869
|
+
if (!ctx) return null;
|
|
1870
|
+
|
|
1871
|
+
try {
|
|
1872
|
+
const state = createPipelineState();
|
|
1873
|
+
const pipeline = createMatchPartialPipeline(ctx, state);
|
|
1874
|
+
return await collectMatchResult(pipeline, ctx, state);
|
|
1875
|
+
} catch (error) {
|
|
1876
|
+
if (error instanceof Response) throw error;
|
|
1877
|
+
// Report unhandled errors during partial match pipeline
|
|
1878
|
+
callOnError(error, actionContext ? "action" : "revalidation", {
|
|
1879
|
+
request,
|
|
1880
|
+
url: ctx.url,
|
|
1881
|
+
env: context,
|
|
1882
|
+
actionId: actionContext?.actionId,
|
|
1883
|
+
isPartial: true,
|
|
1884
|
+
handledByBoundary: false,
|
|
1885
|
+
});
|
|
1886
|
+
throw sanitizeError(error);
|
|
1887
|
+
}
|
|
1888
|
+
});
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
/**
|
|
1892
|
+
* Preview match - returns route middleware without segment resolution.
|
|
1893
|
+
* Also returns responseType and handler for response routes (non-RSC short-circuit).
|
|
1894
|
+
*/
|
|
1895
|
+
async function previewMatch(
|
|
1896
|
+
request: Request,
|
|
1897
|
+
_context: TEnv,
|
|
1898
|
+
): Promise<{
|
|
1899
|
+
routeMiddleware?: Array<{
|
|
1900
|
+
handler: import("./router/middleware.js").MiddlewareFn;
|
|
1901
|
+
params: Record<string, string>;
|
|
1902
|
+
}>;
|
|
1903
|
+
responseType?: string;
|
|
1904
|
+
handler?: Function;
|
|
1905
|
+
params?: Record<string, string>;
|
|
1906
|
+
negotiated?: boolean;
|
|
1907
|
+
} | null> {
|
|
1908
|
+
const url = new URL(request.url);
|
|
1909
|
+
const pathname = url.pathname;
|
|
1910
|
+
|
|
1911
|
+
// Quick route matching
|
|
1912
|
+
const matched = findMatch(pathname);
|
|
1913
|
+
if (!matched) {
|
|
1914
|
+
return null;
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
// Skip redirect check - will be handled in full match
|
|
1918
|
+
if (matched.redirectTo) {
|
|
1919
|
+
return { routeMiddleware: undefined };
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// Load manifest (without segment resolution)
|
|
1923
|
+
const manifestEntry = await loadManifest(
|
|
1924
|
+
matched.entry,
|
|
1925
|
+
matched.routeKey,
|
|
1926
|
+
pathname,
|
|
1927
|
+
undefined, // No metrics store for preview
|
|
1928
|
+
false, // isSSR - doesn't matter for preview
|
|
1929
|
+
);
|
|
1930
|
+
|
|
1931
|
+
// Collect route-level middleware from entry tree
|
|
1932
|
+
// Includes middleware from orphan layouts (inline layouts within routes)
|
|
1933
|
+
const routeMiddleware = collectRouteMiddleware(
|
|
1934
|
+
traverseBack(manifestEntry),
|
|
1935
|
+
matched.params,
|
|
1936
|
+
);
|
|
1937
|
+
|
|
1938
|
+
// Check for response type (from trie match or manifest entry)
|
|
1939
|
+
const responseType = matched.responseType ||
|
|
1940
|
+
(manifestEntry.type === "route" ? manifestEntry.responseType : undefined);
|
|
1941
|
+
|
|
1942
|
+
// Content negotiation: when negotiate variants exist, pick the best
|
|
1943
|
+
// handler based on the Accept header. Uses q-values and client order
|
|
1944
|
+
// as tiebreaker (matching Express/Hono behavior). RSC routes participate
|
|
1945
|
+
// as text/html candidates so browsers naturally get HTML without
|
|
1946
|
+
// special-casing.
|
|
1947
|
+
if (matched.negotiateVariants && matched.negotiateVariants.length > 0) {
|
|
1948
|
+
const acceptEntries = parseAcceptTypes(request.headers.get("accept") || "");
|
|
1949
|
+
|
|
1950
|
+
// Build candidate list preserving definition order.
|
|
1951
|
+
// For wildcard (*/*) and no-Accept fallback, the first candidate wins.
|
|
1952
|
+
const variants = matched.negotiateVariants;
|
|
1953
|
+
let candidates: Array<{ routeKey: string; responseType: string }>;
|
|
1954
|
+
if (responseType) {
|
|
1955
|
+
// Primary is response-type — include it as a candidate
|
|
1956
|
+
candidates = [...variants, { routeKey: matched.routeKey, responseType }];
|
|
1957
|
+
} else {
|
|
1958
|
+
// Primary is RSC — insert as text/html candidate in definition order
|
|
1959
|
+
const rscCandidate = { routeKey: matched.routeKey, responseType: RSC_RESPONSE_TYPE };
|
|
1960
|
+
candidates = matched.rscFirst
|
|
1961
|
+
? [rscCandidate, ...variants]
|
|
1962
|
+
: [...variants, rscCandidate];
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
const variant = pickNegotiateVariant(acceptEntries, candidates);
|
|
1966
|
+
|
|
1967
|
+
// If the winner is RSC, fall through to default RSC handling
|
|
1968
|
+
if (variant.responseType === RSC_RESPONSE_TYPE) {
|
|
1969
|
+
// Fall through — RSC won negotiation
|
|
1970
|
+
} else if (responseType && variant.routeKey === matched.routeKey) {
|
|
1971
|
+
// Fall through — response-type primary won, already set
|
|
1972
|
+
} else {
|
|
1973
|
+
const negotiateEntry = await loadManifest(
|
|
1974
|
+
matched.entry,
|
|
1975
|
+
variant.routeKey,
|
|
1976
|
+
pathname,
|
|
1977
|
+
undefined,
|
|
1978
|
+
false,
|
|
1979
|
+
);
|
|
1980
|
+
return {
|
|
1981
|
+
routeMiddleware: routeMiddleware.length > 0 ? routeMiddleware : undefined,
|
|
1982
|
+
responseType: variant.responseType,
|
|
1983
|
+
handler: negotiateEntry.type === "route" ? negotiateEntry.handler : undefined,
|
|
1984
|
+
params: matched.params,
|
|
1985
|
+
negotiated: true,
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
// If we passed through the negotiation block (variants exist), mark as
|
|
1991
|
+
// negotiated so the handler sets Vary: Accept on the response.
|
|
1992
|
+
const hasVariants = matched.negotiateVariants && matched.negotiateVariants.length > 0;
|
|
1993
|
+
return {
|
|
1994
|
+
routeMiddleware: routeMiddleware.length > 0 ? routeMiddleware : undefined,
|
|
1995
|
+
...(responseType ? {
|
|
1996
|
+
responseType,
|
|
1997
|
+
handler: manifestEntry.type === "route" ? manifestEntry.handler : undefined,
|
|
1998
|
+
params: matched.params,
|
|
1999
|
+
} : {}),
|
|
2000
|
+
...(hasVariants ? { negotiated: true } : {}),
|
|
2001
|
+
};
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
/**
|
|
2005
|
+
* Create route builder with accumulated route types
|
|
2006
|
+
* The TNewRoutes type parameter captures the new routes being added
|
|
2007
|
+
*/
|
|
2008
|
+
function createRouteBuilder<TNewRoutes extends Record<string, string>>(
|
|
2009
|
+
prefix: string,
|
|
2010
|
+
routes: TNewRoutes,
|
|
2011
|
+
): RouteBuilder<RouteDefinition, TEnv, any, TNewRoutes> {
|
|
2012
|
+
const currentMountIndex = mountIndex++;
|
|
2013
|
+
|
|
2014
|
+
// Merge routes into the reverse map
|
|
2015
|
+
// Keys stay unchanged for composability - only URL patterns get prefixed
|
|
2016
|
+
const routeEntries = routes as Record<string, string>;
|
|
2017
|
+
for (const [key, pattern] of Object.entries(routeEntries)) {
|
|
2018
|
+
// Build prefixed pattern: "/shop" + "/cart" -> "/shop/cart"
|
|
2019
|
+
const prefixedPattern =
|
|
2020
|
+
prefix && pattern !== "/"
|
|
2021
|
+
? `${prefix}${pattern}`
|
|
2022
|
+
: prefix && pattern === "/"
|
|
2023
|
+
? prefix
|
|
2024
|
+
: pattern;
|
|
2025
|
+
|
|
2026
|
+
// Runtime validation: warn if key already exists with different pattern
|
|
2027
|
+
const existingPattern = mergedRouteMap[key];
|
|
2028
|
+
if (
|
|
2029
|
+
existingPattern !== undefined &&
|
|
2030
|
+
existingPattern !== prefixedPattern
|
|
2031
|
+
) {
|
|
2032
|
+
console.warn(
|
|
2033
|
+
`[rsc-router] Route key conflict: "${key}" already maps to "${existingPattern}", ` +
|
|
2034
|
+
`overwriting with "${prefixedPattern}". Use unique key names to avoid this.`,
|
|
2035
|
+
);
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
// Use original key - enables reusable route modules
|
|
2039
|
+
mergedRouteMap[key] = prefixedPattern;
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
// Auto-register route map for runtime reverse() usage
|
|
2043
|
+
registerRouteMap(mergedRouteMap);
|
|
2044
|
+
|
|
2045
|
+
// Extract trailing slash config if present (attached by route())
|
|
2046
|
+
const trailingSlashConfig = (routes as any).__trailingSlash as
|
|
2047
|
+
| Record<string, TrailingSlashMode>
|
|
2048
|
+
| undefined;
|
|
2049
|
+
|
|
2050
|
+
// Create builder object so .use() can return it
|
|
2051
|
+
const builder: RouteBuilder<RouteDefinition, TEnv, any, TNewRoutes> = {
|
|
2052
|
+
use(
|
|
2053
|
+
patternOrMiddleware: string | MiddlewareFn<TEnv>,
|
|
2054
|
+
middleware?: MiddlewareFn<TEnv>,
|
|
2055
|
+
) {
|
|
2056
|
+
// Mount-scoped middleware - prefix is the mount prefix
|
|
2057
|
+
addMiddleware(patternOrMiddleware, middleware, prefix || null);
|
|
2058
|
+
return builder;
|
|
2059
|
+
},
|
|
2060
|
+
|
|
2061
|
+
map(
|
|
2062
|
+
handler:
|
|
2063
|
+
| ((
|
|
2064
|
+
helpers: InlineRouteHelpers<TNewRoutes, TEnv>,
|
|
2065
|
+
) => Array<AllUseItems>)
|
|
2066
|
+
| (() =>
|
|
2067
|
+
| Array<AllUseItems>
|
|
2068
|
+
| Promise<{ default: () => Array<AllUseItems> }>
|
|
2069
|
+
| Promise<() => Array<AllUseItems>>),
|
|
2070
|
+
) {
|
|
2071
|
+
// Store handler as-is - detection happens at call time based on return type
|
|
2072
|
+
// Both patterns use the same signature:
|
|
2073
|
+
// - Inline: ({ route }) => [...] - receives helpers, returns Array
|
|
2074
|
+
// - Lazy: () => import(...) - ignores helpers, returns Promise
|
|
2075
|
+
routesEntries.push({
|
|
2076
|
+
prefix,
|
|
2077
|
+
staticPrefix: extractStaticPrefix(prefix),
|
|
2078
|
+
routes: routes as ResolvedRouteMap<any>,
|
|
2079
|
+
trailingSlash: trailingSlashConfig,
|
|
2080
|
+
handler: handler as any,
|
|
2081
|
+
mountIndex: currentMountIndex,
|
|
2082
|
+
});
|
|
2083
|
+
// Return router with accumulated types
|
|
2084
|
+
// At runtime this is the same object, but TypeScript tracks the accumulated route types
|
|
2085
|
+
return router as any;
|
|
2086
|
+
},
|
|
2087
|
+
|
|
2088
|
+
// Expose accumulated route map for typeof extraction
|
|
2089
|
+
get routeMap() {
|
|
2090
|
+
return mergedRouteMap as TNewRoutes;
|
|
2091
|
+
},
|
|
2092
|
+
};
|
|
2093
|
+
|
|
2094
|
+
return builder;
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
/**
|
|
2098
|
+
* Router instance
|
|
2099
|
+
* The type system tracks accumulated routes through the builder chain
|
|
2100
|
+
* Initial TRoutes is {} (empty) to avoid poisoning accumulated types with Record<string, string>
|
|
2101
|
+
*/
|
|
2102
|
+
const router: RSCRouter<TEnv, {}> = {
|
|
2103
|
+
__brand: RSC_ROUTER_BRAND,
|
|
2104
|
+
id: routerId,
|
|
2105
|
+
|
|
2106
|
+
routes(
|
|
2107
|
+
prefixOrRoutes: string | Record<string, string> | UrlPatterns<TEnv>,
|
|
2108
|
+
maybeRoutes?: Record<string, string>,
|
|
2109
|
+
): any {
|
|
2110
|
+
// Note: Multiple .routes() calls are allowed for backwards compatibility
|
|
2111
|
+
// with the old map() pattern. For new code, prefer urls() with include().
|
|
2112
|
+
|
|
2113
|
+
// Check if argument is UrlPatterns (new Django-style API)
|
|
2114
|
+
// Detect by checking for handler and definitions properties
|
|
2115
|
+
if (
|
|
2116
|
+
typeof prefixOrRoutes === "object" &&
|
|
2117
|
+
prefixOrRoutes !== null &&
|
|
2118
|
+
"handler" in prefixOrRoutes &&
|
|
2119
|
+
"definitions" in prefixOrRoutes &&
|
|
2120
|
+
typeof (prefixOrRoutes as UrlPatterns<TEnv>).handler === "function"
|
|
2121
|
+
) {
|
|
2122
|
+
const urlPatterns = prefixOrRoutes as UrlPatterns<TEnv>;
|
|
2123
|
+
// Store reference for runtime manifest generation
|
|
2124
|
+
storedUrlPatterns = urlPatterns;
|
|
2125
|
+
const currentMountIndex = mountIndex++;
|
|
2126
|
+
|
|
2127
|
+
// Create manifest and patterns maps for route registration
|
|
2128
|
+
const manifest = new Map<string, EntryData>();
|
|
2129
|
+
const patterns = new Map<string, string>();
|
|
2130
|
+
const patternsByPrefix = new Map<string, Map<string, string>>();
|
|
2131
|
+
const trailingSlashMap = new Map<string, TrailingSlashMode>();
|
|
2132
|
+
|
|
2133
|
+
// Run the handler once to extract patterns for route matching
|
|
2134
|
+
// Note: loadManifest will re-run the handler to register entries in its context
|
|
2135
|
+
// Lazy includes are detected in the return value and handled separately
|
|
2136
|
+
let handlerResult: AllUseItems[] = [];
|
|
2137
|
+
RSCRouterContext.run(
|
|
2138
|
+
{
|
|
2139
|
+
manifest,
|
|
2140
|
+
patterns,
|
|
2141
|
+
patternsByPrefix,
|
|
2142
|
+
trailingSlash: trailingSlashMap,
|
|
2143
|
+
namespace: "root",
|
|
2144
|
+
parent: null,
|
|
2145
|
+
counters: {},
|
|
2146
|
+
},
|
|
2147
|
+
() => {
|
|
2148
|
+
// Execute the handler to collect patterns
|
|
2149
|
+
handlerResult = urlPatterns.handler() as AllUseItems[];
|
|
2150
|
+
},
|
|
2151
|
+
);
|
|
2152
|
+
|
|
2153
|
+
// Store the ORIGINAL handler - loadManifest will re-run it to register manifest entries
|
|
2154
|
+
// Convert trailingSlash map to object for the router
|
|
2155
|
+
const trailingSlashConfig =
|
|
2156
|
+
trailingSlashMap.size > 0
|
|
2157
|
+
? Object.fromEntries(trailingSlashMap)
|
|
2158
|
+
: undefined;
|
|
2159
|
+
|
|
2160
|
+
// Create separate RouteEntry for each URL prefix group
|
|
2161
|
+
// This enables prefix-based short-circuit optimization
|
|
2162
|
+
if (patternsByPrefix.size > 0) {
|
|
2163
|
+
for (const [prefix, prefixPatterns] of patternsByPrefix.entries()) {
|
|
2164
|
+
const routesObject: Record<string, string> = {};
|
|
2165
|
+
for (const [name, pattern] of prefixPatterns.entries()) {
|
|
2166
|
+
routesObject[name] = pattern;
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
routesEntries.push({
|
|
2170
|
+
// prefix is "" because patterns already include the URL prefix
|
|
2171
|
+
// (e.g., "/site/:locale/user1/:id" not just "/user1/:id")
|
|
2172
|
+
prefix: "",
|
|
2173
|
+
// staticPrefix is the actual prefix for short-circuit optimization
|
|
2174
|
+
staticPrefix: extractStaticPrefix(prefix),
|
|
2175
|
+
routes: routesObject as ResolvedRouteMap<any>,
|
|
2176
|
+
trailingSlash: trailingSlashConfig,
|
|
2177
|
+
handler: urlPatterns.handler,
|
|
2178
|
+
mountIndex: currentMountIndex,
|
|
2179
|
+
});
|
|
2180
|
+
}
|
|
2181
|
+
} else {
|
|
2182
|
+
// Fallback: no prefix grouping, use flat patterns map
|
|
2183
|
+
const routesObject: Record<string, string> = {};
|
|
2184
|
+
for (const [name, pattern] of patterns.entries()) {
|
|
2185
|
+
routesObject[name] = pattern;
|
|
2186
|
+
}
|
|
2187
|
+
|
|
2188
|
+
routesEntries.push({
|
|
2189
|
+
prefix: "",
|
|
2190
|
+
staticPrefix: "",
|
|
2191
|
+
routes: routesObject as ResolvedRouteMap<any>,
|
|
2192
|
+
trailingSlash: trailingSlashConfig,
|
|
2193
|
+
handler: urlPatterns.handler,
|
|
2194
|
+
mountIndex: currentMountIndex,
|
|
2195
|
+
});
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
// Build route map from registered patterns
|
|
2199
|
+
for (const [name, pattern] of patterns.entries()) {
|
|
2200
|
+
// Runtime validation: warn if key already exists with different pattern
|
|
2201
|
+
const existingPattern = mergedRouteMap[name];
|
|
2202
|
+
if (existingPattern !== undefined && existingPattern !== pattern) {
|
|
2203
|
+
console.warn(
|
|
2204
|
+
`[@rangojs/router] Route name conflict: "${name}" already maps to "${existingPattern}", ` +
|
|
2205
|
+
`overwriting with "${pattern}". Use unique route names to avoid this.`,
|
|
2206
|
+
);
|
|
2207
|
+
}
|
|
2208
|
+
mergedRouteMap[name] = pattern;
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
// Detect lazy includes in handler result and create placeholder entries
|
|
2212
|
+
// Uses findLazyIncludes from outer scope (shared with evaluateLazyEntry)
|
|
2213
|
+
const lazyIncludes = findLazyIncludes(handlerResult);
|
|
2214
|
+
|
|
2215
|
+
// Create placeholder RouteEntry for each lazy include
|
|
2216
|
+
for (const lazyInclude of lazyIncludes) {
|
|
2217
|
+
// Compute the full URL prefix (combining parent prefix if any)
|
|
2218
|
+
const fullPrefix = lazyInclude.context.urlPrefix
|
|
2219
|
+
? lazyInclude.context.urlPrefix + lazyInclude.prefix
|
|
2220
|
+
: lazyInclude.prefix;
|
|
2221
|
+
|
|
2222
|
+
const lazyEntry: RouteEntry<TEnv> & { _lazyPrefix?: string } = {
|
|
2223
|
+
prefix: "",
|
|
2224
|
+
staticPrefix: extractStaticPrefix(fullPrefix),
|
|
2225
|
+
routes: {} as ResolvedRouteMap<any>, // Empty until first match
|
|
2226
|
+
trailingSlash: trailingSlashConfig,
|
|
2227
|
+
handler: urlPatterns.handler,
|
|
2228
|
+
mountIndex: currentMountIndex,
|
|
2229
|
+
// Lazy evaluation fields
|
|
2230
|
+
lazy: true,
|
|
2231
|
+
lazyPatterns: lazyInclude.patterns,
|
|
2232
|
+
lazyContext: lazyInclude.context,
|
|
2233
|
+
lazyEvaluated: false,
|
|
2234
|
+
// Store the include prefix for evaluation
|
|
2235
|
+
_lazyPrefix: lazyInclude.prefix,
|
|
2236
|
+
};
|
|
2237
|
+
// Insert lazy entry before any entry whose staticPrefix is a
|
|
2238
|
+
// prefix of (but shorter than) this lazy entry's staticPrefix.
|
|
2239
|
+
// This ensures more specific lazy includes are matched before
|
|
2240
|
+
// less specific eager entries (e.g., "/href/nested" before "/href/:id").
|
|
2241
|
+
const lazyPrefix = lazyEntry.staticPrefix;
|
|
2242
|
+
let insertIndex = routesEntries.length;
|
|
2243
|
+
if (lazyPrefix) {
|
|
2244
|
+
for (let i = 0; i < routesEntries.length; i++) {
|
|
2245
|
+
const existing = routesEntries[i]!;
|
|
2246
|
+
if (
|
|
2247
|
+
lazyPrefix.startsWith(existing.staticPrefix) &&
|
|
2248
|
+
lazyPrefix.length > existing.staticPrefix.length
|
|
2249
|
+
) {
|
|
2250
|
+
insertIndex = i;
|
|
2251
|
+
break;
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
routesEntries.splice(insertIndex, 0, lazyEntry);
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
// Auto-register route map for runtime reverse() usage
|
|
2259
|
+
registerRouteMap(mergedRouteMap);
|
|
2260
|
+
|
|
2261
|
+
// Return the router (no .map() needed for UrlPatterns)
|
|
2262
|
+
return router;
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
// Legacy API: route() + map() pattern
|
|
2266
|
+
// If second argument exists, first is prefix
|
|
2267
|
+
if (maybeRoutes !== undefined) {
|
|
2268
|
+
return createRouteBuilder(prefixOrRoutes as string, maybeRoutes);
|
|
2269
|
+
}
|
|
2270
|
+
// Otherwise, first argument is routes with empty prefix
|
|
2271
|
+
return createRouteBuilder("", prefixOrRoutes as Record<string, string>);
|
|
2272
|
+
},
|
|
2273
|
+
|
|
2274
|
+
use(
|
|
2275
|
+
patternOrMiddleware: string | MiddlewareFn<TEnv>,
|
|
2276
|
+
middleware?: MiddlewareFn<TEnv>,
|
|
2277
|
+
): any {
|
|
2278
|
+
// Global middleware - no mount prefix
|
|
2279
|
+
addMiddleware(patternOrMiddleware, middleware, null);
|
|
2280
|
+
return router;
|
|
2281
|
+
},
|
|
2282
|
+
|
|
2283
|
+
// Type-safe URL builder using merged route map
|
|
2284
|
+
// Types are tracked through the builder chain via TRoutes parameter
|
|
2285
|
+
reverse: createReverse(mergedRouteMap),
|
|
2286
|
+
|
|
2287
|
+
// Expose accumulated route map for typeof extraction
|
|
2288
|
+
// Returns {} initially, but builder chain accumulates specific route types
|
|
2289
|
+
get routeMap() {
|
|
2290
|
+
return mergedRouteMap as {};
|
|
2291
|
+
},
|
|
2292
|
+
|
|
2293
|
+
// Expose rootLayout for renderSegments
|
|
2294
|
+
rootLayout,
|
|
2295
|
+
|
|
2296
|
+
// Expose onError callback for error handling
|
|
2297
|
+
onError,
|
|
2298
|
+
|
|
2299
|
+
// Expose cache configuration for RSC handler
|
|
2300
|
+
cache,
|
|
2301
|
+
|
|
2302
|
+
// Expose notFound component for RSC handler
|
|
2303
|
+
notFound,
|
|
2304
|
+
|
|
2305
|
+
// Expose resolved theme configuration for NavigationProvider and MetaTags
|
|
2306
|
+
themeConfig: resolvedThemeConfig,
|
|
2307
|
+
|
|
2308
|
+
// Expose warmup enabled flag for handler and client
|
|
2309
|
+
warmupEnabled,
|
|
2310
|
+
|
|
2311
|
+
// Expose debug manifest flag for handler
|
|
2312
|
+
allowDebugManifest: allowDebugManifestOption,
|
|
2313
|
+
|
|
2314
|
+
// Expose global middleware for RSC handler
|
|
2315
|
+
middleware: globalMiddleware,
|
|
2316
|
+
|
|
2317
|
+
match,
|
|
2318
|
+
matchPartial,
|
|
2319
|
+
matchError,
|
|
2320
|
+
previewMatch,
|
|
2321
|
+
|
|
2322
|
+
// Expose nonce provider for fetch
|
|
2323
|
+
nonce,
|
|
2324
|
+
|
|
2325
|
+
// Expose version for fetch
|
|
2326
|
+
version,
|
|
2327
|
+
|
|
2328
|
+
// Expose urlpatterns for runtime manifest generation
|
|
2329
|
+
get urlpatterns() {
|
|
2330
|
+
return storedUrlPatterns ?? undefined;
|
|
2331
|
+
},
|
|
2332
|
+
|
|
2333
|
+
// Expose source file for per-router type generation
|
|
2334
|
+
__sourceFile,
|
|
2335
|
+
|
|
2336
|
+
// RSC request handler (lazily created on first call)
|
|
2337
|
+
fetch: (() => {
|
|
2338
|
+
// Handler is created on first call and reused
|
|
2339
|
+
let handler:
|
|
2340
|
+
| ((
|
|
2341
|
+
request: Request,
|
|
2342
|
+
env: TEnv & { ctx?: ExecutionContext },
|
|
2343
|
+
) => Promise<Response>)
|
|
2344
|
+
| null = null;
|
|
2345
|
+
|
|
2346
|
+
return async (
|
|
2347
|
+
request: Request,
|
|
2348
|
+
env: TEnv & { ctx?: ExecutionContext },
|
|
2349
|
+
) => {
|
|
2350
|
+
if (!handler) {
|
|
2351
|
+
// Lazy import deferred to first request to avoid dev mode issues
|
|
2352
|
+
const { createRSCHandler } = await import("./rsc/handler.js");
|
|
2353
|
+
handler = createRSCHandler({
|
|
2354
|
+
router: router as any,
|
|
2355
|
+
cache,
|
|
2356
|
+
nonce,
|
|
2357
|
+
version,
|
|
2358
|
+
});
|
|
2359
|
+
}
|
|
2360
|
+
return handler(request, env);
|
|
2361
|
+
};
|
|
2362
|
+
})(),
|
|
2363
|
+
|
|
2364
|
+
// Debug utility for manifest inspection
|
|
2365
|
+
async debugManifest(): Promise<SerializedManifest> {
|
|
2366
|
+
const manifest = new Map<string, EntryData>();
|
|
2367
|
+
|
|
2368
|
+
for (const entry of routesEntries) {
|
|
2369
|
+
const Store = {
|
|
2370
|
+
manifest,
|
|
2371
|
+
namespace: `debug.M${entry.mountIndex}`,
|
|
2372
|
+
parent: null as EntryData | null,
|
|
2373
|
+
counters: {} as Record<string, number>,
|
|
2374
|
+
mountIndex: entry.mountIndex,
|
|
2375
|
+
patterns: new Map<string, string>(),
|
|
2376
|
+
trailingSlash: new Map<string, TrailingSlashMode>(),
|
|
2377
|
+
};
|
|
2378
|
+
|
|
2379
|
+
await getContext().runWithStore(
|
|
2380
|
+
Store,
|
|
2381
|
+
`debug.M${entry.mountIndex}`,
|
|
2382
|
+
null,
|
|
2383
|
+
async () => {
|
|
2384
|
+
const helpers = createRouteHelpers();
|
|
2385
|
+
|
|
2386
|
+
// Wrap handler execution in root layout (same as loadManifest)
|
|
2387
|
+
let promiseResult: Promise<any> | null = null;
|
|
2388
|
+
helpers.layout(MapRootLayout, () => {
|
|
2389
|
+
const result = entry.handler();
|
|
2390
|
+
if (result instanceof Promise) {
|
|
2391
|
+
promiseResult = result;
|
|
2392
|
+
return [];
|
|
2393
|
+
}
|
|
2394
|
+
return result;
|
|
2395
|
+
});
|
|
2396
|
+
|
|
2397
|
+
if (promiseResult !== null) {
|
|
2398
|
+
const load = await (promiseResult as Promise<any>);
|
|
2399
|
+
if (load && typeof load === "object" && "default" in load) {
|
|
2400
|
+
const useItems = load.default;
|
|
2401
|
+
if (typeof useItems === "function") {
|
|
2402
|
+
useItems(helpers);
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
},
|
|
2407
|
+
);
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
return serializeManifest(manifest);
|
|
2411
|
+
},
|
|
2412
|
+
};
|
|
2413
|
+
|
|
2414
|
+
// Register router in the global registry for build-time discovery
|
|
2415
|
+
RouterRegistry.set(routerId, router);
|
|
2416
|
+
|
|
2417
|
+
// If urls option was provided, auto-register them
|
|
2418
|
+
if (urlsOption) {
|
|
2419
|
+
return router.routes(urlsOption) as RSCRouter<TEnv, {}>;
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
return router;
|
|
2423
|
+
}
|