@rangojs/router 0.0.0-experimental.8 → 0.0.0-experimental.8a4d0430
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +5 -0
- package/README.md +884 -4
- package/dist/bin/rango.js +1601 -0
- package/dist/vite/index.js +4474 -867
- package/package.json +60 -51
- package/skills/breadcrumbs/SKILL.md +250 -0
- package/skills/cache-guide/SKILL.md +262 -0
- package/skills/caching/SKILL.md +50 -21
- package/skills/composability/SKILL.md +172 -0
- package/skills/debug-manifest/SKILL.md +12 -8
- package/skills/document-cache/SKILL.md +18 -16
- package/skills/fonts/SKILL.md +167 -0
- package/skills/hooks/SKILL.md +334 -72
- package/skills/host-router/SKILL.md +218 -0
- package/skills/intercept/SKILL.md +131 -8
- package/skills/layout/SKILL.md +100 -3
- package/skills/links/SKILL.md +89 -30
- package/skills/loader/SKILL.md +388 -38
- package/skills/middleware/SKILL.md +171 -34
- package/skills/mime-routes/SKILL.md +128 -0
- package/skills/parallel/SKILL.md +78 -1
- package/skills/prerender/SKILL.md +643 -0
- package/skills/rango/SKILL.md +85 -16
- package/skills/response-routes/SKILL.md +411 -0
- package/skills/route/SKILL.md +226 -14
- package/skills/router-setup/SKILL.md +123 -30
- package/skills/tailwind/SKILL.md +129 -0
- package/skills/theme/SKILL.md +9 -8
- package/skills/typesafety/SKILL.md +318 -89
- package/skills/use-cache/SKILL.md +324 -0
- package/src/__internal.ts +102 -4
- package/src/bin/rango.ts +321 -0
- package/src/browser/action-coordinator.ts +97 -0
- package/src/browser/action-response-classifier.ts +99 -0
- package/src/browser/event-controller.ts +87 -64
- package/src/browser/history-state.ts +80 -0
- package/src/browser/intercept-utils.ts +52 -0
- package/src/browser/link-interceptor.ts +24 -4
- package/src/browser/logging.ts +55 -0
- package/src/browser/merge-segment-loaders.ts +20 -12
- package/src/browser/navigation-bridge.ts +285 -553
- package/src/browser/navigation-client.ts +124 -71
- package/src/browser/navigation-store.ts +33 -50
- package/src/browser/navigation-transaction.ts +295 -0
- package/src/browser/network-error-handler.ts +61 -0
- package/src/browser/partial-update.ts +258 -308
- package/src/browser/prefetch/cache.ts +146 -0
- package/src/browser/prefetch/fetch.ts +135 -0
- package/src/browser/prefetch/observer.ts +65 -0
- package/src/browser/prefetch/policy.ts +42 -0
- package/src/browser/prefetch/queue.ts +88 -0
- package/src/browser/rango-state.ts +112 -0
- package/src/browser/react/Link.tsx +185 -73
- package/src/browser/react/NavigationProvider.tsx +51 -11
- package/src/browser/react/context.ts +6 -0
- package/src/browser/react/filter-segment-order.ts +11 -0
- package/src/browser/react/index.ts +12 -12
- package/src/browser/react/location-state-shared.ts +95 -53
- package/src/browser/react/location-state.ts +60 -15
- package/src/browser/react/mount-context.ts +6 -1
- package/src/browser/react/nonce-context.ts +23 -0
- package/src/browser/react/shallow-equal.ts +27 -0
- package/src/browser/react/use-action.ts +29 -51
- package/src/browser/react/use-client-cache.ts +5 -3
- package/src/browser/react/use-handle.ts +32 -79
- package/src/browser/react/use-href.tsx +2 -2
- package/src/browser/react/use-link-status.ts +6 -5
- package/src/browser/react/use-navigation.ts +22 -63
- package/src/browser/react/use-params.ts +65 -0
- package/src/browser/react/use-pathname.ts +47 -0
- package/src/browser/react/use-router.ts +63 -0
- package/src/browser/react/use-search-params.ts +56 -0
- package/src/browser/react/use-segments.ts +80 -97
- package/src/browser/response-adapter.ts +73 -0
- package/src/browser/rsc-router.tsx +107 -26
- package/src/browser/scroll-restoration.ts +92 -16
- package/src/browser/segment-reconciler.ts +216 -0
- package/src/browser/segment-structure-assert.ts +16 -0
- package/src/browser/server-action-bridge.ts +504 -599
- package/src/browser/shallow.ts +6 -1
- package/src/browser/types.ts +109 -47
- package/src/browser/validate-redirect-origin.ts +29 -0
- package/src/build/generate-manifest.ts +235 -24
- package/src/build/generate-route-types.ts +36 -0
- package/src/build/index.ts +13 -0
- package/src/build/route-trie.ts +265 -0
- package/src/build/route-types/ast-helpers.ts +25 -0
- package/src/build/route-types/ast-route-extraction.ts +98 -0
- package/src/build/route-types/codegen.ts +102 -0
- package/src/build/route-types/include-resolution.ts +411 -0
- package/src/build/route-types/param-extraction.ts +48 -0
- package/src/build/route-types/per-module-writer.ts +128 -0
- package/src/build/route-types/router-processing.ts +469 -0
- package/src/build/route-types/scan-filter.ts +78 -0
- package/src/build/runtime-discovery.ts +231 -0
- package/src/cache/background-task.ts +34 -0
- package/src/cache/cache-key-utils.ts +44 -0
- package/src/cache/cache-policy.ts +125 -0
- package/src/cache/cache-runtime.ts +338 -0
- package/src/cache/cache-scope.ts +120 -303
- package/src/cache/cf/cf-cache-store.ts +119 -7
- package/src/cache/cf/index.ts +8 -2
- package/src/cache/document-cache.ts +101 -72
- package/src/cache/handle-capture.ts +81 -0
- package/src/cache/handle-snapshot.ts +41 -0
- package/src/cache/index.ts +0 -15
- package/src/cache/memory-segment-store.ts +191 -13
- package/src/cache/profile-registry.ts +73 -0
- package/src/cache/read-through-swr.ts +134 -0
- package/src/cache/segment-codec.ts +256 -0
- package/src/cache/taint.ts +98 -0
- package/src/cache/types.ts +72 -122
- package/src/client.rsc.tsx +3 -1
- package/src/client.tsx +106 -126
- package/src/component-utils.ts +4 -4
- package/src/components/DefaultDocument.tsx +5 -1
- package/src/context-var.ts +86 -0
- package/src/debug.ts +17 -7
- package/src/errors.ts +108 -2
- package/src/handle.ts +15 -29
- package/src/handles/MetaTags.tsx +73 -20
- package/src/handles/breadcrumbs.ts +66 -0
- package/src/handles/index.ts +1 -0
- package/src/handles/meta.ts +30 -13
- package/src/host/cookie-handler.ts +21 -15
- package/src/host/errors.ts +8 -8
- package/src/host/index.ts +4 -7
- package/src/host/pattern-matcher.ts +27 -27
- package/src/host/router.ts +61 -39
- package/src/host/testing.ts +8 -8
- package/src/host/types.ts +15 -7
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +119 -29
- package/src/index.rsc.ts +153 -19
- package/src/index.ts +211 -30
- package/src/internal-debug.ts +11 -0
- package/src/loader.rsc.ts +26 -157
- package/src/loader.ts +27 -10
- package/src/network-error-thrower.tsx +3 -1
- package/src/outlet-provider.tsx +45 -0
- package/src/prerender/param-hash.ts +37 -0
- package/src/prerender/store.ts +185 -0
- package/src/prerender.ts +463 -0
- package/src/reverse.ts +330 -0
- package/src/root-error-boundary.tsx +41 -29
- package/src/route-content-wrapper.tsx +7 -4
- package/src/route-definition/dsl-helpers.ts +934 -0
- package/src/route-definition/helper-factories.ts +200 -0
- package/src/route-definition/helpers-types.ts +430 -0
- package/src/route-definition/index.ts +52 -0
- package/src/route-definition/redirect.ts +93 -0
- package/src/route-definition.ts +1 -1428
- package/src/route-map-builder.ts +211 -123
- package/src/route-name.ts +53 -0
- package/src/route-types.ts +59 -8
- package/src/router/content-negotiation.ts +116 -0
- package/src/router/debug-manifest.ts +72 -0
- package/src/router/error-handling.ts +9 -9
- package/src/router/find-match.ts +158 -0
- package/src/router/handler-context.ts +374 -81
- package/src/router/intercept-resolution.ts +395 -0
- package/src/router/lazy-includes.ts +234 -0
- package/src/router/loader-resolution.ts +215 -122
- package/src/router/logging.ts +248 -0
- package/src/router/manifest.ts +148 -35
- package/src/router/match-api.ts +620 -0
- package/src/router/match-context.ts +5 -3
- package/src/router/match-handlers.ts +440 -0
- package/src/router/match-middleware/background-revalidation.ts +80 -93
- package/src/router/match-middleware/cache-lookup.ts +382 -9
- package/src/router/match-middleware/cache-store.ts +51 -22
- package/src/router/match-middleware/intercept-resolution.ts +55 -17
- package/src/router/match-middleware/segment-resolution.ts +24 -6
- package/src/router/match-pipelines.ts +10 -45
- package/src/router/match-result.ts +34 -28
- package/src/router/metrics.ts +235 -15
- package/src/router/middleware-cookies.ts +55 -0
- package/src/router/middleware-types.ts +222 -0
- package/src/router/middleware.ts +324 -367
- package/src/router/pattern-matching.ts +211 -43
- package/src/router/prerender-match.ts +402 -0
- package/src/router/preview-match.ts +170 -0
- package/src/router/revalidation.ts +137 -38
- package/src/router/router-context.ts +36 -21
- package/src/router/router-interfaces.ts +452 -0
- package/src/router/router-options.ts +592 -0
- package/src/router/router-registry.ts +24 -0
- package/src/router/segment-resolution/fresh.ts +570 -0
- package/src/router/segment-resolution/helpers.ts +263 -0
- package/src/router/segment-resolution/loader-cache.ts +198 -0
- package/src/router/segment-resolution/revalidation.ts +1241 -0
- package/src/router/segment-resolution/static-store.ts +67 -0
- package/src/router/segment-resolution.ts +21 -0
- package/src/router/segment-wrappers.ts +289 -0
- package/src/router/telemetry-otel.ts +299 -0
- package/src/router/telemetry.ts +300 -0
- package/src/router/timeout.ts +148 -0
- package/src/router/trie-matching.ts +239 -0
- package/src/router/types.ts +77 -3
- package/src/router.ts +692 -4257
- package/src/rsc/handler-context.ts +45 -0
- package/src/rsc/handler.ts +764 -754
- package/src/rsc/helpers.ts +140 -6
- package/src/rsc/index.ts +0 -20
- package/src/rsc/loader-fetch.ts +209 -0
- package/src/rsc/manifest-init.ts +86 -0
- package/src/rsc/nonce.ts +14 -0
- package/src/rsc/origin-guard.ts +141 -0
- package/src/rsc/progressive-enhancement.ts +379 -0
- package/src/rsc/response-error.ts +37 -0
- package/src/rsc/response-route-handler.ts +347 -0
- package/src/rsc/rsc-rendering.ts +235 -0
- package/src/rsc/runtime-warnings.ts +42 -0
- package/src/rsc/server-action.ts +348 -0
- package/src/rsc/ssr-setup.ts +128 -0
- package/src/rsc/types.ts +38 -11
- package/src/search-params.ts +230 -0
- package/src/segment-system.tsx +25 -13
- package/src/server/context.ts +182 -51
- package/src/server/cookie-store.ts +190 -0
- package/src/server/fetchable-loader-store.ts +37 -0
- package/src/server/handle-store.ts +94 -15
- package/src/server/loader-registry.ts +15 -56
- package/src/server/request-context.ts +430 -70
- package/src/server.ts +35 -130
- package/src/ssr/index.tsx +100 -31
- package/src/static-handler.ts +114 -0
- package/src/theme/ThemeProvider.tsx +21 -15
- package/src/theme/ThemeScript.tsx +5 -5
- package/src/theme/constants.ts +5 -2
- package/src/theme/index.ts +4 -14
- package/src/theme/theme-context.ts +4 -30
- package/src/theme/theme-script.ts +21 -18
- package/src/types/boundaries.ts +158 -0
- package/src/types/cache-types.ts +198 -0
- package/src/types/error-types.ts +192 -0
- package/src/types/global-namespace.ts +100 -0
- package/src/types/handler-context.ts +687 -0
- package/src/types/index.ts +88 -0
- package/src/types/loader-types.ts +183 -0
- package/src/types/route-config.ts +170 -0
- package/src/types/route-entry.ts +102 -0
- package/src/types/segments.ts +148 -0
- package/src/types.ts +1 -1623
- package/src/urls/include-helper.ts +197 -0
- package/src/urls/index.ts +53 -0
- package/src/urls/path-helper-types.ts +339 -0
- package/src/urls/path-helper.ts +329 -0
- package/src/urls/pattern-types.ts +95 -0
- package/src/urls/response-types.ts +106 -0
- package/src/urls/type-extraction.ts +372 -0
- package/src/urls/urls-function.ts +98 -0
- package/src/urls.ts +1 -802
- package/src/use-loader.tsx +85 -77
- package/src/vite/discovery/bundle-postprocess.ts +184 -0
- package/src/vite/discovery/discover-routers.ts +344 -0
- package/src/vite/discovery/prerender-collection.ts +385 -0
- package/src/vite/discovery/route-types-writer.ts +258 -0
- package/src/vite/discovery/self-gen-tracking.ts +47 -0
- package/src/vite/discovery/state.ts +110 -0
- package/src/vite/discovery/virtual-module-codegen.ts +203 -0
- package/src/vite/index.ts +11 -1133
- package/src/vite/plugin-types.ts +131 -0
- package/src/vite/plugins/cjs-to-esm.ts +93 -0
- package/src/vite/plugins/client-ref-dedup.ts +115 -0
- package/src/vite/plugins/client-ref-hashing.ts +105 -0
- package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -51
- package/src/vite/plugins/expose-id-utils.ts +287 -0
- package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
- package/src/vite/plugins/expose-ids/handler-transform.ts +179 -0
- package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
- package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
- package/src/vite/plugins/expose-ids/types.ts +45 -0
- package/src/vite/plugins/expose-internal-ids.ts +569 -0
- package/src/vite/plugins/refresh-cmd.ts +65 -0
- package/src/vite/plugins/use-cache-transform.ts +323 -0
- package/src/vite/plugins/version-injector.ts +83 -0
- package/src/vite/plugins/version-plugin.ts +254 -0
- package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
- package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
- package/src/vite/rango.ts +510 -0
- package/src/vite/router-discovery.ts +785 -0
- package/src/vite/utils/ast-handler-extract.ts +517 -0
- package/src/vite/utils/banner.ts +36 -0
- package/src/vite/utils/bundle-analysis.ts +137 -0
- package/src/vite/utils/manifest-utils.ts +70 -0
- package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
- package/src/vite/utils/prerender-utils.ts +189 -0
- package/src/vite/utils/shared-utils.ts +169 -0
- package/CLAUDE.md +0 -43
- package/src/browser/lru-cache.ts +0 -69
- package/src/browser/request-controller.ts +0 -164
- package/src/cache/memory-store.ts +0 -253
- package/src/href-context.ts +0 -33
- package/src/href.ts +0 -255
- package/src/server/route-manifest-cache.ts +0 -173
- package/src/vite/expose-handle-id.ts +0 -209
- package/src/vite/expose-loader-id.ts +0 -426
- package/src/vite/expose-location-state-id.ts +0 -177
- /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/src/rsc/handler.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="@vitejs/plugin-rsc/types" />
|
|
2
|
-
/// <reference path="../vite/version.d.ts" />
|
|
2
|
+
/// <reference path="../vite/plugins/version.d.ts" />
|
|
3
3
|
/**
|
|
4
4
|
* RSC Request Handler
|
|
5
5
|
*
|
|
@@ -8,36 +8,80 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { createElement } from "react";
|
|
11
|
-
import { renderSegments } from "../segment-system.js";
|
|
12
11
|
import { RouteNotFoundError } from "../errors.js";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
matchMiddleware,
|
|
16
|
-
executeMiddleware,
|
|
17
|
-
executeLoaderMiddleware,
|
|
18
|
-
} from "../router/middleware.js";
|
|
12
|
+
import { matchMiddleware, executeMiddleware } from "../router/middleware.js";
|
|
19
13
|
import {
|
|
20
14
|
runWithRequestContext,
|
|
21
15
|
setRequestContextParams,
|
|
22
16
|
requireRequestContext,
|
|
23
17
|
createRequestContext,
|
|
24
|
-
type ExecutionContext,
|
|
25
18
|
} from "../server/request-context.js";
|
|
26
19
|
import * as rscDeps from "@vitejs/plugin-rsc/rsc";
|
|
27
20
|
|
|
28
21
|
import type {
|
|
29
22
|
RscPayload,
|
|
30
|
-
ReactFormState,
|
|
31
23
|
CreateRSCHandlerOptions,
|
|
24
|
+
LoadSSRModule,
|
|
25
|
+
SSRModule,
|
|
32
26
|
} from "./types.js";
|
|
33
|
-
import {
|
|
34
|
-
|
|
27
|
+
import {
|
|
28
|
+
createResponseWithMergedHeaders,
|
|
29
|
+
finalizeResponse,
|
|
30
|
+
interceptRedirectForPartial,
|
|
31
|
+
buildRouteMiddlewareEntries,
|
|
32
|
+
} from "./helpers.js";
|
|
33
|
+
import {
|
|
34
|
+
handleResponseRoute,
|
|
35
|
+
type ResponseRouteMatch,
|
|
36
|
+
} from "./response-route-handler.js";
|
|
37
|
+
import { generateNonce, nonce as nonceToken } from "./nonce.js";
|
|
35
38
|
import { VERSION } from "@rangojs/router:version";
|
|
36
39
|
import type { ErrorPhase } from "../types.js";
|
|
40
|
+
import type { RouterRequestInput } from "../router/router-interfaces.js";
|
|
37
41
|
import { invokeOnError } from "../router/error-handling.js";
|
|
38
|
-
import {
|
|
39
|
-
|
|
40
|
-
|
|
42
|
+
import {
|
|
43
|
+
createReverseFunction,
|
|
44
|
+
stripInternalParams,
|
|
45
|
+
} from "../router/handler-context.js";
|
|
46
|
+
import { getRouterContext } from "../router/router-context.js";
|
|
47
|
+
import { resolveSink, safeEmit } from "../router/telemetry.js";
|
|
48
|
+
import { contextSet } from "../context-var.js";
|
|
49
|
+
import {
|
|
50
|
+
hasCachedManifest,
|
|
51
|
+
getRouteTrie,
|
|
52
|
+
getPrecomputedEntries,
|
|
53
|
+
waitForManifestReady,
|
|
54
|
+
getRouterManifest,
|
|
55
|
+
getRouterTrie,
|
|
56
|
+
} from "../route-map-builder.js";
|
|
57
|
+
import type { HandlerContext } from "./handler-context.js";
|
|
58
|
+
import { buildRouterTrieFromUrlpatterns } from "./manifest-init.js";
|
|
59
|
+
import { handleProgressiveEnhancement } from "./progressive-enhancement.js";
|
|
60
|
+
import {
|
|
61
|
+
executeServerAction,
|
|
62
|
+
revalidateAfterAction,
|
|
63
|
+
type ActionContinuation,
|
|
64
|
+
} from "./server-action.js";
|
|
65
|
+
import { handleLoaderFetch } from "./loader-fetch.js";
|
|
66
|
+
import { checkRequestOrigin, type OriginCheckPhase } from "./origin-guard.js";
|
|
67
|
+
import { handleRscRendering } from "./rsc-rendering.js";
|
|
68
|
+
import {
|
|
69
|
+
withTimeout,
|
|
70
|
+
RouterTimeoutError,
|
|
71
|
+
createDefaultTimeoutResponse,
|
|
72
|
+
type TimeoutPhase,
|
|
73
|
+
} from "../router/timeout.js";
|
|
74
|
+
import {
|
|
75
|
+
createMetricsStore,
|
|
76
|
+
appendMetric,
|
|
77
|
+
buildMetricsTiming,
|
|
78
|
+
} from "../router/metrics.js";
|
|
79
|
+
import {
|
|
80
|
+
startSSRSetup,
|
|
81
|
+
getSSRSetup,
|
|
82
|
+
mayNeedSSR,
|
|
83
|
+
SSR_SETUP_VAR,
|
|
84
|
+
} from "./ssr-setup.js";
|
|
41
85
|
|
|
42
86
|
/**
|
|
43
87
|
* Create an RSC request handler.
|
|
@@ -89,31 +133,179 @@ export function createRSCHandler<
|
|
|
89
133
|
decodeFormState,
|
|
90
134
|
} = deps;
|
|
91
135
|
|
|
92
|
-
// Use provided loadSSRModule or default to vite RSC module loader
|
|
93
|
-
|
|
136
|
+
// Use provided loadSSRModule or default to vite RSC module loader.
|
|
137
|
+
// In production the SSR module is stable across requests, so memoize
|
|
138
|
+
// the dynamic import to avoid repeated module resolution overhead.
|
|
139
|
+
// In dev mode Vite may hot-reload the module, so skip memoization.
|
|
140
|
+
const rawLoadSSRModule: LoadSSRModule =
|
|
94
141
|
options.loadSSRModule ??
|
|
95
142
|
(() => import.meta.viteRsc.loadModule("ssr", "index"));
|
|
143
|
+
let _ssrModulePromise: Promise<SSRModule> | undefined;
|
|
144
|
+
const loadSSRModule: LoadSSRModule =
|
|
145
|
+
process.env.NODE_ENV === "production"
|
|
146
|
+
? () =>
|
|
147
|
+
(_ssrModulePromise ??= rawLoadSSRModule().catch((err) => {
|
|
148
|
+
_ssrModulePromise = undefined;
|
|
149
|
+
throw err;
|
|
150
|
+
}))
|
|
151
|
+
: rawLoadSSRModule;
|
|
96
152
|
|
|
97
153
|
/**
|
|
98
|
-
*
|
|
99
|
-
*
|
|
154
|
+
* Per-request error reporter that deduplicates via the ALS request context.
|
|
155
|
+
*
|
|
156
|
+
* Uses the same _reportedErrors WeakSet as the router layer so errors
|
|
157
|
+
* that propagate across layers are only reported once per request.
|
|
100
158
|
*/
|
|
101
159
|
function callOnError(
|
|
102
160
|
error: unknown,
|
|
103
161
|
phase: ErrorPhase,
|
|
104
162
|
context: Parameters<typeof invokeOnError<TEnv>>[3],
|
|
105
163
|
): void {
|
|
164
|
+
if (error != null && typeof error === "object") {
|
|
165
|
+
const reportedErrors = requireRequestContext()._reportedErrors;
|
|
166
|
+
if (reportedErrors.has(error)) return;
|
|
167
|
+
reportedErrors.add(error);
|
|
168
|
+
}
|
|
106
169
|
invokeOnError(router.onError, error, phase, context, "RSC");
|
|
107
170
|
}
|
|
108
171
|
|
|
109
|
-
|
|
172
|
+
function getRequiredRouteMap(): Record<string, string> {
|
|
173
|
+
const routeMap = getRouterManifest(router.id);
|
|
174
|
+
if (!routeMap) {
|
|
175
|
+
throw new Error(
|
|
176
|
+
`Route manifest for router "${router.id}" is not available.`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
return routeMap;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Handle a timeout by reporting the error, emitting telemetry,
|
|
184
|
+
* and returning either the custom onTimeout response or a default 504.
|
|
185
|
+
*/
|
|
186
|
+
async function handleTimeoutResponse(
|
|
110
187
|
request: Request,
|
|
111
|
-
env: TEnv
|
|
112
|
-
|
|
188
|
+
env: TEnv,
|
|
189
|
+
url: URL,
|
|
190
|
+
phase: TimeoutPhase,
|
|
191
|
+
durationMs: number,
|
|
192
|
+
routeKey?: string,
|
|
193
|
+
actionId?: string,
|
|
194
|
+
): Promise<Response> {
|
|
195
|
+
const timeoutError = new RouterTimeoutError(phase, durationMs);
|
|
196
|
+
|
|
197
|
+
callOnError(timeoutError, phase === "action" ? "action" : "handler", {
|
|
198
|
+
request,
|
|
199
|
+
url,
|
|
200
|
+
env,
|
|
201
|
+
routeKey,
|
|
202
|
+
actionId,
|
|
203
|
+
handledByBoundary: false,
|
|
204
|
+
metadata: { timeout: true, phase, durationMs },
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
const routerCtx = getRouterContext();
|
|
209
|
+
if (routerCtx?.telemetry) {
|
|
210
|
+
safeEmit(resolveSink(routerCtx.telemetry), {
|
|
211
|
+
type: "request.timeout" as const,
|
|
212
|
+
timestamp: performance.now(),
|
|
213
|
+
requestId: routerCtx.requestId,
|
|
214
|
+
phase,
|
|
215
|
+
pathname: url.pathname,
|
|
216
|
+
routeKey,
|
|
217
|
+
actionId,
|
|
218
|
+
durationMs,
|
|
219
|
+
customHandler: !!router.onTimeout,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
} catch {
|
|
223
|
+
// Router context may not be available
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (router.onTimeout) {
|
|
227
|
+
try {
|
|
228
|
+
return await router.onTimeout({
|
|
229
|
+
phase,
|
|
230
|
+
request,
|
|
231
|
+
url,
|
|
232
|
+
env,
|
|
233
|
+
routeKey,
|
|
234
|
+
actionId,
|
|
235
|
+
durationMs,
|
|
236
|
+
});
|
|
237
|
+
} catch (e) {
|
|
238
|
+
if (process.env.NODE_ENV !== "production") {
|
|
239
|
+
console.error("[RSC] onTimeout callback error:", e);
|
|
240
|
+
}
|
|
241
|
+
return createDefaultTimeoutResponse(phase);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return createDefaultTimeoutResponse(phase);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Build a 200 Flight response that carries a redirect URL and optional state.
|
|
250
|
+
* Used when a partial/action request results in a redirect -- fetch
|
|
251
|
+
* auto-follows 3xx so we send the redirect as payload metadata instead.
|
|
252
|
+
*/
|
|
253
|
+
function createRedirectFlightResponse(
|
|
254
|
+
redirectUrl: string,
|
|
255
|
+
locationState?: Record<string, unknown>,
|
|
256
|
+
): Response {
|
|
257
|
+
const redirectPayload: RscPayload = {
|
|
258
|
+
metadata: {
|
|
259
|
+
pathname: redirectUrl,
|
|
260
|
+
segments: [],
|
|
261
|
+
redirect: { url: redirectUrl },
|
|
262
|
+
...(locationState && { locationState }),
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
const rscStream = renderToReadableStream<RscPayload>(redirectPayload);
|
|
266
|
+
return createResponseWithMergedHeaders(rscStream, {
|
|
267
|
+
status: 200,
|
|
268
|
+
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Bundle shared dependencies for extracted handler functions.
|
|
273
|
+
// callOnError reads from ALS so it's inherently per-request scoped.
|
|
274
|
+
const handlerCtx: HandlerContext<TEnv> = {
|
|
275
|
+
router,
|
|
276
|
+
version,
|
|
277
|
+
renderToReadableStream,
|
|
278
|
+
decodeReply,
|
|
279
|
+
createTemporaryReferenceSet,
|
|
280
|
+
loadServerAction,
|
|
281
|
+
decodeAction,
|
|
282
|
+
decodeFormState,
|
|
283
|
+
loadSSRModule,
|
|
284
|
+
callOnError,
|
|
285
|
+
getRequiredRouteMap,
|
|
286
|
+
createRedirectFlightResponse,
|
|
287
|
+
resolveStreamMode: async (request, env, url) => {
|
|
288
|
+
const resolver = router.ssr?.resolveStreaming;
|
|
289
|
+
if (!resolver) return "stream";
|
|
290
|
+
return resolver({ request, env, url });
|
|
113
291
|
},
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
return async function handler(
|
|
295
|
+
request: Request,
|
|
296
|
+
input: RouterRequestInput<TEnv> = {},
|
|
114
297
|
): Promise<Response> {
|
|
298
|
+
const handlerStart = performance.now();
|
|
299
|
+
// Create the metrics store at handler start so handler:total has startTime=0
|
|
300
|
+
// and all metrics are relative to the request entry point.
|
|
301
|
+
const earlyMetricsStore = router.debugPerformance
|
|
302
|
+
? createMetricsStore(true, handlerStart)
|
|
303
|
+
: undefined;
|
|
304
|
+
|
|
305
|
+
const { env = {} as TEnv, vars: initialVars, ctx: executionCtx } = input;
|
|
306
|
+
|
|
115
307
|
// Connection warmup: return 204 immediately before any processing
|
|
116
|
-
if (router
|
|
308
|
+
if (router?.warmupEnabled && request.method === "HEAD") {
|
|
117
309
|
const warmupUrl = new URL(request.url);
|
|
118
310
|
if (warmupUrl.searchParams.has("_rsc_warmup")) {
|
|
119
311
|
return new Response(null, { status: 204 });
|
|
@@ -121,25 +313,30 @@ export function createRSCHandler<
|
|
|
121
313
|
}
|
|
122
314
|
|
|
123
315
|
// Resolve nonce if provider is set
|
|
316
|
+
const nonceStart = performance.now();
|
|
124
317
|
let nonce: string | undefined;
|
|
125
318
|
if (nonceProvider) {
|
|
126
319
|
const result = await nonceProvider(request, env);
|
|
127
320
|
nonce = result === true ? generateNonce() : result;
|
|
128
321
|
}
|
|
322
|
+
const nonceDur = performance.now() - nonceStart;
|
|
129
323
|
|
|
130
324
|
const url = new URL(request.url);
|
|
131
325
|
|
|
132
326
|
// Match global middleware
|
|
327
|
+
const mwMatchStart = performance.now();
|
|
133
328
|
const matchedMiddleware = matchMiddleware(url.pathname, router.middleware);
|
|
329
|
+
const mwMatchDur = performance.now() - mwMatchStart;
|
|
134
330
|
|
|
135
331
|
// Shared variables between middleware and route handlers
|
|
136
|
-
// Initialize from
|
|
137
|
-
const variables: Record<string, any> =
|
|
138
|
-
|
|
139
|
-
|
|
332
|
+
// Initialize from input.vars if provided (allows pre-seeding from worker entry)
|
|
333
|
+
const variables: Record<string, any> = initialVars
|
|
334
|
+
? { ...initialVars }
|
|
335
|
+
: {};
|
|
140
336
|
|
|
141
|
-
// Store nonce
|
|
337
|
+
// Store nonce via ContextVar token and string key for backward compat
|
|
142
338
|
if (nonce) {
|
|
339
|
+
contextSet(variables, nonceToken, nonce);
|
|
143
340
|
variables.nonce = nonce;
|
|
144
341
|
}
|
|
145
342
|
|
|
@@ -150,43 +347,103 @@ export function createRSCHandler<
|
|
|
150
347
|
const cacheOption = options.cache ?? router.cache;
|
|
151
348
|
if (cacheOption && !url.searchParams.has("__no_cache")) {
|
|
152
349
|
const cacheConfig =
|
|
153
|
-
typeof cacheOption === "function"
|
|
350
|
+
typeof cacheOption === "function"
|
|
351
|
+
? cacheOption(env, executionCtx)
|
|
352
|
+
: cacheOption;
|
|
154
353
|
|
|
155
354
|
if (cacheConfig.enabled !== false) {
|
|
156
355
|
cacheStore = cacheConfig.store;
|
|
157
356
|
}
|
|
158
357
|
}
|
|
159
358
|
|
|
160
|
-
//
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
359
|
+
// Route manifest is populated at startup via the virtual module
|
|
360
|
+
// (virtual:rsc-router/routes-manifest). In build/production, it's inlined
|
|
361
|
+
// into the bundle. In dev mode (Node), the discovery plugin populates it
|
|
362
|
+
// via setManifestReadyPromise(). In dev mode (Cloudflare), Miniflare runs
|
|
363
|
+
// in a separate isolate where module-level state doesn't carry over, so
|
|
364
|
+
// we generate inline from the router's urlpatterns.
|
|
365
|
+
//
|
|
366
|
+
// In multi-router setups (e.g. createHostRouter), each router must have
|
|
367
|
+
// its own per-router manifest. We check per-router data first: even if
|
|
368
|
+
// the global manifest was set by a different router, this router still
|
|
369
|
+
// needs its own trie and manifest for correct matching.
|
|
370
|
+
const manifestCacheStart = performance.now();
|
|
371
|
+
const hasRouterData = getRouterManifest(router.id) !== undefined;
|
|
372
|
+
if (!hasRouterData) {
|
|
373
|
+
if (!hasCachedManifest()) {
|
|
374
|
+
const readyPromise = waitForManifestReady();
|
|
375
|
+
if (readyPromise) {
|
|
376
|
+
await readyPromise;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (!getRouterManifest(router.id) && router.urlpatterns) {
|
|
380
|
+
// Cloudflare dev: generate manifest inline for this router.
|
|
381
|
+
// Each router generates its own manifest independently so
|
|
382
|
+
// multi-router setups (host routing) work correctly.
|
|
383
|
+
await buildRouterTrieFromUrlpatterns(router);
|
|
384
|
+
}
|
|
385
|
+
if (!getRouterManifest(router.id) && !hasCachedManifest()) {
|
|
386
|
+
throw new Error(
|
|
387
|
+
'Route manifest not available. Ensure "virtual:rsc-router/routes-manifest" is imported in your entry file.',
|
|
388
|
+
);
|
|
389
|
+
}
|
|
173
390
|
}
|
|
174
391
|
|
|
175
|
-
//
|
|
176
|
-
// This
|
|
392
|
+
// Rebuild the trie when the manifest exists but the per-router trie is
|
|
393
|
+
// missing. This happens in dev mode after HMR: the virtual module sets
|
|
394
|
+
// the manifest (from fresh gen files) but the trie is intentionally not
|
|
395
|
+
// injected to avoid stale discovery-time data. Without the trie, route
|
|
396
|
+
// matching falls back to regex iteration which does not handle wildcard
|
|
397
|
+
// priority correctly (catch-all patterns match before specific routes).
|
|
398
|
+
if (!getRouterTrie(router.id) && router.urlpatterns) {
|
|
399
|
+
await buildRouterTrieFromUrlpatterns(router);
|
|
400
|
+
}
|
|
401
|
+
const manifestCacheDur = performance.now() - manifestCacheStart;
|
|
177
402
|
|
|
178
403
|
// Create unified request context with all methods
|
|
179
404
|
// Includes: stub response, handle store, loader memoization, use(), cookies, headers, cache store
|
|
180
405
|
// params starts empty, populated after route matching via setRequestContextParams
|
|
406
|
+
const ctxCreateStart = performance.now();
|
|
181
407
|
const requestContext = createRequestContext({
|
|
182
408
|
env,
|
|
183
409
|
request,
|
|
184
410
|
url,
|
|
185
411
|
variables,
|
|
186
412
|
cacheStore,
|
|
187
|
-
|
|
413
|
+
cacheProfiles: router.cacheProfiles,
|
|
414
|
+
executionContext: executionCtx,
|
|
188
415
|
themeConfig: router.themeConfig,
|
|
189
416
|
});
|
|
417
|
+
if (earlyMetricsStore) {
|
|
418
|
+
requestContext._debugPerformance = true;
|
|
419
|
+
requestContext._metricsStore = earlyMetricsStore;
|
|
420
|
+
}
|
|
421
|
+
// Wire background error reporting so "use cache" and other subsystems
|
|
422
|
+
// can surface non-fatal errors through the router's onError callback.
|
|
423
|
+
requestContext._reportBackgroundError = (
|
|
424
|
+
error: unknown,
|
|
425
|
+
category: string,
|
|
426
|
+
) => {
|
|
427
|
+
callOnError(error, "cache", {
|
|
428
|
+
request,
|
|
429
|
+
url,
|
|
430
|
+
metadata: { category },
|
|
431
|
+
});
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
const ctxCreateDur = performance.now() - ctxCreateStart;
|
|
435
|
+
|
|
436
|
+
// Accumulate handler-level timing for Server-Timing header
|
|
437
|
+
const handlerTiming = [
|
|
438
|
+
`handler-nonce;dur=${nonceDur.toFixed(2)}`,
|
|
439
|
+
`handler-mw-match;dur=${mwMatchDur.toFixed(2)}`,
|
|
440
|
+
`handler-manifest-cache;dur=${manifestCacheDur.toFixed(2)}`,
|
|
441
|
+
`handler-ctx-create;dur=${ctxCreateDur.toFixed(2)}`,
|
|
442
|
+
];
|
|
443
|
+
|
|
444
|
+
// Store timing data in variables for downstream access
|
|
445
|
+
variables.__handlerTiming = handlerTiming;
|
|
446
|
+
variables.__handlerStart = handlerStart;
|
|
190
447
|
|
|
191
448
|
// Wrap entire request handling in request context
|
|
192
449
|
// Makes context available via getRequestContext() throughout:
|
|
@@ -202,17 +459,71 @@ export function createRSCHandler<
|
|
|
202
459
|
};
|
|
203
460
|
|
|
204
461
|
// Execute middleware chain if any, otherwise call core handler directly
|
|
462
|
+
let response: Response;
|
|
205
463
|
if (matchedMiddleware.length > 0) {
|
|
206
|
-
|
|
464
|
+
const mwResponse = await executeMiddleware(
|
|
207
465
|
matchedMiddleware,
|
|
208
466
|
request,
|
|
209
467
|
env,
|
|
210
468
|
variables,
|
|
211
469
|
coreHandler,
|
|
470
|
+
createReverseFunction(getRequiredRouteMap()),
|
|
212
471
|
);
|
|
472
|
+
|
|
473
|
+
if (
|
|
474
|
+
url.searchParams.has("_rsc_partial") ||
|
|
475
|
+
url.searchParams.has("_rsc_action")
|
|
476
|
+
) {
|
|
477
|
+
const intercepted = interceptRedirectForPartial(
|
|
478
|
+
mwResponse,
|
|
479
|
+
createRedirectFlightResponse,
|
|
480
|
+
);
|
|
481
|
+
response = intercepted ?? finalizeResponse(mwResponse);
|
|
482
|
+
} else {
|
|
483
|
+
response = finalizeResponse(mwResponse);
|
|
484
|
+
}
|
|
485
|
+
} else {
|
|
486
|
+
response = await coreHandler();
|
|
213
487
|
}
|
|
214
488
|
|
|
215
|
-
|
|
489
|
+
// Finalize metrics after all middleware (including post-next work)
|
|
490
|
+
// has completed so :post spans are captured in the timeline.
|
|
491
|
+
// Handler timing parts are always emitted (even without debug metrics)
|
|
492
|
+
// so non-debug requests still get bootstrap Server-Timing entries.
|
|
493
|
+
const handlerTimingArr: string[] = variables.__handlerTiming || [];
|
|
494
|
+
// Preserve any existing Server-Timing set by response routes or middleware
|
|
495
|
+
const existingTiming = response.headers.get("Server-Timing");
|
|
496
|
+
const timingParts = existingTiming
|
|
497
|
+
? [existingTiming, ...handlerTimingArr]
|
|
498
|
+
: [...handlerTimingArr];
|
|
499
|
+
|
|
500
|
+
const metricsStore = requestContext._metricsStore;
|
|
501
|
+
if (metricsStore) {
|
|
502
|
+
// When the store was created at handler start (earlyMetricsStore),
|
|
503
|
+
// handler:total covers the full request. When ctx.debugPerformance()
|
|
504
|
+
// created the store mid-request, use its requestStart to avoid a
|
|
505
|
+
// negative startTime offset.
|
|
506
|
+
const totalStart = earlyMetricsStore
|
|
507
|
+
? handlerStart
|
|
508
|
+
: metricsStore.requestStart;
|
|
509
|
+
appendMetric(
|
|
510
|
+
metricsStore,
|
|
511
|
+
"handler:total",
|
|
512
|
+
totalStart,
|
|
513
|
+
performance.now() - totalStart,
|
|
514
|
+
);
|
|
515
|
+
const metricsTiming = buildMetricsTiming(
|
|
516
|
+
request.method,
|
|
517
|
+
url.pathname,
|
|
518
|
+
metricsStore,
|
|
519
|
+
);
|
|
520
|
+
if (metricsTiming) timingParts.push(metricsTiming);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const fullTiming = timingParts.join(", ");
|
|
524
|
+
if (fullTiming) response.headers.set("Server-Timing", fullTiming);
|
|
525
|
+
|
|
526
|
+
return response;
|
|
216
527
|
});
|
|
217
528
|
};
|
|
218
529
|
|
|
@@ -224,57 +535,314 @@ export function createRSCHandler<
|
|
|
224
535
|
variables: Record<string, any>,
|
|
225
536
|
nonce: string | undefined,
|
|
226
537
|
): Promise<Response> {
|
|
227
|
-
|
|
228
|
-
const preview = await router.previewMatch(request, env);
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
538
|
+
const previewStart = performance.now();
|
|
539
|
+
const preview = await router.previewMatch(request, { env });
|
|
540
|
+
const previewDur = performance.now() - previewStart;
|
|
541
|
+
const handlerTiming: string[] = variables.__handlerTiming || [];
|
|
542
|
+
handlerTiming.push(`handler-preview-match;dur=${previewDur.toFixed(2)}`);
|
|
543
|
+
// Response route short-circuit: skip entire RSC pipeline
|
|
544
|
+
if (preview?.responseType && preview.handler) {
|
|
545
|
+
const responseOutcome = await withTimeout(
|
|
546
|
+
handleResponseRoute(
|
|
547
|
+
handlerCtx,
|
|
548
|
+
preview as ResponseRouteMatch,
|
|
549
|
+
request,
|
|
550
|
+
env,
|
|
551
|
+
url,
|
|
552
|
+
variables,
|
|
553
|
+
),
|
|
554
|
+
router.timeouts.renderStartMs,
|
|
555
|
+
"render-start",
|
|
556
|
+
);
|
|
557
|
+
if (responseOutcome.timedOut) {
|
|
558
|
+
return handleTimeoutResponse(
|
|
559
|
+
request,
|
|
560
|
+
env,
|
|
561
|
+
url,
|
|
562
|
+
"render-start",
|
|
563
|
+
responseOutcome.durationMs,
|
|
564
|
+
preview?.routeKey,
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
return responseOutcome.result;
|
|
568
|
+
}
|
|
241
569
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
570
|
+
// Kick off SSR module loading + stream mode resolution in parallel with
|
|
571
|
+
// segment resolution. Placed after the response-route short-circuit so
|
|
572
|
+
// response/mime routes never pay for SSR work.
|
|
573
|
+
if (mayNeedSSR(request, url)) {
|
|
574
|
+
variables[SSR_SETUP_VAR] = startSSRSetup(
|
|
575
|
+
handlerCtx,
|
|
576
|
+
request,
|
|
577
|
+
env,
|
|
578
|
+
url,
|
|
579
|
+
router.debugPerformance
|
|
580
|
+
? () => requireRequestContext()._metricsStore
|
|
581
|
+
: undefined,
|
|
245
582
|
);
|
|
246
583
|
}
|
|
247
584
|
|
|
248
|
-
|
|
249
|
-
|
|
585
|
+
const routeReverse = createReverseFunction(getRequiredRouteMap());
|
|
586
|
+
|
|
587
|
+
const isAction =
|
|
588
|
+
request.headers.has("rsc-action") || url.searchParams.has("_rsc_action");
|
|
589
|
+
const isLoaderFetch = url.searchParams.has("_rsc_loader");
|
|
590
|
+
const actionId =
|
|
591
|
+
request.headers.get("rsc-action") || url.searchParams.get("_rsc_action");
|
|
592
|
+
|
|
593
|
+
// Origin guard: reject cross-origin actions, loader fetches, and
|
|
594
|
+
// PE form submissions before any execution. Regular page navigations
|
|
595
|
+
// (GET without _rsc_loader/_rsc_action) are not affected.
|
|
596
|
+
const originPhase: OriginCheckPhase | null = isAction
|
|
597
|
+
? "action"
|
|
598
|
+
: isLoaderFetch
|
|
599
|
+
? "loader"
|
|
600
|
+
: request.method === "POST"
|
|
601
|
+
? "pe-form"
|
|
602
|
+
: null;
|
|
603
|
+
if (originPhase) {
|
|
604
|
+
const originResult = await checkRequestOrigin(
|
|
605
|
+
request,
|
|
606
|
+
url,
|
|
607
|
+
router.originCheck,
|
|
608
|
+
env,
|
|
609
|
+
router.id,
|
|
610
|
+
originPhase,
|
|
611
|
+
);
|
|
612
|
+
if (originResult) {
|
|
613
|
+
const originError = new Error(
|
|
614
|
+
`Origin check rejected: ${request.headers.get("origin") ?? "none"} vs ${request.headers.get("host") ?? "none"}`,
|
|
615
|
+
);
|
|
616
|
+
originError.name = "OriginCheckError";
|
|
617
|
+
|
|
618
|
+
callOnError(originError, "origin", {
|
|
619
|
+
request,
|
|
620
|
+
url,
|
|
621
|
+
env,
|
|
622
|
+
handledByBoundary: false,
|
|
623
|
+
metadata: {
|
|
624
|
+
phase: originPhase,
|
|
625
|
+
origin: request.headers.get("origin"),
|
|
626
|
+
host: request.headers.get("host"),
|
|
627
|
+
},
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
try {
|
|
631
|
+
const routerCtx = getRouterContext();
|
|
632
|
+
if (routerCtx?.telemetry) {
|
|
633
|
+
safeEmit(resolveSink(routerCtx.telemetry), {
|
|
634
|
+
type: "request.origin-rejected" as const,
|
|
635
|
+
timestamp: performance.now(),
|
|
636
|
+
requestId: routerCtx.requestId,
|
|
637
|
+
method: request.method,
|
|
638
|
+
pathname: url.pathname,
|
|
639
|
+
phase: originPhase,
|
|
640
|
+
origin: request.headers.get("origin"),
|
|
641
|
+
host: request.headers.get("host"),
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
} catch {
|
|
645
|
+
// Router context may not be available
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
return originResult;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// Get handle store from request context
|
|
653
|
+
const handleStore = requireRequestContext()._handleStore;
|
|
654
|
+
|
|
655
|
+
// Wire up error reporting for late streaming-handle failures
|
|
656
|
+
// (LateHandlePushError: handle pushed after stream completion).
|
|
657
|
+
// Without this, these errors are only caught by React's error boundary
|
|
658
|
+
// and never reach the router's onError callback or telemetry.
|
|
659
|
+
handleStore.onError = (error: Error) => {
|
|
660
|
+
const reqCtx = requireRequestContext();
|
|
661
|
+
callOnError(error, "handler", {
|
|
662
|
+
request,
|
|
663
|
+
url,
|
|
664
|
+
routeKey: reqCtx._routeName,
|
|
665
|
+
params: reqCtx.params as Record<string, string>,
|
|
666
|
+
handledByBoundary: true,
|
|
667
|
+
});
|
|
668
|
+
try {
|
|
669
|
+
const routerCtx = getRouterContext();
|
|
670
|
+
if (routerCtx?.telemetry) {
|
|
671
|
+
safeEmit(resolveSink(routerCtx.telemetry), {
|
|
672
|
+
type: "handler.error" as const,
|
|
673
|
+
timestamp: performance.now(),
|
|
674
|
+
requestId: routerCtx.requestId,
|
|
675
|
+
error,
|
|
676
|
+
handledByBoundary: true,
|
|
677
|
+
pathname: url.pathname,
|
|
678
|
+
routeKey: reqCtx._routeName,
|
|
679
|
+
params: reqCtx.params as Record<string, string>,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
} catch {
|
|
683
|
+
// Router context may not be available (e.g. prerender path)
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
|
|
687
|
+
// Set route params early so all execution paths can access ctx.params.
|
|
688
|
+
if (preview?.params) {
|
|
689
|
+
setRequestContextParams(preview.params, preview.routeKey);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// Progressive enhancement runs before the normal action/render paths.
|
|
693
|
+
// Route middleware wraps the PE re-render so handlers see the same
|
|
694
|
+
// context variables regardless of JS/no-JS transport.
|
|
695
|
+
const progressiveResult = await handleProgressiveEnhancement(
|
|
696
|
+
handlerCtx,
|
|
697
|
+
request,
|
|
698
|
+
env,
|
|
699
|
+
url,
|
|
700
|
+
isAction,
|
|
701
|
+
handleStore,
|
|
702
|
+
nonce,
|
|
703
|
+
{
|
|
704
|
+
routeMiddleware: preview?.routeMiddleware,
|
|
705
|
+
variables,
|
|
706
|
+
routeReverse,
|
|
707
|
+
},
|
|
708
|
+
);
|
|
709
|
+
if (progressiveResult) {
|
|
710
|
+
return progressiveResult;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// --- Action execution: runs BEFORE route middleware ---
|
|
714
|
+
// Route middleware wraps rendering only. For actions, the action runs
|
|
715
|
+
// first in the global middleware context, then route middleware wraps
|
|
716
|
+
// the revalidation pass (identical to a normal render).
|
|
717
|
+
let actionContinuation: ActionContinuation | undefined;
|
|
718
|
+
if (isAction && actionId) {
|
|
719
|
+
try {
|
|
720
|
+
const actionOutcome = await withTimeout(
|
|
721
|
+
executeServerAction(
|
|
722
|
+
handlerCtx,
|
|
723
|
+
request,
|
|
724
|
+
env,
|
|
725
|
+
url,
|
|
726
|
+
actionId,
|
|
727
|
+
handleStore,
|
|
728
|
+
),
|
|
729
|
+
router.timeouts.actionMs,
|
|
730
|
+
"action",
|
|
731
|
+
);
|
|
732
|
+
if (actionOutcome.timedOut) {
|
|
733
|
+
return handleTimeoutResponse(
|
|
734
|
+
request,
|
|
735
|
+
env,
|
|
736
|
+
url,
|
|
737
|
+
"action",
|
|
738
|
+
actionOutcome.durationMs,
|
|
739
|
+
preview?.routeKey,
|
|
740
|
+
actionId,
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
const result = actionOutcome.result;
|
|
744
|
+
// Response means redirect or error boundary — done.
|
|
745
|
+
if (result instanceof Response) return result;
|
|
746
|
+
actionContinuation = result;
|
|
747
|
+
} catch (error) {
|
|
748
|
+
callOnError(error, "action", {
|
|
749
|
+
request,
|
|
750
|
+
url,
|
|
751
|
+
env,
|
|
752
|
+
actionId,
|
|
753
|
+
handledByBoundary: false,
|
|
754
|
+
});
|
|
755
|
+
console.error(`[RSC] Action error:`, error);
|
|
756
|
+
throw error;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// --- Rendering (action revalidation or navigation) ---
|
|
761
|
+
// Route middleware wraps this — same code path for both cases.
|
|
762
|
+
const renderHandler = async () => {
|
|
763
|
+
const response = await coreRequestHandlerInner(
|
|
764
|
+
request,
|
|
765
|
+
env,
|
|
766
|
+
url,
|
|
767
|
+
variables,
|
|
768
|
+
nonce,
|
|
769
|
+
preview?.params,
|
|
770
|
+
preview?.routeKey,
|
|
771
|
+
handleStore,
|
|
772
|
+
actionContinuation,
|
|
773
|
+
);
|
|
774
|
+
if (preview?.negotiated) {
|
|
775
|
+
response.headers.append("Vary", "Accept");
|
|
776
|
+
}
|
|
777
|
+
return response;
|
|
778
|
+
};
|
|
779
|
+
|
|
780
|
+
// Wrap the render path (with or without route middleware) in a
|
|
781
|
+
// renderStartMs timeout so slow renders are caught before output.
|
|
782
|
+
const executeRender = async (): Promise<Response> => {
|
|
783
|
+
if (preview?.routeMiddleware && preview.routeMiddleware.length > 0) {
|
|
784
|
+
const mwResponse = await executeMiddleware(
|
|
785
|
+
buildRouteMiddlewareEntries<TEnv>(preview.routeMiddleware),
|
|
786
|
+
request,
|
|
787
|
+
env,
|
|
788
|
+
variables,
|
|
789
|
+
renderHandler,
|
|
790
|
+
routeReverse,
|
|
791
|
+
);
|
|
792
|
+
|
|
793
|
+
if (
|
|
794
|
+
url.searchParams.has("_rsc_partial") ||
|
|
795
|
+
url.searchParams.has("_rsc_action")
|
|
796
|
+
) {
|
|
797
|
+
const intercepted = interceptRedirectForPartial(
|
|
798
|
+
mwResponse,
|
|
799
|
+
createRedirectFlightResponse,
|
|
800
|
+
);
|
|
801
|
+
if (intercepted) return intercepted;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
return finalizeResponse(mwResponse);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// No route middleware, proceed directly
|
|
808
|
+
return renderHandler();
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
const renderOutcome = await withTimeout(
|
|
812
|
+
executeRender(),
|
|
813
|
+
router.timeouts.renderStartMs,
|
|
814
|
+
"render-start",
|
|
815
|
+
);
|
|
816
|
+
if (renderOutcome.timedOut) {
|
|
817
|
+
return handleTimeoutResponse(
|
|
818
|
+
request,
|
|
819
|
+
env,
|
|
820
|
+
url,
|
|
821
|
+
"render-start",
|
|
822
|
+
renderOutcome.durationMs,
|
|
823
|
+
preview?.routeKey,
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
return renderOutcome.result;
|
|
250
827
|
}
|
|
251
828
|
|
|
252
|
-
// Inner request handler
|
|
829
|
+
// Inner request handler: rendering logic wrapped by route middleware.
|
|
830
|
+
// Handles action revalidation (when actionContinuation is present),
|
|
831
|
+
// loader fetches, and regular RSC rendering.
|
|
253
832
|
async function coreRequestHandlerInner(
|
|
254
833
|
request: Request,
|
|
255
834
|
env: TEnv,
|
|
256
835
|
url: URL,
|
|
257
836
|
variables: Record<string, any>,
|
|
258
837
|
nonce: string | undefined,
|
|
838
|
+
routeParams?: Record<string, string>,
|
|
839
|
+
routeKey?: string,
|
|
840
|
+
handleStore?: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
841
|
+
actionContinuation?: ActionContinuation,
|
|
259
842
|
): Promise<Response> {
|
|
260
|
-
// Early return for static file requests that don't need RSC handling
|
|
261
|
-
if (url.pathname === "/favicon.ico" || url.pathname === "/robots.txt") {
|
|
262
|
-
return new Response(null, { status: 404 });
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// Debug endpoint - only in development
|
|
266
|
-
if (url.pathname === "/__debug_manifest" && process.env.NODE_ENV !== "production") {
|
|
267
|
-
const manifest = await router.debugManifest();
|
|
268
|
-
return new Response(JSON.stringify(manifest, null, 2), {
|
|
269
|
-
headers: { "Content-Type": "application/json" },
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
|
|
273
843
|
const isPartial = url.searchParams.has("_rsc_partial");
|
|
274
844
|
const isAction =
|
|
275
845
|
request.headers.has("rsc-action") || url.searchParams.has("_rsc_action");
|
|
276
|
-
const actionId =
|
|
277
|
-
request.headers.get("rsc-action") || url.searchParams.get("_rsc_action");
|
|
278
846
|
|
|
279
847
|
// Version mismatch detection - client may have stale code after HMR/deployment
|
|
280
848
|
// If versions don't match, tell the client to reload
|
|
@@ -284,20 +852,23 @@ export function createRSCHandler<
|
|
|
284
852
|
`[RSC] Version mismatch: client=${clientVersion}, server=${version}. Forcing reload.`,
|
|
285
853
|
);
|
|
286
854
|
|
|
287
|
-
//
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
855
|
+
// For actions, reload current page (referer) if same origin.
|
|
856
|
+
// For navigation, load the target URL.
|
|
857
|
+
// Validate referer origin to prevent open redirect via crafted header.
|
|
858
|
+
let reloadUrl = stripInternalParams(url).toString();
|
|
859
|
+
if (isAction) {
|
|
860
|
+
const referer = request.headers.get("referer");
|
|
861
|
+
if (referer) {
|
|
862
|
+
try {
|
|
863
|
+
const refererUrl = new URL(referer);
|
|
864
|
+
if (refererUrl.origin === url.origin) {
|
|
865
|
+
reloadUrl = referer;
|
|
866
|
+
}
|
|
867
|
+
} catch {
|
|
868
|
+
// Malformed referer, fall back to cleanUrl
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
301
872
|
|
|
302
873
|
// Return special response that tells client to reload
|
|
303
874
|
return createResponseWithMergedHeaders(null, {
|
|
@@ -308,31 +879,56 @@ export function createRSCHandler<
|
|
|
308
879
|
},
|
|
309
880
|
});
|
|
310
881
|
}
|
|
882
|
+
// Debug manifest endpoint: ?__debug_manifest on any route.
|
|
883
|
+
// Always available in dev, requires allowDebugManifest option in production.
|
|
884
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
885
|
+
if (
|
|
886
|
+
url.searchParams.has("__debug_manifest") &&
|
|
887
|
+
(isDev || router.allowDebugManifest)
|
|
888
|
+
) {
|
|
889
|
+
const trie = getRouterTrie(router.id) ?? getRouteTrie();
|
|
890
|
+
const routeManifest = getRequiredRouteMap();
|
|
891
|
+
const { extractAncestryFromTrie } =
|
|
892
|
+
await import("../build/route-trie.js");
|
|
893
|
+
return new Response(
|
|
894
|
+
JSON.stringify(
|
|
895
|
+
{
|
|
896
|
+
routerId: router.id,
|
|
897
|
+
routeManifest,
|
|
898
|
+
routeAncestry: trie ? extractAncestryFromTrie(trie) : {},
|
|
899
|
+
routeTrie: trie,
|
|
900
|
+
precomputedEntries: getPrecomputedEntries(),
|
|
901
|
+
},
|
|
902
|
+
null,
|
|
903
|
+
2,
|
|
904
|
+
),
|
|
905
|
+
{
|
|
906
|
+
headers: { "Content-Type": "application/json" },
|
|
907
|
+
},
|
|
908
|
+
);
|
|
909
|
+
}
|
|
311
910
|
|
|
312
|
-
|
|
313
|
-
const handleStore = requireRequestContext()._handleStore;
|
|
911
|
+
const store = handleStore ?? requireRequestContext()._handleStore;
|
|
314
912
|
|
|
315
913
|
try {
|
|
316
|
-
//
|
|
317
|
-
//
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
request,
|
|
321
|
-
env,
|
|
322
|
-
url,
|
|
323
|
-
isAction,
|
|
324
|
-
handleStore,
|
|
325
|
-
nonce,
|
|
326
|
-
);
|
|
327
|
-
if (progressiveResult) {
|
|
328
|
-
return progressiveResult;
|
|
914
|
+
// Route params were already set in coreRequestHandler, but set again
|
|
915
|
+
// for callers that enter coreRequestHandlerInner directly.
|
|
916
|
+
if (routeParams) {
|
|
917
|
+
setRequestContextParams(routeParams, routeKey);
|
|
329
918
|
}
|
|
330
919
|
|
|
331
920
|
// ============================================================================
|
|
332
|
-
//
|
|
921
|
+
// ACTION REVALIDATION (action already executed, revalidate segments)
|
|
333
922
|
// ============================================================================
|
|
334
|
-
if (
|
|
335
|
-
return
|
|
923
|
+
if (actionContinuation) {
|
|
924
|
+
return await revalidateAfterAction(
|
|
925
|
+
handlerCtx,
|
|
926
|
+
request,
|
|
927
|
+
env,
|
|
928
|
+
url,
|
|
929
|
+
store,
|
|
930
|
+
actionContinuation,
|
|
931
|
+
);
|
|
336
932
|
}
|
|
337
933
|
|
|
338
934
|
// ============================================================================
|
|
@@ -340,7 +936,14 @@ export function createRSCHandler<
|
|
|
340
936
|
// ============================================================================
|
|
341
937
|
const isLoaderRequest = url.searchParams.has("_rsc_loader");
|
|
342
938
|
if (isLoaderRequest) {
|
|
343
|
-
return handleLoaderFetch(
|
|
939
|
+
return handleLoaderFetch(
|
|
940
|
+
handlerCtx,
|
|
941
|
+
request,
|
|
942
|
+
env,
|
|
943
|
+
url,
|
|
944
|
+
variables,
|
|
945
|
+
routeParams,
|
|
946
|
+
);
|
|
344
947
|
}
|
|
345
948
|
|
|
346
949
|
// ============================================================================
|
|
@@ -348,16 +951,44 @@ export function createRSCHandler<
|
|
|
348
951
|
// ============================================================================
|
|
349
952
|
// Note: Must use "return await" for try/catch to catch async rejections
|
|
350
953
|
return await handleRscRendering(
|
|
954
|
+
handlerCtx,
|
|
351
955
|
request,
|
|
352
956
|
env,
|
|
353
957
|
url,
|
|
354
958
|
isPartial,
|
|
355
|
-
|
|
959
|
+
store,
|
|
356
960
|
nonce,
|
|
357
961
|
);
|
|
358
962
|
} catch (error) {
|
|
359
963
|
// Check if middleware/handler returned Response
|
|
360
964
|
if (error instanceof Response) {
|
|
965
|
+
// During partial (client-side navigation), a 200 Response from a handler
|
|
966
|
+
// means the route serves raw content (JSON, text, etc.), not JSX.
|
|
967
|
+
// Signal the browser to hard-navigate so it renders the raw response.
|
|
968
|
+
// Only for 200 — redirects (3xx) work already because the browser follows
|
|
969
|
+
// them automatically to a URL that serves Flight data.
|
|
970
|
+
if (isPartial && error.status === 200) {
|
|
971
|
+
console.warn(
|
|
972
|
+
`[RSC] Route handler at ${url.pathname} returned a Response during client-side navigation. ` +
|
|
973
|
+
`Falling back to hard navigation. Use data-external on the <Link> to avoid the extra round-trip.`,
|
|
974
|
+
);
|
|
975
|
+
return createResponseWithMergedHeaders(null, {
|
|
976
|
+
status: 200,
|
|
977
|
+
headers: {
|
|
978
|
+
"X-RSC-Reload": stripInternalParams(url).toString(),
|
|
979
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
980
|
+
},
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
if (isPartial) {
|
|
985
|
+
const intercepted = interceptRedirectForPartial(
|
|
986
|
+
error,
|
|
987
|
+
createRedirectFlightResponse,
|
|
988
|
+
);
|
|
989
|
+
if (intercepted) return intercepted;
|
|
990
|
+
}
|
|
991
|
+
|
|
361
992
|
return error;
|
|
362
993
|
}
|
|
363
994
|
|
|
@@ -391,21 +1022,15 @@ export function createRSCHandler<
|
|
|
391
1022
|
params: {},
|
|
392
1023
|
};
|
|
393
1024
|
|
|
394
|
-
// Render with rootLayout to maintain app shell
|
|
395
|
-
const root = await renderSegments([notFoundSegment], {
|
|
396
|
-
rootLayout: router.rootLayout,
|
|
397
|
-
// No routeName for not-found routes
|
|
398
|
-
});
|
|
399
|
-
|
|
400
1025
|
const payload: RscPayload = {
|
|
401
|
-
root,
|
|
402
1026
|
metadata: {
|
|
403
1027
|
pathname: url.pathname,
|
|
404
1028
|
segments: [notFoundSegment],
|
|
405
1029
|
matched: [],
|
|
406
1030
|
diff: [],
|
|
407
1031
|
isPartial: false,
|
|
408
|
-
|
|
1032
|
+
rootLayout: router.rootLayout,
|
|
1033
|
+
handles: store.stream(),
|
|
409
1034
|
version,
|
|
410
1035
|
themeConfig: router.themeConfig,
|
|
411
1036
|
warmupEnabled: router.warmupEnabled,
|
|
@@ -416,8 +1041,10 @@ export function createRSCHandler<
|
|
|
416
1041
|
|
|
417
1042
|
const rscStream = renderToReadableStream(payload);
|
|
418
1043
|
|
|
419
|
-
// Determine if this is an RSC request or HTML request
|
|
1044
|
+
// Determine if this is an RSC request or HTML request.
|
|
1045
|
+
// Partial requests are always RSC (see main isRscRequest comment).
|
|
420
1046
|
const isRscRequest =
|
|
1047
|
+
isPartial ||
|
|
421
1048
|
(!request.headers.get("accept")?.includes("text/html") &&
|
|
422
1049
|
!url.searchParams.has("__html")) ||
|
|
423
1050
|
url.searchParams.has("__rsc");
|
|
@@ -429,9 +1056,18 @@ export function createRSCHandler<
|
|
|
429
1056
|
});
|
|
430
1057
|
}
|
|
431
1058
|
|
|
432
|
-
// Delegate to SSR for HTML response
|
|
433
|
-
const ssrModule = await
|
|
434
|
-
|
|
1059
|
+
// Delegate to SSR for HTML response (reuse early setup if available)
|
|
1060
|
+
const [ssrModule, streamMode] = await getSSRSetup(
|
|
1061
|
+
handlerCtx,
|
|
1062
|
+
request,
|
|
1063
|
+
env,
|
|
1064
|
+
url,
|
|
1065
|
+
requireRequestContext()._metricsStore,
|
|
1066
|
+
);
|
|
1067
|
+
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
1068
|
+
nonce,
|
|
1069
|
+
streamMode,
|
|
1070
|
+
});
|
|
435
1071
|
|
|
436
1072
|
return createResponseWithMergedHeaders(htmlStream, {
|
|
437
1073
|
status: 404,
|
|
@@ -450,630 +1086,4 @@ export function createRSCHandler<
|
|
|
450
1086
|
throw error;
|
|
451
1087
|
}
|
|
452
1088
|
}
|
|
453
|
-
|
|
454
|
-
// ============================================================================
|
|
455
|
-
// PROGRESSIVE ENHANCEMENT HANDLER
|
|
456
|
-
// When JavaScript is disabled, React renders forms with hidden fields
|
|
457
|
-
// ($ACTION_REF_*, $ACTION_KEY) containing the action reference.
|
|
458
|
-
// We detect these and return HTML instead of RSC stream.
|
|
459
|
-
// ============================================================================
|
|
460
|
-
async function handleProgressiveEnhancement(
|
|
461
|
-
request: Request,
|
|
462
|
-
env: TEnv,
|
|
463
|
-
url: URL,
|
|
464
|
-
isAction: boolean,
|
|
465
|
-
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
466
|
-
nonce: string | undefined,
|
|
467
|
-
): Promise<Response | null> {
|
|
468
|
-
const contentType = request.headers.get("content-type") || "";
|
|
469
|
-
const isFormSubmission =
|
|
470
|
-
contentType.includes("multipart/form-data") ||
|
|
471
|
-
contentType.includes("application/x-www-form-urlencoded");
|
|
472
|
-
|
|
473
|
-
if (request.method !== "POST" || isAction || !isFormSubmission) {
|
|
474
|
-
return null;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
// Clone the request to read FormData without consuming it
|
|
478
|
-
const formData = await request.clone().formData();
|
|
479
|
-
|
|
480
|
-
// Look for React's progressive enhancement hidden fields
|
|
481
|
-
let isDirectAction = false;
|
|
482
|
-
let isUseActionState = false;
|
|
483
|
-
let directActionId: string | null = null;
|
|
484
|
-
|
|
485
|
-
formData.forEach((_value, key) => {
|
|
486
|
-
if (key.startsWith("$ACTION_ID_")) {
|
|
487
|
-
isDirectAction = true;
|
|
488
|
-
directActionId = key.slice("$ACTION_ID_".length);
|
|
489
|
-
} else if (key.startsWith("$ACTION_REF_")) {
|
|
490
|
-
isUseActionState = true;
|
|
491
|
-
}
|
|
492
|
-
});
|
|
493
|
-
|
|
494
|
-
if (!isDirectAction && !isUseActionState) {
|
|
495
|
-
return null;
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
// Execute action and return HTML
|
|
499
|
-
let actionResult: unknown = undefined;
|
|
500
|
-
let reactFormState: ReactFormState | null = null;
|
|
501
|
-
|
|
502
|
-
if (isUseActionState) {
|
|
503
|
-
try {
|
|
504
|
-
const boundAction = await decodeAction(formData);
|
|
505
|
-
actionResult = await boundAction();
|
|
506
|
-
} catch (error) {
|
|
507
|
-
callOnError(error, "action", {
|
|
508
|
-
request,
|
|
509
|
-
url,
|
|
510
|
-
env,
|
|
511
|
-
handledByBoundary: false,
|
|
512
|
-
});
|
|
513
|
-
console.error("[RSC] Progressive enhancement action error:", error);
|
|
514
|
-
}
|
|
515
|
-
} else if (isDirectAction && directActionId) {
|
|
516
|
-
const temporaryReferences = createTemporaryReferenceSet();
|
|
517
|
-
|
|
518
|
-
let args: unknown[] = [];
|
|
519
|
-
try {
|
|
520
|
-
args = await decodeReply(formData, { temporaryReferences });
|
|
521
|
-
} catch {
|
|
522
|
-
args = [formData];
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
try {
|
|
526
|
-
const loadedAction = await loadServerAction(directActionId);
|
|
527
|
-
actionResult = await loadedAction.apply(null, args);
|
|
528
|
-
} catch (error) {
|
|
529
|
-
callOnError(error, "action", {
|
|
530
|
-
request,
|
|
531
|
-
url,
|
|
532
|
-
env,
|
|
533
|
-
actionId: directActionId,
|
|
534
|
-
handledByBoundary: false,
|
|
535
|
-
});
|
|
536
|
-
console.error("[RSC] Progressive enhancement action error:", error);
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// Decode form state for useActionState progressive enhancement
|
|
541
|
-
try {
|
|
542
|
-
reactFormState = await decodeFormState(actionResult, formData);
|
|
543
|
-
} catch (error) {
|
|
544
|
-
callOnError(error, "action", {
|
|
545
|
-
request,
|
|
546
|
-
url,
|
|
547
|
-
env,
|
|
548
|
-
handledByBoundary: false,
|
|
549
|
-
});
|
|
550
|
-
console.error("[RSC] Failed to decode form state:", error);
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
// Re-render the page and return HTML
|
|
554
|
-
const renderRequest = new Request(url.toString(), {
|
|
555
|
-
method: "GET",
|
|
556
|
-
headers: new Headers({ accept: "text/html" }),
|
|
557
|
-
});
|
|
558
|
-
|
|
559
|
-
const match = await router.match(renderRequest, env);
|
|
560
|
-
|
|
561
|
-
if (match.redirect) {
|
|
562
|
-
return new Response(null, {
|
|
563
|
-
status: 308,
|
|
564
|
-
headers: { Location: match.redirect },
|
|
565
|
-
});
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
const root = renderSegments(match.segments, {
|
|
569
|
-
rootLayout: router.rootLayout,
|
|
570
|
-
});
|
|
571
|
-
|
|
572
|
-
const payload: RscPayload = {
|
|
573
|
-
root,
|
|
574
|
-
metadata: {
|
|
575
|
-
pathname: url.pathname,
|
|
576
|
-
segments: match.segments,
|
|
577
|
-
matched: match.matched,
|
|
578
|
-
diff: match.diff,
|
|
579
|
-
isPartial: false,
|
|
580
|
-
rootLayout: router.rootLayout,
|
|
581
|
-
handles: handleStore.stream(),
|
|
582
|
-
version,
|
|
583
|
-
themeConfig: router.themeConfig,
|
|
584
|
-
warmupEnabled: router.warmupEnabled,
|
|
585
|
-
initialTheme: requireRequestContext().theme,
|
|
586
|
-
},
|
|
587
|
-
formState: actionResult,
|
|
588
|
-
};
|
|
589
|
-
|
|
590
|
-
const rscStream = renderToReadableStream<RscPayload>(payload);
|
|
591
|
-
const ssrModule = await loadSSRModule();
|
|
592
|
-
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
593
|
-
formState: reactFormState,
|
|
594
|
-
nonce,
|
|
595
|
-
});
|
|
596
|
-
|
|
597
|
-
return new Response(htmlStream, {
|
|
598
|
-
headers: { "content-type": "text/html;charset=utf-8" },
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
// ============================================================================
|
|
603
|
-
// SERVER ACTION HANDLER
|
|
604
|
-
// ============================================================================
|
|
605
|
-
async function handleServerAction(
|
|
606
|
-
request: Request,
|
|
607
|
-
env: TEnv,
|
|
608
|
-
url: URL,
|
|
609
|
-
actionId: string,
|
|
610
|
-
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
611
|
-
): Promise<Response> {
|
|
612
|
-
const temporaryReferences = createTemporaryReferenceSet();
|
|
613
|
-
|
|
614
|
-
// Decode action arguments from request body
|
|
615
|
-
const contentType = request.headers.get("content-type") || "";
|
|
616
|
-
let args: unknown[] = [];
|
|
617
|
-
let actionFormData: FormData | undefined;
|
|
618
|
-
|
|
619
|
-
try {
|
|
620
|
-
const body = contentType.includes("multipart/form-data")
|
|
621
|
-
? await request.formData()
|
|
622
|
-
: await request.text();
|
|
623
|
-
|
|
624
|
-
if (body instanceof FormData) {
|
|
625
|
-
actionFormData = body;
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
if (hasBodyContent(body)) {
|
|
629
|
-
args = await decodeReply(body, { temporaryReferences });
|
|
630
|
-
}
|
|
631
|
-
} catch (error) {
|
|
632
|
-
callOnError(error, "action", {
|
|
633
|
-
request,
|
|
634
|
-
url,
|
|
635
|
-
env,
|
|
636
|
-
actionId,
|
|
637
|
-
handledByBoundary: false,
|
|
638
|
-
});
|
|
639
|
-
throw new Error(`Failed to decode action arguments: ${error}`, {
|
|
640
|
-
cause: error,
|
|
641
|
-
});
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
// Execute the server action
|
|
645
|
-
let returnValue: { ok: boolean; data: unknown };
|
|
646
|
-
let actionStatus = 200;
|
|
647
|
-
let loadedAction: Function | undefined;
|
|
648
|
-
|
|
649
|
-
try {
|
|
650
|
-
loadedAction = await loadServerAction(actionId);
|
|
651
|
-
const data = await loadedAction!.apply(null, args);
|
|
652
|
-
returnValue = { ok: true, data };
|
|
653
|
-
} catch (error) {
|
|
654
|
-
returnValue = { ok: false, data: error };
|
|
655
|
-
actionStatus = 500;
|
|
656
|
-
|
|
657
|
-
// Try to render error boundary
|
|
658
|
-
const errorResult = await router.matchError(request, env, error, "route");
|
|
659
|
-
|
|
660
|
-
// Report the action error (handledByBoundary indicates if error boundary will render)
|
|
661
|
-
callOnError(error, "action", {
|
|
662
|
-
request,
|
|
663
|
-
url,
|
|
664
|
-
env,
|
|
665
|
-
actionId,
|
|
666
|
-
handledByBoundary: !!errorResult,
|
|
667
|
-
});
|
|
668
|
-
|
|
669
|
-
if (errorResult) {
|
|
670
|
-
setRequestContextParams(errorResult.params);
|
|
671
|
-
|
|
672
|
-
const payload: RscPayload = {
|
|
673
|
-
root: null,
|
|
674
|
-
metadata: {
|
|
675
|
-
pathname: url.pathname,
|
|
676
|
-
segments: errorResult.segments,
|
|
677
|
-
isPartial: true,
|
|
678
|
-
matched: errorResult.matched,
|
|
679
|
-
diff: errorResult.diff,
|
|
680
|
-
isError: true,
|
|
681
|
-
handles: handleStore.stream(),
|
|
682
|
-
version,
|
|
683
|
-
},
|
|
684
|
-
returnValue,
|
|
685
|
-
};
|
|
686
|
-
|
|
687
|
-
const rscStream = renderToReadableStream<RscPayload>(payload, {
|
|
688
|
-
temporaryReferences,
|
|
689
|
-
});
|
|
690
|
-
|
|
691
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
692
|
-
status: actionStatus,
|
|
693
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
694
|
-
});
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
// Revalidate after action
|
|
699
|
-
const resolvedActionId =
|
|
700
|
-
(loadedAction as { $id?: string; $$id?: string } | undefined)?.$id ??
|
|
701
|
-
(loadedAction as { $$id?: string } | undefined)?.$$id ??
|
|
702
|
-
actionId;
|
|
703
|
-
const actionContext = {
|
|
704
|
-
actionId: resolvedActionId,
|
|
705
|
-
actionUrl: new URL(request.url),
|
|
706
|
-
actionResult: returnValue.data,
|
|
707
|
-
formData: actionFormData,
|
|
708
|
-
};
|
|
709
|
-
|
|
710
|
-
const matchResult = await router.matchPartial(request, env, actionContext);
|
|
711
|
-
|
|
712
|
-
if (!matchResult) {
|
|
713
|
-
// Fall back to full render
|
|
714
|
-
const fullMatch = await router.match(request, env);
|
|
715
|
-
setRequestContextParams(fullMatch.params);
|
|
716
|
-
|
|
717
|
-
if (fullMatch.redirect) {
|
|
718
|
-
return createResponseWithMergedHeaders(null, {
|
|
719
|
-
status: 308,
|
|
720
|
-
headers: { Location: fullMatch.redirect },
|
|
721
|
-
});
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
const renderStart = performance.now();
|
|
725
|
-
const root = renderSegments(fullMatch.segments, {
|
|
726
|
-
rootLayout: router.rootLayout,
|
|
727
|
-
isAction: true,
|
|
728
|
-
});
|
|
729
|
-
const renderDuration = performance.now() - renderStart;
|
|
730
|
-
const serverTiming = fullMatch.serverTiming
|
|
731
|
-
? `${fullMatch.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
732
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
733
|
-
|
|
734
|
-
const payload: RscPayload = {
|
|
735
|
-
root,
|
|
736
|
-
metadata: {
|
|
737
|
-
pathname: url.pathname,
|
|
738
|
-
segments: fullMatch.segments,
|
|
739
|
-
matched: fullMatch.matched,
|
|
740
|
-
diff: fullMatch.diff,
|
|
741
|
-
handles: handleStore.stream(),
|
|
742
|
-
version,
|
|
743
|
-
},
|
|
744
|
-
returnValue,
|
|
745
|
-
};
|
|
746
|
-
|
|
747
|
-
const rscStream = renderToReadableStream<RscPayload>(payload, {
|
|
748
|
-
temporaryReferences,
|
|
749
|
-
});
|
|
750
|
-
|
|
751
|
-
const headers: Record<string, string> = {
|
|
752
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
753
|
-
};
|
|
754
|
-
if (serverTiming) {
|
|
755
|
-
headers["Server-Timing"] = serverTiming;
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
759
|
-
status: actionStatus,
|
|
760
|
-
headers,
|
|
761
|
-
});
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
// Return updated segments
|
|
765
|
-
setRequestContextParams(matchResult.params);
|
|
766
|
-
|
|
767
|
-
const renderStart = performance.now();
|
|
768
|
-
|
|
769
|
-
const renderDuration = performance.now() - renderStart;
|
|
770
|
-
const serverTiming = matchResult.serverTiming
|
|
771
|
-
? `${matchResult.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
772
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
773
|
-
|
|
774
|
-
const payload: RscPayload = {
|
|
775
|
-
root: null,
|
|
776
|
-
metadata: {
|
|
777
|
-
pathname: url.pathname,
|
|
778
|
-
segments: matchResult.segments,
|
|
779
|
-
isPartial: true,
|
|
780
|
-
matched: matchResult.matched,
|
|
781
|
-
diff: matchResult.diff,
|
|
782
|
-
slots: matchResult.slots,
|
|
783
|
-
handles: handleStore.stream(),
|
|
784
|
-
version,
|
|
785
|
-
},
|
|
786
|
-
returnValue,
|
|
787
|
-
};
|
|
788
|
-
|
|
789
|
-
const rscStream = renderToReadableStream<RscPayload>(payload, {
|
|
790
|
-
temporaryReferences,
|
|
791
|
-
});
|
|
792
|
-
|
|
793
|
-
const actionHeaders: Record<string, string> = {
|
|
794
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
795
|
-
};
|
|
796
|
-
if (serverTiming) {
|
|
797
|
-
actionHeaders["Server-Timing"] = serverTiming;
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
801
|
-
status: actionStatus,
|
|
802
|
-
headers: actionHeaders,
|
|
803
|
-
});
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
// ============================================================================
|
|
807
|
-
// LOADER FETCH HANDLER
|
|
808
|
-
// Supports GET (params in query string) and POST/PUT/PATCH/DELETE (JSON body)
|
|
809
|
-
// ============================================================================
|
|
810
|
-
async function handleLoaderFetch(
|
|
811
|
-
request: Request,
|
|
812
|
-
env: TEnv,
|
|
813
|
-
url: URL,
|
|
814
|
-
variables: Record<string, any>,
|
|
815
|
-
): Promise<Response> {
|
|
816
|
-
const loaderId = url.searchParams.get("_rsc_loader");
|
|
817
|
-
|
|
818
|
-
if (!loaderId) {
|
|
819
|
-
return createResponseWithMergedHeaders("Missing _rsc_loader parameter", {
|
|
820
|
-
status: 400,
|
|
821
|
-
});
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
// Look up loader lazily
|
|
825
|
-
const registeredLoader = await getLoaderLazy(loaderId);
|
|
826
|
-
if (!registeredLoader) {
|
|
827
|
-
return createResponseWithMergedHeaders(
|
|
828
|
-
`Loader "${loaderId}" not found in registry`,
|
|
829
|
-
{ status: 404 },
|
|
830
|
-
);
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
// Parse params and body based on request method
|
|
834
|
-
let loaderParams: Record<string, string> = {};
|
|
835
|
-
let loaderBody: unknown = undefined;
|
|
836
|
-
const isBodyMethod = request.method !== "GET" && request.method !== "HEAD";
|
|
837
|
-
|
|
838
|
-
if (isBodyMethod) {
|
|
839
|
-
try {
|
|
840
|
-
const contentType = request.headers.get("content-type") || "";
|
|
841
|
-
if (contentType.includes("application/json")) {
|
|
842
|
-
const jsonBody = (await request.json()) as {
|
|
843
|
-
params?: Record<string, string>;
|
|
844
|
-
body?: unknown;
|
|
845
|
-
};
|
|
846
|
-
loaderParams = jsonBody.params ?? {};
|
|
847
|
-
loaderBody = jsonBody.body;
|
|
848
|
-
}
|
|
849
|
-
} catch {
|
|
850
|
-
return createResponseWithMergedHeaders("Invalid JSON body", {
|
|
851
|
-
status: 400,
|
|
852
|
-
});
|
|
853
|
-
}
|
|
854
|
-
} else {
|
|
855
|
-
const loaderParamsJson = url.searchParams.get("_rsc_loader_params");
|
|
856
|
-
if (loaderParamsJson) {
|
|
857
|
-
try {
|
|
858
|
-
loaderParams = JSON.parse(loaderParamsJson);
|
|
859
|
-
} catch {
|
|
860
|
-
return createResponseWithMergedHeaders(
|
|
861
|
-
"Invalid _rsc_loader_params JSON",
|
|
862
|
-
{ status: 400 },
|
|
863
|
-
);
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
// Execute the loader with middleware
|
|
869
|
-
try {
|
|
870
|
-
const { fn, middleware } = registeredLoader;
|
|
871
|
-
|
|
872
|
-
return await executeLoaderMiddleware(
|
|
873
|
-
middleware,
|
|
874
|
-
request,
|
|
875
|
-
env,
|
|
876
|
-
loaderParams,
|
|
877
|
-
variables,
|
|
878
|
-
async () => {
|
|
879
|
-
const ctx = requireRequestContext();
|
|
880
|
-
const loaderCtx: any = {
|
|
881
|
-
...ctx,
|
|
882
|
-
params: loaderParams,
|
|
883
|
-
body: loaderBody,
|
|
884
|
-
};
|
|
885
|
-
|
|
886
|
-
const result = await fn(loaderCtx);
|
|
887
|
-
|
|
888
|
-
interface LoaderPayload {
|
|
889
|
-
loaderResult: unknown;
|
|
890
|
-
}
|
|
891
|
-
const loaderPayload: LoaderPayload = { loaderResult: result };
|
|
892
|
-
const rscStream =
|
|
893
|
-
renderToReadableStream<LoaderPayload>(loaderPayload);
|
|
894
|
-
|
|
895
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
896
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
897
|
-
});
|
|
898
|
-
},
|
|
899
|
-
);
|
|
900
|
-
} catch (error) {
|
|
901
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
902
|
-
const isDev = process.env.NODE_ENV !== "production";
|
|
903
|
-
|
|
904
|
-
console.error("[RSC] Loader error:", error);
|
|
905
|
-
|
|
906
|
-
callOnError(error, "loader", {
|
|
907
|
-
request,
|
|
908
|
-
url,
|
|
909
|
-
env,
|
|
910
|
-
loaderName: loaderId,
|
|
911
|
-
handledByBoundary: false,
|
|
912
|
-
});
|
|
913
|
-
|
|
914
|
-
const errorPayload = {
|
|
915
|
-
loaderResult: null,
|
|
916
|
-
loaderError: {
|
|
917
|
-
message: isDev ? err.message : "An error occurred",
|
|
918
|
-
name: err.name,
|
|
919
|
-
},
|
|
920
|
-
};
|
|
921
|
-
const rscStream = renderToReadableStream(errorPayload);
|
|
922
|
-
|
|
923
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
924
|
-
status: 500,
|
|
925
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
926
|
-
});
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
// ============================================================================
|
|
931
|
-
// RSC RENDERING HANDLER (Navigation)
|
|
932
|
-
// ============================================================================
|
|
933
|
-
async function handleRscRendering(
|
|
934
|
-
request: Request,
|
|
935
|
-
env: TEnv,
|
|
936
|
-
url: URL,
|
|
937
|
-
isPartial: boolean,
|
|
938
|
-
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
939
|
-
nonce: string | undefined,
|
|
940
|
-
): Promise<Response> {
|
|
941
|
-
let payload: RscPayload;
|
|
942
|
-
let serverTiming: string | undefined;
|
|
943
|
-
|
|
944
|
-
if (isPartial) {
|
|
945
|
-
// Partial render (navigation)
|
|
946
|
-
const result = await router.matchPartial(request, env);
|
|
947
|
-
|
|
948
|
-
if (!result) {
|
|
949
|
-
// Fall back to full render
|
|
950
|
-
const match = await router.match(request, env);
|
|
951
|
-
setRequestContextParams(match.params);
|
|
952
|
-
|
|
953
|
-
if (match.redirect) {
|
|
954
|
-
return createResponseWithMergedHeaders(null, {
|
|
955
|
-
status: 308,
|
|
956
|
-
headers: { Location: match.redirect },
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
const renderStart = performance.now();
|
|
961
|
-
const root = renderSegments(match.segments, {
|
|
962
|
-
rootLayout: router.rootLayout,
|
|
963
|
-
});
|
|
964
|
-
const renderDuration = performance.now() - renderStart;
|
|
965
|
-
serverTiming = match.serverTiming
|
|
966
|
-
? `${match.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
967
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
968
|
-
|
|
969
|
-
payload = {
|
|
970
|
-
root,
|
|
971
|
-
metadata: {
|
|
972
|
-
pathname: url.pathname,
|
|
973
|
-
segments: match.segments,
|
|
974
|
-
matched: match.matched,
|
|
975
|
-
diff: match.diff,
|
|
976
|
-
isPartial: false,
|
|
977
|
-
handles: handleStore.stream(),
|
|
978
|
-
version,
|
|
979
|
-
themeConfig: router.themeConfig,
|
|
980
|
-
initialTheme: requireRequestContext().theme,
|
|
981
|
-
},
|
|
982
|
-
};
|
|
983
|
-
} else {
|
|
984
|
-
setRequestContextParams(result.params);
|
|
985
|
-
serverTiming = result.serverTiming;
|
|
986
|
-
|
|
987
|
-
payload = {
|
|
988
|
-
root: null,
|
|
989
|
-
metadata: {
|
|
990
|
-
pathname: url.pathname,
|
|
991
|
-
segments: result.segments,
|
|
992
|
-
matched: result.matched,
|
|
993
|
-
diff: result.diff,
|
|
994
|
-
isPartial: true,
|
|
995
|
-
slots: result.slots,
|
|
996
|
-
handles: handleStore.stream(),
|
|
997
|
-
version,
|
|
998
|
-
},
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
} else {
|
|
1002
|
-
// Full render (initial page load)
|
|
1003
|
-
const match = await router.match(request, env);
|
|
1004
|
-
setRequestContextParams(match.params);
|
|
1005
|
-
|
|
1006
|
-
if (match.redirect) {
|
|
1007
|
-
return createResponseWithMergedHeaders(null, {
|
|
1008
|
-
status: 308,
|
|
1009
|
-
headers: { Location: match.redirect },
|
|
1010
|
-
});
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
// Caching is now handled in router.match() via cache provider in request context
|
|
1014
|
-
// match.segments already contains cached or fresh segments as appropriate
|
|
1015
|
-
|
|
1016
|
-
const renderStart = performance.now();
|
|
1017
|
-
const root = renderSegments(match.segments, {
|
|
1018
|
-
rootLayout: router.rootLayout,
|
|
1019
|
-
});
|
|
1020
|
-
const renderDuration = performance.now() - renderStart;
|
|
1021
|
-
serverTiming = match.serverTiming
|
|
1022
|
-
? `${match.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
1023
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
1024
|
-
|
|
1025
|
-
payload = {
|
|
1026
|
-
root,
|
|
1027
|
-
metadata: {
|
|
1028
|
-
pathname: url.pathname,
|
|
1029
|
-
segments: match.segments,
|
|
1030
|
-
matched: match.matched,
|
|
1031
|
-
diff: match.diff,
|
|
1032
|
-
isPartial: false,
|
|
1033
|
-
rootLayout: router.rootLayout,
|
|
1034
|
-
handles: handleStore.stream(),
|
|
1035
|
-
version,
|
|
1036
|
-
themeConfig: router.themeConfig,
|
|
1037
|
-
initialTheme: requireRequestContext().theme,
|
|
1038
|
-
},
|
|
1039
|
-
};
|
|
1040
|
-
}
|
|
1041
|
-
|
|
1042
|
-
// Serialize to RSC stream
|
|
1043
|
-
const rscStream = renderToReadableStream<RscPayload>(payload);
|
|
1044
|
-
|
|
1045
|
-
// Determine if this is an RSC request or HTML request
|
|
1046
|
-
const isRscRequest =
|
|
1047
|
-
(!request.headers.get("accept")?.includes("text/html") &&
|
|
1048
|
-
!url.searchParams.has("__html")) ||
|
|
1049
|
-
url.searchParams.has("__rsc");
|
|
1050
|
-
|
|
1051
|
-
if (isRscRequest) {
|
|
1052
|
-
const rscHeaders: Record<string, string> = {
|
|
1053
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
1054
|
-
vary: "accept",
|
|
1055
|
-
};
|
|
1056
|
-
if (serverTiming) {
|
|
1057
|
-
rscHeaders["Server-Timing"] = serverTiming;
|
|
1058
|
-
}
|
|
1059
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
1060
|
-
headers: rscHeaders,
|
|
1061
|
-
});
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
// Delegate to SSR for HTML response
|
|
1065
|
-
const ssrModule = await loadSSRModule();
|
|
1066
|
-
const htmlStream = await ssrModule.renderHTML(rscStream, { nonce });
|
|
1067
|
-
|
|
1068
|
-
const htmlHeaders: Record<string, string> = {
|
|
1069
|
-
"content-type": "text/html;charset=utf-8",
|
|
1070
|
-
};
|
|
1071
|
-
if (serverTiming) {
|
|
1072
|
-
htmlHeaders["Server-Timing"] = serverTiming;
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
return createResponseWithMergedHeaders(htmlStream, {
|
|
1076
|
-
headers: htmlHeaders,
|
|
1077
|
-
});
|
|
1078
|
-
}
|
|
1079
1089
|
}
|