vinext 0.0.52 → 0.0.54
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/README.md +1 -1
- package/dist/build/clean-output.d.ts +14 -0
- package/dist/build/clean-output.js +36 -0
- package/dist/build/clean-output.js.map +1 -0
- package/dist/build/inline-css.d.ts +7 -0
- package/dist/build/inline-css.js +50 -0
- package/dist/build/inline-css.js.map +1 -0
- package/dist/build/prerender.d.ts +6 -2
- package/dist/build/prerender.js +51 -12
- package/dist/build/prerender.js.map +1 -1
- package/dist/build/run-prerender.js +10 -1
- package/dist/build/run-prerender.js.map +1 -1
- package/dist/build/static-export.d.ts +5 -0
- package/dist/build/static-export.js +8 -3
- package/dist/build/static-export.js.map +1 -1
- package/dist/check.js +4 -0
- package/dist/check.js.map +1 -1
- package/dist/cli.js +19 -4
- package/dist/cli.js.map +1 -1
- package/dist/client/instrumentation-client-inject.d.ts +34 -0
- package/dist/client/instrumentation-client-inject.js +57 -0
- package/dist/client/instrumentation-client-inject.js.map +1 -0
- package/dist/client/navigation-runtime.d.ts +16 -2
- package/dist/client/navigation-runtime.js +16 -1
- package/dist/client/navigation-runtime.js.map +1 -1
- package/dist/client/vinext-next-data.d.ts +2 -1
- package/dist/client/vinext-next-data.js.map +1 -1
- package/dist/client/window-next.d.ts +17 -2
- package/dist/client/window-next.js.map +1 -1
- package/dist/cloudflare/tpr.js +1 -1
- package/dist/cloudflare/tpr.js.map +1 -1
- package/dist/config/config-matchers.js +2 -1
- package/dist/config/config-matchers.js.map +1 -1
- package/dist/config/next-config.d.ts +95 -4
- package/dist/config/next-config.js +173 -14
- package/dist/config/next-config.js.map +1 -1
- package/dist/deploy.js +42 -7
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-browser-entry.d.ts +11 -1
- package/dist/entries/app-browser-entry.js +16 -6
- package/dist/entries/app-browser-entry.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +12 -3
- package/dist/entries/app-rsc-entry.js +41 -8
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/app-rsc-manifest.d.ts +21 -1
- package/dist/entries/app-rsc-manifest.js +6 -4
- package/dist/entries/app-rsc-manifest.js.map +1 -1
- package/dist/entries/pages-client-entry.d.ts +4 -1
- package/dist/entries/pages-client-entry.js +40 -3
- package/dist/entries/pages-client-entry.js.map +1 -1
- package/dist/entries/pages-server-entry.js +292 -34
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/entries/runtime-entry-module.d.ts +1 -10
- package/dist/entries/runtime-entry-module.js +2 -12
- package/dist/entries/runtime-entry-module.js.map +1 -1
- package/dist/index.js +91 -10
- package/dist/index.js.map +1 -1
- package/dist/plugins/fonts.js +25 -2
- package/dist/plugins/fonts.js.map +1 -1
- package/dist/plugins/remove-console.d.ts +16 -0
- package/dist/plugins/remove-console.js +176 -0
- package/dist/plugins/remove-console.js.map +1 -0
- package/dist/routing/app-route-graph.d.ts +24 -1
- package/dist/routing/app-route-graph.js +52 -4
- package/dist/routing/app-route-graph.js.map +1 -1
- package/dist/routing/app-router.d.ts +2 -2
- package/dist/routing/app-router.js +2 -2
- package/dist/routing/app-router.js.map +1 -1
- package/dist/routing/file-matcher.d.ts +21 -1
- package/dist/routing/file-matcher.js +39 -1
- package/dist/routing/file-matcher.js.map +1 -1
- package/dist/routing/pages-router.d.ts +1 -1
- package/dist/routing/pages-router.js +10 -3
- package/dist/routing/pages-router.js.map +1 -1
- package/dist/routing/route-trie.js +13 -18
- package/dist/routing/route-trie.js.map +1 -1
- package/dist/routing/utils.d.ts +11 -1
- package/dist/routing/utils.js +15 -1
- package/dist/routing/utils.js.map +1 -1
- package/dist/server/api-handler.js +19 -10
- package/dist/server/api-handler.js.map +1 -1
- package/dist/server/app-browser-action-result.d.ts +16 -1
- package/dist/server/app-browser-action-result.js +15 -1
- package/dist/server/app-browser-action-result.js.map +1 -1
- package/dist/server/app-browser-entry.js +47 -28
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/app-browser-navigation-controller.d.ts +2 -0
- package/dist/server/app-browser-navigation-controller.js +4 -0
- package/dist/server/app-browser-navigation-controller.js.map +1 -1
- package/dist/server/app-elements-wire.d.ts +13 -4
- package/dist/server/app-elements-wire.js +10 -1
- package/dist/server/app-elements-wire.js.map +1 -1
- package/dist/server/app-elements.d.ts +2 -2
- package/dist/server/app-elements.js +2 -2
- package/dist/server/app-elements.js.map +1 -1
- package/dist/server/app-fallback-renderer.d.ts +27 -8
- package/dist/server/app-fallback-renderer.js +19 -8
- package/dist/server/app-fallback-renderer.js.map +1 -1
- package/dist/server/app-history-state.js +6 -2
- package/dist/server/app-history-state.js.map +1 -1
- package/dist/server/app-inline-css-client.d.ts +7 -0
- package/dist/server/app-inline-css-client.js +37 -0
- package/dist/server/app-inline-css-client.js.map +1 -0
- package/dist/server/app-interception-context-header.d.ts +33 -0
- package/dist/server/app-interception-context-header.js +44 -0
- package/dist/server/app-interception-context-header.js.map +1 -0
- package/dist/server/app-mounted-slots-header.d.ts +19 -0
- package/dist/server/app-mounted-slots-header.js +40 -1
- package/dist/server/app-mounted-slots-header.js.map +1 -1
- package/dist/server/app-optimistic-routing.js +26 -18
- package/dist/server/app-optimistic-routing.js.map +1 -1
- package/dist/server/app-page-boundary-render.d.ts +1 -0
- package/dist/server/app-page-boundary-render.js +2 -0
- package/dist/server/app-page-boundary-render.js.map +1 -1
- package/dist/server/app-page-boundary.d.ts +22 -1
- package/dist/server/app-page-boundary.js +30 -3
- package/dist/server/app-page-boundary.js.map +1 -1
- package/dist/server/app-page-cache.d.ts +9 -3
- package/dist/server/app-page-cache.js +14 -8
- package/dist/server/app-page-cache.js.map +1 -1
- package/dist/server/app-page-dispatch.d.ts +13 -1
- package/dist/server/app-page-dispatch.js +136 -82
- package/dist/server/app-page-dispatch.js.map +1 -1
- package/dist/server/app-page-element-builder.d.ts +2 -1
- package/dist/server/app-page-element-builder.js +17 -30
- package/dist/server/app-page-element-builder.js.map +1 -1
- package/dist/server/app-page-execution.d.ts +1 -0
- package/dist/server/app-page-execution.js +2 -0
- package/dist/server/app-page-execution.js.map +1 -1
- package/dist/server/app-page-head.d.ts +1 -0
- package/dist/server/app-page-head.js +8 -0
- package/dist/server/app-page-head.js.map +1 -1
- package/dist/server/app-page-render-identity.d.ts +22 -0
- package/dist/server/app-page-render-identity.js +42 -0
- package/dist/server/app-page-render-identity.js.map +1 -0
- package/dist/server/app-page-render-observation.js +1 -1
- package/dist/server/app-page-render.d.ts +9 -1
- package/dist/server/app-page-render.js +8 -2
- package/dist/server/app-page-render.js.map +1 -1
- package/dist/server/app-page-request.d.ts +6 -3
- package/dist/server/app-page-request.js +5 -2
- package/dist/server/app-page-request.js.map +1 -1
- package/dist/server/app-page-response.d.ts +11 -1
- package/dist/server/app-page-response.js +16 -4
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-route-wiring.d.ts +16 -0
- package/dist/server/app-page-route-wiring.js +25 -10
- package/dist/server/app-page-route-wiring.js.map +1 -1
- package/dist/server/app-page-stream.d.ts +12 -0
- package/dist/server/app-page-stream.js +3 -0
- package/dist/server/app-page-stream.js.map +1 -1
- package/dist/server/app-route-handler-dispatch.d.ts +1 -0
- package/dist/server/app-route-handler-dispatch.js +3 -0
- package/dist/server/app-route-handler-dispatch.js.map +1 -1
- package/dist/server/app-route-handler-execution.d.ts +1 -0
- package/dist/server/app-route-handler-execution.js +1 -0
- package/dist/server/app-route-handler-execution.js.map +1 -1
- package/dist/server/app-route-handler-response.js +38 -6
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/server/app-rsc-handler.d.ts +16 -3
- package/dist/server/app-rsc-handler.js +60 -11
- package/dist/server/app-rsc-handler.js.map +1 -1
- package/dist/server/app-rsc-request-normalization.d.ts +2 -1
- package/dist/server/app-rsc-request-normalization.js +6 -4
- package/dist/server/app-rsc-request-normalization.js.map +1 -1
- package/dist/server/app-segment-config.d.ts +4 -1
- package/dist/server/app-segment-config.js +6 -1
- package/dist/server/app-segment-config.js.map +1 -1
- package/dist/server/app-server-action-execution.d.ts +22 -3
- package/dist/server/app-server-action-execution.js +46 -7
- package/dist/server/app-server-action-execution.js.map +1 -1
- package/dist/server/app-ssr-entry.d.ts +6 -0
- package/dist/server/app-ssr-entry.js +57 -6
- package/dist/server/app-ssr-entry.js.map +1 -1
- package/dist/server/app-ssr-error-meta.js +3 -3
- package/dist/server/app-ssr-error-meta.js.map +1 -1
- package/dist/server/app-ssr-stream.d.ts +25 -1
- package/dist/server/app-ssr-stream.js +237 -19
- package/dist/server/app-ssr-stream.js.map +1 -1
- package/dist/server/app-static-generation.d.ts +1 -0
- package/dist/server/app-static-generation.js +2 -1
- package/dist/server/app-static-generation.js.map +1 -1
- package/dist/server/client-trace-metadata.d.ts +31 -0
- package/dist/server/client-trace-metadata.js +83 -0
- package/dist/server/client-trace-metadata.js.map +1 -0
- package/dist/server/cookie-utils.d.ts +13 -0
- package/dist/server/cookie-utils.js +20 -0
- package/dist/server/cookie-utils.js.map +1 -0
- package/dist/server/default-not-found-module.d.ts +20 -0
- package/dist/server/default-not-found-module.js +20 -0
- package/dist/server/default-not-found-module.js.map +1 -0
- package/dist/server/dev-server.d.ts +8 -1
- package/dist/server/dev-server.js +56 -11
- package/dist/server/dev-server.js.map +1 -1
- package/dist/server/headers.d.ts +5 -1
- package/dist/server/headers.js +5 -1
- package/dist/server/headers.js.map +1 -1
- package/dist/server/html.d.ts +2 -1
- package/dist/server/html.js +6 -1
- package/dist/server/html.js.map +1 -1
- package/dist/server/image-optimization.d.ts +13 -4
- package/dist/server/image-optimization.js +15 -4
- package/dist/server/image-optimization.js.map +1 -1
- package/dist/server/isr-cache.d.ts +7 -5
- package/dist/server/isr-cache.js +17 -6
- package/dist/server/isr-cache.js.map +1 -1
- package/dist/server/middleware-runtime.js +1 -2
- package/dist/server/middleware-runtime.js.map +1 -1
- package/dist/server/middleware.js +1 -1
- package/dist/server/middleware.js.map +1 -1
- package/dist/server/pages-api-route.d.ts +18 -0
- package/dist/server/pages-api-route.js +3 -1
- package/dist/server/pages-api-route.js.map +1 -1
- package/dist/server/pages-body-parser-config.d.ts +60 -0
- package/dist/server/pages-body-parser-config.js +79 -0
- package/dist/server/pages-body-parser-config.js.map +1 -0
- package/dist/server/pages-data-route.js +1 -0
- package/dist/server/pages-data-route.js.map +1 -1
- package/dist/server/pages-default-404.d.ts +31 -0
- package/dist/server/pages-default-404.js +40 -0
- package/dist/server/pages-default-404.js.map +1 -0
- package/dist/server/pages-document-initial-props.d.ts +7 -0
- package/dist/server/pages-document-initial-props.js +14 -0
- package/dist/server/pages-document-initial-props.js.map +1 -0
- package/dist/server/pages-node-compat.d.ts +10 -0
- package/dist/server/pages-node-compat.js +12 -1
- package/dist/server/pages-node-compat.js.map +1 -1
- package/dist/server/pages-page-data.d.ts +40 -0
- package/dist/server/pages-page-data.js +19 -14
- package/dist/server/pages-page-data.js.map +1 -1
- package/dist/server/pages-page-method.d.ts +48 -0
- package/dist/server/pages-page-method.js +19 -0
- package/dist/server/pages-page-method.js.map +1 -0
- package/dist/server/pages-page-response.d.ts +8 -0
- package/dist/server/pages-page-response.js +21 -11
- package/dist/server/pages-page-response.js.map +1 -1
- package/dist/server/pages-serializable-props.d.ts +25 -0
- package/dist/server/pages-serializable-props.js +69 -0
- package/dist/server/pages-serializable-props.js.map +1 -0
- package/dist/server/prerender-route-params.d.ts +14 -0
- package/dist/server/prerender-route-params.js +94 -0
- package/dist/server/prerender-route-params.js.map +1 -0
- package/dist/server/prod-server.d.ts +3 -23
- package/dist/server/prod-server.js +43 -57
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/proxy-trust.d.ts +41 -0
- package/dist/server/proxy-trust.js +70 -0
- package/dist/server/proxy-trust.js.map +1 -0
- package/dist/server/request-pipeline.d.ts +3 -3
- package/dist/server/request-pipeline.js +5 -4
- package/dist/server/request-pipeline.js.map +1 -1
- package/dist/server/seed-cache.js +12 -6
- package/dist/server/seed-cache.js.map +1 -1
- package/dist/server/server-action-not-found.js +3 -2
- package/dist/server/server-action-not-found.js.map +1 -1
- package/dist/server/static-file-cache.js +2 -1
- package/dist/server/static-file-cache.js.map +1 -1
- package/dist/server/streaming-metadata.d.ts +5 -0
- package/dist/server/streaming-metadata.js +10 -0
- package/dist/server/streaming-metadata.js.map +1 -0
- package/dist/shims/app-router-scroll-state.d.ts +14 -0
- package/dist/shims/app-router-scroll-state.js +51 -0
- package/dist/shims/app-router-scroll-state.js.map +1 -0
- package/dist/shims/app-router-scroll.d.ts +28 -0
- package/dist/shims/app-router-scroll.js +115 -0
- package/dist/shims/app-router-scroll.js.map +1 -0
- package/dist/shims/before-interactive-context.d.ts +30 -0
- package/dist/shims/before-interactive-context.js +10 -0
- package/dist/shims/before-interactive-context.js.map +1 -0
- package/dist/shims/cache-runtime.d.ts +1 -1
- package/dist/shims/cache-runtime.js +14 -1
- package/dist/shims/cache-runtime.js.map +1 -1
- package/dist/shims/cache.d.ts +6 -0
- package/dist/shims/cache.js +7 -0
- package/dist/shims/cache.js.map +1 -1
- package/dist/shims/default-not-found.d.ts +12 -0
- package/dist/shims/default-not-found.js +61 -0
- package/dist/shims/default-not-found.js.map +1 -0
- package/dist/shims/error.js +3 -0
- package/dist/shims/error.js.map +1 -1
- package/dist/shims/font-local.d.ts +5 -0
- package/dist/shims/font-local.js +6 -2
- package/dist/shims/font-local.js.map +1 -1
- package/dist/shims/head.js +4 -4
- package/dist/shims/head.js.map +1 -1
- package/dist/shims/headers.d.ts +13 -2
- package/dist/shims/headers.js +73 -22
- package/dist/shims/headers.js.map +1 -1
- package/dist/shims/image.d.ts +1 -1
- package/dist/shims/image.js +4 -4
- package/dist/shims/image.js.map +1 -1
- package/dist/shims/internal/app-route-detection.d.ts +37 -0
- package/dist/shims/internal/app-route-detection.js +69 -0
- package/dist/shims/internal/app-route-detection.js.map +1 -0
- package/dist/shims/internal/pages-data-target.d.ts +58 -0
- package/dist/shims/internal/pages-data-target.js +91 -0
- package/dist/shims/internal/pages-data-target.js.map +1 -0
- package/dist/shims/internal/pages-data-url.d.ts +42 -0
- package/dist/shims/internal/pages-data-url.js +73 -0
- package/dist/shims/internal/pages-data-url.js.map +1 -0
- package/dist/shims/link.d.ts +18 -2
- package/dist/shims/link.js +129 -15
- package/dist/shims/link.js.map +1 -1
- package/dist/shims/metadata.d.ts +9 -7
- package/dist/shims/metadata.js +70 -7
- package/dist/shims/metadata.js.map +1 -1
- package/dist/shims/navigation.d.ts +1 -2
- package/dist/shims/navigation.js +94 -20
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/router.d.ts +5 -0
- package/dist/shims/router.js +389 -80
- package/dist/shims/router.js.map +1 -1
- package/dist/shims/script.d.ts +11 -1
- package/dist/shims/script.js +158 -15
- package/dist/shims/script.js.map +1 -1
- package/dist/shims/server.js +1 -0
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/url-utils.d.ts +2 -1
- package/dist/shims/url-utils.js +15 -4
- package/dist/shims/url-utils.js.map +1 -1
- package/dist/utils/html-limited-bots.d.ts +5 -0
- package/dist/utils/html-limited-bots.js +15 -0
- package/dist/utils/html-limited-bots.js.map +1 -0
- package/dist/utils/path.d.ts +13 -0
- package/dist/utils/path.js +16 -0
- package/dist/utils/path.js.map +1 -0
- package/dist/utils/query.d.ts +6 -0
- package/dist/utils/query.js +10 -1
- package/dist/utils/query.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isEdgeApiRuntime } from "./edge-api-runtime.js";
|
|
1
2
|
//#region src/server/app-segment-config.ts
|
|
2
3
|
const DYNAMIC_VALUES = new Set([
|
|
3
4
|
"auto",
|
|
@@ -72,6 +73,7 @@ function resolveAppPageSegmentConfig(options) {
|
|
|
72
73
|
else config.fetchCache = fetchCache;
|
|
73
74
|
}
|
|
74
75
|
config.revalidateSeconds = resolveRevalidateSeconds(config.revalidateSeconds, segment.revalidate);
|
|
76
|
+
if (typeof segment.runtime === "string") config.runtime = segment.runtime;
|
|
75
77
|
}
|
|
76
78
|
if (config.dynamicConfig === "force-dynamic") config.revalidateSeconds = 0;
|
|
77
79
|
if (config.fetchCache === void 0) {
|
|
@@ -84,7 +86,10 @@ function resolveAppPageSegmentConfig(options) {
|
|
|
84
86
|
function resolveAppPageFetchCacheMode(options) {
|
|
85
87
|
return resolveAppPageSegmentConfig(options).fetchCache ?? null;
|
|
86
88
|
}
|
|
89
|
+
function isEdgeRuntime(runtime) {
|
|
90
|
+
return isEdgeApiRuntime(runtime);
|
|
91
|
+
}
|
|
87
92
|
//#endregion
|
|
88
|
-
export { resolveAppPageFetchCacheMode, resolveAppPageSegmentConfig };
|
|
93
|
+
export { isEdgeRuntime, resolveAppPageFetchCacheMode, resolveAppPageSegmentConfig };
|
|
89
94
|
|
|
90
95
|
//# sourceMappingURL=app-segment-config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-segment-config.js","names":[],"sources":["../../src/server/app-segment-config.ts"],"sourcesContent":["import type { FetchCacheMode } from \"vinext/shims/fetch-cache\";\n\ntype AppRouteSegmentDynamic = \"auto\" | \"error\" | \"force-dynamic\" | \"force-static\";\n\ntype AppRouteSegmentConfigModule = {\n dynamic?: unknown;\n dynamicParams?: unknown;\n fetchCache?: unknown;\n revalidate?: unknown;\n};\n\ntype EffectiveAppPageSegmentConfig = {\n dynamicConfig?: AppRouteSegmentDynamic;\n dynamicParamsConfig?: boolean;\n fetchCache?: FetchCacheMode;\n revalidateSeconds: number | null;\n};\n\ntype ResolveAppPageSegmentConfigOptions = {\n layouts?: readonly (AppRouteSegmentConfigModule | null | undefined)[];\n page?: AppRouteSegmentConfigModule | null;\n};\n\nconst DYNAMIC_VALUES = new Set<unknown>([\"auto\", \"error\", \"force-dynamic\", \"force-static\"]);\nconst FETCH_CACHE_VALUES = new Set<unknown>([\n \"auto\",\n \"default-cache\",\n \"default-no-store\",\n \"force-cache\",\n \"force-no-store\",\n \"only-cache\",\n \"only-no-store\",\n]);\n\nfunction isRouteSegmentDynamic(value: unknown): value is AppRouteSegmentDynamic {\n return DYNAMIC_VALUES.has(value);\n}\n\nfunction isRouteSegmentFetchCache(value: unknown): value is FetchCacheMode {\n return FETCH_CACHE_VALUES.has(value);\n}\n\nfunction resolveRevalidateSeconds(current: number | null, value: unknown): number | null {\n // revalidate = false means \"cache indefinitely\" in Next.js segment config.\n // Represent it as Infinity so downstream code can distinguish \"never\n // revalidate\" (Infinity) from \"no config / unset\" (null).\n if (value === false) {\n if (current === null) return Infinity;\n // Shortest-wins: any finite interval is shorter than Infinity.\n return current === Infinity ? Infinity : current;\n }\n\n if (typeof value !== \"number\") {\n return current;\n }\n\n if (current === null) {\n return value;\n }\n\n return value < current ? value : current;\n}\n\nfunction isCacheFetchCacheMode(value: FetchCacheMode): boolean {\n return value === \"default-cache\" || value === \"force-cache\" || value === \"only-cache\";\n}\n\nfunction describeFetchCacheConflict(value: FetchCacheMode): string {\n return `Route segment config has incompatible fetchCache values including \"${value}\".`;\n}\n\n/**\n * Resolve the route segment config that applies to an App page route.\n *\n * Next.js collects config from every segment in the loader tree and reduces it\n * into the effective route config. The generated vinext entry already knows\n * the concrete layout/page modules for a route, so it should only describe\n * those modules and delegate the behavior to this helper.\n */\nexport function resolveAppPageSegmentConfig(\n options: ResolveAppPageSegmentConfigOptions,\n): EffectiveAppPageSegmentConfig {\n const segments = [...(options.layouts ?? []), options.page];\n // Reduction strategies differ by field:\n // - dynamic: child segments override parents.\n // - dynamicParams: false is sticky across the route tree.\n // - fetchCache: force/only modes take route-level precedence and reject conflicts.\n // - revalidate: the shortest numeric interval wins.\n const config: EffectiveAppPageSegmentConfig = {\n revalidateSeconds: null,\n };\n let hasForceCache = false;\n let hasForceNoStore = false;\n let hasOnlyCache = false;\n let hasOnlyNoStore = false;\n let hasParentDefaultNoStore = false;\n\n for (const segment of segments) {\n if (!segment) continue;\n\n if (isRouteSegmentDynamic(segment.dynamic)) {\n config.dynamicConfig = segment.dynamic;\n }\n\n if (segment.dynamicParams === false) {\n config.dynamicParamsConfig = false;\n } else if (segment.dynamicParams === true && config.dynamicParamsConfig !== false) {\n config.dynamicParamsConfig = true;\n }\n\n if (isRouteSegmentFetchCache(segment.fetchCache)) {\n const fetchCache = segment.fetchCache;\n\n if (hasParentDefaultNoStore && (fetchCache === \"auto\" || isCacheFetchCacheMode(fetchCache))) {\n throw new Error(describeFetchCacheConflict(fetchCache));\n }\n\n if (fetchCache === \"force-cache\") hasForceCache = true;\n if (fetchCache === \"force-no-store\") hasForceNoStore = true;\n if (fetchCache === \"only-cache\") hasOnlyCache = true;\n if (fetchCache === \"only-no-store\") hasOnlyNoStore = true;\n\n const hasCacheEnforcer = hasForceCache || hasOnlyCache;\n const hasNoStoreEnforcer = hasForceNoStore || hasOnlyNoStore;\n if (hasCacheEnforcer && hasNoStoreEnforcer) {\n throw new Error(describeFetchCacheConflict(fetchCache));\n }\n\n if (fetchCache === \"default-no-store\") {\n hasParentDefaultNoStore = true;\n }\n\n if (hasForceCache) {\n config.fetchCache = \"force-cache\";\n } else if (hasForceNoStore) {\n config.fetchCache = \"force-no-store\";\n } else if (hasOnlyCache) {\n config.fetchCache = \"only-cache\";\n } else if (hasOnlyNoStore) {\n config.fetchCache = \"only-no-store\";\n } else {\n config.fetchCache = fetchCache;\n }\n }\n\n config.revalidateSeconds = resolveRevalidateSeconds(\n config.revalidateSeconds,\n segment.revalidate,\n );\n }\n\n if (config.dynamicConfig === \"force-dynamic\") {\n config.revalidateSeconds = 0;\n }\n\n // Top-level dynamic modes supply fetchCache defaults unless a segment does.\n if (config.fetchCache === undefined) {\n if (config.dynamicConfig === \"force-dynamic\") {\n config.fetchCache = \"force-no-store\";\n } else if (config.dynamicConfig === \"error\") {\n config.fetchCache = \"only-cache\";\n }\n }\n\n // Static-only dynamic modes change the default, but explicit dynamicParams wins.\n if (\n config.dynamicParamsConfig === undefined &&\n (config.dynamicConfig === \"error\" || config.dynamicConfig === \"force-static\")\n ) {\n config.dynamicParamsConfig = false;\n }\n\n return config;\n}\n\nexport function resolveAppPageFetchCacheMode(\n options: ResolveAppPageSegmentConfigOptions,\n): FetchCacheMode | null {\n return resolveAppPageSegmentConfig(options).fetchCache ?? null;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"app-segment-config.js","names":[],"sources":["../../src/server/app-segment-config.ts"],"sourcesContent":["import type { FetchCacheMode } from \"vinext/shims/fetch-cache\";\nimport { isEdgeApiRuntime } from \"./edge-api-runtime.js\";\n\ntype AppRouteSegmentDynamic = \"auto\" | \"error\" | \"force-dynamic\" | \"force-static\";\n\ntype AppRouteSegmentConfigModule = {\n dynamic?: unknown;\n dynamicParams?: unknown;\n fetchCache?: unknown;\n revalidate?: unknown;\n runtime?: unknown;\n};\n\ntype EffectiveAppPageSegmentConfig = {\n dynamicConfig?: AppRouteSegmentDynamic;\n dynamicParamsConfig?: boolean;\n fetchCache?: FetchCacheMode;\n revalidateSeconds: number | null;\n runtime?: string;\n};\n\ntype ResolveAppPageSegmentConfigOptions = {\n layouts?: readonly (AppRouteSegmentConfigModule | null | undefined)[];\n page?: AppRouteSegmentConfigModule | null;\n};\n\nconst DYNAMIC_VALUES = new Set<unknown>([\"auto\", \"error\", \"force-dynamic\", \"force-static\"]);\nconst FETCH_CACHE_VALUES = new Set<unknown>([\n \"auto\",\n \"default-cache\",\n \"default-no-store\",\n \"force-cache\",\n \"force-no-store\",\n \"only-cache\",\n \"only-no-store\",\n]);\n\nfunction isRouteSegmentDynamic(value: unknown): value is AppRouteSegmentDynamic {\n return DYNAMIC_VALUES.has(value);\n}\n\nfunction isRouteSegmentFetchCache(value: unknown): value is FetchCacheMode {\n return FETCH_CACHE_VALUES.has(value);\n}\n\nfunction resolveRevalidateSeconds(current: number | null, value: unknown): number | null {\n // revalidate = false means \"cache indefinitely\" in Next.js segment config.\n // Represent it as Infinity so downstream code can distinguish \"never\n // revalidate\" (Infinity) from \"no config / unset\" (null).\n if (value === false) {\n if (current === null) return Infinity;\n // Shortest-wins: any finite interval is shorter than Infinity.\n return current === Infinity ? Infinity : current;\n }\n\n if (typeof value !== \"number\") {\n return current;\n }\n\n if (current === null) {\n return value;\n }\n\n return value < current ? value : current;\n}\n\nfunction isCacheFetchCacheMode(value: FetchCacheMode): boolean {\n return value === \"default-cache\" || value === \"force-cache\" || value === \"only-cache\";\n}\n\nfunction describeFetchCacheConflict(value: FetchCacheMode): string {\n return `Route segment config has incompatible fetchCache values including \"${value}\".`;\n}\n\n/**\n * Resolve the route segment config that applies to an App page route.\n *\n * Next.js collects config from every segment in the loader tree and reduces it\n * into the effective route config. The generated vinext entry already knows\n * the concrete layout/page modules for a route, so it should only describe\n * those modules and delegate the behavior to this helper.\n */\nexport function resolveAppPageSegmentConfig(\n options: ResolveAppPageSegmentConfigOptions,\n): EffectiveAppPageSegmentConfig {\n const segments = [...(options.layouts ?? []), options.page];\n // Reduction strategies differ by field:\n // - dynamic: child segments override parents.\n // - dynamicParams: false is sticky across the route tree.\n // - fetchCache: force/only modes take route-level precedence and reject conflicts.\n // - revalidate: the shortest numeric interval wins.\n const config: EffectiveAppPageSegmentConfig = {\n revalidateSeconds: null,\n };\n let hasForceCache = false;\n let hasForceNoStore = false;\n let hasOnlyCache = false;\n let hasOnlyNoStore = false;\n let hasParentDefaultNoStore = false;\n\n for (const segment of segments) {\n if (!segment) continue;\n\n if (isRouteSegmentDynamic(segment.dynamic)) {\n config.dynamicConfig = segment.dynamic;\n }\n\n if (segment.dynamicParams === false) {\n config.dynamicParamsConfig = false;\n } else if (segment.dynamicParams === true && config.dynamicParamsConfig !== false) {\n config.dynamicParamsConfig = true;\n }\n\n if (isRouteSegmentFetchCache(segment.fetchCache)) {\n const fetchCache = segment.fetchCache;\n\n if (hasParentDefaultNoStore && (fetchCache === \"auto\" || isCacheFetchCacheMode(fetchCache))) {\n throw new Error(describeFetchCacheConflict(fetchCache));\n }\n\n if (fetchCache === \"force-cache\") hasForceCache = true;\n if (fetchCache === \"force-no-store\") hasForceNoStore = true;\n if (fetchCache === \"only-cache\") hasOnlyCache = true;\n if (fetchCache === \"only-no-store\") hasOnlyNoStore = true;\n\n const hasCacheEnforcer = hasForceCache || hasOnlyCache;\n const hasNoStoreEnforcer = hasForceNoStore || hasOnlyNoStore;\n if (hasCacheEnforcer && hasNoStoreEnforcer) {\n throw new Error(describeFetchCacheConflict(fetchCache));\n }\n\n if (fetchCache === \"default-no-store\") {\n hasParentDefaultNoStore = true;\n }\n\n if (hasForceCache) {\n config.fetchCache = \"force-cache\";\n } else if (hasForceNoStore) {\n config.fetchCache = \"force-no-store\";\n } else if (hasOnlyCache) {\n config.fetchCache = \"only-cache\";\n } else if (hasOnlyNoStore) {\n config.fetchCache = \"only-no-store\";\n } else {\n config.fetchCache = fetchCache;\n }\n }\n\n config.revalidateSeconds = resolveRevalidateSeconds(\n config.revalidateSeconds,\n segment.revalidate,\n );\n\n if (typeof segment.runtime === \"string\") {\n config.runtime = segment.runtime;\n }\n }\n\n if (config.dynamicConfig === \"force-dynamic\") {\n config.revalidateSeconds = 0;\n }\n\n // Top-level dynamic modes supply fetchCache defaults unless a segment does.\n if (config.fetchCache === undefined) {\n if (config.dynamicConfig === \"force-dynamic\") {\n config.fetchCache = \"force-no-store\";\n } else if (config.dynamicConfig === \"error\") {\n config.fetchCache = \"only-cache\";\n }\n }\n\n // Static-only dynamic modes change the default, but explicit dynamicParams wins.\n if (\n config.dynamicParamsConfig === undefined &&\n (config.dynamicConfig === \"error\" || config.dynamicConfig === \"force-static\")\n ) {\n config.dynamicParamsConfig = false;\n }\n\n return config;\n}\n\nexport function resolveAppPageFetchCacheMode(\n options: ResolveAppPageSegmentConfigOptions,\n): FetchCacheMode | null {\n return resolveAppPageSegmentConfig(options).fetchCache ?? null;\n}\n\nexport function isEdgeRuntime(runtime: string | undefined): boolean {\n return isEdgeApiRuntime(runtime);\n}\n"],"mappings":";;AA0BA,MAAM,iBAAiB,IAAI,IAAa;CAAC;CAAQ;CAAS;CAAiB;CAAe,CAAC;AAC3F,MAAM,qBAAqB,IAAI,IAAa;CAC1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BAAkB;GACvD,IAAI,eAAe,cAAc,eAAe;GAChD,IAAI,eAAe,iBAAiB,iBAAiB;GAIrD,KAFyB,iBAAiB,kBACf,mBAAmB,iBAE5C,MAAM,IAAI,MAAM,2BAA2B,WAAW,CAAC;GAGzD,IAAI,eAAe,oBACjB,0BAA0B;GAG5B,IAAI,eACF,OAAO,aAAa;QACf,IAAI,iBACT,OAAO,aAAa;QACf,IAAI,cACT,OAAO,aAAa;QACf,IAAI,gBACT,OAAO,aAAa;QAEpB,OAAO,aAAa;;EAIxB,OAAO,oBAAoB,yBACzB,OAAO,mBACP,QAAQ,WACT;EAED,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,UAAU,QAAQ;;CAI7B,IAAI,OAAO,kBAAkB,iBAC3B,OAAO,oBAAoB;CAI7B,IAAI,OAAO,eAAe,KAAA;MACpB,OAAO,kBAAkB,iBAC3B,OAAO,aAAa;OACf,IAAI,OAAO,kBAAkB,SAClC,OAAO,aAAa;;CAKxB,IACE,OAAO,wBAAwB,KAAA,MAC9B,OAAO,kBAAkB,WAAW,OAAO,kBAAkB,iBAE9D,OAAO,sBAAsB;CAG/B,OAAO;;AAGT,SAAgB,6BACd,SACuB;CACvB,OAAO,4BAA4B,QAAQ,CAAC,cAAc;;AAG5D,SAAgB,cAAc,SAAsC;CAClE,OAAO,iBAAiB,QAAQ"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ActionRevalidationKind } from "../shims/cache.js";
|
|
1
2
|
import { AppRscRenderMode } from "./app-rsc-render-mode.js";
|
|
2
3
|
import { FetchCacheMode } from "../shims/fetch-cache.js";
|
|
3
4
|
import { HeadersAccessPhase } from "../shims/headers.js";
|
|
@@ -28,15 +29,32 @@ type AppServerActionReturnValue = {
|
|
|
28
29
|
type AppServerActionRoute = {
|
|
29
30
|
pattern: string;
|
|
30
31
|
};
|
|
31
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Side-effect headers captured during a progressive (no-JS) server action's
|
|
34
|
+
* non-redirect execution. The caller (app-rsc-handler) must apply these to the
|
|
35
|
+
* page render response so that `cookies().set(...)` and revalidation kinds
|
|
36
|
+
* propagate to the browser. Without this, no-JS form submissions silently
|
|
37
|
+
* lose cookie/header mutations — see issue #1483.
|
|
38
|
+
*
|
|
39
|
+
* Next.js' equivalent path mutates `res.setHeader('set-cookie', ...)` during
|
|
40
|
+
* action execution (action-handler.ts → app-render.tsx), then `sendResponse`
|
|
41
|
+
* merges those headers with the rendered Response. vinext works with Response
|
|
42
|
+
* objects directly so the cookies must ride out via the result instead.
|
|
43
|
+
*/
|
|
44
|
+
type ProgressiveServerActionSideEffects = {
|
|
45
|
+
/** `Set-Cookie` headers from `cookies().set(...)` / `cookies().delete(...)`. */pendingCookies: string[]; /** `Set-Cookie` header from `draftMode().enable()/disable()` (if any). */
|
|
46
|
+
draftCookie: string | null | undefined; /** Resolved revalidation kind to emit via `x-action-revalidated`. */
|
|
47
|
+
revalidationKind: ActionRevalidationKind;
|
|
48
|
+
};
|
|
49
|
+
type ProgressiveServerActionResult = ({
|
|
32
50
|
formState: ReactFormState | null;
|
|
33
51
|
kind: "form-state";
|
|
34
|
-
} | {
|
|
52
|
+
} & ProgressiveServerActionSideEffects) | ({
|
|
35
53
|
actionError: unknown;
|
|
36
54
|
actionFailed: true;
|
|
37
55
|
formState: null;
|
|
38
56
|
kind: "form-state";
|
|
39
|
-
};
|
|
57
|
+
} & ProgressiveServerActionSideEffects);
|
|
40
58
|
type AppServerActionMatch<TRoute extends AppServerActionRoute> = {
|
|
41
59
|
params: AppPageParams;
|
|
42
60
|
route: TRoute;
|
|
@@ -111,6 +129,7 @@ type HandleServerActionRscRequestOptions<TElement, TRoute extends AppServerActio
|
|
|
111
129
|
getDraftModeCookieHeader: () => string | null | undefined;
|
|
112
130
|
getRouteParamNames: (route: TRoute) => readonly string[];
|
|
113
131
|
getSourceRoute: (sourceRouteIndex: number) => TRoute | undefined;
|
|
132
|
+
isEdgeRuntime?: boolean;
|
|
114
133
|
isRscRequest: boolean;
|
|
115
134
|
loadServerAction: (actionId: string) => Promise<unknown>;
|
|
116
135
|
matchRoute: (pathname: string) => AppServerActionMatch<TRoute> | null;
|
|
@@ -7,11 +7,13 @@ import { getAndClearActionRevalidationKind } from "../shims/cache.js";
|
|
|
7
7
|
import { APP_RSC_RENDER_MODE_ACTION_RERENDER_PRESERVE_UI } from "./app-rsc-render-mode.js";
|
|
8
8
|
import { setCurrentFetchCacheMode } from "../shims/fetch-cache.js";
|
|
9
9
|
import { VINEXT_RSC_CONTENT_TYPE, VINEXT_RSC_VARY_HEADER, applyRscCompatibilityIdHeader } from "./app-rsc-cache-busting.js";
|
|
10
|
+
import { readStreamAsTextWithLimit } from "../utils/text-stream.js";
|
|
10
11
|
import { createServerActionNotFoundResponse, getServerActionNotFoundMessage, isServerActionNotFoundError } from "./server-action-not-found.js";
|
|
11
12
|
import { mergeMiddlewareResponseHeaders } from "./middleware-response-headers.js";
|
|
13
|
+
import { applyEdgeRuntimeHeader } from "./app-page-response.js";
|
|
12
14
|
import { getNextErrorDigest, parseNextHttpErrorDigest, parseNextRedirectDigest } from "./next-error-digest.js";
|
|
13
|
-
import { readStreamAsTextWithLimit } from "../utils/text-stream.js";
|
|
14
15
|
import { resolveAppPageActionRerenderTarget } from "./app-page-request.js";
|
|
16
|
+
import { getSetCookieName } from "./cookie-utils.js";
|
|
15
17
|
//#region src/server/app-server-action-execution.ts
|
|
16
18
|
/**
|
|
17
19
|
* Matches Next.js' server action argument cap to prevent stack overflow in
|
|
@@ -32,6 +34,32 @@ function resolveActionRevalidationKind(hasModifiedCookies) {
|
|
|
32
34
|
function isRequestBodyTooLarge(error) {
|
|
33
35
|
return error instanceof Error && error.message === "Request body too large";
|
|
34
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Collapse repeated `cookies().set(name, ...)` / `cookies().delete(name)`
|
|
39
|
+
* calls down to the last value per name, matching Next.js'
|
|
40
|
+
* `MutableRequestCookiesAdapter` semantics. Next.js stores response cookies in
|
|
41
|
+
* a `ResponseCookies` Map keyed by name — multiple sets for the same cookie
|
|
42
|
+
* collapse to the final value, and emit a single Set-Cookie header.
|
|
43
|
+
*
|
|
44
|
+
* Insertion order is preserved by first occurrence (Map iteration order),
|
|
45
|
+
* which mirrors how `ResponseCookies` iterates its underlying Map. See
|
|
46
|
+
* packages/next/src/server/web/spec-extension/adapters/request-cookies.ts.
|
|
47
|
+
* Issue: https://github.com/cloudflare/vinext/issues/1481
|
|
48
|
+
*/
|
|
49
|
+
function dedupePendingCookies(cookies) {
|
|
50
|
+
if (cookies.length <= 1) return cookies.slice();
|
|
51
|
+
const byName = /* @__PURE__ */ new Map();
|
|
52
|
+
const unkeyed = [];
|
|
53
|
+
for (const cookie of cookies) {
|
|
54
|
+
const name = getSetCookieName(cookie);
|
|
55
|
+
if (name === null) {
|
|
56
|
+
unkeyed.push(cookie);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
byName.set(name, cookie);
|
|
60
|
+
}
|
|
61
|
+
return [...unkeyed, ...byName.values()];
|
|
62
|
+
}
|
|
35
63
|
function isAppServerActionFunction(action) {
|
|
36
64
|
return typeof action === "function";
|
|
37
65
|
}
|
|
@@ -209,19 +237,27 @@ async function handleProgressiveServerActionRequest(options) {
|
|
|
209
237
|
options.setHeadersAccessPhase(previousHeadersPhase);
|
|
210
238
|
}
|
|
211
239
|
if (!actionRedirect) {
|
|
212
|
-
|
|
240
|
+
const actionPendingCookies = options.getAndClearPendingCookies();
|
|
241
|
+
const actionDraftCookie = options.getDraftModeCookieHeader();
|
|
242
|
+
const revalidationKind = resolveActionRevalidationKind(actionPendingCookies.length > 0 || Boolean(actionDraftCookie));
|
|
213
243
|
if (actionFailed) return {
|
|
214
244
|
kind: "form-state",
|
|
215
245
|
formState: null,
|
|
216
246
|
actionError,
|
|
217
|
-
actionFailed
|
|
247
|
+
actionFailed,
|
|
248
|
+
pendingCookies: actionPendingCookies,
|
|
249
|
+
draftCookie: actionDraftCookie,
|
|
250
|
+
revalidationKind
|
|
218
251
|
};
|
|
219
252
|
return {
|
|
220
253
|
kind: "form-state",
|
|
221
|
-
formState: await options.decodeFormState(actionResult, body) ?? null
|
|
254
|
+
formState: await options.decodeFormState(actionResult, body) ?? null,
|
|
255
|
+
pendingCookies: actionPendingCookies,
|
|
256
|
+
draftCookie: actionDraftCookie,
|
|
257
|
+
revalidationKind
|
|
222
258
|
};
|
|
223
259
|
}
|
|
224
|
-
const actionPendingCookies = options.getAndClearPendingCookies();
|
|
260
|
+
const actionPendingCookies = dedupePendingCookies(options.getAndClearPendingCookies());
|
|
225
261
|
const actionDraftCookie = options.getDraftModeCookieHeader();
|
|
226
262
|
const actionRevalidationKind = resolveActionRevalidationKind(actionPendingCookies.length > 0 || Boolean(actionDraftCookie));
|
|
227
263
|
options.clearRequestContext();
|
|
@@ -339,7 +375,7 @@ async function handleServerActionRscRequest(options) {
|
|
|
339
375
|
options.setHeadersAccessPhase(previousHeadersPhase);
|
|
340
376
|
}
|
|
341
377
|
if (actionRedirect) {
|
|
342
|
-
const actionPendingCookies = options.getAndClearPendingCookies();
|
|
378
|
+
const actionPendingCookies = dedupePendingCookies(options.getAndClearPendingCookies());
|
|
343
379
|
const actionDraftCookie = options.getDraftModeCookieHeader();
|
|
344
380
|
const actionRevalidationKind = resolveActionRevalidationKind(actionPendingCookies.length > 0 || Boolean(actionDraftCookie));
|
|
345
381
|
options.clearRequestContext();
|
|
@@ -347,6 +383,7 @@ async function handleServerActionRscRequest(options) {
|
|
|
347
383
|
"Content-Type": VINEXT_RSC_CONTENT_TYPE,
|
|
348
384
|
Vary: VINEXT_RSC_VARY_HEADER
|
|
349
385
|
});
|
|
386
|
+
applyEdgeRuntimeHeader(redirectHeaders, options.isEdgeRuntime);
|
|
350
387
|
mergeMiddlewareResponseHeaders(redirectHeaders, options.middlewareHeaders);
|
|
351
388
|
applyRscCompatibilityIdHeader(redirectHeaders);
|
|
352
389
|
redirectHeaders.set(ACTION_REDIRECT_HEADER, applyActionRedirectBasePath(actionRedirect.url, options.basePath ?? ""));
|
|
@@ -360,7 +397,7 @@ async function handleServerActionRscRequest(options) {
|
|
|
360
397
|
headers: redirectHeaders
|
|
361
398
|
});
|
|
362
399
|
}
|
|
363
|
-
const actionPendingCookies = options.getAndClearPendingCookies();
|
|
400
|
+
const actionPendingCookies = dedupePendingCookies(options.getAndClearPendingCookies());
|
|
364
401
|
const actionDraftCookie = options.getDraftModeCookieHeader();
|
|
365
402
|
const actionRevalidationKind = resolveActionRevalidationKind(actionPendingCookies.length > 0 || Boolean(actionDraftCookie));
|
|
366
403
|
if (actionRevalidationKind === ACTION_DID_NOT_REVALIDATE) {
|
|
@@ -374,6 +411,7 @@ async function handleServerActionRscRequest(options) {
|
|
|
374
411
|
"Content-Type": VINEXT_RSC_CONTENT_TYPE,
|
|
375
412
|
Vary: VINEXT_RSC_VARY_HEADER
|
|
376
413
|
});
|
|
414
|
+
applyEdgeRuntimeHeader(actionHeaders, options.isEdgeRuntime);
|
|
377
415
|
mergeMiddlewareResponseHeaders(actionHeaders, options.middlewareHeaders);
|
|
378
416
|
applyRscCompatibilityIdHeader(actionHeaders);
|
|
379
417
|
return new Response(rscStream, {
|
|
@@ -430,6 +468,7 @@ async function handleServerActionRscRequest(options) {
|
|
|
430
468
|
"Content-Type": VINEXT_RSC_CONTENT_TYPE,
|
|
431
469
|
Vary: VINEXT_RSC_VARY_HEADER
|
|
432
470
|
});
|
|
471
|
+
applyEdgeRuntimeHeader(actionHeaders, options.isEdgeRuntime);
|
|
433
472
|
mergeMiddlewareResponseHeaders(actionHeaders, options.middlewareHeaders);
|
|
434
473
|
applyRscCompatibilityIdHeader(actionHeaders);
|
|
435
474
|
setActionRevalidatedHeader(actionHeaders, actionRevalidationKind);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-server-action-execution.js","names":[],"sources":["../../src/server/app-server-action-execution.ts"],"sourcesContent":["import { getAndClearActionRevalidationKind, type ActionRevalidationKind } from \"vinext/shims/cache\";\nimport type { HeadersAccessPhase } from \"vinext/shims/headers\";\nimport { type FetchCacheMode, setCurrentFetchCacheMode } from \"vinext/shims/fetch-cache\";\nimport type { ReactFormState } from \"react-dom/client\";\nimport { isExternalUrl } from \"../config/config-matchers.js\";\nimport { addBasePathToPathname, hasBasePath } from \"../utils/base-path.js\";\nimport {\n ACTION_FORWARDED_HEADER,\n ACTION_REDIRECT_HEADER,\n ACTION_REDIRECT_STATUS_HEADER,\n ACTION_REDIRECT_TYPE_HEADER,\n ACTION_REVALIDATED_HEADER,\n} from \"./headers.js\";\nimport {\n VINEXT_RSC_CONTENT_TYPE,\n VINEXT_RSC_VARY_HEADER,\n applyRscCompatibilityIdHeader,\n} from \"./app-rsc-cache-busting.js\";\nimport { resolveAppPageActionRerenderTarget } from \"./app-page-request.js\";\nimport { mergeMiddlewareResponseHeaders } from \"./middleware-response-headers.js\";\nimport {\n APP_RSC_RENDER_MODE_ACTION_RERENDER_PRESERVE_UI,\n type AppRscRenderMode,\n} from \"./app-rsc-render-mode.js\";\nimport {\n getNextErrorDigest,\n parseNextHttpErrorDigest,\n parseNextRedirectDigest,\n} from \"./next-error-digest.js\";\nimport { validateCsrfOrigin, validateServerActionPayload } from \"./request-pipeline.js\";\nimport { readStreamAsTextWithLimit } from \"../utils/text-stream.js\";\nimport {\n createServerActionNotFoundResponse,\n getServerActionNotFoundMessage,\n isServerActionNotFoundError,\n} from \"./server-action-not-found.js\";\nimport { internalServerErrorResponse, payloadTooLargeResponse } from \"./http-error-responses.js\";\n\ntype AppPageParams = Record<string, string | string[]>;\n\ntype AppServerActionErrorReporter = (\n error: Error,\n request: { path: string; method: string; headers: Record<string, string> },\n route: { routerKind: \"App Router\"; routePath: string; routeType: \"action\" },\n) => void;\n\ntype AppServerActionDecoder = (body: FormData) => Promise<unknown>;\ntype AppServerActionFormStateDecoder = (\n actionResult: unknown,\n body: FormData,\n) => Promise<ReactFormState | undefined>;\n\ntype ReadFormDataWithLimit = (request: Request, maxBytes: number) => Promise<FormData>;\n\ntype ReadBodyWithLimit = (request: Request, maxBytes: number) => Promise<string>;\n\ntype AppServerActionFunction = (...args: unknown[]) => unknown;\n\ntype AppServerActionReturnValue =\n | {\n data: unknown;\n ok: true;\n }\n | {\n data: unknown;\n ok: false;\n };\n\ntype AppServerActionRedirect = {\n status: number;\n type: string;\n url: string;\n};\n\ntype AppServerActionRoute = {\n pattern: string;\n};\n\ntype ProgressiveServerActionResult =\n | {\n formState: ReactFormState | null;\n kind: \"form-state\";\n }\n | {\n actionError: unknown;\n actionFailed: true;\n formState: null;\n kind: \"form-state\";\n };\n\ntype AppServerActionMatch<TRoute extends AppServerActionRoute> = {\n params: AppPageParams;\n route: TRoute;\n};\n\ntype AppServerActionIntercept<TPage = unknown> = {\n matchedParams: AppPageParams;\n page: TPage;\n slotId?: string | null;\n slotKey: string;\n sourceRouteIndex: number;\n};\n\ntype BuildServerActionPageElementOptions<TRoute extends AppServerActionRoute, TInterceptOpts> = {\n cleanPathname: string;\n interceptOpts: TInterceptOpts | undefined;\n isRscRequest: boolean;\n mountedSlotsHeader: string | null;\n params: AppPageParams;\n request: Request;\n route: TRoute;\n searchParams: URLSearchParams;\n renderMode: AppRscRenderMode;\n};\n\ntype AppServerActionRscModel<TElement> = {\n /**\n * Omitted when the action did not invalidate page data. This mirrors Next.js'\n * empty Flight payload for non-revalidating fetch actions: the client resolves\n * the action value without committing a visible router update.\n */\n root?: TElement;\n returnValue: AppServerActionReturnValue;\n};\n\ntype RenderServerActionRscStreamOptions<TTemporaryReferences> = {\n onError: (error: unknown) => unknown;\n temporaryReferences: TTemporaryReferences;\n};\n\ntype DecodeServerActionReplyOptions<TTemporaryReferences> = {\n temporaryReferences: TTemporaryReferences;\n};\n\nexport type HandleProgressiveServerActionRequestOptions = {\n actionId: string | null;\n allowedOrigins: string[];\n /** Configured next.config `basePath`. Prefixed onto progressive Location targets. */\n basePath?: string;\n cleanPathname: string;\n clearRequestContext: () => void;\n contentType: string;\n decodeAction: AppServerActionDecoder;\n decodeFormState: AppServerActionFormStateDecoder;\n getAndClearPendingCookies: () => string[];\n getDraftModeCookieHeader: () => string | null | undefined;\n maxActionBodySize: number;\n middlewareHeaders: Headers | null;\n readFormDataWithLimit: ReadFormDataWithLimit;\n reportRequestError: AppServerActionErrorReporter;\n request: Request;\n setHeadersAccessPhase: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n};\n\nexport type HandleServerActionRscRequestOptions<\n TElement,\n TRoute extends AppServerActionRoute,\n TInterceptOpts,\n TTemporaryReferences,\n TPage = unknown,\n> = {\n actionId: string | null;\n allowedOrigins: string[];\n /** Configured next.config `basePath`. Prefixed onto ACTION_REDIRECT_HEADER targets. */\n basePath?: string;\n buildPageElement: (\n options: BuildServerActionPageElementOptions<TRoute, TInterceptOpts>,\n ) => TElement;\n cleanPathname: string;\n clearRequestContext: () => void;\n contentType: string;\n createNotFoundElement: (routeId: string) => TElement;\n createPayloadRouteId: (pathname: string, interceptionContext: string | null) => string;\n createRscOnErrorHandler: (\n request: Request,\n pathname: string,\n pattern: string,\n ) => (error: unknown) => unknown;\n createTemporaryReferenceSet: () => TTemporaryReferences;\n decodeReply: (\n body: string | FormData,\n options: DecodeServerActionReplyOptions<TTemporaryReferences>,\n ) => Promise<unknown[]> | unknown[];\n findIntercept: (pathname: string) => AppServerActionIntercept<TPage> | null;\n getAndClearPendingCookies: () => string[];\n getDraftModeCookieHeader: () => string | null | undefined;\n getRouteParamNames: (route: TRoute) => readonly string[];\n getSourceRoute: (sourceRouteIndex: number) => TRoute | undefined;\n isRscRequest: boolean;\n loadServerAction: (actionId: string) => Promise<unknown>;\n matchRoute: (pathname: string) => AppServerActionMatch<TRoute> | null;\n maxActionBodySize: number;\n middlewareHeaders: Headers | null;\n middlewareStatus: number | null | undefined;\n mountedSlotsHeader: string | null;\n readBodyWithLimit: ReadBodyWithLimit;\n readFormDataWithLimit: ReadFormDataWithLimit;\n renderToReadableStream: (\n model: AppServerActionRscModel<TElement>,\n options: RenderServerActionRscStreamOptions<TTemporaryReferences>,\n ) => BodyInit | null | Promise<BodyInit | null>;\n reportRequestError: AppServerActionErrorReporter;\n resolveRouteFetchCacheMode?: (route: TRoute) => FetchCacheMode | null;\n request: Request;\n sanitizeErrorForClient: (error: unknown) => unknown;\n searchParams: URLSearchParams;\n setHeadersAccessPhase: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n setNavigationContext: (context: {\n params: AppPageParams;\n pathname: string;\n searchParams: URLSearchParams;\n }) => void;\n toInterceptOpts: (intercept: AppServerActionIntercept<TPage>) => TInterceptOpts;\n};\n\n/**\n * Matches Next.js' server action argument cap to prevent stack overflow in\n * Function.prototype.apply when decoding hostile action payloads.\n */\nconst SERVER_ACTION_ARGS_LIMIT = 1000;\nconst ACTION_DID_NOT_REVALIDATE = 0 satisfies ActionRevalidationKind;\nconst ACTION_DID_REVALIDATE_STATIC_AND_DYNAMIC = 1 satisfies ActionRevalidationKind;\n\nfunction setActionRevalidatedHeader(headers: Headers, kind: ActionRevalidationKind): void {\n if (kind === ACTION_DID_NOT_REVALIDATE) return;\n headers.set(ACTION_REVALIDATED_HEADER, JSON.stringify(kind));\n}\n\nfunction resolveActionRevalidationKind(hasModifiedCookies: boolean): ActionRevalidationKind {\n const revalidationKind = getAndClearActionRevalidationKind();\n // Cookie mutations are a hard override to STATIC_AND_DYNAMIC: any cookie\n // change can invalidate downstream cached payloads regardless of what\n // (if anything) the action explicitly revalidated, so we always emit the\n // strongest kind. STATIC_AND_DYNAMIC is also the lowest numeric value, so\n // this matches the max-precedence semantics in markActionRevalidation.\n if (hasModifiedCookies) return ACTION_DID_REVALIDATE_STATIC_AND_DYNAMIC;\n return revalidationKind;\n}\n\nfunction isRequestBodyTooLarge(error: unknown): boolean {\n return error instanceof Error && error.message === \"Request body too large\";\n}\n\nfunction isAppServerActionFunction(action: unknown): action is AppServerActionFunction {\n return typeof action === \"function\";\n}\n\nfunction normalizeError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction getServerActionFailureMessage(error: unknown): string {\n return error instanceof Error && error.message ? error.message : String(error);\n}\n\nfunction validateServerActionArgs(args: readonly unknown[]): void {\n if (args.length > SERVER_ACTION_ARGS_LIMIT) {\n throw new Error(\n `Server Action arguments list is too long (${args.length}). Maximum allowed is ${SERVER_ACTION_ARGS_LIMIT}.`,\n );\n }\n}\n\nexport async function readActionBodyWithLimit(request: Request, maxBytes: number): Promise<string> {\n if (!request.body) return \"\";\n return readStreamAsTextWithLimit(request.body, maxBytes, () => {\n throw new Error(\"Request body too large\");\n });\n}\n\nexport async function readActionFormDataWithLimit(\n request: Request,\n maxBytes: number,\n): Promise<FormData> {\n if (!request.body) return new FormData();\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalSize = 0;\n\n for (;;) {\n const result = await reader.read();\n if (result.done) break;\n\n totalSize += result.value.byteLength;\n if (totalSize > maxBytes) {\n await reader.cancel();\n throw new Error(\"Request body too large\");\n }\n chunks.push(result.value);\n }\n\n const combined = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return new Response(combined, {\n headers: { \"Content-Type\": request.headers.get(\"content-type\") || \"\" },\n }).formData();\n}\n\nfunction getActionRedirect(error: unknown): AppServerActionRedirect | null {\n const digest = getNextErrorDigest(error);\n if (!digest) return null;\n\n const redirect = parseNextRedirectDigest(digest);\n if (!redirect) return null;\n\n return {\n status: redirect.status,\n type: redirect.type ?? \"push\",\n url: redirect.url,\n };\n}\n\n/**\n * Prepend the configured next.config `basePath` to a server-action redirect\n * target before it goes on the wire.\n *\n * `redirect(\"/foo\")` called from a server action mounted at `/base/...` must\n * land the browser at `/base/foo`, mirroring how Next.js threads basePath\n * through `addPathPrefix(getURLFromRedirectError(err), basePath)` in\n * `app-render.tsx` for SSR redirects and in `action-handler.ts` for action\n * redirects.\n *\n * Idempotent and external-aware:\n * - Empty basePath → returned unchanged.\n * - External URLs (`http://`, `https://`, `data:`, protocol-relative `//`)\n * are returned unchanged because the framework does not own those routes.\n * - Targets that already start with the configured basePath are returned\n * unchanged so this helper can be applied at any layer without risk of\n * double-prefixing (`/base/base/foo`).\n *\n * Exported for tests. Used by both the progressive (no-JS form POST) and\n * RSC (`ACTION_REDIRECT_HEADER`) action redirect paths below.\n *\n * @see https://github.com/vercel/next.js/blob/canary/packages/next/src/server/app-render/action-handler.ts\n */\nexport function applyActionRedirectBasePath(url: string, basePath: string): string {\n if (!basePath) return url;\n if (isExternalUrl(url)) return url;\n // Pathnames that already include basePath are returned as-is.\n if (hasBasePath(url, basePath)) return url;\n // Relative or hash/query-only targets cannot be prefixed safely without an\n // origin; leave them to the caller's URL resolution.\n if (!url.startsWith(\"/\")) return url;\n // Split off optional query+hash so addBasePathToPathname only operates on\n // the path. We must accept hash too because Next.js redirect targets may\n // contain \"#anchor\".\n const queryIndex = url.indexOf(\"?\");\n const hashIndex = url.indexOf(\"#\");\n const splitAt =\n queryIndex === -1 ? hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const pathname = splitAt === -1 ? url : url.slice(0, splitAt);\n const suffix = splitAt === -1 ? \"\" : url.slice(splitAt);\n return `${addBasePathToPathname(pathname, basePath)}${suffix}`;\n}\n\nfunction getActionHttpFallbackStatus(error: unknown): number | null {\n const digest = getNextErrorDigest(error);\n if (!digest) return null;\n\n const httpError = parseNextHttpErrorDigest(digest);\n if (!httpError || !Number.isInteger(httpError.status)) return null;\n\n return httpError.status;\n}\n\nfunction createServerActionErrorResponse(\n error: unknown,\n options: {\n cleanPathname: string;\n clearRequestContext: () => void;\n getAndClearPendingCookies: () => string[];\n reportRequestError: AppServerActionErrorReporter;\n request: Request;\n },\n): Response {\n options.getAndClearPendingCookies();\n console.error(\"[vinext] Server action error:\", error);\n options.reportRequestError(\n normalizeError(error),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n { routerKind: \"App Router\", routePath: options.cleanPathname, routeType: \"action\" },\n );\n options.clearRequestContext();\n return internalServerErrorResponse(\n process.env.NODE_ENV === \"production\"\n ? undefined\n : \"Server action failed: \" + getServerActionFailureMessage(error),\n );\n}\n\nfunction createActionNotFoundResponse(\n actionId: string | null,\n options: {\n clearRequestContext: () => void;\n getAndClearPendingCookies: () => string[];\n },\n): Response {\n options.getAndClearPendingCookies();\n console.warn(getServerActionNotFoundMessage(actionId));\n options.clearRequestContext();\n return createServerActionNotFoundResponse();\n}\n\nexport function isProgressiveServerActionRequest(\n request: Pick<Request, \"method\">,\n contentType: string,\n actionId: string | null,\n): boolean {\n return (\n request.method.toUpperCase() === \"POST\" &&\n contentType.startsWith(\"multipart/form-data\") &&\n !actionId\n );\n}\n\nexport async function handleProgressiveServerActionRequest(\n options: HandleProgressiveServerActionRequestOptions,\n): Promise<Response | ProgressiveServerActionResult | null> {\n if (!isProgressiveServerActionRequest(options.request, options.contentType, options.actionId)) {\n return null;\n }\n\n // Defensive guard: prevent infinite forwarding loops. See handleServerActionRscRequest.\n if (options.request.headers.get(ACTION_FORWARDED_HEADER)) {\n return createActionNotFoundResponse(null, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n const csrfResponse = validateCsrfOrigin(options.request, options.allowedOrigins);\n if (csrfResponse) {\n return csrfResponse;\n }\n\n const contentLength = parseInt(options.request.headers.get(\"content-length\") || \"0\", 10);\n if (contentLength > options.maxActionBodySize) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n\n try {\n let body: FormData;\n try {\n // Progressive submissions can still fall through to a regular page render when\n // the multipart body is not an action payload. Read a clone so that fallback\n // code can still consume the original request body.\n body = await options.readFormDataWithLimit(\n options.request.clone(),\n options.maxActionBodySize,\n );\n } catch (error) {\n if (isRequestBodyTooLarge(error)) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n throw error;\n }\n\n const payloadResponse = await validateServerActionPayload(body);\n if (payloadResponse) {\n options.clearRequestContext();\n return payloadResponse;\n }\n\n const action = await options.decodeAction(body);\n if (!isAppServerActionFunction(action)) {\n return null;\n }\n\n let actionRedirect: AppServerActionRedirect | null = null;\n let actionError: unknown = undefined;\n let actionFailed = false;\n let actionResult: unknown;\n const previousHeadersPhase = options.setHeadersAccessPhase(\"action\");\n try {\n actionResult = await action();\n } catch (error) {\n actionRedirect = getActionRedirect(error);\n if (!actionRedirect) {\n actionError = error;\n actionFailed = true;\n const isControlFlow =\n getActionHttpFallbackStatus(error) !== null || isServerActionNotFoundError(error, null);\n if (!isControlFlow) {\n console.error(\"[vinext] Server action error:\", error);\n options.reportRequestError(\n normalizeError(error),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n { routerKind: \"App Router\", routePath: options.cleanPathname, routeType: \"action\" },\n );\n }\n }\n } finally {\n options.setHeadersAccessPhase(previousHeadersPhase);\n }\n\n if (!actionRedirect) {\n getAndClearActionRevalidationKind();\n if (actionFailed) {\n return { kind: \"form-state\", formState: null, actionError, actionFailed };\n }\n\n const formState = await options.decodeFormState(actionResult, body);\n return { kind: \"form-state\", formState: formState ?? null };\n }\n\n const actionPendingCookies = options.getAndClearPendingCookies();\n const actionDraftCookie = options.getDraftModeCookieHeader();\n const actionRevalidationKind = resolveActionRevalidationKind(\n actionPendingCookies.length > 0 || Boolean(actionDraftCookie),\n );\n options.clearRequestContext();\n\n const headers = new Headers();\n // Prefix the configured basePath onto the redirect target before it\n // becomes an absolute Location URL. Mirrors Next.js, which threads\n // basePath through `addPathPrefix(...)` for server-action redirects.\n const prefixedRedirectUrl = applyActionRedirectBasePath(\n actionRedirect.url,\n options.basePath ?? \"\",\n );\n headers.set(\"Location\", new URL(prefixedRedirectUrl, options.request.url).toString());\n mergeMiddlewareResponseHeaders(headers, options.middlewareHeaders);\n for (const cookie of actionPendingCookies) {\n headers.append(\"Set-Cookie\", cookie);\n }\n if (actionDraftCookie) {\n headers.append(\"Set-Cookie\", actionDraftCookie);\n }\n setActionRevalidatedHeader(headers, actionRevalidationKind);\n\n return new Response(null, {\n status: 303,\n headers,\n });\n } catch (error) {\n if (isServerActionNotFoundError(error, null)) {\n return createActionNotFoundResponse(null, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n getAndClearActionRevalidationKind();\n options.getAndClearPendingCookies();\n console.error(\"[vinext] Server action payload parsing error:\", error);\n options.reportRequestError(\n normalizeError(error),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n { routerKind: \"App Router\", routePath: options.cleanPathname, routeType: \"action\" },\n );\n options.clearRequestContext();\n return internalServerErrorResponse(\n process.env.NODE_ENV === \"production\"\n ? undefined\n : \"Server action parsing failed: \" + getServerActionFailureMessage(error),\n );\n }\n}\n\nexport async function handleServerActionRscRequest<\n TElement,\n TRoute extends AppServerActionRoute,\n TInterceptOpts,\n TTemporaryReferences,\n TPage = unknown,\n>(\n options: HandleServerActionRscRequestOptions<\n TElement,\n TRoute,\n TInterceptOpts,\n TTemporaryReferences,\n TPage\n >,\n): Promise<Response | null> {\n if (options.request.method.toUpperCase() !== \"POST\" || !options.actionId) {\n return null;\n }\n\n // Defensive guard: if this request has already been forwarded between workers,\n // do not attempt to process it again. Prevents infinite forwarding loops when\n // middleware rewrites action POSTs. Matches Next.js behavior:\n // https://github.com/vercel/next.js/commit/20892dd44e1321c13f755f051e48c3cadd75204b\n if (options.request.headers.get(ACTION_FORWARDED_HEADER)) {\n return createActionNotFoundResponse(options.actionId, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n const csrfResponse = validateCsrfOrigin(options.request, options.allowedOrigins);\n if (csrfResponse) return csrfResponse;\n\n const contentLength = parseInt(options.request.headers.get(\"content-length\") || \"0\", 10);\n if (contentLength > options.maxActionBodySize) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n\n try {\n let body: string | FormData;\n try {\n body = options.contentType.startsWith(\"multipart/form-data\")\n ? await options.readFormDataWithLimit(options.request, options.maxActionBodySize)\n : await options.readBodyWithLimit(options.request, options.maxActionBodySize);\n } catch (error) {\n if (isRequestBodyTooLarge(error)) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n throw error;\n }\n\n const payloadResponse = await validateServerActionPayload(body);\n if (payloadResponse) {\n options.clearRequestContext();\n return payloadResponse;\n }\n\n let action: unknown;\n try {\n action = await options.loadServerAction(options.actionId);\n } catch (error) {\n if (isServerActionNotFoundError(error, options.actionId)) {\n return createActionNotFoundResponse(options.actionId, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n throw error;\n }\n\n if (!isAppServerActionFunction(action)) {\n return createActionNotFoundResponse(options.actionId, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n const temporaryReferences = options.createTemporaryReferenceSet();\n const args = await options.decodeReply(body, { temporaryReferences });\n let returnValue: AppServerActionReturnValue;\n let actionRedirect: AppServerActionRedirect | null = null;\n let actionStatus = 200;\n const previousHeadersPhase = options.setHeadersAccessPhase(\"action\");\n try {\n try {\n validateServerActionArgs(args);\n const data = await action.apply(null, args);\n returnValue = { ok: true, data };\n } catch (error) {\n actionRedirect = getActionRedirect(error);\n if (actionRedirect) {\n returnValue = { ok: true, data: undefined };\n } else {\n const httpFallbackStatus = getActionHttpFallbackStatus(error);\n if (httpFallbackStatus !== null) {\n actionStatus = httpFallbackStatus;\n returnValue = { ok: false, data: error };\n } else {\n console.error(\"[vinext] Server action error:\", error);\n returnValue = { ok: false, data: options.sanitizeErrorForClient(error) };\n }\n }\n }\n } finally {\n options.setHeadersAccessPhase(previousHeadersPhase);\n }\n\n if (actionRedirect) {\n const actionPendingCookies = options.getAndClearPendingCookies();\n const actionDraftCookie = options.getDraftModeCookieHeader();\n const actionRevalidationKind = resolveActionRevalidationKind(\n actionPendingCookies.length > 0 || Boolean(actionDraftCookie),\n );\n options.clearRequestContext();\n const redirectHeaders = new Headers({\n \"Content-Type\": VINEXT_RSC_CONTENT_TYPE,\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n mergeMiddlewareResponseHeaders(redirectHeaders, options.middlewareHeaders);\n applyRscCompatibilityIdHeader(redirectHeaders);\n // Prefix basePath onto the redirect target. The client-side handler in\n // app-browser-entry reads ACTION_REDIRECT_HEADER and calls\n // window.location.assign/replace verbatim, so the value must already\n // be a basePath-prefixed URL.\n redirectHeaders.set(\n ACTION_REDIRECT_HEADER,\n applyActionRedirectBasePath(actionRedirect.url, options.basePath ?? \"\"),\n );\n redirectHeaders.set(ACTION_REDIRECT_TYPE_HEADER, actionRedirect.type);\n redirectHeaders.set(ACTION_REDIRECT_STATUS_HEADER, String(actionRedirect.status));\n for (const cookie of actionPendingCookies) {\n redirectHeaders.append(\"Set-Cookie\", cookie);\n }\n if (actionDraftCookie) redirectHeaders.append(\"Set-Cookie\", actionDraftCookie);\n setActionRevalidatedHeader(redirectHeaders, actionRevalidationKind);\n return new Response(\"\", { status: 200, headers: redirectHeaders });\n }\n\n const actionPendingCookies = options.getAndClearPendingCookies();\n const actionDraftCookie = options.getDraftModeCookieHeader();\n const actionRevalidationKind = resolveActionRevalidationKind(\n actionPendingCookies.length > 0 || Boolean(actionDraftCookie),\n );\n\n const shouldSkipPageRendering = actionRevalidationKind === ACTION_DID_NOT_REVALIDATE;\n if (shouldSkipPageRendering) {\n const onRenderError = options.createRscOnErrorHandler(\n options.request,\n options.cleanPathname,\n options.cleanPathname,\n );\n const rscStream = await options.renderToReadableStream(\n { returnValue },\n { temporaryReferences, onError: onRenderError },\n );\n\n options.clearRequestContext();\n\n const actionHeaders = new Headers({\n \"Content-Type\": VINEXT_RSC_CONTENT_TYPE,\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n mergeMiddlewareResponseHeaders(actionHeaders, options.middlewareHeaders);\n applyRscCompatibilityIdHeader(actionHeaders);\n\n return new Response(rscStream, {\n status: options.middlewareStatus ?? actionStatus,\n headers: actionHeaders,\n });\n }\n\n const match = options.matchRoute(options.cleanPathname);\n let element: TElement;\n let errorPattern = match ? match.route.pattern : options.cleanPathname;\n if (match) {\n const { route: actionRoute, params: actionParams } = match;\n const actionRerenderTarget = resolveAppPageActionRerenderTarget({\n cleanPathname: options.cleanPathname,\n currentParams: actionParams,\n currentRoute: actionRoute,\n findIntercept: options.findIntercept,\n getRouteParamNames: options.getRouteParamNames,\n getSourceRoute: options.getSourceRoute,\n isRscRequest: options.isRscRequest,\n toInterceptOpts: options.toInterceptOpts,\n });\n\n options.setNavigationContext({\n pathname: options.cleanPathname,\n searchParams: options.searchParams,\n params: actionRerenderTarget.navigationParams,\n });\n setCurrentFetchCacheMode(\n options.resolveRouteFetchCacheMode?.(actionRerenderTarget.route) ?? null,\n );\n element = options.buildPageElement({\n cleanPathname: options.cleanPathname,\n interceptOpts: actionRerenderTarget.interceptOpts,\n isRscRequest: options.isRscRequest,\n mountedSlotsHeader: options.mountedSlotsHeader,\n params: actionRerenderTarget.params,\n request: options.request,\n route: actionRerenderTarget.route,\n searchParams: options.searchParams,\n renderMode: APP_RSC_RENDER_MODE_ACTION_RERENDER_PRESERVE_UI,\n });\n errorPattern = actionRerenderTarget.route.pattern;\n } else {\n const actionRouteId = options.createPayloadRouteId(options.cleanPathname, null);\n element = options.createNotFoundElement(actionRouteId);\n }\n\n const onRenderError = options.createRscOnErrorHandler(\n options.request,\n options.cleanPathname,\n errorPattern,\n );\n const rscStream = await options.renderToReadableStream(\n { root: element, returnValue },\n { temporaryReferences, onError: onRenderError },\n );\n\n const actionHeaders = new Headers({\n \"Content-Type\": VINEXT_RSC_CONTENT_TYPE,\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n mergeMiddlewareResponseHeaders(actionHeaders, options.middlewareHeaders);\n applyRscCompatibilityIdHeader(actionHeaders);\n setActionRevalidatedHeader(actionHeaders, actionRevalidationKind);\n const actionResponse = new Response(rscStream, {\n status: options.middlewareStatus ?? actionStatus,\n headers: actionHeaders,\n });\n if (actionPendingCookies.length > 0 || actionDraftCookie) {\n for (const cookie of actionPendingCookies) {\n actionResponse.headers.append(\"Set-Cookie\", cookie);\n }\n if (actionDraftCookie) actionResponse.headers.append(\"Set-Cookie\", actionDraftCookie);\n }\n return actionResponse;\n } catch (error) {\n getAndClearActionRevalidationKind();\n return createServerActionErrorResponse(error, {\n cleanPathname: options.cleanPathname,\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n reportRequestError: options.reportRequestError,\n request: options.request,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2NA,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAClC,MAAM,2CAA2C;AAEjD,SAAS,2BAA2B,SAAkB,MAAoC;CACxF,IAAI,SAAS,2BAA2B;CACxC,QAAQ,IAAI,2BAA2B,KAAK,UAAU,KAAK,CAAC;;AAG9D,SAAS,8BAA8B,oBAAqD;CAC1F,MAAM,mBAAmB,mCAAmC;CAM5D,IAAI,oBAAoB,OAAO;CAC/B,OAAO;;AAGT,SAAS,sBAAsB,OAAyB;CACtD,OAAO,iBAAiB,SAAS,MAAM,YAAY;;AAGrD,SAAS,0BAA0B,QAAoD;CACrF,OAAO,OAAO,WAAW;;AAG3B,SAAS,eAAe,OAAuB;CAC7C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;;AAGlE,SAAS,8BAA8B,OAAwB;CAC7D,OAAO,iBAAiB,SAAS,MAAM,UAAU,MAAM,UAAU,OAAO,MAAM;;AAGhF,SAAS,yBAAyB,MAAgC;CAChE,IAAI,KAAK,SAAS,0BAChB,MAAM,IAAI,MACR,6CAA6C,KAAK,OAAO,wBAAwB,yBAAyB,GAC3G;;AAIL,eAAsB,wBAAwB,SAAkB,UAAmC;CACjG,IAAI,CAAC,QAAQ,MAAM,OA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[],"sources":["../../src/server/app-server-action-execution.ts"],"sourcesContent":["import { getAndClearActionRevalidationKind, type ActionRevalidationKind } from \"vinext/shims/cache\";\nimport type { HeadersAccessPhase } from \"vinext/shims/headers\";\nimport { type FetchCacheMode, setCurrentFetchCacheMode } from \"vinext/shims/fetch-cache\";\nimport type { ReactFormState } from \"react-dom/client\";\nimport { isExternalUrl } from \"../config/config-matchers.js\";\nimport { addBasePathToPathname, hasBasePath } from \"../utils/base-path.js\";\nimport {\n ACTION_FORWARDED_HEADER,\n ACTION_REDIRECT_HEADER,\n ACTION_REDIRECT_STATUS_HEADER,\n ACTION_REDIRECT_TYPE_HEADER,\n ACTION_REVALIDATED_HEADER,\n} from \"./headers.js\";\nimport {\n VINEXT_RSC_CONTENT_TYPE,\n VINEXT_RSC_VARY_HEADER,\n applyRscCompatibilityIdHeader,\n} from \"./app-rsc-cache-busting.js\";\nimport { applyEdgeRuntimeHeader } from \"./app-page-response.js\";\nimport { resolveAppPageActionRerenderTarget } from \"./app-page-request.js\";\nimport { mergeMiddlewareResponseHeaders } from \"./middleware-response-headers.js\";\nimport { getSetCookieName } from \"./cookie-utils.js\";\nimport {\n APP_RSC_RENDER_MODE_ACTION_RERENDER_PRESERVE_UI,\n type AppRscRenderMode,\n} from \"./app-rsc-render-mode.js\";\nimport {\n getNextErrorDigest,\n parseNextHttpErrorDigest,\n parseNextRedirectDigest,\n} from \"./next-error-digest.js\";\nimport { validateCsrfOrigin, validateServerActionPayload } from \"./request-pipeline.js\";\nimport { readStreamAsTextWithLimit } from \"../utils/text-stream.js\";\nimport {\n createServerActionNotFoundResponse,\n getServerActionNotFoundMessage,\n isServerActionNotFoundError,\n} from \"./server-action-not-found.js\";\nimport { internalServerErrorResponse, payloadTooLargeResponse } from \"./http-error-responses.js\";\n\ntype AppPageParams = Record<string, string | string[]>;\n\ntype AppServerActionErrorReporter = (\n error: Error,\n request: { path: string; method: string; headers: Record<string, string> },\n route: { routerKind: \"App Router\"; routePath: string; routeType: \"action\" },\n) => void;\n\ntype AppServerActionDecoder = (body: FormData) => Promise<unknown>;\ntype AppServerActionFormStateDecoder = (\n actionResult: unknown,\n body: FormData,\n) => Promise<ReactFormState | undefined>;\n\ntype ReadFormDataWithLimit = (request: Request, maxBytes: number) => Promise<FormData>;\n\ntype ReadBodyWithLimit = (request: Request, maxBytes: number) => Promise<string>;\n\ntype AppServerActionFunction = (...args: unknown[]) => unknown;\n\ntype AppServerActionReturnValue =\n | {\n data: unknown;\n ok: true;\n }\n | {\n data: unknown;\n ok: false;\n };\n\ntype AppServerActionRedirect = {\n status: number;\n type: string;\n url: string;\n};\n\ntype AppServerActionRoute = {\n pattern: string;\n};\n\n/**\n * Side-effect headers captured during a progressive (no-JS) server action's\n * non-redirect execution. The caller (app-rsc-handler) must apply these to the\n * page render response so that `cookies().set(...)` and revalidation kinds\n * propagate to the browser. Without this, no-JS form submissions silently\n * lose cookie/header mutations — see issue #1483.\n *\n * Next.js' equivalent path mutates `res.setHeader('set-cookie', ...)` during\n * action execution (action-handler.ts → app-render.tsx), then `sendResponse`\n * merges those headers with the rendered Response. vinext works with Response\n * objects directly so the cookies must ride out via the result instead.\n */\ntype ProgressiveServerActionSideEffects = {\n /** `Set-Cookie` headers from `cookies().set(...)` / `cookies().delete(...)`. */\n pendingCookies: string[];\n /** `Set-Cookie` header from `draftMode().enable()/disable()` (if any). */\n draftCookie: string | null | undefined;\n /** Resolved revalidation kind to emit via `x-action-revalidated`. */\n revalidationKind: ActionRevalidationKind;\n};\n\ntype ProgressiveServerActionResult =\n | ({\n formState: ReactFormState | null;\n kind: \"form-state\";\n } & ProgressiveServerActionSideEffects)\n | ({\n actionError: unknown;\n actionFailed: true;\n formState: null;\n kind: \"form-state\";\n } & ProgressiveServerActionSideEffects);\n\ntype AppServerActionMatch<TRoute extends AppServerActionRoute> = {\n params: AppPageParams;\n route: TRoute;\n};\n\ntype AppServerActionIntercept<TPage = unknown> = {\n matchedParams: AppPageParams;\n page: TPage;\n slotId?: string | null;\n slotKey: string;\n sourceRouteIndex: number;\n};\n\ntype BuildServerActionPageElementOptions<TRoute extends AppServerActionRoute, TInterceptOpts> = {\n cleanPathname: string;\n interceptOpts: TInterceptOpts | undefined;\n isRscRequest: boolean;\n mountedSlotsHeader: string | null;\n params: AppPageParams;\n request: Request;\n route: TRoute;\n searchParams: URLSearchParams;\n renderMode: AppRscRenderMode;\n};\n\ntype AppServerActionRscModel<TElement> = {\n /**\n * Omitted when the action did not invalidate page data. This mirrors Next.js'\n * empty Flight payload for non-revalidating fetch actions: the client resolves\n * the action value without committing a visible router update.\n */\n root?: TElement;\n returnValue: AppServerActionReturnValue;\n};\n\ntype RenderServerActionRscStreamOptions<TTemporaryReferences> = {\n onError: (error: unknown) => unknown;\n temporaryReferences: TTemporaryReferences;\n};\n\ntype DecodeServerActionReplyOptions<TTemporaryReferences> = {\n temporaryReferences: TTemporaryReferences;\n};\n\nexport type HandleProgressiveServerActionRequestOptions = {\n actionId: string | null;\n allowedOrigins: string[];\n /** Configured next.config `basePath`. Prefixed onto progressive Location targets. */\n basePath?: string;\n cleanPathname: string;\n clearRequestContext: () => void;\n contentType: string;\n decodeAction: AppServerActionDecoder;\n decodeFormState: AppServerActionFormStateDecoder;\n getAndClearPendingCookies: () => string[];\n getDraftModeCookieHeader: () => string | null | undefined;\n maxActionBodySize: number;\n middlewareHeaders: Headers | null;\n readFormDataWithLimit: ReadFormDataWithLimit;\n reportRequestError: AppServerActionErrorReporter;\n request: Request;\n setHeadersAccessPhase: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n};\n\nexport type HandleServerActionRscRequestOptions<\n TElement,\n TRoute extends AppServerActionRoute,\n TInterceptOpts,\n TTemporaryReferences,\n TPage = unknown,\n> = {\n actionId: string | null;\n allowedOrigins: string[];\n /** Configured next.config `basePath`. Prefixed onto ACTION_REDIRECT_HEADER targets. */\n basePath?: string;\n buildPageElement: (\n options: BuildServerActionPageElementOptions<TRoute, TInterceptOpts>,\n ) => TElement;\n cleanPathname: string;\n clearRequestContext: () => void;\n contentType: string;\n createNotFoundElement: (routeId: string) => TElement;\n createPayloadRouteId: (pathname: string, interceptionContext: string | null) => string;\n createRscOnErrorHandler: (\n request: Request,\n pathname: string,\n pattern: string,\n ) => (error: unknown) => unknown;\n createTemporaryReferenceSet: () => TTemporaryReferences;\n decodeReply: (\n body: string | FormData,\n options: DecodeServerActionReplyOptions<TTemporaryReferences>,\n ) => Promise<unknown[]> | unknown[];\n findIntercept: (pathname: string) => AppServerActionIntercept<TPage> | null;\n getAndClearPendingCookies: () => string[];\n getDraftModeCookieHeader: () => string | null | undefined;\n getRouteParamNames: (route: TRoute) => readonly string[];\n getSourceRoute: (sourceRouteIndex: number) => TRoute | undefined;\n isEdgeRuntime?: boolean;\n isRscRequest: boolean;\n loadServerAction: (actionId: string) => Promise<unknown>;\n matchRoute: (pathname: string) => AppServerActionMatch<TRoute> | null;\n maxActionBodySize: number;\n middlewareHeaders: Headers | null;\n middlewareStatus: number | null | undefined;\n mountedSlotsHeader: string | null;\n readBodyWithLimit: ReadBodyWithLimit;\n readFormDataWithLimit: ReadFormDataWithLimit;\n renderToReadableStream: (\n model: AppServerActionRscModel<TElement>,\n options: RenderServerActionRscStreamOptions<TTemporaryReferences>,\n ) => BodyInit | null | Promise<BodyInit | null>;\n reportRequestError: AppServerActionErrorReporter;\n resolveRouteFetchCacheMode?: (route: TRoute) => FetchCacheMode | null;\n request: Request;\n sanitizeErrorForClient: (error: unknown) => unknown;\n searchParams: URLSearchParams;\n setHeadersAccessPhase: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n setNavigationContext: (context: {\n params: AppPageParams;\n pathname: string;\n searchParams: URLSearchParams;\n }) => void;\n toInterceptOpts: (intercept: AppServerActionIntercept<TPage>) => TInterceptOpts;\n};\n\n/**\n * Matches Next.js' server action argument cap to prevent stack overflow in\n * Function.prototype.apply when decoding hostile action payloads.\n */\nconst SERVER_ACTION_ARGS_LIMIT = 1000;\nconst ACTION_DID_NOT_REVALIDATE = 0 satisfies ActionRevalidationKind;\nconst ACTION_DID_REVALIDATE_STATIC_AND_DYNAMIC = 1 satisfies ActionRevalidationKind;\n\nfunction setActionRevalidatedHeader(headers: Headers, kind: ActionRevalidationKind): void {\n if (kind === ACTION_DID_NOT_REVALIDATE) return;\n headers.set(ACTION_REVALIDATED_HEADER, JSON.stringify(kind));\n}\n\nfunction resolveActionRevalidationKind(hasModifiedCookies: boolean): ActionRevalidationKind {\n const revalidationKind = getAndClearActionRevalidationKind();\n // Cookie mutations are a hard override to STATIC_AND_DYNAMIC: any cookie\n // change can invalidate downstream cached payloads regardless of what\n // (if anything) the action explicitly revalidated, so we always emit the\n // strongest kind. STATIC_AND_DYNAMIC is also the lowest numeric value, so\n // this matches the max-precedence semantics in markActionRevalidation.\n if (hasModifiedCookies) return ACTION_DID_REVALIDATE_STATIC_AND_DYNAMIC;\n return revalidationKind;\n}\n\nfunction isRequestBodyTooLarge(error: unknown): boolean {\n return error instanceof Error && error.message === \"Request body too large\";\n}\n\n/**\n * Collapse repeated `cookies().set(name, ...)` / `cookies().delete(name)`\n * calls down to the last value per name, matching Next.js'\n * `MutableRequestCookiesAdapter` semantics. Next.js stores response cookies in\n * a `ResponseCookies` Map keyed by name — multiple sets for the same cookie\n * collapse to the final value, and emit a single Set-Cookie header.\n *\n * Insertion order is preserved by first occurrence (Map iteration order),\n * which mirrors how `ResponseCookies` iterates its underlying Map. See\n * packages/next/src/server/web/spec-extension/adapters/request-cookies.ts.\n * Issue: https://github.com/cloudflare/vinext/issues/1481\n */\nfunction dedupePendingCookies(cookies: readonly string[]): string[] {\n if (cookies.length <= 1) {\n return cookies.slice();\n }\n const byName = new Map<string, string>();\n const unkeyed: string[] = [];\n for (const cookie of cookies) {\n const name = getSetCookieName(cookie);\n if (name === null) {\n unkeyed.push(cookie);\n continue;\n }\n // Map.set on an existing key replaces the value but preserves the\n // insertion position of the original key — exactly the behaviour we need\n // for `cookies().set(\"foo\", \"1\"); cookies().set(\"bar\", \"2\"); cookies().set(\"foo\", \"3\")`\n // to come out as [foo=3, bar=2].\n byName.set(name, cookie);\n }\n return [...unkeyed, ...byName.values()];\n}\n\nfunction isAppServerActionFunction(action: unknown): action is AppServerActionFunction {\n return typeof action === \"function\";\n}\n\nfunction normalizeError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction getServerActionFailureMessage(error: unknown): string {\n return error instanceof Error && error.message ? error.message : String(error);\n}\n\nfunction validateServerActionArgs(args: readonly unknown[]): void {\n if (args.length > SERVER_ACTION_ARGS_LIMIT) {\n throw new Error(\n `Server Action arguments list is too long (${args.length}). Maximum allowed is ${SERVER_ACTION_ARGS_LIMIT}.`,\n );\n }\n}\n\nexport async function readActionBodyWithLimit(request: Request, maxBytes: number): Promise<string> {\n if (!request.body) return \"\";\n return readStreamAsTextWithLimit(request.body, maxBytes, () => {\n throw new Error(\"Request body too large\");\n });\n}\n\nexport async function readActionFormDataWithLimit(\n request: Request,\n maxBytes: number,\n): Promise<FormData> {\n if (!request.body) return new FormData();\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalSize = 0;\n\n for (;;) {\n const result = await reader.read();\n if (result.done) break;\n\n totalSize += result.value.byteLength;\n if (totalSize > maxBytes) {\n await reader.cancel();\n throw new Error(\"Request body too large\");\n }\n chunks.push(result.value);\n }\n\n const combined = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return new Response(combined, {\n headers: { \"Content-Type\": request.headers.get(\"content-type\") || \"\" },\n }).formData();\n}\n\nfunction getActionRedirect(error: unknown): AppServerActionRedirect | null {\n const digest = getNextErrorDigest(error);\n if (!digest) return null;\n\n const redirect = parseNextRedirectDigest(digest);\n if (!redirect) return null;\n\n return {\n status: redirect.status,\n type: redirect.type ?? \"push\",\n url: redirect.url,\n };\n}\n\n/**\n * Prepend the configured next.config `basePath` to a server-action redirect\n * target before it goes on the wire.\n *\n * `redirect(\"/foo\")` called from a server action mounted at `/base/...` must\n * land the browser at `/base/foo`, mirroring how Next.js threads basePath\n * through `addPathPrefix(getURLFromRedirectError(err), basePath)` in\n * `app-render.tsx` for SSR redirects and in `action-handler.ts` for action\n * redirects.\n *\n * Idempotent and external-aware:\n * - Empty basePath → returned unchanged.\n * - External URLs (`http://`, `https://`, `data:`, protocol-relative `//`)\n * are returned unchanged because the framework does not own those routes.\n * - Targets that already start with the configured basePath are returned\n * unchanged so this helper can be applied at any layer without risk of\n * double-prefixing (`/base/base/foo`).\n *\n * Exported for tests. Used by both the progressive (no-JS form POST) and\n * RSC (`ACTION_REDIRECT_HEADER`) action redirect paths below.\n *\n * @see https://github.com/vercel/next.js/blob/canary/packages/next/src/server/app-render/action-handler.ts\n */\nexport function applyActionRedirectBasePath(url: string, basePath: string): string {\n if (!basePath) return url;\n if (isExternalUrl(url)) return url;\n // Pathnames that already include basePath are returned as-is.\n if (hasBasePath(url, basePath)) return url;\n // Relative or hash/query-only targets cannot be prefixed safely without an\n // origin; leave them to the caller's URL resolution.\n if (!url.startsWith(\"/\")) return url;\n // Split off optional query+hash so addBasePathToPathname only operates on\n // the path. We must accept hash too because Next.js redirect targets may\n // contain \"#anchor\".\n const queryIndex = url.indexOf(\"?\");\n const hashIndex = url.indexOf(\"#\");\n const splitAt =\n queryIndex === -1 ? hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const pathname = splitAt === -1 ? url : url.slice(0, splitAt);\n const suffix = splitAt === -1 ? \"\" : url.slice(splitAt);\n return `${addBasePathToPathname(pathname, basePath)}${suffix}`;\n}\n\nfunction getActionHttpFallbackStatus(error: unknown): number | null {\n const digest = getNextErrorDigest(error);\n if (!digest) return null;\n\n const httpError = parseNextHttpErrorDigest(digest);\n if (!httpError || !Number.isInteger(httpError.status)) return null;\n\n return httpError.status;\n}\n\nfunction createServerActionErrorResponse(\n error: unknown,\n options: {\n cleanPathname: string;\n clearRequestContext: () => void;\n getAndClearPendingCookies: () => string[];\n reportRequestError: AppServerActionErrorReporter;\n request: Request;\n },\n): Response {\n options.getAndClearPendingCookies();\n console.error(\"[vinext] Server action error:\", error);\n options.reportRequestError(\n normalizeError(error),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n { routerKind: \"App Router\", routePath: options.cleanPathname, routeType: \"action\" },\n );\n options.clearRequestContext();\n return internalServerErrorResponse(\n process.env.NODE_ENV === \"production\"\n ? undefined\n : \"Server action failed: \" + getServerActionFailureMessage(error),\n );\n}\n\nfunction createActionNotFoundResponse(\n actionId: string | null,\n options: {\n clearRequestContext: () => void;\n getAndClearPendingCookies: () => string[];\n },\n): Response {\n options.getAndClearPendingCookies();\n console.warn(getServerActionNotFoundMessage(actionId));\n options.clearRequestContext();\n return createServerActionNotFoundResponse();\n}\n\nexport function isProgressiveServerActionRequest(\n request: Pick<Request, \"method\">,\n contentType: string,\n actionId: string | null,\n): boolean {\n return (\n request.method.toUpperCase() === \"POST\" &&\n contentType.startsWith(\"multipart/form-data\") &&\n !actionId\n );\n}\n\nexport async function handleProgressiveServerActionRequest(\n options: HandleProgressiveServerActionRequestOptions,\n): Promise<Response | ProgressiveServerActionResult | null> {\n if (!isProgressiveServerActionRequest(options.request, options.contentType, options.actionId)) {\n return null;\n }\n\n // Defensive guard: prevent infinite forwarding loops. See handleServerActionRscRequest.\n if (options.request.headers.get(ACTION_FORWARDED_HEADER)) {\n return createActionNotFoundResponse(null, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n const csrfResponse = validateCsrfOrigin(options.request, options.allowedOrigins);\n if (csrfResponse) {\n return csrfResponse;\n }\n\n const contentLength = parseInt(options.request.headers.get(\"content-length\") || \"0\", 10);\n if (contentLength > options.maxActionBodySize) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n\n try {\n let body: FormData;\n try {\n // Progressive submissions can still fall through to a regular page render when\n // the multipart body is not an action payload. Read a clone so that fallback\n // code can still consume the original request body.\n body = await options.readFormDataWithLimit(\n options.request.clone(),\n options.maxActionBodySize,\n );\n } catch (error) {\n if (isRequestBodyTooLarge(error)) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n throw error;\n }\n\n const payloadResponse = await validateServerActionPayload(body);\n if (payloadResponse) {\n options.clearRequestContext();\n return payloadResponse;\n }\n\n const action = await options.decodeAction(body);\n if (!isAppServerActionFunction(action)) {\n return null;\n }\n\n let actionRedirect: AppServerActionRedirect | null = null;\n let actionError: unknown = undefined;\n let actionFailed = false;\n let actionResult: unknown;\n const previousHeadersPhase = options.setHeadersAccessPhase(\"action\");\n try {\n actionResult = await action();\n } catch (error) {\n actionRedirect = getActionRedirect(error);\n if (!actionRedirect) {\n actionError = error;\n actionFailed = true;\n const isControlFlow =\n getActionHttpFallbackStatus(error) !== null || isServerActionNotFoundError(error, null);\n if (!isControlFlow) {\n console.error(\"[vinext] Server action error:\", error);\n options.reportRequestError(\n normalizeError(error),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n { routerKind: \"App Router\", routePath: options.cleanPathname, routeType: \"action\" },\n );\n }\n }\n } finally {\n options.setHeadersAccessPhase(previousHeadersPhase);\n }\n\n if (!actionRedirect) {\n // Capture cookies/headers set during action execution so the caller can\n // apply them to the rendered page response. Mirrors Next.js'\n // `res.setHeader('set-cookie', ...)` path in app-render.tsx, which\n // flushes `requestStore.mutableCookies` onto the response before SSR\n // streaming begins. Without this, no-JS server-action form POSTs lose\n // cookies/headers — see issue #1483.\n const actionPendingCookies = options.getAndClearPendingCookies();\n const actionDraftCookie = options.getDraftModeCookieHeader();\n const revalidationKind = resolveActionRevalidationKind(\n actionPendingCookies.length > 0 || Boolean(actionDraftCookie),\n );\n\n if (actionFailed) {\n return {\n kind: \"form-state\",\n formState: null,\n actionError,\n actionFailed,\n pendingCookies: actionPendingCookies,\n draftCookie: actionDraftCookie,\n revalidationKind,\n };\n }\n\n const formState = await options.decodeFormState(actionResult, body);\n return {\n kind: \"form-state\",\n formState: formState ?? null,\n pendingCookies: actionPendingCookies,\n draftCookie: actionDraftCookie,\n revalidationKind,\n };\n }\n\n const actionPendingCookies = dedupePendingCookies(options.getAndClearPendingCookies());\n const actionDraftCookie = options.getDraftModeCookieHeader();\n const actionRevalidationKind = resolveActionRevalidationKind(\n actionPendingCookies.length > 0 || Boolean(actionDraftCookie),\n );\n options.clearRequestContext();\n\n const headers = new Headers();\n // Prefix the configured basePath onto the redirect target before it\n // becomes an absolute Location URL. Mirrors Next.js, which threads\n // basePath through `addPathPrefix(...)` for server-action redirects.\n const prefixedRedirectUrl = applyActionRedirectBasePath(\n actionRedirect.url,\n options.basePath ?? \"\",\n );\n headers.set(\"Location\", new URL(prefixedRedirectUrl, options.request.url).toString());\n mergeMiddlewareResponseHeaders(headers, options.middlewareHeaders);\n for (const cookie of actionPendingCookies) {\n headers.append(\"Set-Cookie\", cookie);\n }\n if (actionDraftCookie) {\n headers.append(\"Set-Cookie\", actionDraftCookie);\n }\n setActionRevalidatedHeader(headers, actionRevalidationKind);\n\n return new Response(null, {\n status: 303,\n headers,\n });\n } catch (error) {\n if (isServerActionNotFoundError(error, null)) {\n return createActionNotFoundResponse(null, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n getAndClearActionRevalidationKind();\n options.getAndClearPendingCookies();\n console.error(\"[vinext] Server action payload parsing error:\", error);\n options.reportRequestError(\n normalizeError(error),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n { routerKind: \"App Router\", routePath: options.cleanPathname, routeType: \"action\" },\n );\n options.clearRequestContext();\n return internalServerErrorResponse(\n process.env.NODE_ENV === \"production\"\n ? undefined\n : \"Server action parsing failed: \" + getServerActionFailureMessage(error),\n );\n }\n}\n\nexport async function handleServerActionRscRequest<\n TElement,\n TRoute extends AppServerActionRoute,\n TInterceptOpts,\n TTemporaryReferences,\n TPage = unknown,\n>(\n options: HandleServerActionRscRequestOptions<\n TElement,\n TRoute,\n TInterceptOpts,\n TTemporaryReferences,\n TPage\n >,\n): Promise<Response | null> {\n if (options.request.method.toUpperCase() !== \"POST\" || !options.actionId) {\n return null;\n }\n\n // Defensive guard: if this request has already been forwarded between workers,\n // do not attempt to process it again. Prevents infinite forwarding loops when\n // middleware rewrites action POSTs. Matches Next.js behavior:\n // https://github.com/vercel/next.js/commit/20892dd44e1321c13f755f051e48c3cadd75204b\n if (options.request.headers.get(ACTION_FORWARDED_HEADER)) {\n return createActionNotFoundResponse(options.actionId, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n const csrfResponse = validateCsrfOrigin(options.request, options.allowedOrigins);\n if (csrfResponse) return csrfResponse;\n\n const contentLength = parseInt(options.request.headers.get(\"content-length\") || \"0\", 10);\n if (contentLength > options.maxActionBodySize) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n\n try {\n let body: string | FormData;\n try {\n body = options.contentType.startsWith(\"multipart/form-data\")\n ? await options.readFormDataWithLimit(options.request, options.maxActionBodySize)\n : await options.readBodyWithLimit(options.request, options.maxActionBodySize);\n } catch (error) {\n if (isRequestBodyTooLarge(error)) {\n options.clearRequestContext();\n return payloadTooLargeResponse();\n }\n throw error;\n }\n\n const payloadResponse = await validateServerActionPayload(body);\n if (payloadResponse) {\n options.clearRequestContext();\n return payloadResponse;\n }\n\n let action: unknown;\n try {\n action = await options.loadServerAction(options.actionId);\n } catch (error) {\n if (isServerActionNotFoundError(error, options.actionId)) {\n return createActionNotFoundResponse(options.actionId, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n throw error;\n }\n\n if (!isAppServerActionFunction(action)) {\n return createActionNotFoundResponse(options.actionId, {\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n });\n }\n\n const temporaryReferences = options.createTemporaryReferenceSet();\n const args = await options.decodeReply(body, { temporaryReferences });\n let returnValue: AppServerActionReturnValue;\n let actionRedirect: AppServerActionRedirect | null = null;\n let actionStatus = 200;\n const previousHeadersPhase = options.setHeadersAccessPhase(\"action\");\n try {\n try {\n validateServerActionArgs(args);\n const data = await action.apply(null, args);\n returnValue = { ok: true, data };\n } catch (error) {\n actionRedirect = getActionRedirect(error);\n if (actionRedirect) {\n returnValue = { ok: true, data: undefined };\n } else {\n const httpFallbackStatus = getActionHttpFallbackStatus(error);\n if (httpFallbackStatus !== null) {\n actionStatus = httpFallbackStatus;\n returnValue = { ok: false, data: error };\n } else {\n console.error(\"[vinext] Server action error:\", error);\n returnValue = { ok: false, data: options.sanitizeErrorForClient(error) };\n }\n }\n }\n } finally {\n options.setHeadersAccessPhase(previousHeadersPhase);\n }\n\n if (actionRedirect) {\n const actionPendingCookies = dedupePendingCookies(options.getAndClearPendingCookies());\n const actionDraftCookie = options.getDraftModeCookieHeader();\n const actionRevalidationKind = resolveActionRevalidationKind(\n actionPendingCookies.length > 0 || Boolean(actionDraftCookie),\n );\n options.clearRequestContext();\n const redirectHeaders = new Headers({\n \"Content-Type\": VINEXT_RSC_CONTENT_TYPE,\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n applyEdgeRuntimeHeader(redirectHeaders, options.isEdgeRuntime);\n mergeMiddlewareResponseHeaders(redirectHeaders, options.middlewareHeaders);\n applyRscCompatibilityIdHeader(redirectHeaders);\n // Prefix basePath onto the redirect target. The client-side handler in\n // app-browser-entry reads ACTION_REDIRECT_HEADER and calls\n // window.location.assign/replace verbatim, so the value must already\n // be a basePath-prefixed URL.\n redirectHeaders.set(\n ACTION_REDIRECT_HEADER,\n applyActionRedirectBasePath(actionRedirect.url, options.basePath ?? \"\"),\n );\n redirectHeaders.set(ACTION_REDIRECT_TYPE_HEADER, actionRedirect.type);\n redirectHeaders.set(ACTION_REDIRECT_STATUS_HEADER, String(actionRedirect.status));\n for (const cookie of actionPendingCookies) {\n redirectHeaders.append(\"Set-Cookie\", cookie);\n }\n if (actionDraftCookie) redirectHeaders.append(\"Set-Cookie\", actionDraftCookie);\n setActionRevalidatedHeader(redirectHeaders, actionRevalidationKind);\n return new Response(\"\", { status: 200, headers: redirectHeaders });\n }\n\n const actionPendingCookies = dedupePendingCookies(options.getAndClearPendingCookies());\n const actionDraftCookie = options.getDraftModeCookieHeader();\n const actionRevalidationKind = resolveActionRevalidationKind(\n actionPendingCookies.length > 0 || Boolean(actionDraftCookie),\n );\n\n const shouldSkipPageRendering = actionRevalidationKind === ACTION_DID_NOT_REVALIDATE;\n if (shouldSkipPageRendering) {\n const onRenderError = options.createRscOnErrorHandler(\n options.request,\n options.cleanPathname,\n options.cleanPathname,\n );\n const rscStream = await options.renderToReadableStream(\n { returnValue },\n { temporaryReferences, onError: onRenderError },\n );\n\n options.clearRequestContext();\n\n const actionHeaders = new Headers({\n \"Content-Type\": VINEXT_RSC_CONTENT_TYPE,\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n applyEdgeRuntimeHeader(actionHeaders, options.isEdgeRuntime);\n mergeMiddlewareResponseHeaders(actionHeaders, options.middlewareHeaders);\n applyRscCompatibilityIdHeader(actionHeaders);\n\n return new Response(rscStream, {\n status: options.middlewareStatus ?? actionStatus,\n headers: actionHeaders,\n });\n }\n\n const match = options.matchRoute(options.cleanPathname);\n let element: TElement;\n let errorPattern = match ? match.route.pattern : options.cleanPathname;\n if (match) {\n const { route: actionRoute, params: actionParams } = match;\n const actionRerenderTarget = resolveAppPageActionRerenderTarget({\n cleanPathname: options.cleanPathname,\n currentParams: actionParams,\n currentRoute: actionRoute,\n findIntercept: options.findIntercept,\n getRouteParamNames: options.getRouteParamNames,\n getSourceRoute: options.getSourceRoute,\n isRscRequest: options.isRscRequest,\n toInterceptOpts: options.toInterceptOpts,\n });\n\n options.setNavigationContext({\n pathname: options.cleanPathname,\n searchParams: options.searchParams,\n params: actionRerenderTarget.navigationParams,\n });\n setCurrentFetchCacheMode(\n options.resolveRouteFetchCacheMode?.(actionRerenderTarget.route) ?? null,\n );\n element = options.buildPageElement({\n cleanPathname: options.cleanPathname,\n interceptOpts: actionRerenderTarget.interceptOpts,\n isRscRequest: options.isRscRequest,\n mountedSlotsHeader: options.mountedSlotsHeader,\n params: actionRerenderTarget.params,\n request: options.request,\n route: actionRerenderTarget.route,\n searchParams: options.searchParams,\n renderMode: APP_RSC_RENDER_MODE_ACTION_RERENDER_PRESERVE_UI,\n });\n errorPattern = actionRerenderTarget.route.pattern;\n } else {\n const actionRouteId = options.createPayloadRouteId(options.cleanPathname, null);\n element = options.createNotFoundElement(actionRouteId);\n }\n\n const onRenderError = options.createRscOnErrorHandler(\n options.request,\n options.cleanPathname,\n errorPattern,\n );\n const rscStream = await options.renderToReadableStream(\n { root: element, returnValue },\n { temporaryReferences, onError: onRenderError },\n );\n\n const actionHeaders = new Headers({\n \"Content-Type\": VINEXT_RSC_CONTENT_TYPE,\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n applyEdgeRuntimeHeader(actionHeaders, options.isEdgeRuntime);\n mergeMiddlewareResponseHeaders(actionHeaders, options.middlewareHeaders);\n applyRscCompatibilityIdHeader(actionHeaders);\n setActionRevalidatedHeader(actionHeaders, actionRevalidationKind);\n const actionResponse = new Response(rscStream, {\n status: options.middlewareStatus ?? actionStatus,\n headers: actionHeaders,\n });\n if (actionPendingCookies.length > 0 || actionDraftCookie) {\n for (const cookie of actionPendingCookies) {\n actionResponse.headers.append(\"Set-Cookie\", cookie);\n }\n if (actionDraftCookie) actionResponse.headers.append(\"Set-Cookie\", actionDraftCookie);\n }\n return actionResponse;\n } catch (error) {\n getAndClearActionRevalidationKind();\n return createServerActionErrorResponse(error, {\n cleanPathname: options.cleanPathname,\n clearRequestContext: options.clearRequestContext,\n getAndClearPendingCookies: options.getAndClearPendingCookies,\n reportRequestError: options.reportRequestError,\n request: options.request,\n });\n }\n}\n"],"mappings":";;;;;;;;;;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e,QAAQ,OAAO,cAAc,kBAAkB;;EAEvF,OAAO;UACA,OAAO;EACd,mCAAmC;EACnC,OAAO,gCAAgC,OAAO;GAC5C,eAAe,QAAQ;GACvB,qBAAqB,QAAQ;GAC7B,2BAA2B,QAAQ;GACnC,oBAAoB,QAAQ;GAC5B,SAAS,QAAQ;GAClB,CAAC"}
|
|
@@ -23,6 +23,12 @@ declare function handleSsr(rscStream: ReadableStream<Uint8Array>, navContext: Na
|
|
|
23
23
|
};
|
|
24
24
|
formState?: ReactFormState | null;
|
|
25
25
|
basePath?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Allow-list of OpenTelemetry propagation keys (from
|
|
28
|
+
* `experimental.clientTraceMetadata`) to render as `<meta>` tags in the
|
|
29
|
+
* SSR head. Undefined or empty disables emission entirely.
|
|
30
|
+
*/
|
|
31
|
+
clientTraceMetadata?: readonly string[];
|
|
26
32
|
rootParams?: RootParams;
|
|
27
33
|
/** When true, wait for the full React tree (including Suspense boundaries)
|
|
28
34
|
* to resolve before returning the HTML stream. Used for static prerender
|
|
@@ -8,12 +8,14 @@ import { ServerInsertedHTMLContext, appRouterInstance, clearServerInsertedHTML,
|
|
|
8
8
|
import { runWithNavigationContext } from "../shims/navigation-state.js";
|
|
9
9
|
import { withScriptNonce } from "../shims/script-nonce-context.js";
|
|
10
10
|
import { createInlineScriptTag, createNonceAttribute, escapeHtmlAttr, safeJsonStringify } from "./html.js";
|
|
11
|
+
import { getClientTraceMetadataHTML } from "./client-trace-metadata.js";
|
|
11
12
|
import { ElementsContext, Slot } from "../shims/slot.js";
|
|
12
13
|
import { createNavigationRuntimeRscMetadataScript, createRscEmbedTransform, createTickBufferedTransform } from "./app-ssr-stream.js";
|
|
13
14
|
import { RSC_FORM_STATE_GLOBAL } from "./app-browser-hydration.js";
|
|
14
15
|
import { createClientReferencePreloader } from "./app-client-reference-preloader.js";
|
|
15
16
|
import { deferUntilStreamConsumed } from "./app-page-stream.js";
|
|
16
17
|
import { runWithRootParamsScope } from "../shims/root-params.js";
|
|
18
|
+
import { BeforeInteractiveContext } from "../shims/before-interactive-context.js";
|
|
17
19
|
import { createSsrErrorMetaRenderer } from "./app-ssr-error-meta.js";
|
|
18
20
|
import { Fragment, createElement, use } from "react";
|
|
19
21
|
import { renderToReadableStream, renderToStaticMarkup } from "react-dom/server.edge";
|
|
@@ -48,15 +50,48 @@ function renderInsertedHtml(insertedElements) {
|
|
|
48
50
|
} catch {}
|
|
49
51
|
return insertedHTML;
|
|
50
52
|
}
|
|
51
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Render captured `<Script strategy="beforeInteractive">` inline scripts to
|
|
55
|
+
* HTML, ready to splice immediately after `<head ...>` opens. Each entry has
|
|
56
|
+
* already had its inline content escaped via `escapeInlineContent(..., "script")`
|
|
57
|
+
* inside the Script shim, so this function only quotes the attributes that
|
|
58
|
+
* actually go on the tag (id, nonce, plus the residual passthroughs).
|
|
59
|
+
*
|
|
60
|
+
* Keeping this function colocated with the rest of the head-injection
|
|
61
|
+
* helpers makes it obvious where the boundary is: anything passed through
|
|
62
|
+
* here is being concatenated directly into HTML; treat the inputs
|
|
63
|
+
* accordingly.
|
|
64
|
+
*/
|
|
65
|
+
const VALID_ATTR_NAME = /^[a-zA-Z][\w.-]*$/;
|
|
66
|
+
function renderBeforeInteractiveInlineScripts(scripts) {
|
|
67
|
+
if (scripts.length === 0) return "";
|
|
68
|
+
let html = "";
|
|
69
|
+
for (const script of scripts) {
|
|
70
|
+
let attrs = "";
|
|
71
|
+
if (script.id) attrs += ` id="${escapeHtmlAttr(script.id)}"`;
|
|
72
|
+
attrs += createNonceAttribute(script.nonce);
|
|
73
|
+
if (script.attributes) for (const [key, value] of Object.entries(script.attributes)) {
|
|
74
|
+
if (!VALID_ATTR_NAME.test(key)) continue;
|
|
75
|
+
if (value === true) attrs += ` ${key}`;
|
|
76
|
+
else if (typeof value === "string") attrs += ` ${key}="${escapeHtmlAttr(value)}"`;
|
|
77
|
+
}
|
|
78
|
+
html += `<script${attrs}>${script.innerHTML}<\/script>`;
|
|
79
|
+
}
|
|
80
|
+
return html;
|
|
81
|
+
}
|
|
82
|
+
function renderFontHtml(fontData, nonce, options = {}) {
|
|
52
83
|
if (!fontData) return "";
|
|
53
84
|
let fontHTML = "";
|
|
54
85
|
const nonceAttr = createNonceAttribute(nonce);
|
|
86
|
+
const includeStyles = options.includeStyles ?? true;
|
|
55
87
|
for (const url of fontData.links ?? []) fontHTML += `<link rel="stylesheet"${nonceAttr} href="${escapeHtmlAttr(url)}" />\n`;
|
|
56
88
|
for (const preload of fontData.preloads ?? []) fontHTML += `<link rel="preload"${nonceAttr} href="${escapeHtmlAttr(preload.href)}" as="font" type="${escapeHtmlAttr(preload.type)}" crossorigin />\n`;
|
|
57
|
-
if (fontData.styles && fontData.styles.length > 0) fontHTML += `<style data-vinext-fonts${nonceAttr}>${fontData.styles.join("\n")}</style>\n`;
|
|
89
|
+
if (includeStyles && fontData.styles && fontData.styles.length > 0) fontHTML += `<style data-vinext-fonts${nonceAttr}>${fontData.styles.join("\n")}</style>\n`;
|
|
58
90
|
return fontHTML;
|
|
59
91
|
}
|
|
92
|
+
function hasInlineCssManifest(manifest) {
|
|
93
|
+
return manifest !== void 0 && Object.keys(manifest).length > 0;
|
|
94
|
+
}
|
|
60
95
|
/**
|
|
61
96
|
* Extract the bootstrap module URL from the `import("...")` string that
|
|
62
97
|
* `import.meta.viteRsc.loadBootstrapScriptContent("index")` returns.
|
|
@@ -119,7 +154,12 @@ async function handleSsr(rscStream, navContext, fontData, options) {
|
|
|
119
154
|
}
|
|
120
155
|
const flightRootElement = createElement(VinextFlightRoot);
|
|
121
156
|
const root = AppRouterContext ? createElement(AppRouterContext.Provider, { value: appRouterInstance }, flightRootElement) : flightRootElement;
|
|
122
|
-
const
|
|
157
|
+
const ssrTree = ServerInsertedHTMLContext ? createElement(ServerInsertedHTMLContext.Provider, { value: useServerInsertedHTML }, root) : root;
|
|
158
|
+
const beforeInteractiveInlineScripts = [];
|
|
159
|
+
const registerBeforeInteractiveInlineScript = (script) => {
|
|
160
|
+
beforeInteractiveInlineScripts.push(script);
|
|
161
|
+
};
|
|
162
|
+
const ssrRoot = withScriptNonce(createElement(BeforeInteractiveContext.Provider, { value: registerBeforeInteractiveInlineScript }, ssrTree), options?.scriptNonce);
|
|
123
163
|
const bootstrapModuleUrl = extractBootstrapModuleUrl(await import.meta.viteRsc.loadBootstrapScriptContent("index"));
|
|
124
164
|
const errorMetaRenderer = createSsrErrorMetaRenderer({ basePath: options?.basePath });
|
|
125
165
|
const htmlStream = await renderToReadableStream(ssrRoot, {
|
|
@@ -133,16 +173,27 @@ async function handleSsr(rscStream, navContext, fontData, options) {
|
|
|
133
173
|
}
|
|
134
174
|
});
|
|
135
175
|
if (options?.waitForAllReady === true) await htmlStream.allReady;
|
|
136
|
-
const
|
|
176
|
+
const inlineCssManifest = globalThis.__VINEXT_INLINE_CSS__;
|
|
177
|
+
const fontStyles = fontData?.styles ?? [];
|
|
178
|
+
const mergeFontStylesIntoInlineCss = fontStyles.length > 0 && hasInlineCssManifest(inlineCssManifest);
|
|
179
|
+
const inlineCssFontStyles = mergeFontStylesIntoInlineCss ? fontStyles.join("\n") : "";
|
|
180
|
+
const inlineCssFontStyleFallbackHTML = mergeFontStylesIntoInlineCss ? renderFontHtml({ styles: fontStyles }, options?.scriptNonce) : "";
|
|
181
|
+
const fontHTML = renderFontHtml(fontData, options?.scriptNonce, { includeStyles: !mergeFontStylesIntoInlineCss });
|
|
182
|
+
let traceMetaHTML = null;
|
|
183
|
+
const getTraceMetaHTML = () => {
|
|
184
|
+
if (traceMetaHTML === null) traceMetaHTML = getClientTraceMetadataHTML(options?.clientTraceMetadata);
|
|
185
|
+
return traceMetaHTML;
|
|
186
|
+
};
|
|
137
187
|
let didInjectHeadHTML = false;
|
|
138
188
|
const getInsertedHTML = () => {
|
|
139
189
|
const insertedHTML = renderInsertedHtml(renderServerInsertedHTML());
|
|
140
190
|
const errorMetaHTML = errorMetaRenderer.flush();
|
|
141
191
|
if (didInjectHeadHTML) return insertedHTML + errorMetaHTML;
|
|
142
192
|
didInjectHeadHTML = true;
|
|
143
|
-
return buildHeadInjectionHtml(navContext, bootstrapModuleUrl, options?.formState ?? null, insertedHTML + errorMetaHTML, fontHTML, options?.scriptNonce);
|
|
193
|
+
return buildHeadInjectionHtml(navContext, bootstrapModuleUrl, options?.formState ?? null, insertedHTML + errorMetaHTML + getTraceMetaHTML(), fontHTML, options?.scriptNonce);
|
|
144
194
|
};
|
|
145
|
-
|
|
195
|
+
const getBeforeInteractiveHeadHTML = () => renderBeforeInteractiveInlineScripts(beforeInteractiveInlineScripts);
|
|
196
|
+
return deferUntilStreamConsumed(htmlStream.pipeThrough(createTickBufferedTransform(rscEmbed, getInsertedHTML, getBeforeInteractiveHeadHTML, inlineCssManifest, inlineCssFontStyles, inlineCssFontStyleFallbackHTML, options?.scriptNonce)), cleanup);
|
|
146
197
|
} catch (error) {
|
|
147
198
|
cleanup();
|
|
148
199
|
throw error;
|