@rangojs/router 0.0.0-experimental.9 → 0.0.0-experimental.a5f27bd5
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/AGENTS.md +5 -0
- package/README.md +884 -4
- package/dist/bin/rango.js +1531 -155
- package/dist/vite/index.js +4440 -2170
- package/package.json +60 -54
- package/skills/breadcrumbs/SKILL.md +250 -0
- package/skills/cache-guide/SKILL.md +262 -0
- package/skills/caching/SKILL.md +50 -21
- package/skills/composability/SKILL.md +172 -0
- package/skills/debug-manifest/SKILL.md +12 -8
- package/skills/document-cache/SKILL.md +18 -16
- package/skills/fonts/SKILL.md +6 -4
- package/skills/hooks/SKILL.md +333 -71
- package/skills/host-router/SKILL.md +218 -0
- package/skills/intercept/SKILL.md +131 -8
- package/skills/layout/SKILL.md +100 -3
- package/skills/links/SKILL.md +74 -15
- package/skills/loader/SKILL.md +388 -38
- package/skills/middleware/SKILL.md +171 -34
- package/skills/mime-routes/SKILL.md +15 -11
- package/skills/parallel/SKILL.md +78 -1
- package/skills/prerender/SKILL.md +405 -45
- package/skills/rango/SKILL.md +85 -21
- package/skills/response-routes/SKILL.md +144 -91
- package/skills/route/SKILL.md +226 -14
- package/skills/router-setup/SKILL.md +123 -30
- package/skills/theme/SKILL.md +9 -8
- package/skills/typesafety/SKILL.md +316 -87
- package/skills/use-cache/SKILL.md +324 -0
- package/src/__internal.ts +102 -4
- package/src/bin/rango.ts +312 -15
- package/src/browser/action-coordinator.ts +97 -0
- package/src/browser/action-response-classifier.ts +99 -0
- package/src/browser/event-controller.ts +87 -64
- package/src/browser/history-state.ts +80 -0
- package/src/browser/intercept-utils.ts +52 -0
- package/src/browser/link-interceptor.ts +24 -4
- package/src/browser/logging.ts +55 -0
- package/src/browser/merge-segment-loaders.ts +20 -12
- package/src/browser/navigation-bridge.ts +285 -553
- package/src/browser/navigation-client.ts +123 -73
- package/src/browser/navigation-store.ts +33 -50
- package/src/browser/navigation-transaction.ts +295 -0
- package/src/browser/network-error-handler.ts +61 -0
- package/src/browser/partial-update.ts +261 -309
- package/src/browser/prefetch/cache.ts +154 -0
- package/src/browser/prefetch/fetch.ts +135 -0
- package/src/browser/prefetch/observer.ts +65 -0
- package/src/browser/prefetch/policy.ts +48 -0
- package/src/browser/prefetch/queue.ts +88 -0
- package/src/browser/rango-state.ts +112 -0
- package/src/browser/react/Link.tsx +182 -70
- package/src/browser/react/NavigationProvider.tsx +51 -11
- package/src/browser/react/context.ts +6 -0
- package/src/browser/react/filter-segment-order.ts +11 -0
- package/src/browser/react/index.ts +12 -12
- package/src/browser/react/location-state-shared.ts +95 -53
- package/src/browser/react/location-state.ts +60 -15
- package/src/browser/react/mount-context.ts +6 -1
- package/src/browser/react/nonce-context.ts +23 -0
- package/src/browser/react/shallow-equal.ts +27 -0
- package/src/browser/react/use-action.ts +29 -51
- package/src/browser/react/use-client-cache.ts +5 -3
- package/src/browser/react/use-handle.ts +29 -70
- package/src/browser/react/use-link-status.ts +6 -5
- package/src/browser/react/use-navigation.ts +22 -63
- package/src/browser/react/use-params.ts +65 -0
- package/src/browser/react/use-pathname.ts +47 -0
- package/src/browser/react/use-router.ts +63 -0
- package/src/browser/react/use-search-params.ts +56 -0
- package/src/browser/react/use-segments.ts +80 -97
- package/src/browser/response-adapter.ts +73 -0
- package/src/browser/rsc-router.tsx +106 -27
- package/src/browser/scroll-restoration.ts +92 -16
- package/src/browser/segment-reconciler.ts +216 -0
- package/src/browser/segment-structure-assert.ts +16 -0
- package/src/browser/server-action-bridge.ts +504 -599
- package/src/browser/shallow.ts +6 -1
- package/src/browser/types.ts +107 -47
- package/src/browser/validate-redirect-origin.ts +29 -0
- package/src/build/generate-manifest.ts +82 -21
- package/src/build/generate-route-types.ts +36 -752
- package/src/build/index.ts +6 -5
- package/src/build/route-trie.ts +39 -13
- package/src/build/route-types/ast-helpers.ts +25 -0
- package/src/build/route-types/ast-route-extraction.ts +98 -0
- package/src/build/route-types/codegen.ts +102 -0
- package/src/build/route-types/include-resolution.ts +411 -0
- package/src/build/route-types/param-extraction.ts +48 -0
- package/src/build/route-types/per-module-writer.ts +128 -0
- package/src/build/route-types/router-processing.ts +469 -0
- package/src/build/route-types/scan-filter.ts +78 -0
- package/src/build/runtime-discovery.ts +231 -0
- package/src/cache/background-task.ts +34 -0
- package/src/cache/cache-key-utils.ts +44 -0
- package/src/cache/cache-policy.ts +125 -0
- package/src/cache/cache-runtime.ts +338 -0
- package/src/cache/cache-scope.ts +120 -301
- package/src/cache/cf/cf-cache-store.ts +119 -7
- package/src/cache/cf/index.ts +8 -2
- package/src/cache/document-cache.ts +101 -72
- package/src/cache/handle-capture.ts +81 -0
- package/src/cache/handle-snapshot.ts +41 -0
- package/src/cache/index.ts +0 -15
- package/src/cache/memory-segment-store.ts +191 -13
- package/src/cache/profile-registry.ts +73 -0
- package/src/cache/read-through-swr.ts +134 -0
- package/src/cache/segment-codec.ts +256 -0
- package/src/cache/taint.ts +98 -0
- package/src/cache/types.ts +72 -122
- package/src/client.rsc.tsx +3 -1
- package/src/client.tsx +84 -126
- package/src/component-utils.ts +4 -4
- package/src/components/DefaultDocument.tsx +5 -1
- package/src/context-var.ts +86 -0
- package/src/debug.ts +17 -7
- package/src/errors.ts +77 -7
- package/src/handle.ts +15 -10
- package/src/handles/MetaTags.tsx +73 -20
- package/src/handles/breadcrumbs.ts +66 -0
- package/src/handles/index.ts +1 -0
- package/src/handles/meta.ts +30 -13
- package/src/host/cookie-handler.ts +21 -15
- package/src/host/errors.ts +8 -8
- package/src/host/index.ts +4 -7
- package/src/host/pattern-matcher.ts +27 -27
- package/src/host/router.ts +61 -39
- package/src/host/testing.ts +8 -8
- package/src/host/types.ts +15 -7
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +65 -45
- package/src/index.rsc.ts +133 -21
- package/src/index.ts +164 -52
- package/src/internal-debug.ts +11 -0
- package/src/loader.rsc.ts +25 -143
- package/src/loader.ts +27 -10
- package/src/network-error-thrower.tsx +3 -1
- package/src/outlet-provider.tsx +45 -0
- package/src/prerender/param-hash.ts +4 -2
- package/src/prerender/store.ts +158 -13
- package/src/prerender.ts +333 -26
- package/src/reverse.ts +184 -121
- package/src/root-error-boundary.tsx +41 -29
- package/src/route-content-wrapper.tsx +7 -4
- package/src/route-definition/dsl-helpers.ts +934 -0
- package/src/route-definition/helper-factories.ts +200 -0
- package/src/route-definition/helpers-types.ts +430 -0
- package/src/route-definition/index.ts +52 -0
- package/src/route-definition/redirect.ts +93 -0
- package/src/route-definition.ts +1 -1431
- package/src/route-map-builder.ts +156 -123
- package/src/route-name.ts +53 -0
- package/src/route-types.ts +48 -9
- package/src/router/content-negotiation.ts +116 -0
- package/src/router/debug-manifest.ts +72 -0
- package/src/router/error-handling.ts +9 -9
- package/src/router/find-match.ts +158 -0
- package/src/router/handler-context.ts +374 -81
- package/src/router/intercept-resolution.ts +24 -16
- package/src/router/lazy-includes.ts +234 -0
- package/src/router/loader-resolution.ts +215 -122
- package/src/router/logging.ts +248 -0
- package/src/router/manifest.ts +83 -32
- package/src/router/match-api.ts +118 -119
- package/src/router/match-context.ts +4 -2
- package/src/router/match-handlers.ts +440 -0
- package/src/router/match-middleware/background-revalidation.ts +80 -93
- package/src/router/match-middleware/cache-lookup.ts +336 -84
- package/src/router/match-middleware/cache-store.ts +43 -24
- package/src/router/match-middleware/intercept-resolution.ts +45 -20
- package/src/router/match-middleware/segment-resolution.ts +16 -8
- package/src/router/match-pipelines.ts +10 -45
- package/src/router/match-result.ts +34 -28
- package/src/router/metrics.ts +235 -15
- package/src/router/middleware-cookies.ts +55 -0
- package/src/router/middleware-types.ts +222 -0
- package/src/router/middleware.ts +324 -367
- package/src/router/pattern-matching.ts +197 -41
- package/src/router/prerender-match.ts +402 -0
- package/src/router/preview-match.ts +170 -0
- package/src/router/revalidation.ts +137 -38
- package/src/router/router-context.ts +36 -21
- package/src/router/router-interfaces.ts +452 -0
- package/src/router/router-options.ts +592 -0
- package/src/router/router-registry.ts +24 -0
- package/src/router/segment-resolution/fresh.ts +570 -0
- package/src/router/segment-resolution/helpers.ts +263 -0
- package/src/router/segment-resolution/loader-cache.ts +198 -0
- package/src/router/segment-resolution/revalidation.ts +1239 -0
- package/src/router/segment-resolution/static-store.ts +67 -0
- package/src/router/segment-resolution.ts +21 -1315
- package/src/router/segment-wrappers.ts +289 -0
- package/src/router/telemetry-otel.ts +299 -0
- package/src/router/telemetry.ts +300 -0
- package/src/router/timeout.ts +148 -0
- package/src/router/trie-matching.ts +96 -29
- package/src/router/types.ts +16 -9
- package/src/router.ts +590 -1983
- package/src/rsc/handler-context.ts +45 -0
- package/src/rsc/handler.ts +661 -1015
- package/src/rsc/helpers.ts +140 -6
- package/src/rsc/index.ts +0 -20
- package/src/rsc/loader-fetch.ts +209 -0
- package/src/rsc/manifest-init.ts +86 -0
- package/src/rsc/nonce.ts +14 -0
- package/src/rsc/origin-guard.ts +141 -0
- package/src/rsc/progressive-enhancement.ts +379 -0
- package/src/rsc/response-error.ts +37 -0
- package/src/rsc/response-route-handler.ts +347 -0
- package/src/rsc/rsc-rendering.ts +237 -0
- package/src/rsc/runtime-warnings.ts +42 -0
- package/src/rsc/server-action.ts +348 -0
- package/src/rsc/ssr-setup.ts +128 -0
- package/src/rsc/types.ts +38 -11
- package/src/search-params.ts +230 -0
- package/src/segment-system.tsx +25 -13
- package/src/server/context.ts +173 -48
- package/src/server/cookie-store.ts +190 -0
- package/src/server/fetchable-loader-store.ts +37 -0
- package/src/server/handle-store.ts +94 -15
- package/src/server/loader-registry.ts +15 -56
- package/src/server/request-context.ts +430 -70
- package/src/server.ts +35 -155
- package/src/ssr/index.tsx +100 -31
- package/src/static-handler.ts +114 -0
- package/src/theme/ThemeProvider.tsx +21 -15
- package/src/theme/ThemeScript.tsx +5 -5
- package/src/theme/constants.ts +5 -2
- package/src/theme/index.ts +4 -14
- package/src/theme/theme-context.ts +4 -30
- package/src/theme/theme-script.ts +21 -18
- package/src/types/boundaries.ts +158 -0
- package/src/types/cache-types.ts +198 -0
- package/src/types/error-types.ts +192 -0
- package/src/types/global-namespace.ts +100 -0
- package/src/types/handler-context.ts +687 -0
- package/src/types/index.ts +88 -0
- package/src/types/loader-types.ts +183 -0
- package/src/types/route-config.ts +170 -0
- package/src/types/route-entry.ts +102 -0
- package/src/types/segments.ts +148 -0
- package/src/types.ts +1 -1757
- package/src/urls/include-helper.ts +197 -0
- package/src/urls/index.ts +53 -0
- package/src/urls/path-helper-types.ts +339 -0
- package/src/urls/path-helper.ts +329 -0
- package/src/urls/pattern-types.ts +95 -0
- package/src/urls/response-types.ts +106 -0
- package/src/urls/type-extraction.ts +372 -0
- package/src/urls/urls-function.ts +98 -0
- package/src/urls.ts +1 -1282
- package/src/use-loader.tsx +85 -77
- package/src/vite/discovery/bundle-postprocess.ts +184 -0
- package/src/vite/discovery/discover-routers.ts +344 -0
- package/src/vite/discovery/prerender-collection.ts +385 -0
- package/src/vite/discovery/route-types-writer.ts +258 -0
- package/src/vite/discovery/self-gen-tracking.ts +47 -0
- package/src/vite/discovery/state.ts +110 -0
- package/src/vite/discovery/virtual-module-codegen.ts +203 -0
- package/src/vite/index.ts +11 -1963
- package/src/vite/plugin-types.ts +131 -0
- package/src/vite/plugins/cjs-to-esm.ts +93 -0
- package/src/vite/plugins/client-ref-dedup.ts +115 -0
- package/src/vite/plugins/client-ref-hashing.ts +105 -0
- package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -51
- package/src/vite/plugins/expose-id-utils.ts +287 -0
- package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
- package/src/vite/plugins/expose-ids/handler-transform.ts +179 -0
- package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
- package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
- package/src/vite/plugins/expose-ids/types.ts +45 -0
- package/src/vite/plugins/expose-internal-ids.ts +569 -0
- package/src/vite/plugins/refresh-cmd.ts +65 -0
- package/src/vite/plugins/use-cache-transform.ts +323 -0
- package/src/vite/plugins/version-injector.ts +83 -0
- package/src/vite/plugins/version-plugin.ts +254 -0
- package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
- package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
- package/src/vite/rango.ts +510 -0
- package/src/vite/router-discovery.ts +785 -0
- package/src/vite/utils/ast-handler-extract.ts +517 -0
- package/src/vite/utils/banner.ts +36 -0
- package/src/vite/utils/bundle-analysis.ts +137 -0
- package/src/vite/utils/manifest-utils.ts +70 -0
- package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
- package/src/vite/utils/prerender-utils.ts +189 -0
- package/src/vite/utils/shared-utils.ts +169 -0
- package/CLAUDE.md +0 -43
- package/src/browser/lru-cache.ts +0 -69
- package/src/browser/request-controller.ts +0 -164
- package/src/cache/memory-store.ts +0 -253
- package/src/href-context.ts +0 -33
- package/src/router.gen.ts +0 -6
- package/src/urls.gen.ts +0 -8
- package/src/vite/expose-handle-id.ts +0 -209
- package/src/vite/expose-loader-id.ts +0 -426
- package/src/vite/expose-location-state-id.ts +0 -177
- package/src/vite/expose-prerender-handler-id.ts +0 -429
- /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/src/router.ts
CHANGED
|
@@ -1,60 +1,44 @@
|
|
|
1
|
-
import type { ComponentType } from "react";
|
|
2
1
|
import { type ReactNode } from "react";
|
|
3
2
|
import { createCacheScope } from "./cache/cache-scope.js";
|
|
4
|
-
import
|
|
3
|
+
import {
|
|
4
|
+
setCacheProfiles,
|
|
5
|
+
resolveCacheProfiles,
|
|
6
|
+
} from "./cache/profile-registry.js";
|
|
7
|
+
import { isCachedFunction } from "./cache/taint.js";
|
|
5
8
|
import { assertClientComponent } from "./component-utils.js";
|
|
6
9
|
import { DefaultDocument } from "./components/DefaultDocument.js";
|
|
7
|
-
import {
|
|
8
|
-
|
|
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";
|
|
10
|
+
import type { SerializedManifest } from "./debug.js";
|
|
11
|
+
import { createReverse, type ReverseFunction } from "./reverse.js";
|
|
16
12
|
import {
|
|
17
13
|
registerRouteMap,
|
|
18
14
|
getPrecomputedEntries,
|
|
19
|
-
|
|
15
|
+
getRouterManifest,
|
|
16
|
+
getRouterPrecomputedEntries,
|
|
17
|
+
ensureRouterManifest,
|
|
20
18
|
} 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
19
|
import MapRootLayout from "./server/root-layout.js";
|
|
27
|
-
import type { AllUseItems
|
|
20
|
+
import type { AllUseItems } from "./route-types.js";
|
|
28
21
|
import type { UrlPatterns } from "./urls.js";
|
|
29
22
|
import {
|
|
30
23
|
EntryData,
|
|
31
|
-
InterceptEntry,
|
|
32
24
|
InterceptSelectorContext,
|
|
33
25
|
getContext,
|
|
34
26
|
RSCRouterContext,
|
|
35
|
-
runWithPrefixes,
|
|
36
27
|
type MetricsStore,
|
|
37
28
|
} from "./server/context";
|
|
38
29
|
import { createHandleStore, type HandleStore } from "./server/handle-store.js";
|
|
39
|
-
import {
|
|
30
|
+
import {
|
|
31
|
+
getRequestContext,
|
|
32
|
+
_getRequestContext,
|
|
33
|
+
} from "./server/request-context.js";
|
|
40
34
|
import type {
|
|
41
|
-
ErrorBoundaryHandler,
|
|
42
|
-
ErrorInfo,
|
|
43
35
|
ErrorPhase,
|
|
44
36
|
HandlerContext,
|
|
45
37
|
LoaderDataResult,
|
|
46
|
-
MatchResult,
|
|
47
|
-
NotFoundBoundaryHandler,
|
|
48
|
-
OnErrorCallback,
|
|
49
38
|
ResolvedRouteMap,
|
|
50
|
-
RouteDefinition,
|
|
51
39
|
RouteEntry,
|
|
52
40
|
TrailingSlashMode,
|
|
53
41
|
} from "./types";
|
|
54
|
-
import type {
|
|
55
|
-
NonceProvider,
|
|
56
|
-
} from "./rsc/types.js";
|
|
57
|
-
import type { ExecutionContext } from "./server/request-context.js";
|
|
58
42
|
|
|
59
43
|
// Extracted router utilities
|
|
60
44
|
import {
|
|
@@ -64,28 +48,10 @@ import {
|
|
|
64
48
|
invokeOnError,
|
|
65
49
|
} from "./router/error-handling.js";
|
|
66
50
|
|
|
67
|
-
// Extracted
|
|
68
|
-
import {
|
|
69
|
-
|
|
70
|
-
|
|
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";
|
|
51
|
+
// Extracted module factories
|
|
52
|
+
import { createSegmentWrappers } from "./router/segment-wrappers.js";
|
|
53
|
+
import { createMatchHandlers } from "./router/match-handlers.js";
|
|
54
|
+
import { buildDebugManifest } from "./router/debug-manifest.js";
|
|
89
55
|
|
|
90
56
|
import type { SegmentResolutionDeps, MatchApiDeps } from "./router/types.js";
|
|
91
57
|
import { createHandlerContext } from "./router/handler-context.js";
|
|
@@ -95,993 +61,78 @@ import {
|
|
|
95
61
|
wrapLoaderWithErrorHandling,
|
|
96
62
|
} from "./router/loader-resolution.js";
|
|
97
63
|
import { loadManifest } from "./router/manifest.js";
|
|
64
|
+
import { createMetricsStore } from "./router/metrics.js";
|
|
98
65
|
import {
|
|
99
|
-
createMetricsStore,
|
|
100
|
-
} from "./router/metrics.js";
|
|
101
|
-
import {
|
|
102
|
-
collectRouteMiddleware,
|
|
103
66
|
parsePattern,
|
|
104
67
|
type MiddlewareEntry,
|
|
105
68
|
type MiddlewareFn,
|
|
106
69
|
} from "./router/middleware.js";
|
|
107
70
|
import {
|
|
108
71
|
extractStaticPrefix,
|
|
109
|
-
findMatch as findRouteMatch,
|
|
110
|
-
isLazyEvaluationNeeded,
|
|
111
72
|
traverseBack,
|
|
112
|
-
type RouteMatchResult,
|
|
113
73
|
} from "./router/pattern-matching.js";
|
|
74
|
+
import { resolveSink, safeEmit, getRequestId } from "./router/telemetry.js";
|
|
114
75
|
import { evaluateRevalidation } from "./router/revalidation.js";
|
|
115
76
|
import {
|
|
116
77
|
type RouterContext,
|
|
117
78
|
runWithRouterContext,
|
|
118
79
|
} 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
80
|
import { resolveThemeConfig } from "./theme/constants.js";
|
|
81
|
+
import { resolveTimeouts } from "./router/timeout.js";
|
|
127
82
|
|
|
128
|
-
//
|
|
129
|
-
|
|
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;
|
|
83
|
+
// Extracted content negotiation utilities
|
|
84
|
+
import { flattenNamedRoutes } from "./router/content-negotiation.js";
|
|
686
85
|
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
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
|
-
match(request: Request, context: TEnv): Promise<MatchResult>;
|
|
964
|
-
|
|
965
|
-
/**
|
|
966
|
-
* Preview match - returns route middleware without segment resolution.
|
|
967
|
-
* Also returns responseType and handler for response routes (non-RSC short-circuit).
|
|
968
|
-
*/
|
|
969
|
-
previewMatch(
|
|
970
|
-
request: Request,
|
|
971
|
-
context: TEnv,
|
|
972
|
-
): Promise<{
|
|
973
|
-
routeMiddleware?: Array<{
|
|
974
|
-
handler: import("./router/middleware.js").MiddlewareFn;
|
|
975
|
-
params: Record<string, string>;
|
|
976
|
-
}>;
|
|
977
|
-
responseType?: string;
|
|
978
|
-
handler?: Function;
|
|
979
|
-
params?: Record<string, string>;
|
|
980
|
-
negotiated?: boolean;
|
|
981
|
-
} | null>;
|
|
982
|
-
|
|
983
|
-
matchPartial(
|
|
984
|
-
request: Request,
|
|
985
|
-
context: TEnv,
|
|
986
|
-
actionContext?: {
|
|
987
|
-
actionId?: string;
|
|
988
|
-
actionUrl?: URL;
|
|
989
|
-
actionResult?: any;
|
|
990
|
-
formData?: FormData;
|
|
991
|
-
},
|
|
992
|
-
): Promise<MatchResult | null>;
|
|
993
|
-
|
|
994
|
-
/**
|
|
995
|
-
* Match an error to the nearest error boundary and return error segments
|
|
996
|
-
*
|
|
997
|
-
* Used when an action or other operation fails and we need to render
|
|
998
|
-
* the error boundary UI. Finds the nearest errorBoundary in the route tree
|
|
999
|
-
* for the current URL and renders it with the error info.
|
|
1000
|
-
*
|
|
1001
|
-
* @param request - The current request (used to match the route)
|
|
1002
|
-
* @param context - Environment context
|
|
1003
|
-
* @param error - The error that occurred
|
|
1004
|
-
* @param segmentType - Type of segment where error occurred (default: "route")
|
|
1005
|
-
* @returns MatchResult with error segment, or null if no error boundary found
|
|
1006
|
-
*/
|
|
1007
|
-
matchError(
|
|
1008
|
-
request: Request,
|
|
1009
|
-
context: TEnv,
|
|
1010
|
-
error: unknown,
|
|
1011
|
-
segmentType?: ErrorInfo["segmentType"],
|
|
1012
|
-
): Promise<MatchResult | null>;
|
|
1013
|
-
|
|
1014
|
-
/**
|
|
1015
|
-
* @internal
|
|
1016
|
-
* Debug utility to serialize the manifest for inspection
|
|
1017
|
-
* Returns a JSON-friendly representation of all routes and layouts
|
|
1018
|
-
*/
|
|
1019
|
-
debugManifest(): Promise<SerializedManifest>;
|
|
1020
|
-
|
|
1021
|
-
/**
|
|
1022
|
-
* Handle an RSC request.
|
|
1023
|
-
*
|
|
1024
|
-
* Uses the router's configuration (nonce, version, cache) automatically.
|
|
1025
|
-
* The handler is lazily created on first call.
|
|
1026
|
-
*
|
|
1027
|
-
* @example Cloudflare Workers
|
|
1028
|
-
* ```tsx
|
|
1029
|
-
* import { router } from "./router";
|
|
1030
|
-
*
|
|
1031
|
-
* export default { fetch: router.fetch };
|
|
1032
|
-
* ```
|
|
1033
|
-
*
|
|
1034
|
-
* @example Direct export
|
|
1035
|
-
* ```tsx
|
|
1036
|
-
* const router = createRouter({
|
|
1037
|
-
* document: Document,
|
|
1038
|
-
* urls: urlpatterns,
|
|
1039
|
-
* nonce: () => true,
|
|
1040
|
-
* });
|
|
1041
|
-
*
|
|
1042
|
-
* export const fetch = router.fetch;
|
|
1043
|
-
* ```
|
|
1044
|
-
*/
|
|
1045
|
-
fetch(
|
|
1046
|
-
request: Request,
|
|
1047
|
-
env: TEnv & { ctx?: ExecutionContext },
|
|
1048
|
-
): Promise<Response>;
|
|
1049
|
-
}
|
|
86
|
+
// Extracted router types and registry
|
|
87
|
+
import {
|
|
88
|
+
RSC_ROUTER_BRAND,
|
|
89
|
+
RouterRegistry,
|
|
90
|
+
nextRouterAutoId,
|
|
91
|
+
} from "./router/router-registry.js";
|
|
92
|
+
import type {
|
|
93
|
+
RSCRouterOptions,
|
|
94
|
+
RootLayoutProps,
|
|
95
|
+
} from "./router/router-options.js";
|
|
96
|
+
import type {
|
|
97
|
+
RSCRouter,
|
|
98
|
+
RSCRouterInternal,
|
|
99
|
+
RouterRequestInput,
|
|
100
|
+
} from "./router/router-interfaces.js";
|
|
1050
101
|
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
*/
|
|
102
|
+
// Extracted closure functions
|
|
103
|
+
import {
|
|
104
|
+
findLazyIncludes,
|
|
105
|
+
evaluateLazyEntry as _evaluateLazyEntry,
|
|
106
|
+
type LazyEvalDeps,
|
|
107
|
+
} from "./router/lazy-includes.js";
|
|
108
|
+
import { createFindMatch } from "./router/find-match.js";
|
|
109
|
+
import {
|
|
110
|
+
matchForPrerender as _matchForPrerender,
|
|
111
|
+
renderStaticSegment as _renderStaticSegment,
|
|
112
|
+
} from "./router/prerender-match.js";
|
|
113
|
+
|
|
114
|
+
// Re-export public types and values from extracted modules
|
|
115
|
+
export { RSC_ROUTER_BRAND, RouterRegistry } from "./router/router-registry.js";
|
|
116
|
+
export type {
|
|
117
|
+
RSCRouterOptions,
|
|
118
|
+
RootLayoutProps,
|
|
119
|
+
SSRStreamMode,
|
|
120
|
+
SSROptions,
|
|
121
|
+
ResolveStreamingContext,
|
|
122
|
+
} from "./router/router-options.js";
|
|
123
|
+
export type {
|
|
124
|
+
RSCRouter,
|
|
125
|
+
RSCRouterInternal,
|
|
126
|
+
RouterRequestInput,
|
|
127
|
+
} from "./router/router-interfaces.js";
|
|
128
|
+
export { toInternal } from "./router/router-interfaces.js";
|
|
1079
129
|
|
|
1080
130
|
export function createRouter<TEnv = any>(
|
|
1081
131
|
options: RSCRouterOptions<TEnv> = {},
|
|
1082
132
|
): RSCRouter<TEnv, {}> {
|
|
1083
133
|
const {
|
|
1084
134
|
id: userProvidedId,
|
|
135
|
+
$$id: injectedId,
|
|
1085
136
|
debugPerformance = false,
|
|
1086
137
|
document: documentOption,
|
|
1087
138
|
defaultErrorBoundary,
|
|
@@ -1089,15 +140,77 @@ export function createRouter<TEnv = any>(
|
|
|
1089
140
|
notFound,
|
|
1090
141
|
onError,
|
|
1091
142
|
cache,
|
|
143
|
+
cacheProfiles: cacheProfilesOption,
|
|
1092
144
|
theme: themeOption,
|
|
1093
145
|
urls: urlsOption,
|
|
146
|
+
$$routeNames: staticRouteNames,
|
|
147
|
+
$$sourceFile: injectedSourceFile,
|
|
1094
148
|
nonce,
|
|
1095
149
|
version,
|
|
150
|
+
prefetchCacheTTL: prefetchCacheTTLOption,
|
|
1096
151
|
warmup: warmupOption,
|
|
1097
|
-
allowDebugManifest: allowDebugManifestOption =
|
|
152
|
+
allowDebugManifest: allowDebugManifestOption = false,
|
|
153
|
+
telemetry: telemetrySink,
|
|
154
|
+
ssr: ssrOption,
|
|
155
|
+
timeout: timeoutShorthand,
|
|
156
|
+
timeouts: timeoutsOption,
|
|
157
|
+
onTimeout,
|
|
158
|
+
originCheck: originCheckOption,
|
|
1098
159
|
} = options;
|
|
1099
160
|
|
|
1100
|
-
|
|
161
|
+
// Resolve telemetry sink (no-op when not configured)
|
|
162
|
+
const telemetry = resolveSink(telemetrySink);
|
|
163
|
+
|
|
164
|
+
// Resolve cache profiles: merge user config with guaranteed default profile.
|
|
165
|
+
// This resolved map is both stored on the router (for per-request context)
|
|
166
|
+
// and written to the global registry (for DSL-time cache("profileName")).
|
|
167
|
+
const resolvedCacheProfiles = resolveCacheProfiles(cacheProfilesOption);
|
|
168
|
+
setCacheProfiles(resolvedCacheProfiles);
|
|
169
|
+
|
|
170
|
+
// Source file: prefer Vite-injected path (zero cost), fall back to
|
|
171
|
+
// stack trace parsing for non-Vite environments (e.g. tests).
|
|
172
|
+
let __sourceFile: string | undefined = injectedSourceFile;
|
|
173
|
+
if (!__sourceFile) {
|
|
174
|
+
try {
|
|
175
|
+
const stack = new Error().stack;
|
|
176
|
+
if (stack) {
|
|
177
|
+
const lines = stack.split("\n");
|
|
178
|
+
for (const line of lines) {
|
|
179
|
+
const match = line.match(/\((.+?\.(ts|tsx|js|jsx)):\d+:\d+\)/);
|
|
180
|
+
if (
|
|
181
|
+
match &&
|
|
182
|
+
!match[1].endsWith("/router.ts") &&
|
|
183
|
+
!match[1].includes("@rangojs/router") &&
|
|
184
|
+
!match[1].includes("node_modules")
|
|
185
|
+
) {
|
|
186
|
+
__sourceFile = match[1].startsWith("file:")
|
|
187
|
+
? match[1].slice(5)
|
|
188
|
+
: match[1];
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
} catch {}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Router ID priority: explicit id > Vite-injected $$id > counter fallback.
|
|
197
|
+
// $$id is a hash of filename+line injected by the Vite transform at compile
|
|
198
|
+
// time, so it's stable across build/runtime regardless of module evaluation
|
|
199
|
+
// order (unlike the counter which depends on import order).
|
|
200
|
+
const routerId =
|
|
201
|
+
userProvidedId ?? injectedId ?? `router_${nextRouterAutoId()}`;
|
|
202
|
+
|
|
203
|
+
// Resolve prefetch cache TTL (default: 300 seconds / 5 minutes)
|
|
204
|
+
// Clamp to a non-negative integer for valid Cache-Control max-age.
|
|
205
|
+
const rawTTL =
|
|
206
|
+
prefetchCacheTTLOption !== undefined ? prefetchCacheTTLOption : 300;
|
|
207
|
+
const prefetchCacheTTLSeconds =
|
|
208
|
+
rawTTL === false ? 0 : Math.max(0, Math.floor(rawTTL));
|
|
209
|
+
const prefetchCacheTTL = prefetchCacheTTLSeconds * 1000;
|
|
210
|
+
const prefetchCacheControl: string | false =
|
|
211
|
+
prefetchCacheTTLSeconds === 0
|
|
212
|
+
? false
|
|
213
|
+
: `private, max-age=${prefetchCacheTTLSeconds}`;
|
|
1101
214
|
|
|
1102
215
|
// Resolve warmup enabled flag (default: true)
|
|
1103
216
|
const warmupEnabled = warmupOption !== false;
|
|
@@ -1107,15 +220,29 @@ export function createRouter<TEnv = any>(
|
|
|
1107
220
|
? resolveThemeConfig(themeOption)
|
|
1108
221
|
: null;
|
|
1109
222
|
|
|
223
|
+
// Resolve timeout config (merge shorthand + structured)
|
|
224
|
+
const resolvedTimeouts = resolveTimeouts(timeoutShorthand, timeoutsOption);
|
|
225
|
+
|
|
1110
226
|
/**
|
|
1111
227
|
* Wrapper for invokeOnError that binds the router's onError callback.
|
|
1112
228
|
* Uses the shared utility from router/error-handling.ts for consistent behavior.
|
|
229
|
+
*
|
|
230
|
+
* Deduplicates via per-request WeakSet stored on the ALS request context.
|
|
231
|
+
* A closure-level WeakSet would silently swallow errors if the same object
|
|
232
|
+
* instance is thrown across separate requests (e.g. a singleton error).
|
|
1113
233
|
*/
|
|
1114
234
|
function callOnError(
|
|
1115
235
|
error: unknown,
|
|
1116
236
|
phase: ErrorPhase,
|
|
1117
237
|
context: Parameters<typeof invokeOnError<TEnv>>[3],
|
|
1118
238
|
): void {
|
|
239
|
+
if (error != null && typeof error === "object") {
|
|
240
|
+
const reportedErrors = _getRequestContext()?._reportedErrors;
|
|
241
|
+
if (reportedErrors) {
|
|
242
|
+
if (reportedErrors.has(error)) return;
|
|
243
|
+
reportedErrors.add(error);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
1119
246
|
invokeOnError(onError, error, phase, context, "Router");
|
|
1120
247
|
}
|
|
1121
248
|
|
|
@@ -1158,6 +285,18 @@ export function createRouter<TEnv = any>(
|
|
|
1158
285
|
handler = patternOrMiddleware;
|
|
1159
286
|
}
|
|
1160
287
|
|
|
288
|
+
// Prevent "use cache" functions from being used as middleware.
|
|
289
|
+
// They return data/JSX and do not call next() — silently accepting
|
|
290
|
+
// them would be a confusing no-op.
|
|
291
|
+
if (isCachedFunction(handler)) {
|
|
292
|
+
throw new Error(
|
|
293
|
+
`A "use cache" function cannot be used as middleware. ` +
|
|
294
|
+
`Cached functions return data and do not participate in the ` +
|
|
295
|
+
`middleware chain. Remove the "use cache" directive or use a ` +
|
|
296
|
+
`regular middleware function instead.`,
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
1161
300
|
// If mount-scoped, prepend mount prefix to pattern
|
|
1162
301
|
let fullPattern = pattern;
|
|
1163
302
|
if (mountPrefix && pattern) {
|
|
@@ -1187,20 +326,55 @@ export function createRouter<TEnv = any>(
|
|
|
1187
326
|
});
|
|
1188
327
|
}
|
|
1189
328
|
|
|
1190
|
-
// Track all registered routes with their prefixes for reverse()
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
329
|
+
// Track all registered routes with their prefixes for reverse().
|
|
330
|
+
// Seed from injected NamedRoutes so reverse() works at module load time
|
|
331
|
+
// for routes that come from lazy includes.
|
|
332
|
+
const mergedRouteMap: Record<string, string> =
|
|
333
|
+
flattenNamedRoutes(staticRouteNames);
|
|
334
|
+
|
|
335
|
+
// Track names that came from the static seed so we can silently overwrite
|
|
336
|
+
// them during routes() registration. The gen file may be stale during HMR,
|
|
337
|
+
// so conflicts between seeded and runtime-registered values are expected.
|
|
338
|
+
const seededNames = new Set(Object.keys(mergedRouteMap));
|
|
339
|
+
|
|
340
|
+
// Lazy precomputed entries lookup: rebuilt when per-router data arrives.
|
|
341
|
+
// In production multi-router setups, per-router data is loaded lazily via
|
|
342
|
+
// ensureRouterManifest(). At createRouter() time the data isn't available yet,
|
|
343
|
+
// so we defer building the Map until first use and invalidate when the
|
|
344
|
+
// per-router source changes.
|
|
345
|
+
let precomputedByPrefix: Map<string, Record<string, string>> | null = null;
|
|
346
|
+
let precomputedSource:
|
|
347
|
+
| Array<{ staticPrefix: string; routes: Record<string, string> }>
|
|
348
|
+
| null
|
|
349
|
+
| undefined;
|
|
350
|
+
|
|
351
|
+
function getPrecomputedByPrefix(): Map<
|
|
352
|
+
string,
|
|
353
|
+
Record<string, string>
|
|
354
|
+
> | null {
|
|
355
|
+
const current =
|
|
356
|
+
getRouterPrecomputedEntries(routerId) ?? getPrecomputedEntries();
|
|
357
|
+
if (current !== precomputedSource) {
|
|
358
|
+
precomputedSource = current;
|
|
359
|
+
precomputedByPrefix = current
|
|
360
|
+
? new Map(current.map((e) => [e.staticPrefix, e.routes]))
|
|
361
|
+
: null;
|
|
362
|
+
}
|
|
363
|
+
return precomputedByPrefix;
|
|
364
|
+
}
|
|
1201
365
|
|
|
1202
|
-
// Wrapper to pass debugPerformance to external createMetricsStore
|
|
1203
|
-
|
|
366
|
+
// Wrapper to pass debugPerformance to external createMetricsStore.
|
|
367
|
+
// Also checks per-request flag set by ctx.debugPerformance() in middleware.
|
|
368
|
+
const getMetricsStore = () => {
|
|
369
|
+
const reqCtx = _getRequestContext();
|
|
370
|
+
const enabled = debugPerformance || !!reqCtx?._debugPerformance;
|
|
371
|
+
if (!enabled) return undefined;
|
|
372
|
+
if (!reqCtx) {
|
|
373
|
+
return createMetricsStore(true);
|
|
374
|
+
}
|
|
375
|
+
reqCtx._metricsStore ??= createMetricsStore(true);
|
|
376
|
+
return reqCtx._metricsStore;
|
|
377
|
+
};
|
|
1204
378
|
|
|
1205
379
|
// Wrapper to pass defaults to error/notFound boundary finders
|
|
1206
380
|
const findNearestErrorBoundary = (entry: EntryData | null) =>
|
|
@@ -1211,17 +385,46 @@ export function createRouter<TEnv = any>(
|
|
|
1211
385
|
|
|
1212
386
|
// Helper to get handleStore from request context
|
|
1213
387
|
const getHandleStore = (): HandleStore | undefined => {
|
|
1214
|
-
return
|
|
388
|
+
return _getRequestContext()?._handleStore;
|
|
1215
389
|
};
|
|
1216
390
|
|
|
1217
|
-
// Track a pending handler promise (non-blocking)
|
|
1218
|
-
|
|
391
|
+
// Track a pending handler promise (non-blocking).
|
|
392
|
+
// Attaches a side-effect .catch() to report streaming handler errors to onError
|
|
393
|
+
// without altering the rejection chain (React's streaming error boundary still handles it).
|
|
394
|
+
const trackHandler = <T>(
|
|
395
|
+
promise: Promise<T>,
|
|
396
|
+
errorContext?: {
|
|
397
|
+
segmentId?: string;
|
|
398
|
+
segmentType?: string;
|
|
399
|
+
},
|
|
400
|
+
): Promise<T> => {
|
|
1219
401
|
const store = getHandleStore();
|
|
1220
|
-
|
|
402
|
+
const tracked = store ? store.track(promise) : promise;
|
|
403
|
+
|
|
404
|
+
// Report streaming handler errors to onError as a side-effect.
|
|
405
|
+
// The rejection still propagates to the RSC stream for client error boundaries.
|
|
406
|
+
// Captures request context eagerly (closure) so the catch handler has full context.
|
|
407
|
+
const reqCtx = _getRequestContext();
|
|
408
|
+
if (reqCtx && onError) {
|
|
409
|
+
tracked.catch((error) => {
|
|
410
|
+
callOnError(error, "handler", {
|
|
411
|
+
request: reqCtx.request,
|
|
412
|
+
url: reqCtx.url,
|
|
413
|
+
routeKey: reqCtx._routeName,
|
|
414
|
+
params: reqCtx.params as Record<string, string>,
|
|
415
|
+
env: reqCtx.env as TEnv,
|
|
416
|
+
segmentId: errorContext?.segmentId,
|
|
417
|
+
segmentType: errorContext?.segmentType as any,
|
|
418
|
+
handledByBoundary: true,
|
|
419
|
+
});
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return tracked;
|
|
1221
424
|
};
|
|
1222
425
|
|
|
1223
426
|
// Wrapper for wrapLoaderWithErrorHandling that uses router's error boundary finder
|
|
1224
|
-
// Includes onError callback for loader error notification
|
|
427
|
+
// Includes onError callback for loader error notification and telemetry emission.
|
|
1225
428
|
function wrapLoaderPromise<T>(
|
|
1226
429
|
promise: Promise<T>,
|
|
1227
430
|
entry: EntryData,
|
|
@@ -1237,7 +440,25 @@ export function createRouter<TEnv = any>(
|
|
|
1237
440
|
requestStartTime?: number;
|
|
1238
441
|
},
|
|
1239
442
|
): Promise<LoaderDataResult<T>> {
|
|
1240
|
-
|
|
443
|
+
const loaderStart = telemetrySink ? performance.now() : 0;
|
|
444
|
+
const loaderRequestId = telemetrySink
|
|
445
|
+
? errorContext?.request
|
|
446
|
+
? getRequestId(errorContext.request)
|
|
447
|
+
: undefined
|
|
448
|
+
: undefined;
|
|
449
|
+
if (telemetrySink) {
|
|
450
|
+
const loaderName = segmentId.split(".").pop() || "unknown";
|
|
451
|
+
safeEmit(telemetry, {
|
|
452
|
+
type: "loader.start",
|
|
453
|
+
timestamp: loaderStart,
|
|
454
|
+
requestId: loaderRequestId,
|
|
455
|
+
segmentId,
|
|
456
|
+
loaderName,
|
|
457
|
+
pathname,
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const result = wrapLoaderWithErrorHandling(
|
|
1241
462
|
promise,
|
|
1242
463
|
entry,
|
|
1243
464
|
segmentId,
|
|
@@ -1260,9 +481,42 @@ export function createRouter<TEnv = any>(
|
|
|
1260
481
|
handledByBoundary: ctx.handledByBoundary,
|
|
1261
482
|
requestStartTime: errorContext.requestStartTime,
|
|
1262
483
|
});
|
|
484
|
+
if (telemetrySink) {
|
|
485
|
+
const errorObj =
|
|
486
|
+
error instanceof Error ? error : new Error(String(error));
|
|
487
|
+
safeEmit(telemetry, {
|
|
488
|
+
type: "loader.error",
|
|
489
|
+
timestamp: performance.now(),
|
|
490
|
+
requestId: loaderRequestId,
|
|
491
|
+
segmentId: ctx.segmentId,
|
|
492
|
+
loaderName: ctx.loaderName,
|
|
493
|
+
pathname,
|
|
494
|
+
error: errorObj,
|
|
495
|
+
handledByBoundary: ctx.handledByBoundary,
|
|
496
|
+
});
|
|
497
|
+
}
|
|
1263
498
|
}
|
|
1264
499
|
: undefined,
|
|
1265
500
|
);
|
|
501
|
+
|
|
502
|
+
// Emit loader.end after the promise settles (fire-and-forget)
|
|
503
|
+
if (telemetrySink) {
|
|
504
|
+
const loaderName = segmentId.split(".").pop() || "unknown";
|
|
505
|
+
result.then((r) => {
|
|
506
|
+
safeEmit(telemetry, {
|
|
507
|
+
type: "loader.end",
|
|
508
|
+
timestamp: performance.now(),
|
|
509
|
+
requestId: loaderRequestId,
|
|
510
|
+
segmentId,
|
|
511
|
+
loaderName,
|
|
512
|
+
pathname,
|
|
513
|
+
durationMs: performance.now() - loaderStart,
|
|
514
|
+
ok: r.ok,
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
return result;
|
|
1266
520
|
}
|
|
1267
521
|
|
|
1268
522
|
// Dependencies object for extracted segment resolution functions.
|
|
@@ -1283,438 +537,45 @@ export function createRouter<TEnv = any>(
|
|
|
1283
537
|
findInterceptForRoute(routeKey, parentEntry, selectorContext, isAction),
|
|
1284
538
|
callOnError,
|
|
1285
539
|
findNearestErrorBoundary,
|
|
540
|
+
// Use per-router manifest when available, otherwise the static named map
|
|
541
|
+
// seeded into mergedRouteMap at router creation.
|
|
542
|
+
getRouteMap: () => getRouterManifest(routerId) ?? mergedRouteMap,
|
|
1286
543
|
};
|
|
1287
544
|
|
|
1288
|
-
//
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
)
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
|
-
function resolveLoadersOnlyWithRevalidation(
|
|
1310
|
-
entries: EntryData[],
|
|
1311
|
-
context: HandlerContext<any, TEnv>,
|
|
1312
|
-
clientSegmentIds: Set<string>,
|
|
1313
|
-
prevParams: Record<string, string>,
|
|
1314
|
-
request: Request,
|
|
1315
|
-
prevUrl: URL,
|
|
1316
|
-
nextUrl: URL,
|
|
1317
|
-
routeKey: string,
|
|
1318
|
-
actionContext?: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData },
|
|
1319
|
-
) {
|
|
1320
|
-
return _resolveLoadersOnlyWithRevalidation(
|
|
1321
|
-
entries, context, clientSegmentIds, prevParams, request,
|
|
1322
|
-
prevUrl, nextUrl, routeKey, segmentDeps, actionContext,
|
|
1323
|
-
);
|
|
1324
|
-
}
|
|
1325
|
-
|
|
1326
|
-
function buildEntryRevalidateMap(entries: EntryData[]) {
|
|
1327
|
-
return _buildEntryRevalidateMap(entries);
|
|
1328
|
-
}
|
|
1329
|
-
|
|
1330
|
-
function resolveAllSegmentsWithRevalidation(
|
|
1331
|
-
entries: EntryData[],
|
|
1332
|
-
routeKey: string,
|
|
1333
|
-
params: Record<string, string>,
|
|
1334
|
-
context: HandlerContext<any, TEnv>,
|
|
1335
|
-
clientSegmentSet: Set<string>,
|
|
1336
|
-
prevParams: Record<string, string>,
|
|
1337
|
-
request: Request,
|
|
1338
|
-
prevUrl: URL,
|
|
1339
|
-
nextUrl: URL,
|
|
1340
|
-
loaderPromises: Map<string, Promise<any>>,
|
|
1341
|
-
actionContext: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData } | undefined,
|
|
1342
|
-
interceptResult: { intercept: InterceptEntry; entry: EntryData } | null,
|
|
1343
|
-
localRouteName: string,
|
|
1344
|
-
pathname: string,
|
|
1345
|
-
) {
|
|
1346
|
-
return _resolveAllSegmentsWithRevalidation(
|
|
1347
|
-
entries, routeKey, params, context, clientSegmentSet, prevParams, request,
|
|
1348
|
-
prevUrl, nextUrl, loaderPromises, actionContext, interceptResult,
|
|
1349
|
-
localRouteName, pathname, segmentDeps,
|
|
1350
|
-
);
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
function findInterceptForRoute(
|
|
1354
|
-
targetRouteKey: string,
|
|
1355
|
-
fromEntry: EntryData | null,
|
|
1356
|
-
selectorContext: InterceptSelectorContext | null = null,
|
|
1357
|
-
isAction: boolean = false,
|
|
1358
|
-
) {
|
|
1359
|
-
return _findInterceptForRoute(targetRouteKey, fromEntry, selectorContext, isAction);
|
|
1360
|
-
}
|
|
1361
|
-
|
|
1362
|
-
function resolveInterceptEntry(
|
|
1363
|
-
interceptEntry: InterceptEntry,
|
|
1364
|
-
parentEntry: EntryData,
|
|
1365
|
-
params: Record<string, string>,
|
|
1366
|
-
context: HandlerContext<any, TEnv>,
|
|
1367
|
-
belongsToRoute: boolean = true,
|
|
1368
|
-
revalidationContext?: any,
|
|
1369
|
-
) {
|
|
1370
|
-
return _resolveInterceptEntry(
|
|
1371
|
-
interceptEntry, parentEntry, params, context, belongsToRoute,
|
|
1372
|
-
segmentDeps, revalidationContext,
|
|
1373
|
-
);
|
|
1374
|
-
}
|
|
1375
|
-
|
|
1376
|
-
function resolveInterceptLoadersOnly(
|
|
1377
|
-
interceptEntry: InterceptEntry,
|
|
1378
|
-
parentEntry: EntryData,
|
|
1379
|
-
params: Record<string, string>,
|
|
1380
|
-
context: HandlerContext<any, TEnv>,
|
|
1381
|
-
belongsToRoute: boolean = true,
|
|
1382
|
-
revalidationContext: any,
|
|
1383
|
-
) {
|
|
1384
|
-
return _resolveInterceptLoadersOnly(
|
|
1385
|
-
interceptEntry, parentEntry, params, context, belongsToRoute,
|
|
1386
|
-
segmentDeps, revalidationContext,
|
|
1387
|
-
);
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
// Detect lazy includes in handler result and create placeholder entries
|
|
1391
|
-
// Lazy includes are IncludeItem with lazy: true and _lazyContext
|
|
1392
|
-
// Moved to outer scope so it can be reused by evaluateLazyEntry for nested includes
|
|
1393
|
-
function findLazyIncludes(items: AllUseItems[]): Array<{
|
|
1394
|
-
prefix: string;
|
|
1395
|
-
patterns: UrlPatterns<TEnv>;
|
|
1396
|
-
context: {
|
|
1397
|
-
urlPrefix: string;
|
|
1398
|
-
namePrefix: string | undefined;
|
|
1399
|
-
parent: unknown;
|
|
1400
|
-
};
|
|
1401
|
-
}> {
|
|
1402
|
-
const lazyItems: Array<{
|
|
1403
|
-
prefix: string;
|
|
1404
|
-
patterns: UrlPatterns<TEnv>;
|
|
1405
|
-
context: {
|
|
1406
|
-
urlPrefix: string;
|
|
1407
|
-
namePrefix: string | undefined;
|
|
1408
|
-
parent: unknown;
|
|
1409
|
-
};
|
|
1410
|
-
}> = [];
|
|
1411
|
-
|
|
1412
|
-
for (const item of items) {
|
|
1413
|
-
if (!item) continue;
|
|
1414
|
-
if (item.type === "include") {
|
|
1415
|
-
const includeItem = item as IncludeItem;
|
|
1416
|
-
if (includeItem.lazy === true && includeItem._lazyContext) {
|
|
1417
|
-
lazyItems.push({
|
|
1418
|
-
prefix: includeItem.prefix,
|
|
1419
|
-
patterns: includeItem.patterns as UrlPatterns<TEnv>,
|
|
1420
|
-
context: includeItem._lazyContext,
|
|
1421
|
-
});
|
|
1422
|
-
}
|
|
1423
|
-
}
|
|
1424
|
-
// Recursively check nested items (in layouts, etc.)
|
|
1425
|
-
if ((item as any).uses && Array.isArray((item as any).uses)) {
|
|
1426
|
-
lazyItems.push(...findLazyIncludes((item as any).uses));
|
|
1427
|
-
}
|
|
1428
|
-
}
|
|
1429
|
-
|
|
1430
|
-
return lazyItems;
|
|
1431
|
-
}
|
|
545
|
+
// Create segment resolution wrappers bound to segmentDeps
|
|
546
|
+
const {
|
|
547
|
+
resolveAllSegments,
|
|
548
|
+
resolveLoadersOnly,
|
|
549
|
+
resolveLoadersOnlyWithRevalidation,
|
|
550
|
+
buildEntryRevalidateMap,
|
|
551
|
+
resolveAllSegmentsWithRevalidation,
|
|
552
|
+
findInterceptForRoute,
|
|
553
|
+
resolveInterceptEntry,
|
|
554
|
+
resolveInterceptLoadersOnly,
|
|
555
|
+
} = createSegmentWrappers<TEnv>(segmentDeps);
|
|
556
|
+
|
|
557
|
+
// Lazy evaluation deps — captures closure state for extracted evaluateLazyEntry
|
|
558
|
+
const lazyEvalDeps: LazyEvalDeps<TEnv> = {
|
|
559
|
+
routesEntries,
|
|
560
|
+
mergedRouteMap,
|
|
561
|
+
nextMountIndex: () => mountIndex++,
|
|
562
|
+
getPrecomputedByPrefix,
|
|
563
|
+
};
|
|
1432
564
|
|
|
1433
|
-
/**
|
|
1434
|
-
* Evaluate a lazy entry's patterns and populate its routes
|
|
1435
|
-
* This runs the lazy patterns handler and updates the entry in-place
|
|
1436
|
-
* Also detects nested lazy includes and registers them as new entries
|
|
1437
|
-
*/
|
|
1438
565
|
function evaluateLazyEntry(entry: RouteEntry<TEnv>): void {
|
|
1439
|
-
|
|
1440
|
-
return;
|
|
1441
|
-
}
|
|
1442
|
-
|
|
1443
|
-
// Check for pre-computed routes from build-time data.
|
|
1444
|
-
// Only leaf nodes (no nested includes) are precomputed, so entries with
|
|
1445
|
-
// nested lazy includes fall through to the handler below.
|
|
1446
|
-
if (precomputedByPrefix) {
|
|
1447
|
-
const routes = precomputedByPrefix.get(entry.staticPrefix);
|
|
1448
|
-
if (routes) {
|
|
1449
|
-
entry.lazyEvaluated = true;
|
|
1450
|
-
entry.routes = routes as ResolvedRouteMap<any>;
|
|
1451
|
-
for (const [name, pattern] of Object.entries(routes)) {
|
|
1452
|
-
mergedRouteMap[name] = pattern;
|
|
1453
|
-
}
|
|
1454
|
-
registerRouteMap(mergedRouteMap);
|
|
1455
|
-
return;
|
|
1456
|
-
}
|
|
1457
|
-
}
|
|
1458
|
-
|
|
1459
|
-
// Mark as evaluated immediately to prevent concurrent evaluation.
|
|
1460
|
-
// JS is single-threaded but handlers.handler() could theoretically yield,
|
|
1461
|
-
// and the while-loop in findMatch retries after evaluation.
|
|
1462
|
-
entry.lazyEvaluated = true;
|
|
1463
|
-
|
|
1464
|
-
const lazyPatterns = entry.lazyPatterns as UrlPatterns<TEnv>;
|
|
1465
|
-
const lazyContext = entry.lazyContext;
|
|
1466
|
-
|
|
1467
|
-
// Create a new context for evaluating the lazy patterns
|
|
1468
|
-
const manifest = new Map<string, EntryData>();
|
|
1469
|
-
const patterns = new Map<string, string>();
|
|
1470
|
-
const patternsByPrefix = new Map<string, Map<string, string>>();
|
|
1471
|
-
const trailingSlashMap = new Map<string, TrailingSlashMode>();
|
|
1472
|
-
|
|
1473
|
-
// Capture the handler result to detect nested lazy includes
|
|
1474
|
-
let handlerResult: AllUseItems[] = [];
|
|
1475
|
-
|
|
1476
|
-
RSCRouterContext.run(
|
|
1477
|
-
{
|
|
1478
|
-
manifest,
|
|
1479
|
-
patterns,
|
|
1480
|
-
patternsByPrefix,
|
|
1481
|
-
trailingSlash: trailingSlashMap,
|
|
1482
|
-
namespace: "lazy",
|
|
1483
|
-
parent: (lazyContext?.parent as EntryData | null) ?? null,
|
|
1484
|
-
counters: {},
|
|
1485
|
-
},
|
|
1486
|
-
() => {
|
|
1487
|
-
// Run the lazy patterns handler with the original context prefixes
|
|
1488
|
-
// The prefix comes from the IncludeItem stored in lazyPatterns
|
|
1489
|
-
const includePrefix = (entry as any)._lazyPrefix || "";
|
|
1490
|
-
const fullPrefix = (lazyContext?.urlPrefix || "") + includePrefix;
|
|
1491
|
-
|
|
1492
|
-
if (fullPrefix || lazyContext?.namePrefix) {
|
|
1493
|
-
runWithPrefixes(fullPrefix, lazyContext?.namePrefix, () => {
|
|
1494
|
-
handlerResult = lazyPatterns.handler() as AllUseItems[];
|
|
1495
|
-
});
|
|
1496
|
-
} else {
|
|
1497
|
-
handlerResult = lazyPatterns.handler() as AllUseItems[];
|
|
1498
|
-
}
|
|
1499
|
-
},
|
|
1500
|
-
);
|
|
1501
|
-
|
|
1502
|
-
// Populate the entry's routes from the patterns
|
|
1503
|
-
const routesObject: Record<string, string> = {};
|
|
1504
|
-
for (const [name, pattern] of patterns.entries()) {
|
|
1505
|
-
routesObject[name] = pattern;
|
|
1506
|
-
// Also add to merged route map for reverse() support
|
|
1507
|
-
const existingPattern = mergedRouteMap[name];
|
|
1508
|
-
if (existingPattern !== undefined && existingPattern !== pattern) {
|
|
1509
|
-
console.warn(
|
|
1510
|
-
`[@rangojs/router] Route name conflict: "${name}" already maps to "${existingPattern}", ` +
|
|
1511
|
-
`overwriting with "${pattern}" (from lazy include). Use unique route names to avoid this.`,
|
|
1512
|
-
);
|
|
1513
|
-
}
|
|
1514
|
-
mergedRouteMap[name] = pattern;
|
|
1515
|
-
}
|
|
1516
|
-
|
|
1517
|
-
// Update the entry in-place
|
|
1518
|
-
entry.routes = routesObject as ResolvedRouteMap<any>;
|
|
1519
|
-
|
|
1520
|
-
// Note: Do NOT clear lazyPatterns/lazyContext here.
|
|
1521
|
-
// loadManifest() needs them on every request to re-run the handler
|
|
1522
|
-
// in the correct AsyncLocalStorage context (Store.manifest).
|
|
1523
|
-
|
|
1524
|
-
// Update trailing slash config if available
|
|
1525
|
-
if (trailingSlashMap.size > 0) {
|
|
1526
|
-
entry.trailingSlash = Object.fromEntries(trailingSlashMap);
|
|
1527
|
-
}
|
|
1528
|
-
|
|
1529
|
-
// Detect nested lazy includes and register them as new entries
|
|
1530
|
-
const nestedLazyIncludes = findLazyIncludes(handlerResult);
|
|
1531
|
-
for (const lazyInclude of nestedLazyIncludes) {
|
|
1532
|
-
// Compute the full URL prefix (combining parent prefix if any)
|
|
1533
|
-
const fullPrefix = lazyInclude.context.urlPrefix
|
|
1534
|
-
? lazyInclude.context.urlPrefix + lazyInclude.prefix
|
|
1535
|
-
: lazyInclude.prefix;
|
|
1536
|
-
|
|
1537
|
-
const nestedEntry: RouteEntry<TEnv> & { _lazyPrefix?: string } = {
|
|
1538
|
-
prefix: "",
|
|
1539
|
-
staticPrefix: extractStaticPrefix(fullPrefix),
|
|
1540
|
-
routes: {} as ResolvedRouteMap<any>, // Empty until first match
|
|
1541
|
-
trailingSlash: entry.trailingSlash,
|
|
1542
|
-
handler: (lazyInclude.patterns as UrlPatterns<TEnv>).handler,
|
|
1543
|
-
mountIndex: entry.mountIndex,
|
|
1544
|
-
// Lazy evaluation fields
|
|
1545
|
-
lazy: true,
|
|
1546
|
-
lazyPatterns: lazyInclude.patterns,
|
|
1547
|
-
lazyContext: lazyInclude.context,
|
|
1548
|
-
lazyEvaluated: false,
|
|
1549
|
-
// Store the include prefix for evaluation
|
|
1550
|
-
_lazyPrefix: lazyInclude.prefix,
|
|
1551
|
-
};
|
|
1552
|
-
// Insert nested lazy entry before any entry whose staticPrefix is a
|
|
1553
|
-
// prefix of (but shorter than) this lazy entry's staticPrefix.
|
|
1554
|
-
// This ensures more specific lazy includes are matched before
|
|
1555
|
-
// less specific eager entries (e.g., "/href/nested" before "/href/:id").
|
|
1556
|
-
const nestedPrefix = nestedEntry.staticPrefix;
|
|
1557
|
-
let insertIndex = routesEntries.length;
|
|
1558
|
-
if (nestedPrefix) {
|
|
1559
|
-
for (let i = 0; i < routesEntries.length; i++) {
|
|
1560
|
-
const existing = routesEntries[i]!;
|
|
1561
|
-
if (
|
|
1562
|
-
nestedPrefix.startsWith(existing.staticPrefix) &&
|
|
1563
|
-
nestedPrefix.length > existing.staticPrefix.length
|
|
1564
|
-
) {
|
|
1565
|
-
insertIndex = i;
|
|
1566
|
-
break;
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
|
-
routesEntries.splice(insertIndex, 0, nestedEntry);
|
|
1571
|
-
}
|
|
1572
|
-
|
|
1573
|
-
// Re-register route map for runtime reverse() usage
|
|
1574
|
-
registerRouteMap(mergedRouteMap);
|
|
1575
|
-
}
|
|
1576
|
-
|
|
1577
|
-
// Single-entry cache for findMatch to avoid redundant matching within the same request.
|
|
1578
|
-
// previewMatch and match both call findMatch with the same pathname — this ensures
|
|
1579
|
-
// the route matching work (which may check thousands of routes) only happens once.
|
|
1580
|
-
let lastFindMatchPathname: string | null = null;
|
|
1581
|
-
let lastFindMatchResult: RouteMatchResult<TEnv> | null = null;
|
|
1582
|
-
|
|
1583
|
-
// Wrapper for findMatch that uses routesEntries
|
|
1584
|
-
// Handles lazy evaluation by evaluating lazy entries on first match.
|
|
1585
|
-
// Phase 1: try O(path_length) trie match.
|
|
1586
|
-
// Phase 2: fall back to regex iteration.
|
|
1587
|
-
function findMatch(
|
|
1588
|
-
pathname: string,
|
|
1589
|
-
ms?: MetricsStore,
|
|
1590
|
-
): RouteMatchResult<TEnv> | null {
|
|
1591
|
-
// Return cached result if same pathname (avoids double-match per request)
|
|
1592
|
-
if (lastFindMatchPathname === pathname) {
|
|
1593
|
-
return lastFindMatchResult;
|
|
1594
|
-
}
|
|
1595
|
-
|
|
1596
|
-
// Helper to push sub-metrics
|
|
1597
|
-
const pushMetric = ms
|
|
1598
|
-
? (label: string, start: number) => {
|
|
1599
|
-
ms.metrics.push({
|
|
1600
|
-
label,
|
|
1601
|
-
duration: performance.now() - start,
|
|
1602
|
-
startTime: start - ms.requestStart,
|
|
1603
|
-
});
|
|
1604
|
-
}
|
|
1605
|
-
: undefined;
|
|
1606
|
-
|
|
1607
|
-
// Phase 1: Try trie match (O(path_length))
|
|
1608
|
-
const routeTrie = getRouteTrie();
|
|
1609
|
-
if (routeTrie) {
|
|
1610
|
-
const trieStart = performance.now();
|
|
1611
|
-
const trieResult = tryTrieMatch(routeTrie, pathname);
|
|
1612
|
-
pushMetric?.("match:trie", trieStart);
|
|
1613
|
-
|
|
1614
|
-
if (trieResult) {
|
|
1615
|
-
// Find the RouteEntry that contains this route.
|
|
1616
|
-
// Multiple entries can share the same staticPrefix (e.g., several
|
|
1617
|
-
// include("/", patterns) calls all produce staticPrefix=""). Evaluate
|
|
1618
|
-
// each candidate and pick the one whose routes include the matched key.
|
|
1619
|
-
const entryStart = performance.now();
|
|
1620
|
-
let entry: RouteEntry<TEnv> | undefined;
|
|
1621
|
-
let fallbackEntry: RouteEntry<TEnv> | undefined;
|
|
1622
|
-
|
|
1623
|
-
for (const e of routesEntries) {
|
|
1624
|
-
if (e.staticPrefix !== trieResult.sp) continue;
|
|
1625
|
-
if (!fallbackEntry) fallbackEntry = e;
|
|
1626
|
-
evaluateLazyEntry(e);
|
|
1627
|
-
if (
|
|
1628
|
-
e.routes &&
|
|
1629
|
-
trieResult.routeKey in (e.routes as Record<string, unknown>)
|
|
1630
|
-
) {
|
|
1631
|
-
entry = e;
|
|
1632
|
-
break;
|
|
1633
|
-
}
|
|
1634
|
-
}
|
|
1635
|
-
|
|
1636
|
-
// If no entry had the route in its routes map, use the first matching
|
|
1637
|
-
// entry as fallback (handles main entry with inline routes not yet
|
|
1638
|
-
// reflected in its routes object).
|
|
1639
|
-
if (!entry) entry = fallbackEntry;
|
|
1640
|
-
|
|
1641
|
-
// If entry not found (nested include not yet discovered), evaluate parent
|
|
1642
|
-
if (!entry) {
|
|
1643
|
-
const parent = routesEntries.find(
|
|
1644
|
-
(e) =>
|
|
1645
|
-
trieResult.sp.startsWith(e.staticPrefix) &&
|
|
1646
|
-
e.staticPrefix !== trieResult.sp,
|
|
1647
|
-
);
|
|
1648
|
-
if (parent) {
|
|
1649
|
-
const lazyStart = performance.now();
|
|
1650
|
-
evaluateLazyEntry(parent);
|
|
1651
|
-
pushMetric?.("match:lazy-eval", lazyStart);
|
|
1652
|
-
}
|
|
1653
|
-
entry = routesEntries.find((e) => e.staticPrefix === trieResult.sp);
|
|
1654
|
-
}
|
|
1655
|
-
pushMetric?.("match:entry-resolve", entryStart);
|
|
1656
|
-
|
|
1657
|
-
if (entry) {
|
|
1658
|
-
lastFindMatchPathname = pathname;
|
|
1659
|
-
lastFindMatchResult = {
|
|
1660
|
-
entry,
|
|
1661
|
-
routeKey: trieResult.routeKey,
|
|
1662
|
-
params: trieResult.params,
|
|
1663
|
-
optionalParams: new Set(trieResult.optionalParams || []),
|
|
1664
|
-
redirectTo: trieResult.redirectTo,
|
|
1665
|
-
ancestry: trieResult.ancestry,
|
|
1666
|
-
...(trieResult.pr ? { pr: true } : {}),
|
|
1667
|
-
...(trieResult.pt ? { pt: true } : {}),
|
|
1668
|
-
...(trieResult.responseType ? { responseType: trieResult.responseType } : {}),
|
|
1669
|
-
...(trieResult.negotiateVariants ? { negotiateVariants: trieResult.negotiateVariants } : {}),
|
|
1670
|
-
...(trieResult.rscFirst ? { rscFirst: true } : {}),
|
|
1671
|
-
};
|
|
1672
|
-
return lastFindMatchResult;
|
|
1673
|
-
}
|
|
1674
|
-
}
|
|
1675
|
-
}
|
|
1676
|
-
|
|
1677
|
-
// Phase 2: Fall back to existing matching (regex iteration)
|
|
1678
|
-
const regexStart = performance.now();
|
|
1679
|
-
let result = findRouteMatch(pathname, routesEntries);
|
|
1680
|
-
|
|
1681
|
-
// If we hit a lazy entry that needs evaluation, evaluate and retry.
|
|
1682
|
-
// Cap iterations to prevent infinite loops from pathological nesting.
|
|
1683
|
-
const MAX_LAZY_ITERATIONS = 100;
|
|
1684
|
-
let iterations = 0;
|
|
1685
|
-
while (isLazyEvaluationNeeded(result)) {
|
|
1686
|
-
if (++iterations > MAX_LAZY_ITERATIONS) {
|
|
1687
|
-
console.error(
|
|
1688
|
-
`[@rangojs/router] Exceeded ${MAX_LAZY_ITERATIONS} lazy evaluation iterations ` +
|
|
1689
|
-
`for pathname "${pathname}". This likely indicates circular lazy includes.`,
|
|
1690
|
-
);
|
|
1691
|
-
lastFindMatchPathname = pathname;
|
|
1692
|
-
lastFindMatchResult = null;
|
|
1693
|
-
return null;
|
|
1694
|
-
}
|
|
1695
|
-
evaluateLazyEntry(result.lazyEntry);
|
|
1696
|
-
result = findRouteMatch(pathname, routesEntries);
|
|
1697
|
-
}
|
|
1698
|
-
pushMetric?.("match:regex-fallback", regexStart);
|
|
1699
|
-
|
|
1700
|
-
lastFindMatchPathname = pathname;
|
|
1701
|
-
lastFindMatchResult = result;
|
|
1702
|
-
return result;
|
|
566
|
+
_evaluateLazyEntry(entry, lazyEvalDeps);
|
|
1703
567
|
}
|
|
1704
568
|
|
|
569
|
+
// Create findMatch with single-entry cache, bound to router state
|
|
570
|
+
const findMatch = createFindMatch<TEnv>({
|
|
571
|
+
routesEntries,
|
|
572
|
+
evaluateLazyEntry,
|
|
573
|
+
routerId,
|
|
574
|
+
});
|
|
1705
575
|
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
* Uses generator middleware pipeline for clean separation of concerns:
|
|
1710
|
-
* - cache-lookup: Check cache first
|
|
1711
|
-
* - segment-resolution: Resolve segments on cache miss
|
|
1712
|
-
* - cache-store: Store results in cache
|
|
1713
|
-
* - background-revalidation: SWR revalidation
|
|
1714
|
-
*/
|
|
1715
|
-
async function match(request: Request, env: TEnv): Promise<MatchResult> {
|
|
1716
|
-
// Build RouterContext with all closure functions needed by middleware
|
|
1717
|
-
const routerCtx: RouterContext<TEnv> = {
|
|
576
|
+
// Build a RouterContext once — shared by match, matchPartial, matchForPrerender
|
|
577
|
+
function buildRouterContext(): RouterContext<TEnv> {
|
|
578
|
+
return {
|
|
1718
579
|
findMatch,
|
|
1719
580
|
loadManifest,
|
|
1720
581
|
traverseBack,
|
|
@@ -1735,515 +596,255 @@ export function createRouter<TEnv = any>(
|
|
|
1735
596
|
resolveLoadersOnlyWithRevalidation,
|
|
1736
597
|
resolveInterceptLoadersOnly,
|
|
1737
598
|
resolveLoadersOnly,
|
|
599
|
+
telemetry: telemetrySink,
|
|
1738
600
|
};
|
|
1739
|
-
|
|
1740
|
-
return runWithRouterContext(routerCtx, async () => {
|
|
1741
|
-
const result = await createMatchContextForFull(request, env);
|
|
1742
|
-
|
|
1743
|
-
// Handle redirect case
|
|
1744
|
-
if ("type" in result && result.type === "redirect") {
|
|
1745
|
-
return {
|
|
1746
|
-
segments: [],
|
|
1747
|
-
matched: [],
|
|
1748
|
-
diff: [],
|
|
1749
|
-
params: {},
|
|
1750
|
-
redirect: result.redirectUrl,
|
|
1751
|
-
};
|
|
1752
|
-
}
|
|
1753
|
-
|
|
1754
|
-
const ctx = result as MatchContext<TEnv>;
|
|
1755
|
-
|
|
1756
|
-
try {
|
|
1757
|
-
const state = createPipelineState();
|
|
1758
|
-
const pipeline = createMatchPartialPipeline(ctx, state);
|
|
1759
|
-
return await collectMatchResult(pipeline, ctx, state);
|
|
1760
|
-
} catch (error) {
|
|
1761
|
-
if (error instanceof Response) throw error;
|
|
1762
|
-
// Report unhandled errors during full match pipeline
|
|
1763
|
-
callOnError(error, "routing", {
|
|
1764
|
-
request,
|
|
1765
|
-
url: ctx.url,
|
|
1766
|
-
env,
|
|
1767
|
-
isPartial: false,
|
|
1768
|
-
handledByBoundary: false,
|
|
1769
|
-
});
|
|
1770
|
-
throw sanitizeError(error);
|
|
1771
|
-
}
|
|
1772
|
-
});
|
|
1773
|
-
}
|
|
1774
|
-
|
|
1775
|
-
async function matchError(
|
|
1776
|
-
request: Request,
|
|
1777
|
-
_context: TEnv,
|
|
1778
|
-
error: unknown,
|
|
1779
|
-
segmentType: ErrorInfo["segmentType"] = "route",
|
|
1780
|
-
): Promise<MatchResult | null> {
|
|
1781
|
-
return _matchError(request, _context, error, matchApiDeps, defaultErrorBoundary, segmentType);
|
|
1782
601
|
}
|
|
1783
602
|
|
|
603
|
+
// Prerender/static match deps (bind closure state for extracted functions)
|
|
604
|
+
const prerenderDeps = {
|
|
605
|
+
findMatch,
|
|
606
|
+
buildRouterContext,
|
|
607
|
+
mergedRouteMap,
|
|
608
|
+
resolveAllSegments,
|
|
609
|
+
};
|
|
1784
610
|
|
|
1785
|
-
async function
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
}
|
|
1791
|
-
|
|
1792
|
-
async function createMatchContextForPartial(
|
|
1793
|
-
request: Request,
|
|
1794
|
-
env: TEnv,
|
|
1795
|
-
actionContext?: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData },
|
|
611
|
+
async function matchForPrerender(
|
|
612
|
+
pathname: string,
|
|
613
|
+
params: Record<string, string>,
|
|
614
|
+
buildVars?: Record<string, any>,
|
|
615
|
+
isPassthroughRoute?: boolean,
|
|
1796
616
|
) {
|
|
1797
|
-
return
|
|
1798
|
-
}
|
|
1799
|
-
|
|
1800
|
-
/**
|
|
1801
|
-
* Match partial request with revalidation
|
|
1802
|
-
*
|
|
1803
|
-
* Uses generator middleware pipeline for clean separation of concerns:
|
|
1804
|
-
* - cache-lookup: Check cache first
|
|
1805
|
-
* - segment-resolution: Resolve segments on cache miss
|
|
1806
|
-
* - intercept-resolution: Handle intercept routes
|
|
1807
|
-
* - cache-store: Store results in cache
|
|
1808
|
-
* - background-revalidation: SWR revalidation
|
|
1809
|
-
*/
|
|
1810
|
-
async function matchPartial(
|
|
1811
|
-
request: Request,
|
|
1812
|
-
context: TEnv,
|
|
1813
|
-
actionContext?: ActionContext,
|
|
1814
|
-
): Promise<MatchResult | null> {
|
|
1815
|
-
// Build RouterContext with all closure functions needed by middleware
|
|
1816
|
-
const routerCtx: RouterContext<TEnv> = {
|
|
1817
|
-
findMatch,
|
|
1818
|
-
loadManifest,
|
|
1819
|
-
traverseBack,
|
|
1820
|
-
createHandlerContext,
|
|
1821
|
-
setupLoaderAccess,
|
|
1822
|
-
setupLoaderAccessSilent,
|
|
1823
|
-
getContext,
|
|
1824
|
-
getMetricsStore,
|
|
1825
|
-
createCacheScope,
|
|
1826
|
-
findInterceptForRoute,
|
|
1827
|
-
resolveAllSegmentsWithRevalidation,
|
|
1828
|
-
resolveInterceptEntry,
|
|
1829
|
-
evaluateRevalidation,
|
|
1830
|
-
getRequestContext,
|
|
1831
|
-
resolveAllSegments,
|
|
1832
|
-
createHandleStore,
|
|
1833
|
-
buildEntryRevalidateMap,
|
|
1834
|
-
resolveLoadersOnlyWithRevalidation,
|
|
1835
|
-
resolveInterceptLoadersOnly,
|
|
1836
|
-
};
|
|
1837
|
-
|
|
1838
|
-
return runWithRouterContext(routerCtx, async () => {
|
|
1839
|
-
const ctx = await createMatchContextForPartial(
|
|
1840
|
-
request,
|
|
1841
|
-
context,
|
|
1842
|
-
actionContext,
|
|
1843
|
-
);
|
|
1844
|
-
if (!ctx) return null;
|
|
1845
|
-
|
|
1846
|
-
try {
|
|
1847
|
-
const state = createPipelineState();
|
|
1848
|
-
const pipeline = createMatchPartialPipeline(ctx, state);
|
|
1849
|
-
return await collectMatchResult(pipeline, ctx, state);
|
|
1850
|
-
} catch (error) {
|
|
1851
|
-
if (error instanceof Response) throw error;
|
|
1852
|
-
// Report unhandled errors during partial match pipeline
|
|
1853
|
-
callOnError(error, actionContext ? "action" : "revalidation", {
|
|
1854
|
-
request,
|
|
1855
|
-
url: ctx.url,
|
|
1856
|
-
env: context,
|
|
1857
|
-
actionId: actionContext?.actionId,
|
|
1858
|
-
isPartial: true,
|
|
1859
|
-
handledByBoundary: false,
|
|
1860
|
-
});
|
|
1861
|
-
throw sanitizeError(error);
|
|
1862
|
-
}
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
|
|
1866
|
-
/**
|
|
1867
|
-
* Preview match - returns route middleware without segment resolution.
|
|
1868
|
-
* Also returns responseType and handler for response routes (non-RSC short-circuit).
|
|
1869
|
-
*/
|
|
1870
|
-
async function previewMatch(
|
|
1871
|
-
request: Request,
|
|
1872
|
-
_context: TEnv,
|
|
1873
|
-
): Promise<{
|
|
1874
|
-
routeMiddleware?: Array<{
|
|
1875
|
-
handler: import("./router/middleware.js").MiddlewareFn;
|
|
1876
|
-
params: Record<string, string>;
|
|
1877
|
-
}>;
|
|
1878
|
-
responseType?: string;
|
|
1879
|
-
handler?: Function;
|
|
1880
|
-
params?: Record<string, string>;
|
|
1881
|
-
negotiated?: boolean;
|
|
1882
|
-
} | null> {
|
|
1883
|
-
const url = new URL(request.url);
|
|
1884
|
-
const pathname = url.pathname;
|
|
1885
|
-
|
|
1886
|
-
// Quick route matching
|
|
1887
|
-
const matched = findMatch(pathname);
|
|
1888
|
-
if (!matched) {
|
|
1889
|
-
return null;
|
|
1890
|
-
}
|
|
1891
|
-
|
|
1892
|
-
// Skip redirect check - will be handled in full match
|
|
1893
|
-
if (matched.redirectTo) {
|
|
1894
|
-
return { routeMiddleware: undefined };
|
|
1895
|
-
}
|
|
1896
|
-
|
|
1897
|
-
// Load manifest (without segment resolution)
|
|
1898
|
-
const manifestEntry = await loadManifest(
|
|
1899
|
-
matched.entry,
|
|
1900
|
-
matched.routeKey,
|
|
617
|
+
return _matchForPrerender(
|
|
1901
618
|
pathname,
|
|
1902
|
-
|
|
1903
|
-
|
|
619
|
+
params,
|
|
620
|
+
prerenderDeps,
|
|
621
|
+
buildVars,
|
|
622
|
+
isPassthroughRoute,
|
|
1904
623
|
);
|
|
624
|
+
}
|
|
1905
625
|
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
626
|
+
async function renderStaticSegment(
|
|
627
|
+
handler: Function,
|
|
628
|
+
handlerId: string,
|
|
629
|
+
routeName?: string,
|
|
630
|
+
) {
|
|
631
|
+
return _renderStaticSegment<TEnv>(
|
|
632
|
+
handler,
|
|
633
|
+
handlerId,
|
|
634
|
+
mergedRouteMap,
|
|
635
|
+
routeName,
|
|
1911
636
|
);
|
|
1912
|
-
|
|
1913
|
-
// Check for response type (from trie match or manifest entry)
|
|
1914
|
-
const responseType = matched.responseType ||
|
|
1915
|
-
(manifestEntry.type === "route" ? manifestEntry.responseType : undefined);
|
|
1916
|
-
|
|
1917
|
-
// Content negotiation: when negotiate variants exist, pick the best
|
|
1918
|
-
// handler based on the Accept header. Uses q-values and client order
|
|
1919
|
-
// as tiebreaker (matching Express/Hono behavior). RSC routes participate
|
|
1920
|
-
// as text/html candidates so browsers naturally get HTML without
|
|
1921
|
-
// special-casing.
|
|
1922
|
-
if (matched.negotiateVariants && matched.negotiateVariants.length > 0) {
|
|
1923
|
-
const acceptEntries = parseAcceptTypes(request.headers.get("accept") || "");
|
|
1924
|
-
|
|
1925
|
-
// Build candidate list preserving definition order.
|
|
1926
|
-
// For wildcard (*/*) and no-Accept fallback, the first candidate wins.
|
|
1927
|
-
const variants = matched.negotiateVariants;
|
|
1928
|
-
let candidates: Array<{ routeKey: string; responseType: string }>;
|
|
1929
|
-
if (responseType) {
|
|
1930
|
-
// Primary is response-type — include it as a candidate
|
|
1931
|
-
candidates = [...variants, { routeKey: matched.routeKey, responseType }];
|
|
1932
|
-
} else {
|
|
1933
|
-
// Primary is RSC — insert as text/html candidate in definition order
|
|
1934
|
-
const rscCandidate = { routeKey: matched.routeKey, responseType: RSC_RESPONSE_TYPE };
|
|
1935
|
-
candidates = matched.rscFirst
|
|
1936
|
-
? [rscCandidate, ...variants]
|
|
1937
|
-
: [...variants, rscCandidate];
|
|
1938
|
-
}
|
|
1939
|
-
|
|
1940
|
-
const variant = pickNegotiateVariant(acceptEntries, candidates);
|
|
1941
|
-
|
|
1942
|
-
// If the winner is RSC, fall through to default RSC handling
|
|
1943
|
-
if (variant.responseType === RSC_RESPONSE_TYPE) {
|
|
1944
|
-
// Fall through — RSC won negotiation
|
|
1945
|
-
} else if (responseType && variant.routeKey === matched.routeKey) {
|
|
1946
|
-
// Fall through — response-type primary won, already set
|
|
1947
|
-
} else {
|
|
1948
|
-
const negotiateEntry = await loadManifest(
|
|
1949
|
-
matched.entry,
|
|
1950
|
-
variant.routeKey,
|
|
1951
|
-
pathname,
|
|
1952
|
-
undefined,
|
|
1953
|
-
false,
|
|
1954
|
-
);
|
|
1955
|
-
return {
|
|
1956
|
-
routeMiddleware: routeMiddleware.length > 0 ? routeMiddleware : undefined,
|
|
1957
|
-
responseType: variant.responseType,
|
|
1958
|
-
handler: negotiateEntry.type === "route" ? negotiateEntry.handler : undefined,
|
|
1959
|
-
params: matched.params,
|
|
1960
|
-
negotiated: true,
|
|
1961
|
-
};
|
|
1962
|
-
}
|
|
1963
|
-
}
|
|
1964
|
-
|
|
1965
|
-
// If we passed through the negotiation block (variants exist), mark as
|
|
1966
|
-
// negotiated so the handler sets Vary: Accept on the response.
|
|
1967
|
-
const hasVariants = matched.negotiateVariants && matched.negotiateVariants.length > 0;
|
|
1968
|
-
return {
|
|
1969
|
-
routeMiddleware: routeMiddleware.length > 0 ? routeMiddleware : undefined,
|
|
1970
|
-
...(responseType ? {
|
|
1971
|
-
responseType,
|
|
1972
|
-
handler: manifestEntry.type === "route" ? manifestEntry.handler : undefined,
|
|
1973
|
-
params: matched.params,
|
|
1974
|
-
} : {}),
|
|
1975
|
-
...(hasVariants ? { negotiated: true } : {}),
|
|
1976
|
-
};
|
|
1977
637
|
}
|
|
1978
638
|
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
// Merge routes into the reverse map
|
|
1990
|
-
// Keys stay unchanged for composability - only URL patterns get prefixed
|
|
1991
|
-
const routeEntries = routes as Record<string, string>;
|
|
1992
|
-
for (const [key, pattern] of Object.entries(routeEntries)) {
|
|
1993
|
-
// Build prefixed pattern: "/shop" + "/cart" -> "/shop/cart"
|
|
1994
|
-
const prefixedPattern =
|
|
1995
|
-
prefix && pattern !== "/"
|
|
1996
|
-
? `${prefix}${pattern}`
|
|
1997
|
-
: prefix && pattern === "/"
|
|
1998
|
-
? prefix
|
|
1999
|
-
: pattern;
|
|
2000
|
-
|
|
2001
|
-
// Runtime validation: warn if key already exists with different pattern
|
|
2002
|
-
const existingPattern = mergedRouteMap[key];
|
|
2003
|
-
if (
|
|
2004
|
-
existingPattern !== undefined &&
|
|
2005
|
-
existingPattern !== prefixedPattern
|
|
2006
|
-
) {
|
|
2007
|
-
console.warn(
|
|
2008
|
-
`[rsc-router] Route key conflict: "${key}" already maps to "${existingPattern}", ` +
|
|
2009
|
-
`overwriting with "${prefixedPattern}". Use unique key names to avoid this.`,
|
|
2010
|
-
);
|
|
2011
|
-
}
|
|
2012
|
-
|
|
2013
|
-
// Use original key - enables reusable route modules
|
|
2014
|
-
mergedRouteMap[key] = prefixedPattern;
|
|
2015
|
-
}
|
|
2016
|
-
|
|
2017
|
-
// Auto-register route map for runtime reverse() usage
|
|
2018
|
-
registerRouteMap(mergedRouteMap);
|
|
2019
|
-
|
|
2020
|
-
// Extract trailing slash config if present (attached by route())
|
|
2021
|
-
const trailingSlashConfig = (routes as any).__trailingSlash as
|
|
2022
|
-
| Record<string, TrailingSlashMode>
|
|
2023
|
-
| undefined;
|
|
2024
|
-
|
|
2025
|
-
// Create builder object so .use() can return it
|
|
2026
|
-
const builder: RouteBuilder<RouteDefinition, TEnv, any, TNewRoutes> = {
|
|
2027
|
-
use(
|
|
2028
|
-
patternOrMiddleware: string | MiddlewareFn<TEnv>,
|
|
2029
|
-
middleware?: MiddlewareFn<TEnv>,
|
|
2030
|
-
) {
|
|
2031
|
-
// Mount-scoped middleware - prefix is the mount prefix
|
|
2032
|
-
addMiddleware(patternOrMiddleware, middleware, prefix || null);
|
|
2033
|
-
return builder;
|
|
2034
|
-
},
|
|
2035
|
-
|
|
2036
|
-
map(
|
|
2037
|
-
handler:
|
|
2038
|
-
| ((
|
|
2039
|
-
helpers: InlineRouteHelpers<TNewRoutes, TEnv>,
|
|
2040
|
-
) => Array<AllUseItems>)
|
|
2041
|
-
| (() =>
|
|
2042
|
-
| Array<AllUseItems>
|
|
2043
|
-
| Promise<{ default: () => Array<AllUseItems> }>
|
|
2044
|
-
| Promise<() => Array<AllUseItems>>),
|
|
2045
|
-
) {
|
|
2046
|
-
// Store handler as-is - detection happens at call time based on return type
|
|
2047
|
-
// Both patterns use the same signature:
|
|
2048
|
-
// - Inline: ({ route }) => [...] - receives helpers, returns Array
|
|
2049
|
-
// - Lazy: () => import(...) - ignores helpers, returns Promise
|
|
2050
|
-
routesEntries.push({
|
|
2051
|
-
prefix,
|
|
2052
|
-
staticPrefix: extractStaticPrefix(prefix),
|
|
2053
|
-
routes: routes as ResolvedRouteMap<any>,
|
|
2054
|
-
trailingSlash: trailingSlashConfig,
|
|
2055
|
-
handler: handler as any,
|
|
2056
|
-
mountIndex: currentMountIndex,
|
|
2057
|
-
});
|
|
2058
|
-
// Return router with accumulated types
|
|
2059
|
-
// At runtime this is the same object, but TypeScript tracks the accumulated route types
|
|
2060
|
-
return router as any;
|
|
2061
|
-
},
|
|
2062
|
-
|
|
2063
|
-
// Expose accumulated route map for typeof extraction
|
|
2064
|
-
get routeMap() {
|
|
2065
|
-
return mergedRouteMap as TNewRoutes;
|
|
2066
|
-
},
|
|
2067
|
-
};
|
|
639
|
+
// Create match handler functions bound to router state
|
|
640
|
+
const matchHandlers = createMatchHandlers<TEnv>({
|
|
641
|
+
buildRouterContext,
|
|
642
|
+
callOnError,
|
|
643
|
+
matchApiDeps,
|
|
644
|
+
defaultErrorBoundary,
|
|
645
|
+
findMatch,
|
|
646
|
+
findInterceptForRoute,
|
|
647
|
+
telemetry: telemetrySink,
|
|
648
|
+
});
|
|
2068
649
|
|
|
2069
|
-
|
|
2070
|
-
}
|
|
650
|
+
const { match, matchPartial, matchError, previewMatch } = matchHandlers;
|
|
2071
651
|
|
|
2072
652
|
/**
|
|
2073
653
|
* Router instance
|
|
2074
654
|
* The type system tracks accumulated routes through the builder chain
|
|
2075
655
|
* Initial TRoutes is {} (empty) to avoid poisoning accumulated types with Record<string, string>
|
|
2076
656
|
*/
|
|
2077
|
-
const router:
|
|
657
|
+
const router: RSCRouterInternal<TEnv, {}> = {
|
|
2078
658
|
__brand: RSC_ROUTER_BRAND,
|
|
2079
659
|
id: routerId,
|
|
2080
660
|
|
|
2081
|
-
routes(
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
// Note: Multiple .routes() calls are allowed for backwards compatibility
|
|
2086
|
-
// with the old map() pattern. For new code, prefer urls() with include().
|
|
2087
|
-
|
|
2088
|
-
// Check if argument is UrlPatterns (new Django-style API)
|
|
2089
|
-
// Detect by checking for handler and definitions properties
|
|
2090
|
-
if (
|
|
2091
|
-
typeof prefixOrRoutes === "object" &&
|
|
2092
|
-
prefixOrRoutes !== null &&
|
|
2093
|
-
"handler" in prefixOrRoutes &&
|
|
2094
|
-
"definitions" in prefixOrRoutes &&
|
|
2095
|
-
typeof (prefixOrRoutes as UrlPatterns<TEnv>).handler === "function"
|
|
2096
|
-
) {
|
|
2097
|
-
const urlPatterns = prefixOrRoutes as UrlPatterns<TEnv>;
|
|
2098
|
-
// Store reference for runtime manifest generation
|
|
2099
|
-
storedUrlPatterns = urlPatterns;
|
|
2100
|
-
const currentMountIndex = mountIndex++;
|
|
2101
|
-
|
|
2102
|
-
// Create manifest and patterns maps for route registration
|
|
2103
|
-
const manifest = new Map<string, EntryData>();
|
|
2104
|
-
const patterns = new Map<string, string>();
|
|
2105
|
-
const patternsByPrefix = new Map<string, Map<string, string>>();
|
|
2106
|
-
const trailingSlashMap = new Map<string, TrailingSlashMode>();
|
|
2107
|
-
|
|
2108
|
-
// Run the handler once to extract patterns for route matching
|
|
2109
|
-
// Note: loadManifest will re-run the handler to register entries in its context
|
|
2110
|
-
// Lazy includes are detected in the return value and handled separately
|
|
2111
|
-
let handlerResult: AllUseItems[] = [];
|
|
2112
|
-
RSCRouterContext.run(
|
|
2113
|
-
{
|
|
2114
|
-
manifest,
|
|
2115
|
-
patterns,
|
|
2116
|
-
patternsByPrefix,
|
|
2117
|
-
trailingSlash: trailingSlashMap,
|
|
2118
|
-
namespace: "root",
|
|
2119
|
-
parent: null,
|
|
2120
|
-
counters: {},
|
|
2121
|
-
},
|
|
2122
|
-
() => {
|
|
2123
|
-
// Execute the handler to collect patterns
|
|
2124
|
-
handlerResult = urlPatterns.handler() as AllUseItems[];
|
|
2125
|
-
},
|
|
2126
|
-
);
|
|
661
|
+
routes(urlPatterns: UrlPatterns<TEnv>): any {
|
|
662
|
+
// Store reference for runtime manifest generation
|
|
663
|
+
storedUrlPatterns = urlPatterns;
|
|
664
|
+
const currentMountIndex = mountIndex++;
|
|
2127
665
|
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
666
|
+
// Create manifest and patterns maps for route registration
|
|
667
|
+
const manifest = new Map<string, EntryData>();
|
|
668
|
+
const routePatterns = new Map<string, string>();
|
|
669
|
+
const patternsByPrefix = new Map<string, Map<string, string>>();
|
|
670
|
+
const trailingSlashMap = new Map<string, TrailingSlashMode>();
|
|
671
|
+
|
|
672
|
+
// Run the handler once to extract patterns for route matching.
|
|
673
|
+
// Note: loadManifest will re-run the handler to register entries in its context.
|
|
674
|
+
// Lazy includes are detected in the return value and handled separately.
|
|
675
|
+
//
|
|
676
|
+
// Pattern extraction must use the same mountIndex and MapRootLayout root
|
|
677
|
+
// parent as loadManifest so that shortCodes produced here match those at
|
|
678
|
+
// runtime. include() captures the current parent and counters; if those
|
|
679
|
+
// shortCodes diverge from the runtime tree the segment reconciliation on
|
|
680
|
+
// the client will see a full mismatch and remount the entire page.
|
|
681
|
+
const syntheticMapRoot: EntryData = {
|
|
682
|
+
type: "layout",
|
|
683
|
+
id: `#synthetic-maproot-M${currentMountIndex}`,
|
|
684
|
+
shortCode: `M${currentMountIndex}L0`,
|
|
685
|
+
parent: null,
|
|
686
|
+
handler: MapRootLayout,
|
|
687
|
+
middleware: [],
|
|
688
|
+
revalidate: [],
|
|
689
|
+
errorBoundary: [],
|
|
690
|
+
notFoundBoundary: [],
|
|
691
|
+
layout: [],
|
|
692
|
+
parallel: [],
|
|
693
|
+
intercept: [],
|
|
694
|
+
loader: [],
|
|
695
|
+
};
|
|
2143
696
|
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
697
|
+
let handlerResult: AllUseItems[] = [];
|
|
698
|
+
RSCRouterContext.run(
|
|
699
|
+
{
|
|
700
|
+
manifest,
|
|
701
|
+
patterns: routePatterns,
|
|
702
|
+
patternsByPrefix,
|
|
703
|
+
trailingSlash: trailingSlashMap,
|
|
704
|
+
namespace: "root",
|
|
705
|
+
parent: syntheticMapRoot,
|
|
706
|
+
counters: {},
|
|
707
|
+
mountIndex: currentMountIndex,
|
|
708
|
+
cacheProfiles: resolvedCacheProfiles,
|
|
709
|
+
},
|
|
710
|
+
() => {
|
|
711
|
+
handlerResult = urlPatterns.handler() as AllUseItems[];
|
|
712
|
+
},
|
|
713
|
+
);
|
|
714
|
+
|
|
715
|
+
// Convert trailingSlash map to object for the router
|
|
716
|
+
const trailingSlashConfig =
|
|
717
|
+
trailingSlashMap.size > 0
|
|
718
|
+
? Object.fromEntries(trailingSlashMap)
|
|
719
|
+
: undefined;
|
|
720
|
+
|
|
721
|
+
// Collect route keys that have prerender handlers (for non-trie match path)
|
|
722
|
+
let prerenderRouteKeys: Set<string> | undefined;
|
|
723
|
+
let passthroughRouteKeys: Set<string> | undefined;
|
|
724
|
+
for (const [name, entry] of manifest.entries()) {
|
|
725
|
+
if (entry.type === "route" && entry.isPrerender) {
|
|
726
|
+
if (!prerenderRouteKeys) prerenderRouteKeys = new Set();
|
|
727
|
+
prerenderRouteKeys.add(name);
|
|
728
|
+
if (entry.prerenderDef?.options?.passthrough === true) {
|
|
729
|
+
if (!passthroughRouteKeys) passthroughRouteKeys = new Set();
|
|
730
|
+
passthroughRouteKeys.add(name);
|
|
2155
731
|
}
|
|
2156
|
-
}
|
|
2157
|
-
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// Create separate RouteEntry for each URL prefix group
|
|
736
|
+
// This enables prefix-based short-circuit optimization
|
|
737
|
+
if (patternsByPrefix.size > 0) {
|
|
738
|
+
for (const [prefix, prefixPatterns] of patternsByPrefix.entries()) {
|
|
2158
739
|
const routesObject: Record<string, string> = {};
|
|
2159
|
-
for (const [name, pattern] of
|
|
740
|
+
for (const [name, pattern] of prefixPatterns.entries()) {
|
|
2160
741
|
routesObject[name] = pattern;
|
|
2161
742
|
}
|
|
2162
743
|
|
|
2163
744
|
routesEntries.push({
|
|
745
|
+
// prefix is "" because patterns already include the URL prefix
|
|
746
|
+
// (e.g., "/site/:locale/user1/:id" not just "/user1/:id")
|
|
2164
747
|
prefix: "",
|
|
2165
|
-
staticPrefix
|
|
748
|
+
// staticPrefix is the actual prefix for short-circuit optimization
|
|
749
|
+
staticPrefix: extractStaticPrefix(prefix),
|
|
2166
750
|
routes: routesObject as ResolvedRouteMap<any>,
|
|
2167
751
|
trailingSlash: trailingSlashConfig,
|
|
2168
752
|
handler: urlPatterns.handler,
|
|
2169
753
|
mountIndex: currentMountIndex,
|
|
754
|
+
cacheProfiles: resolvedCacheProfiles,
|
|
755
|
+
...(prerenderRouteKeys ? { prerenderRouteKeys } : {}),
|
|
756
|
+
...(passthroughRouteKeys ? { passthroughRouteKeys } : {}),
|
|
2170
757
|
});
|
|
2171
758
|
}
|
|
759
|
+
} else {
|
|
760
|
+
// Fallback: no prefix grouping, use flat patterns map
|
|
761
|
+
const routesObject: Record<string, string> = {};
|
|
762
|
+
for (const [name, pattern] of routePatterns.entries()) {
|
|
763
|
+
routesObject[name] = pattern;
|
|
764
|
+
}
|
|
2172
765
|
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
}
|
|
2183
|
-
|
|
766
|
+
routesEntries.push({
|
|
767
|
+
prefix: "",
|
|
768
|
+
staticPrefix: "",
|
|
769
|
+
routes: routesObject as ResolvedRouteMap<any>,
|
|
770
|
+
trailingSlash: trailingSlashConfig,
|
|
771
|
+
handler: urlPatterns.handler,
|
|
772
|
+
mountIndex: currentMountIndex,
|
|
773
|
+
cacheProfiles: resolvedCacheProfiles,
|
|
774
|
+
...(prerenderRouteKeys ? { prerenderRouteKeys } : {}),
|
|
775
|
+
...(passthroughRouteKeys ? { passthroughRouteKeys } : {}),
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// Build route map from registered patterns
|
|
780
|
+
for (const [name, pattern] of routePatterns.entries()) {
|
|
781
|
+
// Runtime validation: warn if key already exists with different pattern.
|
|
782
|
+
// Skip warning for entries that came from the static seed — the gen file
|
|
783
|
+
// can be stale during HMR, so runtime registration is authoritative.
|
|
784
|
+
const existingPattern = mergedRouteMap[name];
|
|
785
|
+
if (
|
|
786
|
+
existingPattern !== undefined &&
|
|
787
|
+
existingPattern !== pattern &&
|
|
788
|
+
!seededNames.has(name)
|
|
789
|
+
) {
|
|
790
|
+
console.warn(
|
|
791
|
+
`[@rangojs/router] Route name conflict: "${name}" already maps to "${existingPattern}", ` +
|
|
792
|
+
`overwriting with "${pattern}". Use unique route names to avoid this.`,
|
|
793
|
+
);
|
|
2184
794
|
}
|
|
795
|
+
mergedRouteMap[name] = pattern;
|
|
796
|
+
seededNames.delete(name);
|
|
797
|
+
}
|
|
2185
798
|
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
const lazyIncludes = findLazyIncludes(handlerResult);
|
|
799
|
+
// Detect lazy includes in handler result and create placeholder entries
|
|
800
|
+
const lazyIncludes = findLazyIncludes(handlerResult);
|
|
2189
801
|
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
802
|
+
// Create placeholder RouteEntry for each lazy include
|
|
803
|
+
for (const lazyInclude of lazyIncludes) {
|
|
804
|
+
// Compute the full URL prefix (combining parent prefix if any)
|
|
805
|
+
const fullPrefix = lazyInclude.context.urlPrefix
|
|
806
|
+
? lazyInclude.context.urlPrefix + lazyInclude.prefix
|
|
807
|
+
: lazyInclude.prefix;
|
|
2196
808
|
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
break;
|
|
2227
|
-
}
|
|
809
|
+
const lazyEntry: RouteEntry<TEnv> & { _lazyPrefix?: string } = {
|
|
810
|
+
prefix: "",
|
|
811
|
+
staticPrefix: extractStaticPrefix(fullPrefix),
|
|
812
|
+
routes: {} as ResolvedRouteMap<any>, // Empty until first match
|
|
813
|
+
trailingSlash: trailingSlashConfig,
|
|
814
|
+
handler: urlPatterns.handler,
|
|
815
|
+
mountIndex: mountIndex++,
|
|
816
|
+
// Lazy evaluation fields
|
|
817
|
+
lazy: true,
|
|
818
|
+
lazyPatterns: lazyInclude.patterns,
|
|
819
|
+
lazyContext: lazyInclude.context,
|
|
820
|
+
lazyEvaluated: false,
|
|
821
|
+
_lazyPrefix: lazyInclude.prefix,
|
|
822
|
+
};
|
|
823
|
+
// Insert lazy entry before any entry whose staticPrefix is a
|
|
824
|
+
// prefix of (but shorter than) this lazy entry's staticPrefix.
|
|
825
|
+
// This ensures more specific lazy includes are matched before
|
|
826
|
+
// less specific eager entries (e.g., "/href/nested" before "/href/:id").
|
|
827
|
+
const lazyPrefix = lazyEntry.staticPrefix;
|
|
828
|
+
let insertIndex = routesEntries.length;
|
|
829
|
+
if (lazyPrefix) {
|
|
830
|
+
for (let i = 0; i < routesEntries.length; i++) {
|
|
831
|
+
const existing = routesEntries[i]!;
|
|
832
|
+
if (
|
|
833
|
+
lazyPrefix.startsWith(existing.staticPrefix) &&
|
|
834
|
+
lazyPrefix.length > existing.staticPrefix.length
|
|
835
|
+
) {
|
|
836
|
+
insertIndex = i;
|
|
837
|
+
break;
|
|
2228
838
|
}
|
|
2229
839
|
}
|
|
2230
|
-
routesEntries.splice(insertIndex, 0, lazyEntry);
|
|
2231
840
|
}
|
|
2232
|
-
|
|
2233
|
-
// Auto-register route map for runtime reverse() usage
|
|
2234
|
-
registerRouteMap(mergedRouteMap);
|
|
2235
|
-
|
|
2236
|
-
// Return the router (no .map() needed for UrlPatterns)
|
|
2237
|
-
return router;
|
|
841
|
+
routesEntries.splice(insertIndex, 0, lazyEntry);
|
|
2238
842
|
}
|
|
2239
843
|
|
|
2240
|
-
//
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
}
|
|
2245
|
-
// Otherwise, first argument is routes with empty prefix
|
|
2246
|
-
return createRouteBuilder("", prefixOrRoutes as Record<string, string>);
|
|
844
|
+
// Auto-register route map for runtime reverse() usage
|
|
845
|
+
registerRouteMap(mergedRouteMap);
|
|
846
|
+
|
|
847
|
+
return router;
|
|
2247
848
|
},
|
|
2248
849
|
|
|
2249
850
|
use(
|
|
@@ -2257,6 +858,7 @@ export function createRouter<TEnv = any>(
|
|
|
2257
858
|
|
|
2258
859
|
// Type-safe URL builder using merged route map
|
|
2259
860
|
// Types are tracked through the builder chain via TRoutes parameter
|
|
861
|
+
// Seeded with static route names from the generated file (injected by Vite)
|
|
2260
862
|
reverse: createReverse(mergedRouteMap),
|
|
2261
863
|
|
|
2262
864
|
// Expose accumulated route map for typeof extraction
|
|
@@ -2280,19 +882,62 @@ export function createRouter<TEnv = any>(
|
|
|
2280
882
|
// Expose resolved theme configuration for NavigationProvider and MetaTags
|
|
2281
883
|
themeConfig: resolvedThemeConfig,
|
|
2282
884
|
|
|
885
|
+
// Expose resolved cache profiles for per-request resolution
|
|
886
|
+
cacheProfiles: resolvedCacheProfiles,
|
|
887
|
+
|
|
888
|
+
// Expose prefetch cache settings
|
|
889
|
+
prefetchCacheControl,
|
|
890
|
+
prefetchCacheTTL,
|
|
891
|
+
|
|
2283
892
|
// Expose warmup enabled flag for handler and client
|
|
2284
893
|
warmupEnabled,
|
|
2285
894
|
|
|
895
|
+
// Expose router-wide performance debugging for request-level metrics setup
|
|
896
|
+
debugPerformance,
|
|
897
|
+
|
|
2286
898
|
// Expose debug manifest flag for handler
|
|
2287
899
|
allowDebugManifest: allowDebugManifestOption,
|
|
2288
900
|
|
|
901
|
+
// Expose origin check configuration for handler (default: enabled)
|
|
902
|
+
originCheck: originCheckOption ?? true,
|
|
903
|
+
|
|
904
|
+
// Expose SSR configuration for handler
|
|
905
|
+
ssr: ssrOption,
|
|
906
|
+
|
|
907
|
+
// Expose resolved timeouts for RSC handler
|
|
908
|
+
timeouts: resolvedTimeouts,
|
|
909
|
+
onTimeout,
|
|
910
|
+
|
|
2289
911
|
// Expose global middleware for RSC handler
|
|
2290
912
|
middleware: globalMiddleware,
|
|
2291
913
|
|
|
2292
|
-
match,
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
914
|
+
match: (request: Request, input: RouterRequestInput<TEnv> = {}) => {
|
|
915
|
+
const env = input.env ?? ({} as TEnv);
|
|
916
|
+
return match(request, env);
|
|
917
|
+
},
|
|
918
|
+
matchForPrerender,
|
|
919
|
+
renderStaticSegment,
|
|
920
|
+
matchPartial: (
|
|
921
|
+
request: Request,
|
|
922
|
+
input: RouterRequestInput<TEnv> = {},
|
|
923
|
+
actionContext?: Parameters<typeof matchPartial>[2],
|
|
924
|
+
) => {
|
|
925
|
+
const env = input.env ?? ({} as TEnv);
|
|
926
|
+
return matchPartial(request, env, actionContext);
|
|
927
|
+
},
|
|
928
|
+
matchError: (
|
|
929
|
+
request: Request,
|
|
930
|
+
input: RouterRequestInput<TEnv> | undefined,
|
|
931
|
+
error: unknown,
|
|
932
|
+
segmentType?: Parameters<typeof matchError>[3],
|
|
933
|
+
) => {
|
|
934
|
+
const env = input?.env ?? ({} as TEnv);
|
|
935
|
+
return matchError(request, env, error, segmentType);
|
|
936
|
+
},
|
|
937
|
+
previewMatch: (request: Request, input: RouterRequestInput<TEnv> = {}) => {
|
|
938
|
+
const env = input.env ?? ({} as TEnv);
|
|
939
|
+
return previewMatch(request, env);
|
|
940
|
+
},
|
|
2296
941
|
|
|
2297
942
|
// Expose nonce provider for fetch
|
|
2298
943
|
nonce,
|
|
@@ -2305,82 +950,44 @@ export function createRouter<TEnv = any>(
|
|
|
2305
950
|
return storedUrlPatterns ?? undefined;
|
|
2306
951
|
},
|
|
2307
952
|
|
|
953
|
+
// Expose source file for per-router type generation
|
|
954
|
+
__sourceFile,
|
|
955
|
+
|
|
2308
956
|
// RSC request handler (lazily created on first call)
|
|
2309
957
|
fetch: (() => {
|
|
2310
958
|
// Handler is created on first call and reused
|
|
2311
959
|
let handler:
|
|
2312
960
|
| ((
|
|
2313
961
|
request: Request,
|
|
2314
|
-
|
|
962
|
+
input: RouterRequestInput<TEnv>,
|
|
2315
963
|
) => Promise<Response>)
|
|
2316
964
|
| null = null;
|
|
2317
965
|
|
|
2318
|
-
return async (
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
966
|
+
return async (request: Request, input: RouterRequestInput<TEnv> = {}) => {
|
|
967
|
+
// Trigger lazy import of per-router manifest data before route matching.
|
|
968
|
+
// No-op if data is already loaded or no loader is registered.
|
|
969
|
+
await ensureRouterManifest(routerId);
|
|
2322
970
|
if (!handler) {
|
|
2323
971
|
// Lazy import deferred to first request to avoid dev mode issues
|
|
2324
972
|
const { createRSCHandler } = await import("./rsc/handler.js");
|
|
973
|
+
// Cast: handler.ts still accepts (request, env) — will be updated
|
|
974
|
+
// separately to accept RouterRequestInput.
|
|
2325
975
|
handler = createRSCHandler({
|
|
2326
976
|
router: router as any,
|
|
2327
977
|
cache,
|
|
2328
978
|
nonce,
|
|
2329
979
|
version,
|
|
2330
|
-
})
|
|
980
|
+
}) as (
|
|
981
|
+
request: Request,
|
|
982
|
+
input: RouterRequestInput<TEnv>,
|
|
983
|
+
) => Promise<Response>;
|
|
2331
984
|
}
|
|
2332
|
-
return handler(request,
|
|
985
|
+
return handler!(request, input);
|
|
2333
986
|
};
|
|
2334
987
|
})(),
|
|
2335
988
|
|
|
2336
989
|
// Debug utility for manifest inspection
|
|
2337
|
-
|
|
2338
|
-
const manifest = new Map<string, EntryData>();
|
|
2339
|
-
|
|
2340
|
-
for (const entry of routesEntries) {
|
|
2341
|
-
const Store = {
|
|
2342
|
-
manifest,
|
|
2343
|
-
namespace: `debug.M${entry.mountIndex}`,
|
|
2344
|
-
parent: null as EntryData | null,
|
|
2345
|
-
counters: {} as Record<string, number>,
|
|
2346
|
-
mountIndex: entry.mountIndex,
|
|
2347
|
-
patterns: new Map<string, string>(),
|
|
2348
|
-
trailingSlash: new Map<string, TrailingSlashMode>(),
|
|
2349
|
-
};
|
|
2350
|
-
|
|
2351
|
-
await getContext().runWithStore(
|
|
2352
|
-
Store,
|
|
2353
|
-
`debug.M${entry.mountIndex}`,
|
|
2354
|
-
null,
|
|
2355
|
-
async () => {
|
|
2356
|
-
const helpers = createRouteHelpers();
|
|
2357
|
-
|
|
2358
|
-
// Wrap handler execution in root layout (same as loadManifest)
|
|
2359
|
-
let promiseResult: Promise<any> | null = null;
|
|
2360
|
-
helpers.layout(MapRootLayout, () => {
|
|
2361
|
-
const result = entry.handler();
|
|
2362
|
-
if (result instanceof Promise) {
|
|
2363
|
-
promiseResult = result;
|
|
2364
|
-
return [];
|
|
2365
|
-
}
|
|
2366
|
-
return result;
|
|
2367
|
-
});
|
|
2368
|
-
|
|
2369
|
-
if (promiseResult !== null) {
|
|
2370
|
-
const load = await (promiseResult as Promise<any>);
|
|
2371
|
-
if (load && typeof load === "object" && "default" in load) {
|
|
2372
|
-
const useItems = load.default;
|
|
2373
|
-
if (typeof useItems === "function") {
|
|
2374
|
-
useItems(helpers);
|
|
2375
|
-
}
|
|
2376
|
-
}
|
|
2377
|
-
}
|
|
2378
|
-
},
|
|
2379
|
-
);
|
|
2380
|
-
}
|
|
2381
|
-
|
|
2382
|
-
return serializeManifest(manifest);
|
|
2383
|
-
},
|
|
990
|
+
debugManifest: () => buildDebugManifest<TEnv>(routesEntries),
|
|
2384
991
|
};
|
|
2385
992
|
|
|
2386
993
|
// Register router in the global registry for build-time discovery
|