@rangojs/router 0.0.0-experimental.20 → 0.0.0-experimental.204030a9
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 +4 -0
- package/README.md +242 -55
- package/dist/bin/rango.js +277 -99
- package/dist/vite/index.js +2929 -1132
- package/dist/vite/index.js.bak +5448 -0
- package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/package.json +68 -21
- package/skills/breadcrumbs/SKILL.md +252 -0
- package/skills/bundle-analysis/SKILL.md +159 -0
- package/skills/cache-guide/SKILL.md +243 -21
- package/skills/caching/SKILL.md +159 -10
- package/skills/composability/SKILL.md +27 -2
- package/skills/document-cache/SKILL.md +78 -55
- package/skills/handler-use/SKILL.md +364 -0
- package/skills/hooks/SKILL.md +262 -51
- package/skills/host-router/SKILL.md +243 -0
- package/skills/i18n/SKILL.md +276 -0
- package/skills/intercept/SKILL.md +46 -4
- package/skills/layout/SKILL.md +28 -7
- package/skills/links/SKILL.md +249 -17
- package/skills/loader/SKILL.md +291 -31
- package/skills/middleware/SKILL.md +49 -12
- package/skills/migrate-nextjs/SKILL.md +562 -0
- package/skills/migrate-react-router/SKILL.md +769 -0
- package/skills/mime-routes/SKILL.md +27 -0
- package/skills/observability/SKILL.md +137 -0
- package/skills/parallel/SKILL.md +197 -6
- package/skills/prerender/SKILL.md +125 -102
- package/skills/rango/SKILL.md +242 -23
- package/skills/react-compiler/SKILL.md +168 -0
- package/skills/response-routes/SKILL.md +66 -9
- package/skills/route/SKILL.md +91 -8
- package/skills/router-setup/SKILL.md +98 -8
- package/skills/server-actions/SKILL.md +751 -0
- package/skills/streams-and-websockets/SKILL.md +283 -0
- package/skills/testing/SKILL.md +511 -188
- package/skills/typesafety/SKILL.md +354 -50
- package/skills/use-cache/SKILL.md +34 -5
- package/skills/view-transitions/SKILL.md +294 -0
- package/src/__augment-tests__/augment.ts +81 -0
- package/src/__augment-tests__/augmented.check.ts +117 -0
- package/src/__internal.ts +92 -0
- package/src/browser/action-coordinator.ts +53 -36
- package/src/browser/app-shell.ts +52 -0
- package/src/browser/app-version.ts +14 -0
- package/src/browser/event-controller.ts +91 -70
- package/src/browser/history-state.ts +21 -0
- package/src/browser/index.ts +3 -3
- package/src/browser/link-interceptor.ts +4 -0
- package/src/browser/navigation-bridge.ts +183 -18
- package/src/browser/navigation-client.ts +187 -57
- package/src/browser/navigation-store.ts +75 -17
- package/src/browser/navigation-transaction.ts +21 -37
- package/src/browser/partial-update.ts +143 -40
- package/src/browser/prefetch/cache.ts +275 -28
- package/src/browser/prefetch/fetch.ts +191 -46
- package/src/browser/prefetch/policy.ts +6 -0
- package/src/browser/prefetch/queue.ts +123 -20
- package/src/browser/prefetch/resource-ready.ts +77 -0
- package/src/browser/rango-state.ts +53 -13
- package/src/browser/react/Link.tsx +98 -14
- package/src/browser/react/NavigationProvider.tsx +110 -33
- package/src/browser/react/context.ts +7 -2
- package/src/browser/react/filter-segment-order.ts +51 -7
- package/src/browser/react/index.ts +3 -0
- package/src/browser/react/location-state-shared.ts +175 -4
- package/src/browser/react/location-state.ts +39 -13
- package/src/browser/react/use-handle.ts +23 -64
- package/src/browser/react/use-navigation.ts +22 -2
- package/src/browser/react/use-params.ts +20 -8
- package/src/browser/react/use-reverse.ts +106 -0
- package/src/browser/react/use-router.ts +43 -10
- package/src/browser/react/use-segments.ts +11 -8
- package/src/browser/response-adapter.ts +25 -0
- package/src/browser/rsc-router.tsx +200 -75
- package/src/browser/scroll-restoration.ts +46 -39
- package/src/browser/segment-reconciler.ts +36 -9
- package/src/browser/segment-structure-assert.ts +2 -2
- package/src/browser/server-action-bridge.ts +31 -36
- package/src/browser/types.ts +81 -5
- package/src/build/collect-fallback-refs.ts +107 -0
- package/src/build/generate-manifest.ts +65 -40
- package/src/build/generate-route-types.ts +5 -0
- package/src/build/index.ts +2 -0
- package/src/build/route-trie.ts +69 -26
- package/src/build/route-types/codegen.ts +4 -4
- package/src/build/route-types/include-resolution.ts +9 -2
- package/src/build/route-types/per-module-writer.ts +7 -4
- package/src/build/route-types/router-processing.ts +278 -88
- package/src/build/route-types/scan-filter.ts +9 -2
- package/src/build/route-types/source-scan.ts +118 -0
- package/src/build/runtime-discovery.ts +9 -20
- package/src/cache/cache-runtime.ts +15 -11
- package/src/cache/cache-scope.ts +76 -49
- package/src/cache/cf/cf-cache-store.ts +501 -18
- package/src/cache/cf/index.ts +5 -1
- package/src/cache/document-cache.ts +17 -7
- package/src/cache/index.ts +1 -0
- package/src/cache/taint.ts +55 -0
- package/src/client.rsc.tsx +5 -1
- package/src/client.tsx +95 -284
- package/src/context-var.ts +72 -2
- package/src/debug.ts +2 -2
- package/src/decode-loader-results.ts +36 -0
- package/src/errors.ts +30 -1
- package/src/handle.ts +65 -12
- package/src/handles/breadcrumbs.ts +66 -0
- package/src/handles/index.ts +1 -0
- package/src/host/index.ts +2 -5
- package/src/host/router.ts +129 -57
- package/src/host/types.ts +31 -2
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +140 -20
- package/src/index.rsc.ts +15 -40
- package/src/index.ts +92 -76
- package/src/loader-store.ts +500 -0
- package/src/loader.rsc.ts +2 -5
- package/src/loader.ts +3 -10
- package/src/missing-id-error.ts +68 -0
- package/src/outlet-context.ts +1 -1
- package/src/prerender/store.ts +57 -15
- package/src/prerender.ts +141 -80
- package/src/response-utils.ts +37 -0
- package/src/reverse.ts +65 -15
- package/src/route-content-wrapper.tsx +6 -28
- package/src/route-definition/dsl-helpers.ts +435 -260
- package/src/route-definition/helper-factories.ts +29 -139
- package/src/route-definition/helpers-types.ts +110 -34
- package/src/route-definition/index.ts +3 -3
- package/src/route-definition/redirect.ts +11 -3
- package/src/route-definition/resolve-handler-use.ts +155 -0
- package/src/route-definition/use-item-types.ts +32 -0
- package/src/route-map-builder.ts +7 -1
- package/src/route-types.ts +37 -41
- package/src/router/basename.ts +14 -0
- package/src/router/content-negotiation.ts +113 -1
- package/src/router/error-handling.ts +1 -1
- package/src/router/find-match.ts +4 -2
- package/src/router/handler-context.ts +105 -39
- package/src/router/intercept-resolution.ts +15 -22
- package/src/router/lazy-includes.ts +12 -9
- package/src/router/loader-resolution.ts +175 -23
- package/src/router/logging.ts +5 -2
- package/src/router/manifest.ts +31 -16
- package/src/router/match-api.ts +129 -193
- package/src/router/match-handlers.ts +63 -20
- package/src/router/match-middleware/background-revalidation.ts +30 -2
- package/src/router/match-middleware/cache-lookup.ts +136 -106
- package/src/router/match-middleware/cache-store.ts +54 -10
- package/src/router/match-middleware/intercept-resolution.ts +9 -7
- package/src/router/match-middleware/segment-resolution.ts +61 -5
- package/src/router/match-result.ts +124 -18
- package/src/router/metrics.ts +239 -14
- package/src/router/middleware-types.ts +61 -31
- package/src/router/middleware.ts +226 -124
- package/src/router/navigation-snapshot.ts +182 -0
- package/src/router/pattern-matching.ts +118 -19
- package/src/router/prerender-match.ts +114 -10
- package/src/router/preview-match.ts +32 -102
- package/src/router/request-classification.ts +286 -0
- package/src/router/revalidation.ts +85 -9
- package/src/router/route-snapshot.ts +245 -0
- package/src/router/router-context.ts +6 -1
- package/src/router/router-interfaces.ts +91 -29
- package/src/router/router-options.ts +89 -19
- package/src/router/router-registry.ts +2 -5
- package/src/router/segment-resolution/fresh.ts +240 -23
- package/src/router/segment-resolution/helpers.ts +30 -25
- package/src/router/segment-resolution/loader-cache.ts +1 -0
- package/src/router/segment-resolution/revalidation.ts +483 -289
- package/src/router/segment-resolution/view-transition-default.ts +36 -0
- package/src/router/segment-wrappers.ts +2 -0
- package/src/router/substitute-pattern-params.ts +56 -0
- package/src/router/telemetry.ts +99 -0
- package/src/router/trie-matching.ts +38 -15
- package/src/router/types.ts +9 -0
- package/src/router/url-params.ts +49 -0
- package/src/router.ts +120 -32
- package/src/rsc/handler-context.ts +2 -2
- package/src/rsc/handler.ts +524 -370
- package/src/rsc/helpers.ts +91 -43
- package/src/rsc/index.ts +1 -21
- package/src/rsc/loader-fetch.ts +23 -3
- package/src/rsc/manifest-init.ts +5 -1
- package/src/rsc/origin-guard.ts +28 -10
- package/src/rsc/progressive-enhancement.ts +39 -10
- package/src/rsc/response-route-handler.ts +46 -53
- package/src/rsc/rsc-rendering.ts +69 -89
- package/src/rsc/runtime-warnings.ts +9 -10
- package/src/rsc/server-action.ts +39 -47
- package/src/rsc/ssr-setup.ts +144 -0
- package/src/rsc/types.ts +19 -3
- package/src/search-params.ts +20 -17
- package/src/segment-content-promise.ts +67 -0
- package/src/segment-loader-promise.ts +122 -0
- package/src/segment-system.tsx +219 -67
- package/src/serialize.ts +243 -0
- package/src/server/context.ts +285 -63
- package/src/server/cookie-store.ts +28 -4
- package/src/server/handle-store.ts +19 -0
- package/src/server/loader-registry.ts +9 -8
- package/src/server/request-context.ts +228 -65
- package/src/server.ts +6 -0
- package/src/ssr/index.tsx +9 -1
- package/src/static-handler.ts +19 -7
- package/src/testing/cache-status.ts +166 -0
- package/src/testing/collect-handle.ts +63 -0
- package/src/testing/dispatch.ts +440 -0
- package/src/testing/dom.entry.ts +22 -0
- package/src/testing/e2e/fixture.ts +154 -0
- package/src/testing/e2e/index.ts +149 -0
- package/src/testing/e2e/matchers.ts +51 -0
- package/src/testing/e2e/page-helpers.ts +272 -0
- package/src/testing/e2e/parity.ts +306 -0
- package/src/testing/e2e/server.ts +183 -0
- package/src/testing/flight-matchers.ts +104 -0
- package/src/testing/flight-runtime.d.ts +21 -0
- package/src/testing/flight.entry.ts +22 -0
- package/src/testing/flight.ts +182 -0
- package/src/testing/generated-routes.ts +223 -0
- package/src/testing/index.ts +98 -0
- package/src/testing/internal/context.ts +151 -0
- package/src/testing/render-route.tsx +536 -0
- package/src/testing/run-loader.ts +296 -0
- package/src/testing/run-middleware.ts +170 -0
- package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
- package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
- package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
- package/src/testing/vitest-stubs/version.ts +5 -0
- package/src/testing/vitest.ts +112 -0
- package/src/theme/index.ts +4 -13
- package/src/types/cache-types.ts +4 -4
- package/src/types/global-namespace.ts +39 -26
- package/src/types/handler-context.ts +197 -79
- package/src/types/index.ts +1 -0
- package/src/types/loader-types.ts +41 -15
- package/src/types/request-scope.ts +126 -0
- package/src/types/route-config.ts +17 -8
- package/src/types/route-entry.ts +19 -1
- package/src/types/segments.ts +37 -6
- package/src/urls/include-helper.ts +34 -67
- package/src/urls/index.ts +0 -3
- package/src/urls/path-helper-types.ts +50 -9
- package/src/urls/path-helper.ts +63 -63
- package/src/urls/pattern-types.ts +48 -19
- package/src/urls/response-types.ts +25 -22
- package/src/urls/type-extraction.ts +26 -116
- package/src/urls/urls-function.ts +1 -5
- package/src/use-loader.tsx +487 -44
- package/src/vite/debug.ts +185 -0
- package/src/vite/discovery/bundle-postprocess.ts +63 -91
- package/src/vite/discovery/discover-routers.ts +106 -53
- package/src/vite/discovery/discovery-errors.ts +194 -0
- package/src/vite/discovery/gate-state.ts +171 -0
- package/src/vite/discovery/prerender-collection.ts +222 -107
- package/src/vite/discovery/route-types-writer.ts +40 -84
- package/src/vite/discovery/self-gen-tracking.ts +27 -1
- package/src/vite/discovery/state.ts +50 -13
- package/src/vite/discovery/virtual-module-codegen.ts +13 -23
- package/src/vite/index.ts +10 -3
- package/src/vite/plugin-types.ts +111 -72
- package/src/vite/plugins/cjs-to-esm.ts +8 -7
- package/src/vite/plugins/client-ref-dedup.ts +16 -0
- package/src/vite/plugins/client-ref-hashing.ts +28 -5
- package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
- package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
- package/src/vite/plugins/expose-action-id.ts +55 -33
- package/src/vite/plugins/expose-id-utils.ts +24 -8
- package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
- package/src/vite/plugins/expose-ids/handler-transform.ts +12 -35
- package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
- package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
- package/src/vite/plugins/expose-internal-ids.ts +544 -317
- package/src/vite/plugins/performance-tracks.ts +92 -0
- package/src/vite/plugins/refresh-cmd.ts +127 -0
- package/src/vite/plugins/use-cache-transform.ts +65 -50
- package/src/vite/plugins/version-injector.ts +39 -23
- package/src/vite/plugins/version-plugin.ts +72 -3
- package/src/vite/plugins/virtual-entries.ts +2 -2
- package/src/vite/rango.ts +265 -226
- package/src/vite/router-discovery.ts +924 -137
- package/src/vite/utils/ast-handler-extract.ts +15 -15
- package/src/vite/utils/banner.ts +4 -4
- package/src/vite/utils/bundle-analysis.ts +4 -2
- package/src/vite/utils/client-chunks.ts +190 -0
- package/src/vite/utils/forward-user-plugins.ts +193 -0
- package/src/vite/utils/manifest-utils.ts +21 -5
- package/src/vite/utils/package-resolution.ts +41 -1
- package/src/vite/utils/prerender-utils.ts +98 -5
- package/src/vite/utils/shared-utils.ts +109 -27
- package/src/browser/action-response-classifier.ts +0 -99
- package/src/route-definition/route-function.ts +0 -119
package/src/rsc/handler.ts
CHANGED
|
@@ -8,23 +8,30 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { createElement } from "react";
|
|
11
|
-
import {
|
|
11
|
+
import { isRouteNotFoundError } from "../errors.js";
|
|
12
12
|
import { matchMiddleware, executeMiddleware } from "../router/middleware.js";
|
|
13
13
|
import {
|
|
14
14
|
runWithRequestContext,
|
|
15
15
|
setRequestContextParams,
|
|
16
16
|
requireRequestContext,
|
|
17
|
+
getRequestContext,
|
|
18
|
+
_getRequestContext,
|
|
17
19
|
createRequestContext,
|
|
18
20
|
} from "../server/request-context.js";
|
|
19
21
|
import * as rscDeps from "@vitejs/plugin-rsc/rsc";
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
import type {
|
|
23
|
+
RscPayload,
|
|
24
|
+
CreateRSCHandlerOptions,
|
|
25
|
+
LoadSSRModule,
|
|
26
|
+
SSRModule,
|
|
27
|
+
} from "./types.js";
|
|
22
28
|
import {
|
|
23
29
|
createResponseWithMergedHeaders,
|
|
24
30
|
finalizeResponse,
|
|
25
31
|
interceptRedirectForPartial,
|
|
26
32
|
buildRouteMiddlewareEntries,
|
|
27
33
|
} from "./helpers.js";
|
|
34
|
+
import { isWebSocketUpgradeResponse } from "../response-utils.js";
|
|
28
35
|
import {
|
|
29
36
|
handleResponseRoute,
|
|
30
37
|
type ResponseRouteMatch,
|
|
@@ -50,6 +57,7 @@ import {
|
|
|
50
57
|
getRouterTrie,
|
|
51
58
|
} from "../route-map-builder.js";
|
|
52
59
|
import type { HandlerContext } from "./handler-context.js";
|
|
60
|
+
import type { SegmentCacheStore } from "../cache/types.js";
|
|
53
61
|
import { buildRouterTrieFromUrlpatterns } from "./manifest-init.js";
|
|
54
62
|
import { handleProgressiveEnhancement } from "./progressive-enhancement.js";
|
|
55
63
|
import {
|
|
@@ -58,7 +66,10 @@ import {
|
|
|
58
66
|
type ActionContinuation,
|
|
59
67
|
} from "./server-action.js";
|
|
60
68
|
import { handleLoaderFetch } from "./loader-fetch.js";
|
|
61
|
-
import {
|
|
69
|
+
import {
|
|
70
|
+
checkRequestOrigin,
|
|
71
|
+
ORIGIN_CHECK_PHASE_BY_MODE,
|
|
72
|
+
} from "./origin-guard.js";
|
|
62
73
|
import { handleRscRendering } from "./rsc-rendering.js";
|
|
63
74
|
import {
|
|
64
75
|
withTimeout,
|
|
@@ -66,6 +77,23 @@ import {
|
|
|
66
77
|
createDefaultTimeoutResponse,
|
|
67
78
|
type TimeoutPhase,
|
|
68
79
|
} from "../router/timeout.js";
|
|
80
|
+
import {
|
|
81
|
+
createMetricsStore,
|
|
82
|
+
appendMetric,
|
|
83
|
+
buildMetricsTiming,
|
|
84
|
+
} from "../router/metrics.js";
|
|
85
|
+
import {
|
|
86
|
+
startSSRSetup,
|
|
87
|
+
getSSRSetup,
|
|
88
|
+
mayNeedSSR,
|
|
89
|
+
isRscRequest,
|
|
90
|
+
SSR_SETUP_VAR,
|
|
91
|
+
} from "./ssr-setup.js";
|
|
92
|
+
import {
|
|
93
|
+
classifyRequest,
|
|
94
|
+
type RequestPlan,
|
|
95
|
+
type ExecutableRequestPlan,
|
|
96
|
+
} from "../router/request-classification.js";
|
|
69
97
|
|
|
70
98
|
/**
|
|
71
99
|
* Create an RSC request handler.
|
|
@@ -117,10 +145,22 @@ export function createRSCHandler<
|
|
|
117
145
|
decodeFormState,
|
|
118
146
|
} = deps;
|
|
119
147
|
|
|
120
|
-
// Use provided loadSSRModule or default to vite RSC module loader
|
|
121
|
-
|
|
148
|
+
// Use provided loadSSRModule or default to vite RSC module loader.
|
|
149
|
+
// In production the SSR module is stable across requests, so memoize
|
|
150
|
+
// the dynamic import to avoid repeated module resolution overhead.
|
|
151
|
+
// In dev mode Vite may hot-reload the module, so skip memoization.
|
|
152
|
+
const rawLoadSSRModule: LoadSSRModule =
|
|
122
153
|
options.loadSSRModule ??
|
|
123
154
|
(() => import.meta.viteRsc.loadModule("ssr", "index"));
|
|
155
|
+
let _ssrModulePromise: Promise<SSRModule> | undefined;
|
|
156
|
+
const loadSSRModule: LoadSSRModule =
|
|
157
|
+
process.env.NODE_ENV === "production"
|
|
158
|
+
? () =>
|
|
159
|
+
(_ssrModulePromise ??= rawLoadSSRModule().catch((err) => {
|
|
160
|
+
_ssrModulePromise = undefined;
|
|
161
|
+
throw err;
|
|
162
|
+
}))
|
|
163
|
+
: rawLoadSSRModule;
|
|
124
164
|
|
|
125
165
|
/**
|
|
126
166
|
* Per-request error reporter that deduplicates via the ALS request context.
|
|
@@ -133,10 +173,13 @@ export function createRSCHandler<
|
|
|
133
173
|
phase: ErrorPhase,
|
|
134
174
|
context: Parameters<typeof invokeOnError<TEnv>>[3],
|
|
135
175
|
): void {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
176
|
+
// Guard: abort signal handlers fire asynchronously outside the ALS
|
|
177
|
+
// request scope, so the context may be gone. Skip dedup in that
|
|
178
|
+
// case — the error is from a cancelled stream, not a real failure.
|
|
179
|
+
const reqCtx = _getRequestContext();
|
|
180
|
+
if (error != null && typeof error === "object" && reqCtx) {
|
|
181
|
+
if (reqCtx._reportedErrors.has(error)) return;
|
|
182
|
+
reqCtx._reportedErrors.add(error);
|
|
140
183
|
}
|
|
141
184
|
invokeOnError(router.onError, error, phase, context, "RSC");
|
|
142
185
|
}
|
|
@@ -268,6 +311,11 @@ export function createRSCHandler<
|
|
|
268
311
|
input: RouterRequestInput<TEnv> = {},
|
|
269
312
|
): Promise<Response> {
|
|
270
313
|
const handlerStart = performance.now();
|
|
314
|
+
// Create the metrics store at handler start so handler:total has startTime=0
|
|
315
|
+
// and all metrics are relative to the request entry point.
|
|
316
|
+
const earlyMetricsStore = router.debugPerformance
|
|
317
|
+
? createMetricsStore(true, handlerStart)
|
|
318
|
+
: undefined;
|
|
271
319
|
|
|
272
320
|
const { env = {} as TEnv, vars: initialVars, ctx: executionCtx } = input;
|
|
273
321
|
|
|
@@ -310,7 +358,7 @@ export function createRSCHandler<
|
|
|
310
358
|
// Resolve cache store configuration
|
|
311
359
|
// Priority: options.cache (handler override) > router.cache (router default)
|
|
312
360
|
// Store is enabled only if: config provided, enabled, and no ?__no_cache query param
|
|
313
|
-
let cacheStore
|
|
361
|
+
let cacheStore: SegmentCacheStore | undefined;
|
|
314
362
|
const cacheOption = options.cache ?? router.cache;
|
|
315
363
|
if (cacheOption && !url.searchParams.has("__no_cache")) {
|
|
316
364
|
const cacheConfig =
|
|
@@ -381,6 +429,10 @@ export function createRSCHandler<
|
|
|
381
429
|
executionContext: executionCtx,
|
|
382
430
|
themeConfig: router.themeConfig,
|
|
383
431
|
});
|
|
432
|
+
if (earlyMetricsStore) {
|
|
433
|
+
requestContext._debugPerformance = true;
|
|
434
|
+
requestContext._metricsStore = earlyMetricsStore;
|
|
435
|
+
}
|
|
384
436
|
// Wire background error reporting so "use cache" and other subsystems
|
|
385
437
|
// can surface non-fatal errors through the router's onError callback.
|
|
386
438
|
requestContext._reportBackgroundError = (
|
|
@@ -415,6 +467,9 @@ export function createRSCHandler<
|
|
|
415
467
|
// - Server components during rendering
|
|
416
468
|
// - Error boundaries
|
|
417
469
|
// - Streaming
|
|
470
|
+
// Store basename on request context (scoped per-request via existing ALS)
|
|
471
|
+
requestContext._basename = router.basename;
|
|
472
|
+
|
|
418
473
|
return runWithRequestContext(requestContext, async () => {
|
|
419
474
|
// Core handler logic (wrapped by middleware)
|
|
420
475
|
const coreHandler = async (): Promise<Response> => {
|
|
@@ -422,6 +477,7 @@ export function createRSCHandler<
|
|
|
422
477
|
};
|
|
423
478
|
|
|
424
479
|
// Execute middleware chain if any, otherwise call core handler directly
|
|
480
|
+
let response: Response;
|
|
425
481
|
if (matchedMiddleware.length > 0) {
|
|
426
482
|
const mwResponse = await executeMiddleware(
|
|
427
483
|
matchedMiddleware,
|
|
@@ -440,17 +496,60 @@ export function createRSCHandler<
|
|
|
440
496
|
mwResponse,
|
|
441
497
|
createRedirectFlightResponse,
|
|
442
498
|
);
|
|
443
|
-
|
|
499
|
+
response = intercepted ?? finalizeResponse(mwResponse);
|
|
500
|
+
} else {
|
|
501
|
+
response = finalizeResponse(mwResponse);
|
|
444
502
|
}
|
|
503
|
+
} else {
|
|
504
|
+
response = await coreHandler();
|
|
505
|
+
}
|
|
445
506
|
|
|
446
|
-
|
|
507
|
+
// Finalize metrics after all middleware (including post-next work)
|
|
508
|
+
// has completed so :post spans are captured in the timeline.
|
|
509
|
+
// Handler timing parts are always emitted (even without debug metrics)
|
|
510
|
+
// so non-debug requests still get bootstrap Server-Timing entries.
|
|
511
|
+
const handlerTimingArr: string[] = variables.__handlerTiming || [];
|
|
512
|
+
// Preserve any existing Server-Timing set by response routes or middleware
|
|
513
|
+
const existingTiming = response.headers.get("Server-Timing");
|
|
514
|
+
const timingParts = existingTiming
|
|
515
|
+
? [existingTiming, ...handlerTimingArr]
|
|
516
|
+
: [...handlerTimingArr];
|
|
517
|
+
|
|
518
|
+
const metricsStore = requestContext._metricsStore;
|
|
519
|
+
if (metricsStore) {
|
|
520
|
+
// When the store was created at handler start (earlyMetricsStore),
|
|
521
|
+
// handler:total covers the full request. When ctx.debugPerformance()
|
|
522
|
+
// created the store mid-request, use its requestStart to avoid a
|
|
523
|
+
// negative startTime offset.
|
|
524
|
+
const totalStart = earlyMetricsStore
|
|
525
|
+
? handlerStart
|
|
526
|
+
: metricsStore.requestStart;
|
|
527
|
+
appendMetric(
|
|
528
|
+
metricsStore,
|
|
529
|
+
"handler:total",
|
|
530
|
+
totalStart,
|
|
531
|
+
performance.now() - totalStart,
|
|
532
|
+
);
|
|
533
|
+
const metricsTiming = buildMetricsTiming(
|
|
534
|
+
request.method,
|
|
535
|
+
url.pathname,
|
|
536
|
+
metricsStore,
|
|
537
|
+
);
|
|
538
|
+
if (metricsTiming) timingParts.push(metricsTiming);
|
|
447
539
|
}
|
|
448
540
|
|
|
449
|
-
|
|
541
|
+
const fullTiming = timingParts.join(", ");
|
|
542
|
+
if (fullTiming && !isWebSocketUpgradeResponse(response)) {
|
|
543
|
+
response.headers.set("Server-Timing", fullTiming);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
return response;
|
|
450
547
|
});
|
|
451
548
|
};
|
|
452
549
|
|
|
453
|
-
// Core request handling logic (separated for middleware wrapping)
|
|
550
|
+
// Core request handling logic (separated for middleware wrapping).
|
|
551
|
+
// Uses the classify → execute model: classifyRequest produces a RequestPlan,
|
|
552
|
+
// then execution dispatches on the plan mode.
|
|
454
553
|
async function coreRequestHandler(
|
|
455
554
|
request: Request,
|
|
456
555
|
env: TEnv,
|
|
@@ -458,56 +557,102 @@ export function createRSCHandler<
|
|
|
458
557
|
variables: Record<string, any>,
|
|
459
558
|
nonce: string | undefined,
|
|
460
559
|
): Promise<Response> {
|
|
461
|
-
const previewStart = performance.now();
|
|
462
|
-
const preview = await router.previewMatch(request, { env });
|
|
463
|
-
const previewDur = performance.now() - previewStart;
|
|
464
560
|
const handlerTiming: string[] = variables.__handlerTiming || [];
|
|
465
|
-
|
|
466
|
-
//
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
561
|
+
|
|
562
|
+
// Debug manifest endpoint: handled before classification since it
|
|
563
|
+
// doesn't need a route match and needs trie access from the closure.
|
|
564
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
565
|
+
if (
|
|
566
|
+
url.searchParams.has("__debug_manifest") &&
|
|
567
|
+
(isDev || router.allowDebugManifest)
|
|
568
|
+
) {
|
|
569
|
+
const trie = getRouterTrie(router.id) ?? getRouteTrie();
|
|
570
|
+
const routeManifest = getRequiredRouteMap();
|
|
571
|
+
const { extractAncestryFromTrie } =
|
|
572
|
+
await import("../build/route-trie.js");
|
|
573
|
+
return new Response(
|
|
574
|
+
JSON.stringify(
|
|
575
|
+
{
|
|
576
|
+
routerId: router.id,
|
|
577
|
+
routeManifest,
|
|
578
|
+
routeAncestry: trie ? extractAncestryFromTrie(trie) : {},
|
|
579
|
+
routeTrie: trie,
|
|
580
|
+
precomputedEntries: getPrecomputedEntries(),
|
|
581
|
+
},
|
|
582
|
+
null,
|
|
583
|
+
2,
|
|
476
584
|
),
|
|
477
|
-
|
|
478
|
-
|
|
585
|
+
{
|
|
586
|
+
headers: { "Content-Type": "application/json" },
|
|
587
|
+
},
|
|
479
588
|
);
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// ---- 1. Classify ----
|
|
592
|
+
// classifyRequest may throw RouteNotFoundError for unknown routes.
|
|
593
|
+
// In that case, fall through to a full-render plan so the pipeline
|
|
594
|
+
// can render the 404 page via the existing error handling path.
|
|
595
|
+
const classifyStart = performance.now();
|
|
596
|
+
let plan: RequestPlan<TEnv>;
|
|
597
|
+
try {
|
|
598
|
+
plan = await classifyRequest<TEnv>(request, url, {
|
|
599
|
+
findMatch: router.findMatch,
|
|
600
|
+
routerVersion: version,
|
|
601
|
+
routerId: router.id,
|
|
602
|
+
});
|
|
603
|
+
} catch (error) {
|
|
604
|
+
if (isRouteNotFoundError(error)) {
|
|
605
|
+
// Let the render path handle 404 — match()/matchPartial() will
|
|
606
|
+
// re-throw RouteNotFoundError and the catch block in
|
|
607
|
+
// executeRenderWithMiddleware renders the not-found page.
|
|
608
|
+
plan = {
|
|
609
|
+
mode: "full-render",
|
|
610
|
+
route: {
|
|
611
|
+
matched: null as any,
|
|
612
|
+
manifestEntry: null as any,
|
|
613
|
+
entries: [],
|
|
614
|
+
routeKey: "",
|
|
615
|
+
localRouteName: "",
|
|
616
|
+
params: {},
|
|
617
|
+
routeMiddleware: [],
|
|
618
|
+
cacheScope: null,
|
|
619
|
+
isPassthrough: false,
|
|
620
|
+
},
|
|
621
|
+
negotiated: false,
|
|
622
|
+
};
|
|
623
|
+
} else {
|
|
624
|
+
throw error;
|
|
489
625
|
}
|
|
490
|
-
|
|
626
|
+
}
|
|
627
|
+
const classifyDur = performance.now() - classifyStart;
|
|
628
|
+
handlerTiming.push(`handler-classify;dur=${classifyDur.toFixed(2)}`);
|
|
629
|
+
|
|
630
|
+
// ---- 2. Terminal plans (no execution needed) ----
|
|
631
|
+
if (plan.mode === "redirect") {
|
|
632
|
+
// Redirects are handled by the pipeline (match/matchPartial),
|
|
633
|
+
// but for partial requests we short-circuit with a Flight redirect.
|
|
634
|
+
if (url.searchParams.has("_rsc_partial")) {
|
|
635
|
+
return createRedirectFlightResponse(plan.redirectUrl);
|
|
636
|
+
}
|
|
637
|
+
// Full requests: let the pipeline handle the redirect via match()
|
|
638
|
+
// which returns { redirect: url }. Fall through to full-render.
|
|
491
639
|
}
|
|
492
640
|
|
|
493
|
-
|
|
641
|
+
if (plan.mode === "version-mismatch") {
|
|
642
|
+
console.log(
|
|
643
|
+
`[RSC] Version mismatch: client=${url.searchParams.get("_rsc_v")}, server=${version}. Forcing reload.`,
|
|
644
|
+
);
|
|
645
|
+
return createResponseWithMergedHeaders(null, {
|
|
646
|
+
status: 200,
|
|
647
|
+
headers: {
|
|
648
|
+
"X-RSC-Reload": plan.reloadUrl,
|
|
649
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
650
|
+
},
|
|
651
|
+
});
|
|
652
|
+
}
|
|
494
653
|
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
const isLoaderFetch = url.searchParams.has("_rsc_loader");
|
|
498
|
-
const actionId =
|
|
499
|
-
request.headers.get("rsc-action") || url.searchParams.get("_rsc_action");
|
|
500
|
-
|
|
501
|
-
// Origin guard: reject cross-origin actions, loader fetches, and
|
|
502
|
-
// PE form submissions before any execution. Regular page navigations
|
|
503
|
-
// (GET without _rsc_loader/_rsc_action) are not affected.
|
|
504
|
-
const originPhase: OriginCheckPhase | null = isAction
|
|
505
|
-
? "action"
|
|
506
|
-
: isLoaderFetch
|
|
507
|
-
? "loader"
|
|
508
|
-
: request.method === "POST"
|
|
509
|
-
? "pe-form"
|
|
510
|
-
: null;
|
|
654
|
+
// ---- 3. Origin guard (gate for action/loader/PE modes) ----
|
|
655
|
+
const originPhase = ORIGIN_CHECK_PHASE_BY_MODE[plan.mode];
|
|
511
656
|
if (originPhase) {
|
|
512
657
|
const originResult = await checkRequestOrigin(
|
|
513
658
|
request,
|
|
@@ -557,13 +702,33 @@ export function createRSCHandler<
|
|
|
557
702
|
}
|
|
558
703
|
}
|
|
559
704
|
|
|
560
|
-
//
|
|
705
|
+
// ---- 4. Execute ----
|
|
706
|
+
return executeRequest(
|
|
707
|
+
plan as ExecutableRequestPlan<TEnv>,
|
|
708
|
+
request,
|
|
709
|
+
env,
|
|
710
|
+
url,
|
|
711
|
+
variables,
|
|
712
|
+
nonce,
|
|
713
|
+
);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// Execute a classified request plan. Dispatches to the appropriate handler
|
|
717
|
+
// based on plan.mode. Lives in the createRSCHandler closure for access to
|
|
718
|
+
// handlerCtx, router, callOnError, etc.
|
|
719
|
+
// Only receives executable plans (version-mismatch is handled above).
|
|
720
|
+
async function executeRequest(
|
|
721
|
+
plan: ExecutableRequestPlan<TEnv>,
|
|
722
|
+
request: Request,
|
|
723
|
+
env: TEnv,
|
|
724
|
+
url: URL,
|
|
725
|
+
variables: Record<string, any>,
|
|
726
|
+
nonce: string | undefined,
|
|
727
|
+
): Promise<Response> {
|
|
728
|
+
// Common setup
|
|
561
729
|
const handleStore = requireRequestContext()._handleStore;
|
|
562
730
|
|
|
563
731
|
// Wire up error reporting for late streaming-handle failures
|
|
564
|
-
// (LateHandlePushError: handle pushed after stream completion).
|
|
565
|
-
// Without this, these errors are only caught by React's error boundary
|
|
566
|
-
// and never reach the router's onError callback or telemetry.
|
|
567
732
|
handleStore.onError = (error: Error) => {
|
|
568
733
|
const reqCtx = requireRequestContext();
|
|
569
734
|
callOnError(error, "handler", {
|
|
@@ -593,37 +758,106 @@ export function createRSCHandler<
|
|
|
593
758
|
};
|
|
594
759
|
|
|
595
760
|
// Set route params early so all execution paths can access ctx.params.
|
|
596
|
-
|
|
597
|
-
|
|
761
|
+
// Also store the classified snapshot so match/matchPartial can reuse it
|
|
762
|
+
// instead of calling resolveRoute again.
|
|
763
|
+
if (plan.mode !== "redirect") {
|
|
764
|
+
setRequestContextParams(plan.route.params, plan.route.routeKey);
|
|
765
|
+
requireRequestContext()._classifiedRoute = plan.route;
|
|
598
766
|
}
|
|
599
767
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
//
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
routeMiddleware:
|
|
768
|
+
const routeReverse = createReverseFunction(getRequiredRouteMap());
|
|
769
|
+
|
|
770
|
+
// ---- Response route: skip entire RSC pipeline ----
|
|
771
|
+
if (plan.mode === "response") {
|
|
772
|
+
// Build ResponseRouteMatch from plan fields. handleResponseRoute
|
|
773
|
+
// expects a flat object with params at the top level.
|
|
774
|
+
const responseMatch: ResponseRouteMatch = {
|
|
775
|
+
responseType: plan.responseType,
|
|
776
|
+
handler: plan.handler,
|
|
777
|
+
params: plan.route.params,
|
|
778
|
+
negotiated: plan.negotiated,
|
|
779
|
+
manifestEntry: plan.manifestEntry,
|
|
780
|
+
routeMiddleware: plan.routeMiddleware,
|
|
781
|
+
};
|
|
782
|
+
const responseOutcome = await withTimeout(
|
|
783
|
+
handleResponseRoute(
|
|
784
|
+
handlerCtx,
|
|
785
|
+
responseMatch,
|
|
786
|
+
request,
|
|
787
|
+
env,
|
|
788
|
+
url,
|
|
789
|
+
variables,
|
|
790
|
+
),
|
|
791
|
+
router.timeouts.renderStartMs,
|
|
792
|
+
"render-start",
|
|
793
|
+
);
|
|
794
|
+
if (responseOutcome.timedOut) {
|
|
795
|
+
return handleTimeoutResponse(
|
|
796
|
+
request,
|
|
797
|
+
env,
|
|
798
|
+
url,
|
|
799
|
+
"render-start",
|
|
800
|
+
responseOutcome.durationMs,
|
|
801
|
+
plan.route.routeKey,
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
const response = responseOutcome.result;
|
|
805
|
+
if (plan.negotiated && !isWebSocketUpgradeResponse(response)) {
|
|
806
|
+
response.headers.append("Vary", "Accept");
|
|
807
|
+
}
|
|
808
|
+
return response;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// SSR setup: kick off in parallel for modes that need HTML rendering.
|
|
812
|
+
// Placed after response-route short-circuit so response/mime routes
|
|
813
|
+
// never pay for SSR work.
|
|
814
|
+
if (plan.mode !== "loader" && mayNeedSSR(request, url)) {
|
|
815
|
+
variables[SSR_SETUP_VAR] = startSSRSetup(
|
|
816
|
+
handlerCtx,
|
|
817
|
+
request,
|
|
818
|
+
env,
|
|
819
|
+
url,
|
|
820
|
+
router.debugPerformance
|
|
821
|
+
? () => requireRequestContext()._metricsStore
|
|
822
|
+
: undefined,
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// ---- Loader fetch ----
|
|
827
|
+
if (plan.mode === "loader") {
|
|
828
|
+
return handleLoaderFetch(
|
|
829
|
+
handlerCtx,
|
|
830
|
+
request,
|
|
831
|
+
env,
|
|
832
|
+
url,
|
|
613
833
|
variables,
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
834
|
+
plan.route.params,
|
|
835
|
+
);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// ---- Progressive enhancement ----
|
|
839
|
+
if (plan.mode === "pe-render") {
|
|
840
|
+
const peResult = await handleProgressiveEnhancement(
|
|
841
|
+
handlerCtx,
|
|
842
|
+
request,
|
|
843
|
+
env,
|
|
844
|
+
url,
|
|
845
|
+
false, // isAction = false for PE
|
|
846
|
+
handleStore,
|
|
847
|
+
nonce,
|
|
848
|
+
{
|
|
849
|
+
routeMiddleware: plan.route.routeMiddleware,
|
|
850
|
+
variables,
|
|
851
|
+
routeReverse,
|
|
852
|
+
},
|
|
853
|
+
);
|
|
854
|
+
if (peResult) return peResult;
|
|
855
|
+
// PE handler returned null (not a PE form) — fall through to render
|
|
619
856
|
}
|
|
620
857
|
|
|
621
|
-
//
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
// the revalidation pass (identical to a normal render).
|
|
625
|
-
let actionContinuation: ActionContinuation | undefined;
|
|
626
|
-
if (isAction && actionId) {
|
|
858
|
+
// ---- Action: execute action, then revalidate wrapped in route middleware ----
|
|
859
|
+
if (plan.mode === "action") {
|
|
860
|
+
let actionContinuation: ActionContinuation | undefined;
|
|
627
861
|
try {
|
|
628
862
|
const actionOutcome = await withTimeout(
|
|
629
863
|
executeServerAction(
|
|
@@ -631,7 +865,7 @@ export function createRSCHandler<
|
|
|
631
865
|
request,
|
|
632
866
|
env,
|
|
633
867
|
url,
|
|
634
|
-
actionId,
|
|
868
|
+
plan.actionId,
|
|
635
869
|
handleStore,
|
|
636
870
|
),
|
|
637
871
|
router.timeouts.actionMs,
|
|
@@ -644,8 +878,8 @@ export function createRSCHandler<
|
|
|
644
878
|
url,
|
|
645
879
|
"action",
|
|
646
880
|
actionOutcome.durationMs,
|
|
647
|
-
|
|
648
|
-
actionId,
|
|
881
|
+
plan.route.routeKey,
|
|
882
|
+
plan.actionId,
|
|
649
883
|
);
|
|
650
884
|
}
|
|
651
885
|
const result = actionOutcome.result;
|
|
@@ -657,40 +891,222 @@ export function createRSCHandler<
|
|
|
657
891
|
request,
|
|
658
892
|
url,
|
|
659
893
|
env,
|
|
660
|
-
actionId,
|
|
894
|
+
actionId: plan.actionId,
|
|
661
895
|
handledByBoundary: false,
|
|
662
896
|
});
|
|
663
897
|
console.error(`[RSC] Action error:`, error);
|
|
664
898
|
throw error;
|
|
665
899
|
}
|
|
666
|
-
}
|
|
667
900
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
901
|
+
// Revalidation render wrapped in route middleware.
|
|
902
|
+
// Actions from client-side navigation include _rsc_partial — preserve
|
|
903
|
+
// the partial flag so the revalidation returns a Flight stream, not HTML.
|
|
904
|
+
// App-switch is already excluded by classifyRequest (would be full-render).
|
|
905
|
+
const isPartialAction = url.searchParams.has("_rsc_partial");
|
|
906
|
+
return executeRenderWithMiddleware(
|
|
907
|
+
plan.route.routeMiddleware,
|
|
908
|
+
plan.negotiated,
|
|
909
|
+
plan.route.routeKey,
|
|
910
|
+
routeReverse,
|
|
672
911
|
request,
|
|
673
912
|
env,
|
|
674
913
|
url,
|
|
675
914
|
variables,
|
|
676
915
|
nonce,
|
|
677
|
-
preview?.params,
|
|
678
|
-
preview?.routeKey,
|
|
679
916
|
handleStore,
|
|
917
|
+
isPartialAction,
|
|
680
918
|
actionContinuation,
|
|
681
919
|
);
|
|
682
|
-
|
|
683
|
-
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// Full render, partial render, fallen-through PE, and full-page redirect all
|
|
923
|
+
// render through the same middleware-wrapped path. Only full/partial-render
|
|
924
|
+
// carry negotiation + the partial flag; pe/redirect render plainly.
|
|
925
|
+
const isPartial = plan.mode === "partial-render";
|
|
926
|
+
const negotiated =
|
|
927
|
+
plan.mode === "full-render" || plan.mode === "partial-render"
|
|
928
|
+
? plan.negotiated
|
|
929
|
+
: false;
|
|
930
|
+
return executeRenderWithMiddleware(
|
|
931
|
+
plan.route.routeMiddleware,
|
|
932
|
+
negotiated,
|
|
933
|
+
plan.route.routeKey,
|
|
934
|
+
routeReverse,
|
|
935
|
+
request,
|
|
936
|
+
env,
|
|
937
|
+
url,
|
|
938
|
+
variables,
|
|
939
|
+
nonce,
|
|
940
|
+
handleStore,
|
|
941
|
+
isPartial,
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// Shared render execution: wraps handleRscRendering (or revalidateAfterAction)
|
|
946
|
+
// in route middleware and timeout handling. Consolidates the pattern used by
|
|
947
|
+
// action-revalidate, full-render, and partial-render modes.
|
|
948
|
+
async function executeRenderWithMiddleware(
|
|
949
|
+
routeMiddleware: import("../router/middleware-types.js").CollectedMiddleware[],
|
|
950
|
+
negotiated: boolean,
|
|
951
|
+
routeKey: string,
|
|
952
|
+
routeReverse: ReturnType<typeof createReverseFunction>,
|
|
953
|
+
request: Request,
|
|
954
|
+
env: TEnv,
|
|
955
|
+
url: URL,
|
|
956
|
+
variables: Record<string, any>,
|
|
957
|
+
nonce: string | undefined,
|
|
958
|
+
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
959
|
+
isPartial: boolean,
|
|
960
|
+
actionContinuation?: ActionContinuation,
|
|
961
|
+
): Promise<Response> {
|
|
962
|
+
const renderHandler = async (): Promise<Response> => {
|
|
963
|
+
try {
|
|
964
|
+
let response: Response;
|
|
965
|
+
if (actionContinuation) {
|
|
966
|
+
response = await revalidateAfterAction(
|
|
967
|
+
handlerCtx,
|
|
968
|
+
request,
|
|
969
|
+
env,
|
|
970
|
+
url,
|
|
971
|
+
handleStore,
|
|
972
|
+
actionContinuation,
|
|
973
|
+
);
|
|
974
|
+
} else {
|
|
975
|
+
response = await handleRscRendering(
|
|
976
|
+
handlerCtx,
|
|
977
|
+
request,
|
|
978
|
+
env,
|
|
979
|
+
url,
|
|
980
|
+
isPartial,
|
|
981
|
+
handleStore,
|
|
982
|
+
nonce,
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
if (negotiated && !isWebSocketUpgradeResponse(response)) {
|
|
986
|
+
response.headers.append("Vary", "Accept");
|
|
987
|
+
}
|
|
988
|
+
return response;
|
|
989
|
+
} catch (error) {
|
|
990
|
+
// Check if middleware/handler returned Response
|
|
991
|
+
if (error instanceof Response) {
|
|
992
|
+
// During partial (client-side navigation), a 200 Response from a handler
|
|
993
|
+
// means the route serves raw content (JSON, text, etc.), not JSX.
|
|
994
|
+
// Signal the browser to hard-navigate so it renders the raw response.
|
|
995
|
+
if (isPartial && error.status === 200) {
|
|
996
|
+
console.warn(
|
|
997
|
+
`[RSC] Route handler at ${url.pathname} returned a Response during client-side navigation. ` +
|
|
998
|
+
`Falling back to hard navigation. Use data-external on the <Link> to avoid the extra round-trip.`,
|
|
999
|
+
);
|
|
1000
|
+
return createResponseWithMergedHeaders(null, {
|
|
1001
|
+
status: 200,
|
|
1002
|
+
headers: {
|
|
1003
|
+
"X-RSC-Reload": stripInternalParams(url).toString(),
|
|
1004
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
1005
|
+
},
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
if (isPartial) {
|
|
1010
|
+
const intercepted = interceptRedirectForPartial(
|
|
1011
|
+
error,
|
|
1012
|
+
createRedirectFlightResponse,
|
|
1013
|
+
);
|
|
1014
|
+
if (intercepted) return intercepted;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
return error;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// Render 404 page for unmatched routes
|
|
1021
|
+
if (isRouteNotFoundError(error)) {
|
|
1022
|
+
callOnError(error, "routing", {
|
|
1023
|
+
request,
|
|
1024
|
+
url,
|
|
1025
|
+
env,
|
|
1026
|
+
handledByBoundary: true,
|
|
1027
|
+
});
|
|
1028
|
+
|
|
1029
|
+
const notFoundOption = router.notFound;
|
|
1030
|
+
const notFoundComponent =
|
|
1031
|
+
typeof notFoundOption === "function"
|
|
1032
|
+
? notFoundOption({ pathname: url.pathname })
|
|
1033
|
+
: (notFoundOption ?? createElement("h1", null, "Not Found"));
|
|
1034
|
+
|
|
1035
|
+
const notFoundSegment = {
|
|
1036
|
+
id: "notFound",
|
|
1037
|
+
namespace: "notFound",
|
|
1038
|
+
type: "route" as const,
|
|
1039
|
+
index: 0,
|
|
1040
|
+
component: notFoundComponent,
|
|
1041
|
+
params: {},
|
|
1042
|
+
};
|
|
1043
|
+
|
|
1044
|
+
const payload: RscPayload = {
|
|
1045
|
+
metadata: {
|
|
1046
|
+
pathname: url.pathname,
|
|
1047
|
+
routerId: router.id,
|
|
1048
|
+
basename: router.basename,
|
|
1049
|
+
segments: [notFoundSegment],
|
|
1050
|
+
matched: [],
|
|
1051
|
+
diff: [],
|
|
1052
|
+
isPartial: false,
|
|
1053
|
+
rootLayout: router.rootLayout,
|
|
1054
|
+
handles: handleStore.stream(),
|
|
1055
|
+
version,
|
|
1056
|
+
themeConfig: router.themeConfig,
|
|
1057
|
+
warmupEnabled: router.warmupEnabled,
|
|
1058
|
+
initialTheme: requireRequestContext().theme,
|
|
1059
|
+
},
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
const rscStream = renderToReadableStream(payload, {
|
|
1063
|
+
onError: (error: unknown) => {
|
|
1064
|
+
callOnError(error, "rendering", { request, url, env });
|
|
1065
|
+
},
|
|
1066
|
+
});
|
|
1067
|
+
|
|
1068
|
+
if (isRscRequest(request, url, isPartial)) {
|
|
1069
|
+
return createResponseWithMergedHeaders(rscStream, {
|
|
1070
|
+
status: 404,
|
|
1071
|
+
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
const [ssrModule, streamMode] = await getSSRSetup(
|
|
1076
|
+
handlerCtx,
|
|
1077
|
+
request,
|
|
1078
|
+
env,
|
|
1079
|
+
url,
|
|
1080
|
+
requireRequestContext()._metricsStore,
|
|
1081
|
+
);
|
|
1082
|
+
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
1083
|
+
nonce,
|
|
1084
|
+
streamMode,
|
|
1085
|
+
});
|
|
1086
|
+
|
|
1087
|
+
return createResponseWithMergedHeaders(htmlStream, {
|
|
1088
|
+
status: 404,
|
|
1089
|
+
headers: { "content-type": "text/html;charset=utf-8" },
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// Report unhandled errors
|
|
1094
|
+
callOnError(error, "routing", {
|
|
1095
|
+
request,
|
|
1096
|
+
url,
|
|
1097
|
+
env,
|
|
1098
|
+
handledByBoundary: false,
|
|
1099
|
+
});
|
|
1100
|
+
console.error(`[RSC] Error:`, error);
|
|
1101
|
+
throw error;
|
|
684
1102
|
}
|
|
685
|
-
return response;
|
|
686
1103
|
};
|
|
687
1104
|
|
|
688
|
-
// Wrap the render path
|
|
689
|
-
// renderStartMs timeout so slow renders are caught before output.
|
|
1105
|
+
// Wrap the render path in a renderStartMs timeout
|
|
690
1106
|
const executeRender = async (): Promise<Response> => {
|
|
691
|
-
if (
|
|
1107
|
+
if (routeMiddleware.length > 0) {
|
|
692
1108
|
const mwResponse = await executeMiddleware(
|
|
693
|
-
buildRouteMiddlewareEntries<TEnv>(
|
|
1109
|
+
buildRouteMiddlewareEntries<TEnv>(routeMiddleware),
|
|
694
1110
|
request,
|
|
695
1111
|
env,
|
|
696
1112
|
variables,
|
|
@@ -698,10 +1114,7 @@ export function createRSCHandler<
|
|
|
698
1114
|
routeReverse,
|
|
699
1115
|
);
|
|
700
1116
|
|
|
701
|
-
if (
|
|
702
|
-
url.searchParams.has("_rsc_partial") ||
|
|
703
|
-
url.searchParams.has("_rsc_action")
|
|
704
|
-
) {
|
|
1117
|
+
if (isPartial || actionContinuation) {
|
|
705
1118
|
const intercepted = interceptRedirectForPartial(
|
|
706
1119
|
mwResponse,
|
|
707
1120
|
createRedirectFlightResponse,
|
|
@@ -712,7 +1125,6 @@ export function createRSCHandler<
|
|
|
712
1125
|
return finalizeResponse(mwResponse);
|
|
713
1126
|
}
|
|
714
1127
|
|
|
715
|
-
// No route middleware, proceed directly
|
|
716
1128
|
return renderHandler();
|
|
717
1129
|
};
|
|
718
1130
|
|
|
@@ -728,267 +1140,9 @@ export function createRSCHandler<
|
|
|
728
1140
|
url,
|
|
729
1141
|
"render-start",
|
|
730
1142
|
renderOutcome.durationMs,
|
|
731
|
-
|
|
1143
|
+
routeKey,
|
|
732
1144
|
);
|
|
733
1145
|
}
|
|
734
1146
|
return renderOutcome.result;
|
|
735
1147
|
}
|
|
736
|
-
|
|
737
|
-
// Inner request handler: rendering logic wrapped by route middleware.
|
|
738
|
-
// Handles action revalidation (when actionContinuation is present),
|
|
739
|
-
// loader fetches, and regular RSC rendering.
|
|
740
|
-
async function coreRequestHandlerInner(
|
|
741
|
-
request: Request,
|
|
742
|
-
env: TEnv,
|
|
743
|
-
url: URL,
|
|
744
|
-
variables: Record<string, any>,
|
|
745
|
-
nonce: string | undefined,
|
|
746
|
-
routeParams?: Record<string, string>,
|
|
747
|
-
routeKey?: string,
|
|
748
|
-
handleStore?: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
749
|
-
actionContinuation?: ActionContinuation,
|
|
750
|
-
): Promise<Response> {
|
|
751
|
-
const isPartial = url.searchParams.has("_rsc_partial");
|
|
752
|
-
const isAction =
|
|
753
|
-
request.headers.has("rsc-action") || url.searchParams.has("_rsc_action");
|
|
754
|
-
|
|
755
|
-
// Version mismatch detection - client may have stale code after HMR/deployment
|
|
756
|
-
// If versions don't match, tell the client to reload
|
|
757
|
-
const clientVersion = url.searchParams.get("_rsc_v");
|
|
758
|
-
if (version && clientVersion && clientVersion !== version) {
|
|
759
|
-
console.log(
|
|
760
|
-
`[RSC] Version mismatch: client=${clientVersion}, server=${version}. Forcing reload.`,
|
|
761
|
-
);
|
|
762
|
-
|
|
763
|
-
// For actions, reload current page (referer) if same origin.
|
|
764
|
-
// For navigation, load the target URL.
|
|
765
|
-
// Validate referer origin to prevent open redirect via crafted header.
|
|
766
|
-
let reloadUrl = stripInternalParams(url).toString();
|
|
767
|
-
if (isAction) {
|
|
768
|
-
const referer = request.headers.get("referer");
|
|
769
|
-
if (referer) {
|
|
770
|
-
try {
|
|
771
|
-
const refererUrl = new URL(referer);
|
|
772
|
-
if (refererUrl.origin === url.origin) {
|
|
773
|
-
reloadUrl = referer;
|
|
774
|
-
}
|
|
775
|
-
} catch {
|
|
776
|
-
// Malformed referer, fall back to cleanUrl
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
// Return special response that tells client to reload
|
|
782
|
-
return createResponseWithMergedHeaders(null, {
|
|
783
|
-
status: 200,
|
|
784
|
-
headers: {
|
|
785
|
-
"X-RSC-Reload": reloadUrl,
|
|
786
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
787
|
-
},
|
|
788
|
-
});
|
|
789
|
-
}
|
|
790
|
-
// Debug manifest endpoint: ?__debug_manifest on any route.
|
|
791
|
-
// Always available in dev, requires allowDebugManifest option in production.
|
|
792
|
-
const isDev = process.env.NODE_ENV !== "production";
|
|
793
|
-
if (
|
|
794
|
-
url.searchParams.has("__debug_manifest") &&
|
|
795
|
-
(isDev || router.allowDebugManifest)
|
|
796
|
-
) {
|
|
797
|
-
const trie = getRouterTrie(router.id) ?? getRouteTrie();
|
|
798
|
-
const routeManifest = getRequiredRouteMap();
|
|
799
|
-
const { extractAncestryFromTrie } =
|
|
800
|
-
await import("../build/route-trie.js");
|
|
801
|
-
return new Response(
|
|
802
|
-
JSON.stringify(
|
|
803
|
-
{
|
|
804
|
-
routerId: router.id,
|
|
805
|
-
routeManifest,
|
|
806
|
-
routeAncestry: trie ? extractAncestryFromTrie(trie) : {},
|
|
807
|
-
routeTrie: trie,
|
|
808
|
-
precomputedEntries: getPrecomputedEntries(),
|
|
809
|
-
},
|
|
810
|
-
null,
|
|
811
|
-
2,
|
|
812
|
-
),
|
|
813
|
-
{
|
|
814
|
-
headers: { "Content-Type": "application/json" },
|
|
815
|
-
},
|
|
816
|
-
);
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
const store = handleStore ?? requireRequestContext()._handleStore;
|
|
820
|
-
|
|
821
|
-
try {
|
|
822
|
-
// Route params were already set in coreRequestHandler, but set again
|
|
823
|
-
// for callers that enter coreRequestHandlerInner directly.
|
|
824
|
-
if (routeParams) {
|
|
825
|
-
setRequestContextParams(routeParams, routeKey);
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
// ============================================================================
|
|
829
|
-
// ACTION REVALIDATION (action already executed, revalidate segments)
|
|
830
|
-
// ============================================================================
|
|
831
|
-
if (actionContinuation) {
|
|
832
|
-
return await revalidateAfterAction(
|
|
833
|
-
handlerCtx,
|
|
834
|
-
request,
|
|
835
|
-
env,
|
|
836
|
-
url,
|
|
837
|
-
store,
|
|
838
|
-
actionContinuation,
|
|
839
|
-
);
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
// ============================================================================
|
|
843
|
-
// LOADER FETCH EXECUTION (data fetching with RSC serialization)
|
|
844
|
-
// ============================================================================
|
|
845
|
-
const isLoaderRequest = url.searchParams.has("_rsc_loader");
|
|
846
|
-
if (isLoaderRequest) {
|
|
847
|
-
return handleLoaderFetch(
|
|
848
|
-
handlerCtx,
|
|
849
|
-
request,
|
|
850
|
-
env,
|
|
851
|
-
url,
|
|
852
|
-
variables,
|
|
853
|
-
routeParams,
|
|
854
|
-
);
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
// ============================================================================
|
|
858
|
-
// REGULAR RSC RENDERING (Navigation)
|
|
859
|
-
// ============================================================================
|
|
860
|
-
// Note: Must use "return await" for try/catch to catch async rejections
|
|
861
|
-
return await handleRscRendering(
|
|
862
|
-
handlerCtx,
|
|
863
|
-
request,
|
|
864
|
-
env,
|
|
865
|
-
url,
|
|
866
|
-
isPartial,
|
|
867
|
-
store,
|
|
868
|
-
nonce,
|
|
869
|
-
);
|
|
870
|
-
} catch (error) {
|
|
871
|
-
// Check if middleware/handler returned Response
|
|
872
|
-
if (error instanceof Response) {
|
|
873
|
-
// During partial (client-side navigation), a 200 Response from a handler
|
|
874
|
-
// means the route serves raw content (JSON, text, etc.), not JSX.
|
|
875
|
-
// Signal the browser to hard-navigate so it renders the raw response.
|
|
876
|
-
// Only for 200 — redirects (3xx) work already because the browser follows
|
|
877
|
-
// them automatically to a URL that serves Flight data.
|
|
878
|
-
if (isPartial && error.status === 200) {
|
|
879
|
-
console.warn(
|
|
880
|
-
`[RSC] Route handler at ${url.pathname} returned a Response during client-side navigation. ` +
|
|
881
|
-
`Falling back to hard navigation. Use data-external on the <Link> to avoid the extra round-trip.`,
|
|
882
|
-
);
|
|
883
|
-
return createResponseWithMergedHeaders(null, {
|
|
884
|
-
status: 200,
|
|
885
|
-
headers: {
|
|
886
|
-
"X-RSC-Reload": stripInternalParams(url).toString(),
|
|
887
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
888
|
-
},
|
|
889
|
-
});
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
if (isPartial) {
|
|
893
|
-
const intercepted = interceptRedirectForPartial(
|
|
894
|
-
error,
|
|
895
|
-
createRedirectFlightResponse,
|
|
896
|
-
);
|
|
897
|
-
if (intercepted) return intercepted;
|
|
898
|
-
}
|
|
899
|
-
|
|
900
|
-
return error;
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
// Render 404 page for unmatched routes
|
|
904
|
-
// Check both instanceof and error.name for cross-bundle compatibility
|
|
905
|
-
const isRouteNotFound =
|
|
906
|
-
error instanceof RouteNotFoundError ||
|
|
907
|
-
(error instanceof Error && error.name === "RouteNotFoundError");
|
|
908
|
-
if (isRouteNotFound) {
|
|
909
|
-
callOnError(error, "routing", {
|
|
910
|
-
request,
|
|
911
|
-
url,
|
|
912
|
-
env,
|
|
913
|
-
handledByBoundary: true, // Handled by notFound component
|
|
914
|
-
});
|
|
915
|
-
|
|
916
|
-
// Get notFound component from router options or use default
|
|
917
|
-
const notFoundOption = router.notFound;
|
|
918
|
-
const notFoundComponent =
|
|
919
|
-
typeof notFoundOption === "function"
|
|
920
|
-
? notFoundOption({ pathname: url.pathname })
|
|
921
|
-
: (notFoundOption ?? createElement("h1", null, "Not Found"));
|
|
922
|
-
|
|
923
|
-
// Create a simple segment for the 404 page
|
|
924
|
-
const notFoundSegment = {
|
|
925
|
-
id: "notFound",
|
|
926
|
-
namespace: "notFound",
|
|
927
|
-
type: "route" as const,
|
|
928
|
-
index: 0,
|
|
929
|
-
component: notFoundComponent,
|
|
930
|
-
params: {},
|
|
931
|
-
};
|
|
932
|
-
|
|
933
|
-
const payload: RscPayload = {
|
|
934
|
-
metadata: {
|
|
935
|
-
pathname: url.pathname,
|
|
936
|
-
segments: [notFoundSegment],
|
|
937
|
-
matched: [],
|
|
938
|
-
diff: [],
|
|
939
|
-
isPartial: false,
|
|
940
|
-
rootLayout: router.rootLayout,
|
|
941
|
-
handles: store.stream(),
|
|
942
|
-
version,
|
|
943
|
-
themeConfig: router.themeConfig,
|
|
944
|
-
warmupEnabled: router.warmupEnabled,
|
|
945
|
-
initialTheme: requireRequestContext().theme,
|
|
946
|
-
// No routeName for not-found routes
|
|
947
|
-
},
|
|
948
|
-
};
|
|
949
|
-
|
|
950
|
-
const rscStream = renderToReadableStream(payload);
|
|
951
|
-
|
|
952
|
-
// Determine if this is an RSC request or HTML request.
|
|
953
|
-
// Partial requests are always RSC (see main isRscRequest comment).
|
|
954
|
-
const isRscRequest =
|
|
955
|
-
isPartial ||
|
|
956
|
-
(!request.headers.get("accept")?.includes("text/html") &&
|
|
957
|
-
!url.searchParams.has("__html")) ||
|
|
958
|
-
url.searchParams.has("__rsc");
|
|
959
|
-
|
|
960
|
-
if (isRscRequest) {
|
|
961
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
962
|
-
status: 404,
|
|
963
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
964
|
-
});
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
// Delegate to SSR for HTML response
|
|
968
|
-
const [ssrModule, streamMode] = await Promise.all([
|
|
969
|
-
loadSSRModule(),
|
|
970
|
-
handlerCtx.resolveStreamMode(request, env, url),
|
|
971
|
-
]);
|
|
972
|
-
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
973
|
-
nonce,
|
|
974
|
-
streamMode,
|
|
975
|
-
});
|
|
976
|
-
|
|
977
|
-
return createResponseWithMergedHeaders(htmlStream, {
|
|
978
|
-
status: 404,
|
|
979
|
-
headers: { "content-type": "text/html;charset=utf-8" },
|
|
980
|
-
});
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
// Report unhandled errors
|
|
984
|
-
callOnError(error, "routing", {
|
|
985
|
-
request,
|
|
986
|
-
url,
|
|
987
|
-
env,
|
|
988
|
-
handledByBoundary: false,
|
|
989
|
-
});
|
|
990
|
-
console.error(`[RSC] Error:`, error);
|
|
991
|
-
throw error;
|
|
992
|
-
}
|
|
993
|
-
}
|
|
994
1148
|
}
|