@rangojs/router 0.0.0-experimental.19 → 0.0.0-experimental.1c0bdfad
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 +17 -0
- package/README.md +291 -61
- package/dist/bin/rango.js +544 -143
- package/dist/testing/vitest.js +82 -0
- package/dist/vite/index.js +3744 -1329
- package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/package.json +67 -13
- package/skills/api-client/SKILL.md +211 -0
- package/skills/breadcrumbs/SKILL.md +312 -0
- package/skills/bundle-analysis/SKILL.md +159 -0
- package/skills/cache-guide/SKILL.md +247 -23
- package/skills/caching/SKILL.md +322 -19
- package/skills/composability/SKILL.md +27 -2
- package/skills/css/SKILL.md +76 -0
- package/skills/debug-manifest/SKILL.md +4 -2
- package/skills/document-cache/SKILL.md +78 -55
- package/skills/handler-use/SKILL.md +364 -0
- package/skills/hooks/SKILL.md +282 -60
- package/skills/host-router/SKILL.md +278 -0
- package/skills/i18n/SKILL.md +276 -0
- package/skills/intercept/SKILL.md +50 -6
- package/skills/layout/SKILL.md +35 -9
- package/skills/links/SKILL.md +249 -17
- package/skills/loader/SKILL.md +297 -31
- package/skills/middleware/SKILL.md +52 -13
- package/skills/migrate-nextjs/SKILL.md +584 -0
- package/skills/migrate-react-router/SKILL.md +771 -0
- package/skills/mime-routes/SKILL.md +28 -1
- package/skills/observability/SKILL.md +172 -0
- package/skills/parallel/SKILL.md +203 -7
- package/skills/prerender/SKILL.md +155 -111
- package/skills/rango/SKILL.md +251 -23
- package/skills/react-compiler/SKILL.md +168 -0
- package/skills/response-routes/SKILL.md +123 -48
- package/skills/route/SKILL.md +104 -9
- package/skills/router-setup/SKILL.md +124 -11
- package/skills/scripts/SKILL.md +179 -0
- package/skills/server-actions/SKILL.md +775 -0
- package/skills/streams-and-websockets/SKILL.md +283 -0
- package/skills/tailwind/SKILL.md +27 -3
- package/skills/testing/SKILL.md +125 -222
- package/skills/testing/bindings.md +103 -0
- package/skills/testing/cache-prerender.md +127 -0
- package/skills/testing/client-components.md +124 -0
- package/skills/testing/e2e-parity.md +125 -0
- package/skills/testing/flight.md +91 -0
- package/skills/testing/handles.md +129 -0
- package/skills/testing/loader.md +128 -0
- package/skills/testing/middleware.md +99 -0
- package/skills/testing/render-handler.md +121 -0
- package/skills/testing/response-routes.md +95 -0
- package/skills/testing/reverse-and-types.md +84 -0
- package/skills/testing/server-actions.md +107 -0
- package/skills/testing/server-tree.md +128 -0
- package/skills/testing/setup.md +123 -0
- package/skills/typesafety/SKILL.md +357 -52
- package/skills/use-cache/SKILL.md +46 -14
- package/skills/view-transitions/SKILL.md +294 -0
- package/src/__augment-tests__/augment.ts +81 -0
- package/src/__augment-tests__/augmented.check.ts +116 -0
- package/src/__internal.ts +67 -40
- package/src/bin/rango.ts +18 -0
- package/src/browser/action-coordinator.ts +53 -36
- package/src/browser/action-fence.ts +47 -0
- package/src/browser/app-shell.ts +39 -0
- package/src/browser/app-version.ts +14 -0
- package/src/browser/connection-warmup.ts +134 -0
- package/src/browser/cookie-name.ts +140 -0
- package/src/browser/event-controller.ts +197 -150
- package/src/browser/history-state.ts +21 -0
- package/src/browser/index.ts +3 -3
- package/src/browser/invalidate-client-cache.ts +52 -0
- package/src/browser/link-interceptor.ts +4 -0
- package/src/browser/navigation-bridge.ts +200 -30
- package/src/browser/navigation-client.ts +217 -58
- package/src/browser/navigation-store-handle.ts +38 -0
- package/src/browser/navigation-store.ts +76 -67
- package/src/browser/navigation-transaction.ts +18 -66
- package/src/browser/network-error-handler.ts +34 -7
- package/src/browser/partial-update.ts +187 -112
- package/src/browser/prefetch/cache.ts +312 -30
- package/src/browser/prefetch/fetch.ts +344 -47
- package/src/browser/prefetch/policy.ts +6 -0
- package/src/browser/prefetch/queue.ts +126 -20
- package/src/browser/prefetch/resource-ready.ts +77 -0
- package/src/browser/rango-state.ts +158 -76
- package/src/browser/react/Link.tsx +125 -18
- package/src/browser/react/NavigationProvider.tsx +135 -120
- package/src/browser/react/ScrollRestoration.tsx +10 -6
- package/src/browser/react/context.ts +7 -2
- package/src/browser/react/filter-segment-order.ts +66 -7
- package/src/browser/react/index.ts +0 -48
- package/src/browser/react/location-state-shared.ts +178 -8
- package/src/browser/react/location-state.ts +39 -14
- package/src/browser/react/use-action.ts +6 -15
- package/src/browser/react/use-handle.ts +23 -69
- package/src/browser/react/use-href.tsx +8 -1
- package/src/browser/react/use-link-status.ts +33 -8
- package/src/browser/react/use-navigation.ts +32 -7
- package/src/browser/react/use-params.ts +20 -10
- package/src/browser/react/use-reverse.ts +106 -0
- package/src/browser/react/use-router.ts +46 -11
- package/src/browser/react/use-search-params.ts +0 -5
- package/src/browser/react/use-segments.ts +11 -21
- package/src/browser/response-adapter.ts +80 -5
- package/src/browser/rsc-router.tsx +226 -75
- package/src/browser/scroll-restoration.ts +54 -42
- package/src/browser/segment-reconciler.ts +36 -9
- package/src/browser/segment-structure-assert.ts +2 -2
- package/src/browser/server-action-bridge.ts +619 -442
- package/src/browser/types.ts +115 -11
- package/src/browser/validate-redirect-origin.ts +43 -16
- package/src/build/collect-fallback-refs.ts +107 -0
- package/src/build/generate-manifest.ts +65 -40
- package/src/build/generate-route-types.ts +7 -1
- package/src/build/index.ts +8 -2
- package/src/build/prefix-tree-utils.ts +123 -0
- package/src/build/route-trie.ts +182 -37
- package/src/build/route-types/ast-route-extraction.ts +15 -8
- package/src/build/route-types/codegen.ts +16 -5
- package/src/build/route-types/include-resolution.ts +125 -24
- package/src/build/route-types/param-extraction.ts +6 -3
- package/src/build/route-types/per-module-writer.ts +22 -6
- package/src/build/route-types/router-processing.ts +392 -106
- package/src/build/route-types/scan-filter.ts +9 -2
- package/src/build/route-types/source-scan.ts +216 -0
- package/src/build/runtime-discovery.ts +9 -20
- package/src/cache/cache-error.ts +104 -0
- package/src/cache/cache-key-utils.ts +29 -13
- package/src/cache/cache-policy.ts +108 -34
- package/src/cache/cache-runtime.ts +214 -48
- package/src/cache/cache-scope.ts +236 -89
- package/src/cache/cache-tag.ts +103 -0
- package/src/cache/cf/cf-base64.ts +33 -0
- package/src/cache/cf/cf-cache-constants.ts +127 -0
- package/src/cache/cf/cf-cache-store.ts +2224 -171
- package/src/cache/cf/cf-cache-types.ts +349 -0
- package/src/cache/cf/cf-kv-utils.ts +46 -0
- package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
- package/src/cache/cf/index.ts +11 -17
- package/src/cache/document-cache.ts +89 -27
- package/src/cache/handle-snapshot.ts +70 -0
- package/src/cache/index.ts +11 -20
- package/src/cache/memory-segment-store.ts +136 -37
- package/src/cache/profile-registry.ts +31 -31
- package/src/cache/read-through-swr.ts +41 -11
- package/src/cache/segment-codec.ts +9 -17
- package/src/cache/tag-invalidation.ts +230 -0
- package/src/cache/taint.ts +55 -0
- package/src/cache/types.ts +37 -100
- package/src/client.rsc.tsx +45 -21
- package/src/client.tsx +120 -336
- package/src/cloudflare/index.ts +11 -0
- package/src/cloudflare/tracing.ts +109 -0
- package/src/component-utils.ts +19 -0
- package/src/components/DefaultDocument.tsx +8 -2
- package/src/context-var.ts +84 -2
- package/src/debug.ts +2 -2
- package/src/decode-loader-results.ts +52 -0
- package/src/defer.ts +196 -0
- package/src/deps/ssr.ts +0 -1
- package/src/encode-kv.ts +49 -0
- package/src/errors.ts +30 -4
- package/src/escape-script.ts +52 -0
- package/src/handle.ts +70 -22
- package/src/handles/MetaTags.tsx +56 -19
- package/src/handles/Scripts.tsx +183 -0
- package/src/handles/breadcrumbs.ts +95 -0
- package/src/handles/is-thenable.ts +19 -0
- package/src/handles/meta.ts +51 -40
- package/src/handles/script.ts +244 -0
- package/src/host/cookie-handler.ts +9 -60
- package/src/host/errors.ts +0 -24
- package/src/host/index.ts +8 -5
- package/src/host/pattern-matcher.ts +23 -52
- package/src/host/router.ts +107 -99
- package/src/host/testing.ts +40 -27
- package/src/host/types.ts +37 -4
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +137 -22
- package/src/index.rsc.ts +79 -29
- package/src/index.ts +149 -65
- package/src/internal-debug.ts +11 -10
- package/src/loader-store.ts +500 -0
- package/src/loader.rsc.ts +20 -13
- package/src/loader.ts +12 -11
- package/src/missing-id-error.ts +68 -0
- package/src/outlet-context.ts +1 -1
- package/src/outlet-provider.tsx +1 -5
- package/src/prerender/param-hash.ts +16 -16
- package/src/prerender/store.ts +63 -26
- package/src/prerender.ts +198 -82
- package/src/redirect-origin.ts +100 -0
- package/src/regex-escape.ts +8 -0
- package/src/render-error-thrower.tsx +20 -0
- package/src/response-utils.ts +62 -0
- package/src/reverse.ts +65 -15
- package/src/root-error-boundary.tsx +1 -19
- package/src/route-content-wrapper.tsx +7 -72
- package/src/route-definition/dsl-helpers.ts +469 -276
- package/src/route-definition/helper-factories.ts +29 -139
- package/src/route-definition/helpers-types.ts +113 -37
- package/src/route-definition/index.ts +3 -3
- package/src/route-definition/redirect.ts +53 -12
- package/src/route-definition/resolve-handler-use.ts +161 -0
- package/src/route-definition/use-item-types.ts +32 -0
- package/src/route-map-builder.ts +7 -17
- package/src/route-types.ts +37 -41
- package/src/router/basename.ts +14 -0
- package/src/router/content-negotiation.ts +164 -17
- package/src/router/error-handling.ts +45 -18
- package/src/router/find-match.ts +45 -22
- package/src/router/handler-context.ts +110 -39
- package/src/router/instrument.ts +350 -0
- package/src/router/intercept-resolution.ts +50 -24
- package/src/router/lazy-includes.ts +19 -53
- package/src/router/loader-resolution.ts +274 -56
- package/src/router/logging.ts +5 -8
- package/src/router/manifest.ts +49 -45
- package/src/router/match-api.ts +121 -205
- package/src/router/match-context.ts +0 -22
- package/src/router/match-handlers.ts +58 -58
- package/src/router/match-middleware/background-revalidation.ts +33 -6
- package/src/router/match-middleware/cache-lookup.ts +214 -263
- package/src/router/match-middleware/cache-store.ts +73 -33
- package/src/router/match-middleware/intercept-resolution.ts +8 -28
- package/src/router/match-middleware/segment-resolution.ts +52 -18
- package/src/router/match-pipelines.ts +1 -42
- package/src/router/match-result.ts +104 -49
- package/src/router/metrics.ts +217 -26
- package/src/router/middleware-types.ts +24 -110
- package/src/router/middleware.ts +384 -197
- package/src/router/navigation-snapshot.ts +131 -0
- package/src/router/params-util.ts +23 -0
- package/src/router/pattern-matching.ts +148 -91
- package/src/router/prefetch-cache-ttl.ts +51 -0
- package/src/router/prerender-match.ts +199 -56
- package/src/router/preview-match.ts +32 -102
- package/src/router/request-classification.ts +276 -0
- package/src/router/revalidation.ts +144 -74
- package/src/router/route-snapshot.ts +244 -0
- package/src/router/router-context.ts +8 -28
- package/src/router/router-interfaces.ts +129 -36
- package/src/router/router-options.ts +185 -23
- package/src/router/router-registry.ts +2 -5
- package/src/router/segment-resolution/fresh.ts +281 -76
- package/src/router/segment-resolution/helpers.ts +116 -31
- package/src/router/segment-resolution/loader-cache.ts +63 -37
- package/src/router/segment-resolution/revalidation.ts +493 -391
- package/src/router/segment-resolution/static-store.ts +19 -5
- package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
- package/src/router/segment-resolution/view-transition-default.ts +36 -0
- package/src/router/segment-resolution.ts +5 -1
- package/src/router/segment-wrappers.ts +8 -5
- package/src/router/state-cookie-name.ts +33 -0
- package/src/router/substitute-pattern-params.ts +56 -0
- package/src/router/telemetry-otel.ts +161 -199
- package/src/router/telemetry.ts +96 -19
- package/src/router/timeout.ts +0 -20
- package/src/router/tracing.ts +206 -0
- package/src/router/trie-matching.ts +180 -58
- package/src/router/types.ts +10 -63
- package/src/router/url-params.ts +44 -0
- package/src/router.ts +182 -54
- package/src/rsc/handler-context.ts +3 -2
- package/src/rsc/handler.ts +702 -460
- package/src/rsc/helpers.ts +168 -46
- package/src/rsc/index.ts +2 -25
- package/src/rsc/json-route-result.ts +38 -0
- package/src/rsc/loader-fetch.ts +127 -31
- package/src/rsc/manifest-init.ts +33 -42
- package/src/rsc/origin-guard.ts +39 -25
- package/src/rsc/progressive-enhancement.ts +98 -19
- package/src/rsc/redirect-guard.ts +99 -0
- package/src/rsc/response-cache-serve.ts +238 -0
- package/src/rsc/response-error.ts +79 -12
- package/src/rsc/response-route-handler.ts +99 -189
- package/src/rsc/rsc-rendering.ts +126 -106
- package/src/rsc/runtime-warnings.ts +23 -10
- package/src/rsc/server-action.ts +269 -114
- package/src/rsc/ssr-setup.ts +144 -0
- package/src/rsc/types.ts +34 -6
- package/src/runtime-env.ts +18 -0
- package/src/search-params.ts +49 -41
- package/src/segment-content-promise.ts +67 -0
- package/src/segment-loader-promise.ts +149 -0
- package/src/segment-system.tsx +281 -129
- package/src/serialize.ts +243 -0
- package/src/server/context.ts +317 -63
- package/src/server/cookie-parse.ts +32 -0
- package/src/server/cookie-store.ts +80 -5
- package/src/server/handle-store.ts +40 -38
- package/src/server/loader-registry.ts +26 -46
- package/src/server/request-context.ts +425 -177
- package/src/server.ts +6 -0
- package/src/ssr/index.tsx +25 -16
- package/src/static-handler.ts +27 -18
- package/src/testing/cache-status.ts +162 -0
- package/src/testing/collect-handle.ts +40 -0
- package/src/testing/dispatch.ts +701 -0
- package/src/testing/dom.entry.ts +22 -0
- package/src/testing/e2e/fixture.ts +188 -0
- package/src/testing/e2e/index.ts +128 -0
- package/src/testing/e2e/matchers.ts +35 -0
- package/src/testing/e2e/page-helpers.ts +272 -0
- package/src/testing/e2e/parity.ts +387 -0
- package/src/testing/e2e/server.ts +195 -0
- package/src/testing/flight-matchers.ts +97 -0
- package/src/testing/flight-normalize.ts +11 -0
- package/src/testing/flight-runtime.d.ts +57 -0
- package/src/testing/flight-tree.ts +682 -0
- package/src/testing/flight.entry.ts +52 -0
- package/src/testing/flight.ts +257 -0
- package/src/testing/generated-routes.ts +183 -0
- package/src/testing/index.ts +99 -0
- package/src/testing/internal/context.ts +371 -0
- package/src/testing/internal/flight-client-globals.ts +30 -0
- package/src/testing/internal/seed-vars.ts +54 -0
- package/src/testing/render-handler.ts +343 -0
- package/src/testing/render-route.tsx +581 -0
- package/src/testing/run-loader.ts +385 -0
- package/src/testing/run-middleware.ts +205 -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 +305 -0
- package/src/theme/ThemeProvider.tsx +20 -58
- package/src/theme/ThemeScript.tsx +7 -9
- package/src/theme/constants.ts +52 -13
- package/src/theme/index.ts +3 -19
- package/src/theme/theme-context.ts +1 -5
- package/src/theme/theme-script.ts +22 -21
- package/src/theme/use-theme.ts +0 -3
- package/src/types/boundaries.ts +0 -35
- package/src/types/cache-types.ts +17 -8
- package/src/types/error-types.ts +30 -90
- package/src/types/global-namespace.ts +54 -41
- package/src/types/handler-context.ts +236 -88
- package/src/types/index.ts +1 -10
- package/src/types/loader-types.ts +44 -15
- package/src/types/request-scope.ts +112 -0
- package/src/types/route-config.ts +10 -45
- package/src/types/route-entry.ts +19 -7
- package/src/types/segments.ts +37 -19
- package/src/urls/include-helper.ts +33 -70
- package/src/urls/index.ts +1 -11
- package/src/urls/path-helper-types.ts +58 -11
- package/src/urls/path-helper.ts +57 -111
- package/src/urls/pattern-types.ts +48 -19
- package/src/urls/response-types.ts +25 -22
- package/src/urls/type-extraction.ts +58 -139
- package/src/urls/urls-function.ts +1 -18
- package/src/use-loader.tsx +346 -89
- package/src/vite/debug.ts +185 -0
- package/src/vite/discovery/bundle-postprocess.ts +64 -91
- package/src/vite/discovery/discover-routers.ts +147 -88
- 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 +247 -145
- 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 +61 -13
- package/src/vite/discovery/virtual-module-codegen.ts +14 -34
- package/src/vite/index.ts +10 -3
- package/src/vite/inject-client-debug.ts +36 -0
- package/src/vite/plugin-types.ts +155 -65
- package/src/vite/plugins/cjs-to-esm.ts +16 -19
- package/src/vite/plugins/client-ref-dedup.ts +120 -0
- package/src/vite/plugins/client-ref-hashing.ts +28 -15
- 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 +194 -0
- package/src/vite/plugins/expose-action-id.ts +49 -98
- package/src/vite/plugins/expose-id-utils.ts +96 -51
- package/src/vite/plugins/expose-ids/export-analysis.ts +101 -34
- package/src/vite/plugins/expose-ids/handler-transform.ts +15 -64
- package/src/vite/plugins/expose-ids/loader-transform.ts +14 -24
- package/src/vite/plugins/expose-ids/router-transform.ts +118 -29
- package/src/vite/plugins/expose-internal-ids.ts +553 -317
- package/src/vite/plugins/performance-tracks.ts +89 -0
- package/src/vite/plugins/refresh-cmd.ts +127 -0
- package/src/vite/plugins/use-cache-transform.ts +73 -83
- package/src/vite/plugins/version-injector.ts +21 -25
- package/src/vite/plugins/version-plugin.ts +46 -37
- package/src/vite/plugins/virtual-entries.ts +13 -18
- package/src/vite/rango.ts +241 -287
- package/src/vite/router-discovery.ts +956 -149
- package/src/vite/utils/ast-handler-extract.ts +26 -35
- package/src/vite/utils/banner.ts +4 -4
- package/src/vite/utils/bundle-analysis.ts +10 -15
- package/src/vite/utils/client-chunks.ts +184 -0
- package/src/vite/utils/directive-prologue.ts +40 -0
- package/src/vite/utils/forward-user-plugins.ts +171 -0
- package/src/vite/utils/manifest-utils.ts +4 -59
- package/src/vite/utils/package-resolution.ts +20 -52
- package/src/vite/utils/prerender-utils.ts +141 -34
- package/src/vite/utils/shared-utils.ts +92 -42
- package/CLAUDE.md +0 -5
- package/src/browser/action-response-classifier.ts +0 -99
- package/src/browser/react/use-client-cache.ts +0 -58
- package/src/browser/shallow.ts +0 -40
- package/src/handles/index.ts +0 -6
- package/src/network-error-thrower.tsx +0 -23
- package/src/route-definition/route-function.ts +0 -119
- package/src/router/middleware-cookies.ts +0 -55
package/src/rsc/handler.ts
CHANGED
|
@@ -8,23 +8,33 @@
|
|
|
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
|
+
getRequestContext,
|
|
17
|
+
_getRequestContext,
|
|
17
18
|
createRequestContext,
|
|
18
19
|
} from "../server/request-context.js";
|
|
19
20
|
import * as rscDeps from "@vitejs/plugin-rsc/rsc";
|
|
20
|
-
|
|
21
|
-
|
|
21
|
+
import type {
|
|
22
|
+
RscPayload,
|
|
23
|
+
CreateRSCHandlerOptions,
|
|
24
|
+
LoadSSRModule,
|
|
25
|
+
SSRModule,
|
|
26
|
+
} from "./types.js";
|
|
22
27
|
import {
|
|
23
28
|
createResponseWithMergedHeaders,
|
|
24
29
|
finalizeResponse,
|
|
25
30
|
interceptRedirectForPartial,
|
|
26
31
|
buildRouteMiddlewareEntries,
|
|
27
32
|
} from "./helpers.js";
|
|
33
|
+
import { guardOutgoingRedirect } from "./redirect-guard.js";
|
|
34
|
+
import {
|
|
35
|
+
isWebSocketUpgradeResponse,
|
|
36
|
+
appendVaryAccept,
|
|
37
|
+
} from "../response-utils.js";
|
|
28
38
|
import {
|
|
29
39
|
handleResponseRoute,
|
|
30
40
|
type ResponseRouteMatch,
|
|
@@ -38,8 +48,6 @@ import {
|
|
|
38
48
|
createReverseFunction,
|
|
39
49
|
stripInternalParams,
|
|
40
50
|
} from "../router/handler-context.js";
|
|
41
|
-
import { getRouterContext } from "../router/router-context.js";
|
|
42
|
-
import { resolveSink, safeEmit } from "../router/telemetry.js";
|
|
43
51
|
import { contextSet } from "../context-var.js";
|
|
44
52
|
import {
|
|
45
53
|
hasCachedManifest,
|
|
@@ -50,6 +58,8 @@ import {
|
|
|
50
58
|
getRouterTrie,
|
|
51
59
|
} from "../route-map-builder.js";
|
|
52
60
|
import type { HandlerContext } from "./handler-context.js";
|
|
61
|
+
import type { CacheErrorCategory } from "../cache/cache-error.js";
|
|
62
|
+
import type { SegmentCacheStore } from "../cache/types.js";
|
|
53
63
|
import { buildRouterTrieFromUrlpatterns } from "./manifest-init.js";
|
|
54
64
|
import { handleProgressiveEnhancement } from "./progressive-enhancement.js";
|
|
55
65
|
import {
|
|
@@ -58,7 +68,10 @@ import {
|
|
|
58
68
|
type ActionContinuation,
|
|
59
69
|
} from "./server-action.js";
|
|
60
70
|
import { handleLoaderFetch } from "./loader-fetch.js";
|
|
61
|
-
import {
|
|
71
|
+
import {
|
|
72
|
+
checkRequestOrigin,
|
|
73
|
+
ORIGIN_CHECK_PHASE_BY_MODE,
|
|
74
|
+
} from "./origin-guard.js";
|
|
62
75
|
import { handleRscRendering } from "./rsc-rendering.js";
|
|
63
76
|
import {
|
|
64
77
|
withTimeout,
|
|
@@ -66,6 +79,24 @@ import {
|
|
|
66
79
|
createDefaultTimeoutResponse,
|
|
67
80
|
type TimeoutPhase,
|
|
68
81
|
} from "../router/timeout.js";
|
|
82
|
+
import {
|
|
83
|
+
createMetricsStore,
|
|
84
|
+
appendMetric,
|
|
85
|
+
buildMetricsTiming,
|
|
86
|
+
} from "../router/metrics.js";
|
|
87
|
+
import { observePhase, observeEvent, PHASES } from "../router/instrument.js";
|
|
88
|
+
import {
|
|
89
|
+
startSSRSetup,
|
|
90
|
+
getSSRSetup,
|
|
91
|
+
mayNeedSSR,
|
|
92
|
+
isRscRequest,
|
|
93
|
+
SSR_SETUP_VAR,
|
|
94
|
+
} from "./ssr-setup.js";
|
|
95
|
+
import {
|
|
96
|
+
classifyRequest,
|
|
97
|
+
type RequestPlan,
|
|
98
|
+
type ExecutableRequestPlan,
|
|
99
|
+
} from "../router/request-classification.js";
|
|
69
100
|
|
|
70
101
|
/**
|
|
71
102
|
* Create an RSC request handler.
|
|
@@ -100,12 +131,35 @@ import {
|
|
|
100
131
|
* });
|
|
101
132
|
* ```
|
|
102
133
|
*/
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Response that tells the client to do a full document navigation. Shared by
|
|
137
|
+
* the terminal reload plans (version-mismatch and app-switch): an empty 200
|
|
138
|
+
* carrying X-RSC-Reload, which the client turns into window.location.href.
|
|
139
|
+
*/
|
|
140
|
+
function createReloadResponse(reloadUrl: string) {
|
|
141
|
+
return createResponseWithMergedHeaders(null, {
|
|
142
|
+
status: 200,
|
|
143
|
+
headers: {
|
|
144
|
+
"X-RSC-Reload": reloadUrl,
|
|
145
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
103
150
|
export function createRSCHandler<
|
|
104
151
|
TEnv = unknown,
|
|
105
152
|
TRoutes extends Record<string, string> = Record<string, string>,
|
|
106
153
|
>(options: CreateRSCHandlerOptions<TEnv, TRoutes>) {
|
|
107
154
|
const { router, version = VERSION, nonce: nonceProvider } = options;
|
|
108
155
|
|
|
156
|
+
// Handler-owned registry of explicit per-scope stores from cache({ store }).
|
|
157
|
+
// Lives in the closure so it is scoped per handler (multi-router deployments
|
|
158
|
+
// get separate registries) and accumulates every explicit store this handler
|
|
159
|
+
// resolves across requests. updateTag()/revalidateTag() iterate it to reach
|
|
160
|
+
// stores not covered by the app-level ctx._cacheStore.
|
|
161
|
+
const explicitTaggedStores = new Set<SegmentCacheStore>();
|
|
162
|
+
|
|
109
163
|
// Use provided deps or default to @vitejs/plugin-rsc/rsc exports
|
|
110
164
|
const deps = options.deps ?? rscDeps;
|
|
111
165
|
const {
|
|
@@ -117,10 +171,22 @@ export function createRSCHandler<
|
|
|
117
171
|
decodeFormState,
|
|
118
172
|
} = deps;
|
|
119
173
|
|
|
120
|
-
// Use provided loadSSRModule or default to vite RSC module loader
|
|
121
|
-
|
|
174
|
+
// Use provided loadSSRModule or default to vite RSC module loader.
|
|
175
|
+
// In production the SSR module is stable across requests, so memoize
|
|
176
|
+
// the dynamic import to avoid repeated module resolution overhead.
|
|
177
|
+
// In dev mode Vite may hot-reload the module, so skip memoization.
|
|
178
|
+
const rawLoadSSRModule: LoadSSRModule =
|
|
122
179
|
options.loadSSRModule ??
|
|
123
180
|
(() => import.meta.viteRsc.loadModule("ssr", "index"));
|
|
181
|
+
let _ssrModulePromise: Promise<SSRModule> | undefined;
|
|
182
|
+
const loadSSRModule: LoadSSRModule =
|
|
183
|
+
process.env.NODE_ENV === "production"
|
|
184
|
+
? () =>
|
|
185
|
+
(_ssrModulePromise ??= rawLoadSSRModule().catch((err) => {
|
|
186
|
+
_ssrModulePromise = undefined;
|
|
187
|
+
throw err;
|
|
188
|
+
}))
|
|
189
|
+
: rawLoadSSRModule;
|
|
124
190
|
|
|
125
191
|
/**
|
|
126
192
|
* Per-request error reporter that deduplicates via the ALS request context.
|
|
@@ -133,10 +199,13 @@ export function createRSCHandler<
|
|
|
133
199
|
phase: ErrorPhase,
|
|
134
200
|
context: Parameters<typeof invokeOnError<TEnv>>[3],
|
|
135
201
|
): void {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
202
|
+
// Guard: abort signal handlers fire asynchronously outside the ALS
|
|
203
|
+
// request scope, so the context may be gone. Skip dedup in that
|
|
204
|
+
// case — the error is from a cancelled stream, not a real failure.
|
|
205
|
+
const reqCtx = _getRequestContext();
|
|
206
|
+
if (error != null && typeof error === "object" && reqCtx) {
|
|
207
|
+
if (reqCtx._reportedErrors.has(error)) return;
|
|
208
|
+
reqCtx._reportedErrors.add(error);
|
|
140
209
|
}
|
|
141
210
|
invokeOnError(router.onError, error, phase, context, "RSC");
|
|
142
211
|
}
|
|
@@ -176,24 +245,16 @@ export function createRSCHandler<
|
|
|
176
245
|
metadata: { timeout: true, phase, durationMs },
|
|
177
246
|
});
|
|
178
247
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
actionId,
|
|
190
|
-
durationMs,
|
|
191
|
-
customHandler: !!router.onTimeout,
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
} catch {
|
|
195
|
-
// Router context may not be available
|
|
196
|
-
}
|
|
248
|
+
observeEvent({
|
|
249
|
+
type: "request.timeout",
|
|
250
|
+
timestamp: performance.now(),
|
|
251
|
+
phase,
|
|
252
|
+
pathname: url.pathname,
|
|
253
|
+
routeKey,
|
|
254
|
+
actionId,
|
|
255
|
+
durationMs,
|
|
256
|
+
customHandler: !!router.onTimeout,
|
|
257
|
+
});
|
|
197
258
|
|
|
198
259
|
if (router.onTimeout) {
|
|
199
260
|
try {
|
|
@@ -225,16 +286,27 @@ export function createRSCHandler<
|
|
|
225
286
|
function createRedirectFlightResponse(
|
|
226
287
|
redirectUrl: string,
|
|
227
288
|
locationState?: Record<string, unknown>,
|
|
289
|
+
external?: boolean,
|
|
228
290
|
): Response {
|
|
229
291
|
const redirectPayload: RscPayload = {
|
|
230
292
|
metadata: {
|
|
231
293
|
pathname: redirectUrl,
|
|
232
294
|
segments: [],
|
|
233
|
-
redirect: { url: redirectUrl },
|
|
295
|
+
redirect: { url: redirectUrl, ...(external && { external: true }) },
|
|
234
296
|
...(locationState && { locationState }),
|
|
235
297
|
},
|
|
236
298
|
};
|
|
237
|
-
const rscStream = renderToReadableStream<RscPayload>(redirectPayload
|
|
299
|
+
const rscStream = renderToReadableStream<RscPayload>(redirectPayload, {
|
|
300
|
+
onError: (error: unknown) => {
|
|
301
|
+
const reqCtx = _getRequestContext<TEnv>();
|
|
302
|
+
if (!reqCtx) return;
|
|
303
|
+
callOnError(error, "rendering", {
|
|
304
|
+
request: reqCtx.request,
|
|
305
|
+
url: reqCtx.url,
|
|
306
|
+
env: reqCtx.env,
|
|
307
|
+
});
|
|
308
|
+
},
|
|
309
|
+
});
|
|
238
310
|
return createResponseWithMergedHeaders(rscStream, {
|
|
239
311
|
status: 200,
|
|
240
312
|
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
@@ -268,6 +340,11 @@ export function createRSCHandler<
|
|
|
268
340
|
input: RouterRequestInput<TEnv> = {},
|
|
269
341
|
): Promise<Response> {
|
|
270
342
|
const handlerStart = performance.now();
|
|
343
|
+
// Create the metrics store at handler start so handler:total has startTime=0
|
|
344
|
+
// and all metrics are relative to the request entry point.
|
|
345
|
+
const earlyMetricsStore = router.debugPerformance
|
|
346
|
+
? createMetricsStore(true, handlerStart)
|
|
347
|
+
: undefined;
|
|
271
348
|
|
|
272
349
|
const { env = {} as TEnv, vars: initialVars, ctx: executionCtx } = input;
|
|
273
350
|
|
|
@@ -310,7 +387,7 @@ export function createRSCHandler<
|
|
|
310
387
|
// Resolve cache store configuration
|
|
311
388
|
// Priority: options.cache (handler override) > router.cache (router default)
|
|
312
389
|
// Store is enabled only if: config provided, enabled, and no ?__no_cache query param
|
|
313
|
-
let cacheStore
|
|
390
|
+
let cacheStore: SegmentCacheStore | undefined;
|
|
314
391
|
const cacheOption = options.cache ?? router.cache;
|
|
315
392
|
if (cacheOption && !url.searchParams.has("__no_cache")) {
|
|
316
393
|
const cacheConfig =
|
|
@@ -377,15 +454,22 @@ export function createRSCHandler<
|
|
|
377
454
|
url,
|
|
378
455
|
variables,
|
|
379
456
|
cacheStore,
|
|
457
|
+
explicitTaggedStores,
|
|
380
458
|
cacheProfiles: router.cacheProfiles,
|
|
381
459
|
executionContext: executionCtx,
|
|
382
460
|
themeConfig: router.themeConfig,
|
|
461
|
+
stateCookieName: router.resolvedStateCookieName,
|
|
462
|
+
version,
|
|
383
463
|
});
|
|
464
|
+
if (earlyMetricsStore) {
|
|
465
|
+
requestContext._debugPerformance = true;
|
|
466
|
+
requestContext._metricsStore = earlyMetricsStore;
|
|
467
|
+
}
|
|
384
468
|
// Wire background error reporting so "use cache" and other subsystems
|
|
385
469
|
// can surface non-fatal errors through the router's onError callback.
|
|
386
470
|
requestContext._reportBackgroundError = (
|
|
387
471
|
error: unknown,
|
|
388
|
-
category:
|
|
472
|
+
category: CacheErrorCategory,
|
|
389
473
|
) => {
|
|
390
474
|
callOnError(error, "cache", {
|
|
391
475
|
request,
|
|
@@ -415,42 +499,112 @@ export function createRSCHandler<
|
|
|
415
499
|
// - Server components during rendering
|
|
416
500
|
// - Error boundaries
|
|
417
501
|
// - Streaming
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
502
|
+
// Store basename on request context (scoped per-request via existing ALS)
|
|
503
|
+
requestContext._basename = router.basename;
|
|
504
|
+
|
|
505
|
+
// Resolved span tracing for this request (read at each traced phase).
|
|
506
|
+
requestContext._tracing = router.tracing;
|
|
507
|
+
|
|
508
|
+
// The "rango.request" span is opened inside the request context so the
|
|
509
|
+
// Cloudflare runner can read executionContext.tracing, and so every nested
|
|
510
|
+
// phase span (and the platform's automatic KV/D1/fetch spans) nests under
|
|
511
|
+
// it. Construction-bound: the span ends when the Response is built, never
|
|
512
|
+
// wrapping the streamed body. metric:false — handler:total is metered
|
|
513
|
+
// directly below (a grand total incl. the pre-context bootstrap timings).
|
|
514
|
+
// When tracing is off this is a direct pass-through.
|
|
515
|
+
return runWithRequestContext(requestContext, () =>
|
|
516
|
+
observePhase(PHASES.request, async (span) => {
|
|
517
|
+
span.setAttribute("http.method", request.method);
|
|
518
|
+
// The matched route template is not known until match() runs later, so
|
|
519
|
+
// emit the concrete path as url.path (low-level), NOT http.route — the
|
|
520
|
+
// latter is reserved for the low-cardinality template (OTel convention).
|
|
521
|
+
span.setAttribute("url.path", url.pathname);
|
|
522
|
+
|
|
523
|
+
// Core handler logic (wrapped by middleware)
|
|
524
|
+
const coreHandler = async (): Promise<Response> => {
|
|
525
|
+
return coreRequestHandler(request, env, url, variables, nonce);
|
|
526
|
+
};
|
|
423
527
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
528
|
+
// Execute middleware chain if any, otherwise call core handler directly
|
|
529
|
+
let response: Response;
|
|
530
|
+
if (matchedMiddleware.length > 0) {
|
|
531
|
+
const mwResponse = await executeMiddleware(
|
|
532
|
+
matchedMiddleware,
|
|
533
|
+
request,
|
|
534
|
+
env,
|
|
535
|
+
variables,
|
|
536
|
+
coreHandler,
|
|
537
|
+
createReverseFunction(getRequiredRouteMap()),
|
|
538
|
+
);
|
|
434
539
|
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
540
|
+
if (
|
|
541
|
+
url.searchParams.has("_rsc_partial") ||
|
|
542
|
+
url.searchParams.has("_rsc_action")
|
|
543
|
+
) {
|
|
544
|
+
const intercepted = interceptRedirectForPartial(
|
|
545
|
+
mwResponse,
|
|
546
|
+
createRedirectFlightResponse,
|
|
547
|
+
);
|
|
548
|
+
response = intercepted ?? finalizeResponse(mwResponse);
|
|
549
|
+
} else {
|
|
550
|
+
response = finalizeResponse(mwResponse);
|
|
551
|
+
}
|
|
552
|
+
} else {
|
|
553
|
+
response = await coreHandler();
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// Finalize metrics after all middleware (including post-next work)
|
|
557
|
+
// has completed so :post spans are captured in the timeline.
|
|
558
|
+
// Handler timing parts are always emitted (even without debug metrics)
|
|
559
|
+
// so non-debug requests still get bootstrap Server-Timing entries.
|
|
560
|
+
const handlerTimingArr: string[] = variables.__handlerTiming || [];
|
|
561
|
+
// Preserve any existing Server-Timing set by response routes or middleware
|
|
562
|
+
const existingTiming = response.headers.get("Server-Timing");
|
|
563
|
+
const timingParts = existingTiming
|
|
564
|
+
? [existingTiming, ...handlerTimingArr]
|
|
565
|
+
: [...handlerTimingArr];
|
|
566
|
+
|
|
567
|
+
const metricsStore = requestContext._metricsStore;
|
|
568
|
+
if (metricsStore) {
|
|
569
|
+
// When the store was created at handler start (earlyMetricsStore),
|
|
570
|
+
// handler:total covers the full request. When ctx.debugPerformance()
|
|
571
|
+
// created the store mid-request, use its requestStart to avoid a
|
|
572
|
+
// negative startTime offset.
|
|
573
|
+
const totalStart = earlyMetricsStore
|
|
574
|
+
? handlerStart
|
|
575
|
+
: metricsStore.requestStart;
|
|
576
|
+
appendMetric(
|
|
577
|
+
metricsStore,
|
|
578
|
+
"handler:total",
|
|
579
|
+
totalStart,
|
|
580
|
+
performance.now() - totalStart,
|
|
442
581
|
);
|
|
443
|
-
|
|
582
|
+
const metricsTiming = buildMetricsTiming(
|
|
583
|
+
request.method,
|
|
584
|
+
url.pathname,
|
|
585
|
+
metricsStore,
|
|
586
|
+
);
|
|
587
|
+
if (metricsTiming) timingParts.push(metricsTiming);
|
|
444
588
|
}
|
|
445
589
|
|
|
446
|
-
|
|
447
|
-
|
|
590
|
+
const fullTiming = timingParts.join(", ");
|
|
591
|
+
if (fullTiming && !isWebSocketUpgradeResponse(response)) {
|
|
592
|
+
response.headers.set("Server-Timing", fullTiming);
|
|
593
|
+
}
|
|
448
594
|
|
|
449
|
-
|
|
450
|
-
|
|
595
|
+
// Single open-redirect chokepoint: every response (PE, full-page,
|
|
596
|
+
// middleware short-circuit, response-route) funnels through here, so
|
|
597
|
+
// guarding browser-followed (3xx) redirects once covers them all and any
|
|
598
|
+
// future redirect exit. Soft SPA/Flight redirects are 200/204 and pass
|
|
599
|
+
// through untouched (validated client-side instead).
|
|
600
|
+
return guardOutgoingRedirect(response, url.origin, router.basename);
|
|
601
|
+
}),
|
|
602
|
+
);
|
|
451
603
|
};
|
|
452
604
|
|
|
453
|
-
// Core request handling logic (separated for middleware wrapping)
|
|
605
|
+
// Core request handling logic (separated for middleware wrapping).
|
|
606
|
+
// Uses the classify → execute model: classifyRequest produces a RequestPlan,
|
|
607
|
+
// then execution dispatches on the plan mode.
|
|
454
608
|
async function coreRequestHandler(
|
|
455
609
|
request: Request,
|
|
456
610
|
env: TEnv,
|
|
@@ -458,56 +612,103 @@ export function createRSCHandler<
|
|
|
458
612
|
variables: Record<string, any>,
|
|
459
613
|
nonce: string | undefined,
|
|
460
614
|
): Promise<Response> {
|
|
461
|
-
const previewStart = performance.now();
|
|
462
|
-
const preview = await router.previewMatch(request, { env });
|
|
463
|
-
const previewDur = performance.now() - previewStart;
|
|
464
615
|
const handlerTiming: string[] = variables.__handlerTiming || [];
|
|
465
|
-
|
|
466
|
-
//
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
616
|
+
|
|
617
|
+
// Debug manifest endpoint: handled before classification since it
|
|
618
|
+
// doesn't need a route match and needs trie access from the closure.
|
|
619
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
620
|
+
if (
|
|
621
|
+
url.searchParams.has("__debug_manifest") &&
|
|
622
|
+
(isDev || router.allowDebugManifest)
|
|
623
|
+
) {
|
|
624
|
+
const trie = getRouterTrie(router.id) ?? getRouteTrie();
|
|
625
|
+
const routeManifest = getRequiredRouteMap();
|
|
626
|
+
const { extractAncestryFromTrie } =
|
|
627
|
+
await import("../build/route-trie.js");
|
|
628
|
+
return new Response(
|
|
629
|
+
JSON.stringify(
|
|
630
|
+
{
|
|
631
|
+
routerId: router.id,
|
|
632
|
+
routeManifest,
|
|
633
|
+
routeAncestry: trie ? extractAncestryFromTrie(trie) : {},
|
|
634
|
+
routeTrie: trie,
|
|
635
|
+
precomputedEntries: getPrecomputedEntries(),
|
|
636
|
+
},
|
|
637
|
+
null,
|
|
638
|
+
2,
|
|
476
639
|
),
|
|
477
|
-
|
|
478
|
-
|
|
640
|
+
{
|
|
641
|
+
headers: { "Content-Type": "application/json" },
|
|
642
|
+
},
|
|
479
643
|
);
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// ---- 1. Classify ----
|
|
647
|
+
// classifyRequest may throw RouteNotFoundError for unknown routes.
|
|
648
|
+
// In that case, fall through to a full-render plan so the pipeline
|
|
649
|
+
// can render the 404 page via the existing error handling path.
|
|
650
|
+
const classifyStart = performance.now();
|
|
651
|
+
let plan: RequestPlan<TEnv>;
|
|
652
|
+
try {
|
|
653
|
+
plan = await classifyRequest<TEnv>(request, url, {
|
|
654
|
+
findMatch: router.findMatch,
|
|
655
|
+
routerVersion: version,
|
|
656
|
+
routerId: router.id,
|
|
657
|
+
});
|
|
658
|
+
} catch (error) {
|
|
659
|
+
if (isRouteNotFoundError(error)) {
|
|
660
|
+
// Let the render path handle 404 — match()/matchPartial() will
|
|
661
|
+
// re-throw RouteNotFoundError and the catch block in
|
|
662
|
+
// executeRenderWithMiddleware renders the not-found page.
|
|
663
|
+
plan = {
|
|
664
|
+
mode: "full-render",
|
|
665
|
+
route: {
|
|
666
|
+
matched: null as any,
|
|
667
|
+
manifestEntry: null as any,
|
|
668
|
+
entries: [],
|
|
669
|
+
routeKey: "",
|
|
670
|
+
localRouteName: "",
|
|
671
|
+
params: {},
|
|
672
|
+
routeMiddleware: [],
|
|
673
|
+
cacheScope: null,
|
|
674
|
+
isPassthrough: false,
|
|
675
|
+
},
|
|
676
|
+
negotiated: false,
|
|
677
|
+
};
|
|
678
|
+
} else {
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
const classifyDur = performance.now() - classifyStart;
|
|
683
|
+
handlerTiming.push(`handler-classify;dur=${classifyDur.toFixed(2)}`);
|
|
684
|
+
|
|
685
|
+
// ---- 2. Terminal plans (no execution needed) ----
|
|
686
|
+
if (plan.mode === "redirect") {
|
|
687
|
+
// Redirects are handled by the pipeline (match/matchPartial),
|
|
688
|
+
// but for partial requests we short-circuit with a Flight redirect.
|
|
689
|
+
if (url.searchParams.has("_rsc_partial")) {
|
|
690
|
+
return createRedirectFlightResponse(plan.redirectUrl);
|
|
489
691
|
}
|
|
490
|
-
|
|
692
|
+
// Full requests: let the pipeline handle the redirect via match()
|
|
693
|
+
// which returns { redirect: url }. Fall through to full-render.
|
|
491
694
|
}
|
|
492
695
|
|
|
493
|
-
|
|
696
|
+
if (plan.mode === "version-mismatch") {
|
|
697
|
+
console.log(
|
|
698
|
+
`[RSC] Version mismatch: client=${url.searchParams.get("_rsc_v")}, server=${version}. Forcing reload.`,
|
|
699
|
+
);
|
|
700
|
+
return createReloadResponse(plan.reloadUrl);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (plan.mode === "app-switch") {
|
|
704
|
+
// Cross-app SPA navigation crossed a host-router app boundary. Force a
|
|
705
|
+
// real document navigation so the target app's document is re-established
|
|
706
|
+
// (stylesheets, theme, warmup, prefetch-TTL). See request-classification.
|
|
707
|
+
return createReloadResponse(plan.reloadUrl);
|
|
708
|
+
}
|
|
494
709
|
|
|
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;
|
|
710
|
+
// ---- 3. Origin guard (gate for action/loader/PE modes) ----
|
|
711
|
+
const originPhase = ORIGIN_CHECK_PHASE_BY_MODE[plan.mode];
|
|
511
712
|
if (originPhase) {
|
|
512
713
|
const originResult = await checkRequestOrigin(
|
|
513
714
|
request,
|
|
@@ -535,37 +736,49 @@ export function createRSCHandler<
|
|
|
535
736
|
},
|
|
536
737
|
});
|
|
537
738
|
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
phase: originPhase,
|
|
548
|
-
origin: request.headers.get("origin"),
|
|
549
|
-
host: request.headers.get("host"),
|
|
550
|
-
});
|
|
551
|
-
}
|
|
552
|
-
} catch {
|
|
553
|
-
// Router context may not be available
|
|
554
|
-
}
|
|
739
|
+
observeEvent({
|
|
740
|
+
type: "request.origin-rejected",
|
|
741
|
+
timestamp: performance.now(),
|
|
742
|
+
method: request.method,
|
|
743
|
+
pathname: url.pathname,
|
|
744
|
+
phase: originPhase,
|
|
745
|
+
origin: request.headers.get("origin"),
|
|
746
|
+
host: request.headers.get("host"),
|
|
747
|
+
});
|
|
555
748
|
|
|
556
749
|
return originResult;
|
|
557
750
|
}
|
|
558
751
|
}
|
|
559
752
|
|
|
560
|
-
//
|
|
561
|
-
|
|
753
|
+
// ---- 4. Execute ----
|
|
754
|
+
return executeRequest(
|
|
755
|
+
plan as ExecutableRequestPlan<TEnv>,
|
|
756
|
+
request,
|
|
757
|
+
env,
|
|
758
|
+
url,
|
|
759
|
+
variables,
|
|
760
|
+
nonce,
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// Execute a classified request plan. Dispatches to the appropriate handler
|
|
765
|
+
// based on plan.mode. Lives in the createRSCHandler closure for access to
|
|
766
|
+
// handlerCtx, router, callOnError, etc.
|
|
767
|
+
// Only receives executable plans (version-mismatch is handled above).
|
|
768
|
+
async function executeRequest(
|
|
769
|
+
plan: ExecutableRequestPlan<TEnv>,
|
|
770
|
+
request: Request,
|
|
771
|
+
env: TEnv,
|
|
772
|
+
url: URL,
|
|
773
|
+
variables: Record<string, any>,
|
|
774
|
+
nonce: string | undefined,
|
|
775
|
+
): Promise<Response> {
|
|
776
|
+
// Common setup
|
|
777
|
+
const handleStore = getRequestContext()._handleStore;
|
|
562
778
|
|
|
563
779
|
// 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
780
|
handleStore.onError = (error: Error) => {
|
|
568
|
-
const reqCtx =
|
|
781
|
+
const reqCtx = getRequestContext();
|
|
569
782
|
callOnError(error, "handler", {
|
|
570
783
|
request,
|
|
571
784
|
url,
|
|
@@ -573,66 +786,149 @@ export function createRSCHandler<
|
|
|
573
786
|
params: reqCtx.params as Record<string, string>,
|
|
574
787
|
handledByBoundary: true,
|
|
575
788
|
});
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
pathname: url.pathname,
|
|
586
|
-
routeKey: reqCtx._routeName,
|
|
587
|
-
params: reqCtx.params as Record<string, string>,
|
|
588
|
-
});
|
|
589
|
-
}
|
|
590
|
-
} catch {
|
|
591
|
-
// Router context may not be available (e.g. prerender path)
|
|
592
|
-
}
|
|
789
|
+
observeEvent({
|
|
790
|
+
type: "handler.error",
|
|
791
|
+
timestamp: performance.now(),
|
|
792
|
+
error,
|
|
793
|
+
handledByBoundary: true,
|
|
794
|
+
pathname: url.pathname,
|
|
795
|
+
routeKey: reqCtx._routeName,
|
|
796
|
+
params: reqCtx.params as Record<string, string>,
|
|
797
|
+
});
|
|
593
798
|
};
|
|
594
799
|
|
|
595
800
|
// Set route params early so all execution paths can access ctx.params.
|
|
596
|
-
|
|
597
|
-
|
|
801
|
+
// Also store the classified snapshot so match/matchPartial can reuse it
|
|
802
|
+
// instead of calling resolveRoute again.
|
|
803
|
+
if (plan.mode !== "redirect") {
|
|
804
|
+
setRequestContextParams(plan.route.params, plan.route.routeKey);
|
|
805
|
+
getRequestContext()._classifiedRoute = plan.route;
|
|
598
806
|
}
|
|
599
807
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
//
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
routeMiddleware:
|
|
808
|
+
const routeReverse = createReverseFunction(getRequiredRouteMap());
|
|
809
|
+
|
|
810
|
+
// ---- Response route: skip entire RSC pipeline ----
|
|
811
|
+
if (plan.mode === "response") {
|
|
812
|
+
// Build ResponseRouteMatch from plan fields. handleResponseRoute
|
|
813
|
+
// expects a flat object with params at the top level.
|
|
814
|
+
const responseMatch: ResponseRouteMatch = {
|
|
815
|
+
responseType: plan.responseType,
|
|
816
|
+
handler: plan.handler,
|
|
817
|
+
params: plan.route.params,
|
|
818
|
+
negotiated: plan.negotiated,
|
|
819
|
+
manifestEntry: plan.manifestEntry,
|
|
820
|
+
routeMiddleware: plan.routeMiddleware,
|
|
821
|
+
};
|
|
822
|
+
const responseOutcome = await withTimeout(
|
|
823
|
+
handleResponseRoute(
|
|
824
|
+
handlerCtx,
|
|
825
|
+
responseMatch,
|
|
826
|
+
request,
|
|
827
|
+
env,
|
|
828
|
+
url,
|
|
829
|
+
variables,
|
|
830
|
+
),
|
|
831
|
+
router.timeouts.renderStartMs,
|
|
832
|
+
"render-start",
|
|
833
|
+
);
|
|
834
|
+
if (responseOutcome.timedOut) {
|
|
835
|
+
return handleTimeoutResponse(
|
|
836
|
+
request,
|
|
837
|
+
env,
|
|
838
|
+
url,
|
|
839
|
+
"render-start",
|
|
840
|
+
responseOutcome.durationMs,
|
|
841
|
+
plan.route.routeKey,
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
const response = responseOutcome.result;
|
|
845
|
+
if (plan.negotiated && !isWebSocketUpgradeResponse(response)) {
|
|
846
|
+
// handleResponseRoute (callHandlerWithVary) already appends Vary: Accept
|
|
847
|
+
// for negotiated responses; dedup so we don't emit Vary: Accept, Accept.
|
|
848
|
+
appendVaryAccept(response);
|
|
849
|
+
}
|
|
850
|
+
return response;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// SSR setup: kick off in parallel for modes that need HTML rendering.
|
|
854
|
+
// Placed after response-route short-circuit so response/mime routes
|
|
855
|
+
// never pay for SSR work.
|
|
856
|
+
//
|
|
857
|
+
// Only kick off when the request will actually render HTML, so the
|
|
858
|
+
// eager loadSSRModule() + user resolveStreaming() are not started (and
|
|
859
|
+
// never consumed) for a request that returns an RSC stream — that wasted
|
|
860
|
+
// work also leaves an orphaned Promise.all that can reject (D7). PE form
|
|
861
|
+
// submissions always render HTML (handleProgressiveEnhancement renders via
|
|
862
|
+
// getSSRSetup regardless of Accept). For full/partial-render and action,
|
|
863
|
+
// the render-time HTML decision is exactly !isRscRequest — mayNeedSSR is
|
|
864
|
+
// the coarse transport pre-filter, isRscRequest is the precise Accept call
|
|
865
|
+
// (it, unlike mayNeedSSR, treats a MISSING Accept as RSC). Both must pass.
|
|
866
|
+
const willRenderHtml =
|
|
867
|
+
plan.mode === "pe-render" ||
|
|
868
|
+
(mayNeedSSR(request, url) &&
|
|
869
|
+
!isRscRequest(request, url, plan.mode === "partial-render"));
|
|
870
|
+
if (plan.mode !== "loader" && willRenderHtml) {
|
|
871
|
+
variables[SSR_SETUP_VAR] = startSSRSetup(
|
|
872
|
+
handlerCtx,
|
|
873
|
+
request,
|
|
874
|
+
env,
|
|
875
|
+
url,
|
|
876
|
+
router.debugPerformance
|
|
877
|
+
? () => getRequestContext()._metricsStore
|
|
878
|
+
: undefined,
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// ---- Loader fetch ----
|
|
883
|
+
if (plan.mode === "loader") {
|
|
884
|
+
return handleLoaderFetch(
|
|
885
|
+
handlerCtx,
|
|
886
|
+
request,
|
|
887
|
+
env,
|
|
888
|
+
url,
|
|
613
889
|
variables,
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
890
|
+
plan.route.params,
|
|
891
|
+
);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// ---- Progressive enhancement ----
|
|
895
|
+
if (plan.mode === "pe-render") {
|
|
896
|
+
const peResult = await handleProgressiveEnhancement(
|
|
897
|
+
handlerCtx,
|
|
898
|
+
request,
|
|
899
|
+
env,
|
|
900
|
+
url,
|
|
901
|
+
false, // isAction = false for PE
|
|
902
|
+
handleStore,
|
|
903
|
+
nonce,
|
|
904
|
+
{
|
|
905
|
+
routeMiddleware: plan.route.routeMiddleware,
|
|
906
|
+
variables,
|
|
907
|
+
routeReverse,
|
|
908
|
+
},
|
|
909
|
+
);
|
|
910
|
+
if (peResult) return peResult;
|
|
911
|
+
// PE handler returned null (not a PE form) — fall through to render
|
|
619
912
|
}
|
|
620
913
|
|
|
621
|
-
//
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
// the revalidation pass (identical to a normal render).
|
|
625
|
-
let actionContinuation: ActionContinuation | undefined;
|
|
626
|
-
if (isAction && actionId) {
|
|
914
|
+
// ---- Action: execute action, then revalidate wrapped in route middleware ----
|
|
915
|
+
if (plan.mode === "action") {
|
|
916
|
+
let actionContinuation: ActionContinuation | undefined;
|
|
627
917
|
try {
|
|
918
|
+
// Instrument the action execution as its own phase (action:<actionId> +
|
|
919
|
+
// rango.action), so a POST shows the mutation time AND which action ran,
|
|
920
|
+
// not just the downstream revalidation render. The action's own
|
|
921
|
+
// loaders/fetches nest under rango.action.
|
|
628
922
|
const actionOutcome = await withTimeout(
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
923
|
+
observePhase(PHASES.action(plan.actionId), () =>
|
|
924
|
+
executeServerAction(
|
|
925
|
+
handlerCtx,
|
|
926
|
+
request,
|
|
927
|
+
env,
|
|
928
|
+
url,
|
|
929
|
+
plan.actionId,
|
|
930
|
+
handleStore,
|
|
931
|
+
),
|
|
636
932
|
),
|
|
637
933
|
router.timeouts.actionMs,
|
|
638
934
|
"action",
|
|
@@ -644,8 +940,8 @@ export function createRSCHandler<
|
|
|
644
940
|
url,
|
|
645
941
|
"action",
|
|
646
942
|
actionOutcome.durationMs,
|
|
647
|
-
|
|
648
|
-
actionId,
|
|
943
|
+
plan.route.routeKey,
|
|
944
|
+
plan.actionId,
|
|
649
945
|
);
|
|
650
946
|
}
|
|
651
947
|
const result = actionOutcome.result;
|
|
@@ -657,40 +953,248 @@ export function createRSCHandler<
|
|
|
657
953
|
request,
|
|
658
954
|
url,
|
|
659
955
|
env,
|
|
660
|
-
actionId,
|
|
956
|
+
actionId: plan.actionId,
|
|
661
957
|
handledByBoundary: false,
|
|
662
958
|
});
|
|
663
959
|
console.error(`[RSC] Action error:`, error);
|
|
664
960
|
throw error;
|
|
665
961
|
}
|
|
666
|
-
}
|
|
667
962
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
963
|
+
// Revalidation render wrapped in route middleware.
|
|
964
|
+
// Actions from client-side navigation include _rsc_partial — preserve
|
|
965
|
+
// the partial flag so the revalidation returns a Flight stream, not HTML.
|
|
966
|
+
// App-switch is already excluded by classifyRequest (would be full-render).
|
|
967
|
+
const isPartialAction = url.searchParams.has("_rsc_partial");
|
|
968
|
+
return executeRenderWithMiddleware(
|
|
969
|
+
plan.route.routeMiddleware,
|
|
970
|
+
plan.negotiated,
|
|
971
|
+
plan.route.routeKey,
|
|
972
|
+
routeReverse,
|
|
672
973
|
request,
|
|
673
974
|
env,
|
|
674
975
|
url,
|
|
675
976
|
variables,
|
|
676
977
|
nonce,
|
|
677
|
-
preview?.params,
|
|
678
|
-
preview?.routeKey,
|
|
679
978
|
handleStore,
|
|
979
|
+
isPartialAction,
|
|
680
980
|
actionContinuation,
|
|
681
981
|
);
|
|
682
|
-
|
|
683
|
-
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// Full render, partial render, fallen-through PE, and full-page redirect all
|
|
985
|
+
// render through the same middleware-wrapped path. Only full/partial-render
|
|
986
|
+
// carry negotiation + the partial flag; pe/redirect render plainly.
|
|
987
|
+
const isPartial = plan.mode === "partial-render";
|
|
988
|
+
const negotiated =
|
|
989
|
+
plan.mode === "full-render" || plan.mode === "partial-render"
|
|
990
|
+
? plan.negotiated
|
|
991
|
+
: false;
|
|
992
|
+
return executeRenderWithMiddleware(
|
|
993
|
+
plan.route.routeMiddleware,
|
|
994
|
+
negotiated,
|
|
995
|
+
plan.route.routeKey,
|
|
996
|
+
routeReverse,
|
|
997
|
+
request,
|
|
998
|
+
env,
|
|
999
|
+
url,
|
|
1000
|
+
variables,
|
|
1001
|
+
nonce,
|
|
1002
|
+
handleStore,
|
|
1003
|
+
isPartial,
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Shared render execution: wraps handleRscRendering (or revalidateAfterAction)
|
|
1008
|
+
// in route middleware and timeout handling. Consolidates the pattern used by
|
|
1009
|
+
// action-revalidate, full-render, and partial-render modes.
|
|
1010
|
+
async function executeRenderWithMiddleware(
|
|
1011
|
+
routeMiddleware: import("../router/middleware-types.js").CollectedMiddleware[],
|
|
1012
|
+
negotiated: boolean,
|
|
1013
|
+
routeKey: string,
|
|
1014
|
+
routeReverse: ReturnType<typeof createReverseFunction>,
|
|
1015
|
+
request: Request,
|
|
1016
|
+
env: TEnv,
|
|
1017
|
+
url: URL,
|
|
1018
|
+
variables: Record<string, any>,
|
|
1019
|
+
nonce: string | undefined,
|
|
1020
|
+
handleStore: ReturnType<typeof getRequestContext>["_handleStore"],
|
|
1021
|
+
isPartial: boolean,
|
|
1022
|
+
actionContinuation?: ActionContinuation,
|
|
1023
|
+
): Promise<Response> {
|
|
1024
|
+
const renderHandler = async (): Promise<Response> => {
|
|
1025
|
+
try {
|
|
1026
|
+
let response: Response;
|
|
1027
|
+
if (actionContinuation) {
|
|
1028
|
+
response = await revalidateAfterAction(
|
|
1029
|
+
handlerCtx,
|
|
1030
|
+
request,
|
|
1031
|
+
env,
|
|
1032
|
+
url,
|
|
1033
|
+
handleStore,
|
|
1034
|
+
actionContinuation,
|
|
1035
|
+
);
|
|
1036
|
+
} else {
|
|
1037
|
+
response = await handleRscRendering(
|
|
1038
|
+
handlerCtx,
|
|
1039
|
+
request,
|
|
1040
|
+
env,
|
|
1041
|
+
url,
|
|
1042
|
+
isPartial,
|
|
1043
|
+
handleStore,
|
|
1044
|
+
nonce,
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
if (negotiated && !isWebSocketUpgradeResponse(response)) {
|
|
1048
|
+
// handleRscRendering bakes `accept` into the RSC response's Vary list;
|
|
1049
|
+
// dedup so the negotiated append does not list accept twice.
|
|
1050
|
+
appendVaryAccept(response);
|
|
1051
|
+
}
|
|
1052
|
+
return response;
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
// Check if middleware/handler returned Response
|
|
1055
|
+
if (error instanceof Response) {
|
|
1056
|
+
// An action revalidation render is delivered to the client over the
|
|
1057
|
+
// same Flight-parsing path as a partial navigation, so a Response
|
|
1058
|
+
// thrown during it must be converted exactly like a partial one
|
|
1059
|
+
// (raw 200 -> hard-nav hint, 3xx -> Flight redirect). Without this,
|
|
1060
|
+
// the no-middleware path returns the raw Response (the with-middleware
|
|
1061
|
+
// path is already covered by the isPartial || actionContinuation
|
|
1062
|
+
// guard below).
|
|
1063
|
+
const treatAsPartial = isPartial || actionContinuation != null;
|
|
1064
|
+
|
|
1065
|
+
// During partial (client-side navigation), a 200 Response from a handler
|
|
1066
|
+
// means the route serves raw content (JSON, text, etc.), not JSX.
|
|
1067
|
+
// Signal the browser to hard-navigate so it renders the raw response.
|
|
1068
|
+
if (treatAsPartial && error.status === 200) {
|
|
1069
|
+
console.warn(
|
|
1070
|
+
`[RSC] Route handler at ${url.pathname} returned a Response during client-side navigation. ` +
|
|
1071
|
+
`Falling back to hard navigation. Use data-external on the <Link> to avoid the extra round-trip.`,
|
|
1072
|
+
);
|
|
1073
|
+
return createResponseWithMergedHeaders(null, {
|
|
1074
|
+
status: 200,
|
|
1075
|
+
headers: {
|
|
1076
|
+
"X-RSC-Reload": stripInternalParams(url).toString(),
|
|
1077
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
1078
|
+
},
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
if (treatAsPartial) {
|
|
1083
|
+
const intercepted = interceptRedirectForPartial(
|
|
1084
|
+
error,
|
|
1085
|
+
createRedirectFlightResponse,
|
|
1086
|
+
);
|
|
1087
|
+
if (intercepted) return intercepted;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
return error;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// Render 404 page for unmatched routes
|
|
1094
|
+
if (isRouteNotFoundError(error)) {
|
|
1095
|
+
callOnError(error, "routing", {
|
|
1096
|
+
request,
|
|
1097
|
+
url,
|
|
1098
|
+
env,
|
|
1099
|
+
handledByBoundary: true,
|
|
1100
|
+
});
|
|
1101
|
+
|
|
1102
|
+
const notFoundOption = router.notFound;
|
|
1103
|
+
const notFoundComponent =
|
|
1104
|
+
typeof notFoundOption === "function"
|
|
1105
|
+
? notFoundOption({ pathname: url.pathname })
|
|
1106
|
+
: (notFoundOption ?? createElement("h1", null, "Not Found"));
|
|
1107
|
+
|
|
1108
|
+
const notFoundSegment = {
|
|
1109
|
+
id: "notFound",
|
|
1110
|
+
namespace: "notFound",
|
|
1111
|
+
type: "route" as const,
|
|
1112
|
+
index: 0,
|
|
1113
|
+
component: notFoundComponent,
|
|
1114
|
+
params: {},
|
|
1115
|
+
};
|
|
1116
|
+
|
|
1117
|
+
const payload: RscPayload = {
|
|
1118
|
+
metadata: {
|
|
1119
|
+
pathname: url.pathname,
|
|
1120
|
+
routerId: router.id,
|
|
1121
|
+
basename: router.basename,
|
|
1122
|
+
segments: [notFoundSegment],
|
|
1123
|
+
matched: [],
|
|
1124
|
+
diff: [],
|
|
1125
|
+
// Shape parity with buildFullPayload (rsc-rendering.ts): the 404
|
|
1126
|
+
// payload carries params/resolvedIds/prefetchCacheTTL the same way a
|
|
1127
|
+
// matched full render does. resolvedIds mirrors the rendered segment
|
|
1128
|
+
// list (the single notFound segment) like the error-boundary path
|
|
1129
|
+
// (match-api.ts) does for its boundary segment.
|
|
1130
|
+
resolvedIds: [notFoundSegment.id],
|
|
1131
|
+
params: {},
|
|
1132
|
+
isPartial: false,
|
|
1133
|
+
rootLayout: router.rootLayout,
|
|
1134
|
+
handles: handleStore.stream(),
|
|
1135
|
+
version,
|
|
1136
|
+
prefetchCacheTTL: router.prefetchCacheTTL,
|
|
1137
|
+
stateCookieName: router.resolvedStateCookieName,
|
|
1138
|
+
themeConfig: router.themeConfig,
|
|
1139
|
+
warmupEnabled: router.warmupEnabled,
|
|
1140
|
+
strictMode: router.strictMode,
|
|
1141
|
+
initialTheme: getRequestContext().theme,
|
|
1142
|
+
},
|
|
1143
|
+
};
|
|
1144
|
+
|
|
1145
|
+
const rscStream = renderToReadableStream(payload, {
|
|
1146
|
+
onError: (error: unknown) => {
|
|
1147
|
+
callOnError(error, "rendering", { request, url, env });
|
|
1148
|
+
},
|
|
1149
|
+
});
|
|
1150
|
+
|
|
1151
|
+
if (isRscRequest(request, url, isPartial)) {
|
|
1152
|
+
return createResponseWithMergedHeaders(rscStream, {
|
|
1153
|
+
status: 404,
|
|
1154
|
+
headers: {
|
|
1155
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
1156
|
+
// Router identity for the client's pre-decode integrity check; a
|
|
1157
|
+
// same-app 404 matches and applies in place. See response-adapter.
|
|
1158
|
+
"X-RSC-Router-Id": router.id,
|
|
1159
|
+
},
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
const [ssrModule, streamMode] = await getSSRSetup(
|
|
1164
|
+
handlerCtx,
|
|
1165
|
+
request,
|
|
1166
|
+
env,
|
|
1167
|
+
url,
|
|
1168
|
+
getRequestContext()._metricsStore,
|
|
1169
|
+
);
|
|
1170
|
+
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
1171
|
+
nonce,
|
|
1172
|
+
streamMode,
|
|
1173
|
+
});
|
|
1174
|
+
|
|
1175
|
+
return createResponseWithMergedHeaders(htmlStream, {
|
|
1176
|
+
status: 404,
|
|
1177
|
+
headers: { "content-type": "text/html;charset=utf-8" },
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// Report unhandled errors
|
|
1182
|
+
callOnError(error, "routing", {
|
|
1183
|
+
request,
|
|
1184
|
+
url,
|
|
1185
|
+
env,
|
|
1186
|
+
handledByBoundary: false,
|
|
1187
|
+
});
|
|
1188
|
+
console.error(`[RSC] Error:`, error);
|
|
1189
|
+
throw error;
|
|
684
1190
|
}
|
|
685
|
-
return response;
|
|
686
1191
|
};
|
|
687
1192
|
|
|
688
|
-
// Wrap the render path
|
|
689
|
-
// renderStartMs timeout so slow renders are caught before output.
|
|
1193
|
+
// Wrap the render path in a renderStartMs timeout
|
|
690
1194
|
const executeRender = async (): Promise<Response> => {
|
|
691
|
-
if (
|
|
1195
|
+
if (routeMiddleware.length > 0) {
|
|
692
1196
|
const mwResponse = await executeMiddleware(
|
|
693
|
-
buildRouteMiddlewareEntries<TEnv>(
|
|
1197
|
+
buildRouteMiddlewareEntries<TEnv>(routeMiddleware),
|
|
694
1198
|
request,
|
|
695
1199
|
env,
|
|
696
1200
|
variables,
|
|
@@ -698,10 +1202,7 @@ export function createRSCHandler<
|
|
|
698
1202
|
routeReverse,
|
|
699
1203
|
);
|
|
700
1204
|
|
|
701
|
-
if (
|
|
702
|
-
url.searchParams.has("_rsc_partial") ||
|
|
703
|
-
url.searchParams.has("_rsc_action")
|
|
704
|
-
) {
|
|
1205
|
+
if (isPartial || actionContinuation) {
|
|
705
1206
|
const intercepted = interceptRedirectForPartial(
|
|
706
1207
|
mwResponse,
|
|
707
1208
|
createRedirectFlightResponse,
|
|
@@ -712,7 +1213,6 @@ export function createRSCHandler<
|
|
|
712
1213
|
return finalizeResponse(mwResponse);
|
|
713
1214
|
}
|
|
714
1215
|
|
|
715
|
-
// No route middleware, proceed directly
|
|
716
1216
|
return renderHandler();
|
|
717
1217
|
};
|
|
718
1218
|
|
|
@@ -728,267 +1228,9 @@ export function createRSCHandler<
|
|
|
728
1228
|
url,
|
|
729
1229
|
"render-start",
|
|
730
1230
|
renderOutcome.durationMs,
|
|
731
|
-
|
|
1231
|
+
routeKey,
|
|
732
1232
|
);
|
|
733
1233
|
}
|
|
734
1234
|
return renderOutcome.result;
|
|
735
1235
|
}
|
|
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
1236
|
}
|