vinext 0.0.52 → 0.0.53

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.
Files changed (238) hide show
  1. package/README.md +1 -1
  2. package/dist/build/clean-output.d.ts +14 -0
  3. package/dist/build/clean-output.js +36 -0
  4. package/dist/build/clean-output.js.map +1 -0
  5. package/dist/build/prerender.d.ts +6 -2
  6. package/dist/build/prerender.js +49 -11
  7. package/dist/build/prerender.js.map +1 -1
  8. package/dist/build/run-prerender.js +10 -1
  9. package/dist/build/run-prerender.js.map +1 -1
  10. package/dist/build/static-export.d.ts +5 -0
  11. package/dist/build/static-export.js +8 -3
  12. package/dist/build/static-export.js.map +1 -1
  13. package/dist/cli.js +19 -4
  14. package/dist/cli.js.map +1 -1
  15. package/dist/client/instrumentation-client-inject.d.ts +34 -0
  16. package/dist/client/instrumentation-client-inject.js +57 -0
  17. package/dist/client/instrumentation-client-inject.js.map +1 -0
  18. package/dist/client/navigation-runtime.d.ts +14 -1
  19. package/dist/client/navigation-runtime.js +16 -1
  20. package/dist/client/navigation-runtime.js.map +1 -1
  21. package/dist/client/vinext-next-data.d.ts +2 -1
  22. package/dist/client/vinext-next-data.js.map +1 -1
  23. package/dist/client/window-next.d.ts +10 -2
  24. package/dist/client/window-next.js.map +1 -1
  25. package/dist/cloudflare/tpr.js +1 -1
  26. package/dist/cloudflare/tpr.js.map +1 -1
  27. package/dist/config/config-matchers.js +2 -1
  28. package/dist/config/config-matchers.js.map +1 -1
  29. package/dist/config/next-config.d.ts +12 -3
  30. package/dist/config/next-config.js +44 -14
  31. package/dist/config/next-config.js.map +1 -1
  32. package/dist/deploy.js +29 -7
  33. package/dist/deploy.js.map +1 -1
  34. package/dist/entries/app-rsc-entry.d.ts +4 -2
  35. package/dist/entries/app-rsc-entry.js +23 -3
  36. package/dist/entries/app-rsc-entry.js.map +1 -1
  37. package/dist/entries/pages-client-entry.js +22 -1
  38. package/dist/entries/pages-client-entry.js.map +1 -1
  39. package/dist/entries/pages-server-entry.js +211 -31
  40. package/dist/entries/pages-server-entry.js.map +1 -1
  41. package/dist/index.js +29 -6
  42. package/dist/index.js.map +1 -1
  43. package/dist/plugins/fonts.js +25 -2
  44. package/dist/plugins/fonts.js.map +1 -1
  45. package/dist/routing/route-trie.js +13 -18
  46. package/dist/routing/route-trie.js.map +1 -1
  47. package/dist/routing/utils.d.ts +11 -1
  48. package/dist/routing/utils.js +15 -1
  49. package/dist/routing/utils.js.map +1 -1
  50. package/dist/server/api-handler.js +18 -9
  51. package/dist/server/api-handler.js.map +1 -1
  52. package/dist/server/app-browser-action-result.d.ts +16 -1
  53. package/dist/server/app-browser-action-result.js +15 -1
  54. package/dist/server/app-browser-action-result.js.map +1 -1
  55. package/dist/server/app-browser-entry.js +22 -12
  56. package/dist/server/app-browser-entry.js.map +1 -1
  57. package/dist/server/app-elements.js +1 -1
  58. package/dist/server/app-fallback-renderer.d.ts +12 -3
  59. package/dist/server/app-fallback-renderer.js +10 -5
  60. package/dist/server/app-fallback-renderer.js.map +1 -1
  61. package/dist/server/app-history-state.js +6 -2
  62. package/dist/server/app-history-state.js.map +1 -1
  63. package/dist/server/app-interception-context-header.d.ts +33 -0
  64. package/dist/server/app-interception-context-header.js +44 -0
  65. package/dist/server/app-interception-context-header.js.map +1 -0
  66. package/dist/server/app-mounted-slots-header.d.ts +19 -0
  67. package/dist/server/app-mounted-slots-header.js +40 -1
  68. package/dist/server/app-mounted-slots-header.js.map +1 -1
  69. package/dist/server/app-optimistic-routing.js +26 -18
  70. package/dist/server/app-optimistic-routing.js.map +1 -1
  71. package/dist/server/app-page-boundary-render.d.ts +1 -0
  72. package/dist/server/app-page-boundary-render.js +2 -0
  73. package/dist/server/app-page-boundary-render.js.map +1 -1
  74. package/dist/server/app-page-boundary.d.ts +1 -0
  75. package/dist/server/app-page-boundary.js +2 -0
  76. package/dist/server/app-page-boundary.js.map +1 -1
  77. package/dist/server/app-page-cache.d.ts +2 -0
  78. package/dist/server/app-page-cache.js +7 -1
  79. package/dist/server/app-page-cache.js.map +1 -1
  80. package/dist/server/app-page-dispatch.d.ts +3 -0
  81. package/dist/server/app-page-dispatch.js +11 -4
  82. package/dist/server/app-page-dispatch.js.map +1 -1
  83. package/dist/server/app-page-element-builder.d.ts +2 -1
  84. package/dist/server/app-page-element-builder.js +5 -2
  85. package/dist/server/app-page-element-builder.js.map +1 -1
  86. package/dist/server/app-page-execution.d.ts +1 -0
  87. package/dist/server/app-page-execution.js +2 -0
  88. package/dist/server/app-page-execution.js.map +1 -1
  89. package/dist/server/app-page-head.d.ts +1 -0
  90. package/dist/server/app-page-head.js +8 -0
  91. package/dist/server/app-page-head.js.map +1 -1
  92. package/dist/server/app-page-render-observation.js +1 -1
  93. package/dist/server/app-page-render.d.ts +1 -0
  94. package/dist/server/app-page-render.js +5 -2
  95. package/dist/server/app-page-render.js.map +1 -1
  96. package/dist/server/app-page-response.d.ts +11 -1
  97. package/dist/server/app-page-response.js +14 -2
  98. package/dist/server/app-page-response.js.map +1 -1
  99. package/dist/server/app-page-route-wiring.d.ts +1 -0
  100. package/dist/server/app-page-route-wiring.js +19 -6
  101. package/dist/server/app-page-route-wiring.js.map +1 -1
  102. package/dist/server/app-page-stream.d.ts +1 -0
  103. package/dist/server/app-page-stream.js +2 -0
  104. package/dist/server/app-page-stream.js.map +1 -1
  105. package/dist/server/app-route-handler-dispatch.d.ts +1 -0
  106. package/dist/server/app-route-handler-dispatch.js +3 -0
  107. package/dist/server/app-route-handler-dispatch.js.map +1 -1
  108. package/dist/server/app-route-handler-execution.d.ts +1 -0
  109. package/dist/server/app-route-handler-execution.js +1 -0
  110. package/dist/server/app-route-handler-execution.js.map +1 -1
  111. package/dist/server/app-route-handler-response.js +1 -1
  112. package/dist/server/app-rsc-handler.d.ts +2 -0
  113. package/dist/server/app-rsc-handler.js +18 -9
  114. package/dist/server/app-rsc-handler.js.map +1 -1
  115. package/dist/server/app-rsc-request-normalization.js +3 -2
  116. package/dist/server/app-rsc-request-normalization.js.map +1 -1
  117. package/dist/server/app-segment-config.d.ts +4 -1
  118. package/dist/server/app-segment-config.js +6 -1
  119. package/dist/server/app-segment-config.js.map +1 -1
  120. package/dist/server/app-server-action-execution.d.ts +1 -0
  121. package/dist/server/app-server-action-execution.js +4 -0
  122. package/dist/server/app-server-action-execution.js.map +1 -1
  123. package/dist/server/app-ssr-entry.js +39 -3
  124. package/dist/server/app-ssr-entry.js.map +1 -1
  125. package/dist/server/app-ssr-stream.d.ts +24 -1
  126. package/dist/server/app-ssr-stream.js +78 -5
  127. package/dist/server/app-ssr-stream.js.map +1 -1
  128. package/dist/server/app-static-generation.d.ts +1 -0
  129. package/dist/server/app-static-generation.js +2 -1
  130. package/dist/server/app-static-generation.js.map +1 -1
  131. package/dist/server/default-not-found-module.d.ts +20 -0
  132. package/dist/server/default-not-found-module.js +20 -0
  133. package/dist/server/default-not-found-module.js.map +1 -0
  134. package/dist/server/dev-server.d.ts +1 -1
  135. package/dist/server/dev-server.js +23 -7
  136. package/dist/server/dev-server.js.map +1 -1
  137. package/dist/server/headers.d.ts +5 -1
  138. package/dist/server/headers.js +5 -1
  139. package/dist/server/headers.js.map +1 -1
  140. package/dist/server/image-optimization.d.ts +13 -4
  141. package/dist/server/image-optimization.js +15 -4
  142. package/dist/server/image-optimization.js.map +1 -1
  143. package/dist/server/middleware.js +1 -1
  144. package/dist/server/middleware.js.map +1 -1
  145. package/dist/server/pages-api-route.d.ts +18 -0
  146. package/dist/server/pages-api-route.js +3 -1
  147. package/dist/server/pages-api-route.js.map +1 -1
  148. package/dist/server/pages-body-parser-config.d.ts +60 -0
  149. package/dist/server/pages-body-parser-config.js +79 -0
  150. package/dist/server/pages-body-parser-config.js.map +1 -0
  151. package/dist/server/pages-data-route.js +1 -0
  152. package/dist/server/pages-data-route.js.map +1 -1
  153. package/dist/server/pages-default-404.d.ts +31 -0
  154. package/dist/server/pages-default-404.js +40 -0
  155. package/dist/server/pages-default-404.js.map +1 -0
  156. package/dist/server/pages-node-compat.d.ts +10 -0
  157. package/dist/server/pages-node-compat.js +12 -1
  158. package/dist/server/pages-node-compat.js.map +1 -1
  159. package/dist/server/pages-page-data.d.ts +40 -0
  160. package/dist/server/pages-page-data.js +16 -14
  161. package/dist/server/pages-page-data.js.map +1 -1
  162. package/dist/server/pages-page-response.d.ts +2 -0
  163. package/dist/server/pages-page-response.js +11 -8
  164. package/dist/server/pages-page-response.js.map +1 -1
  165. package/dist/server/prerender-route-params.d.ts +14 -0
  166. package/dist/server/prerender-route-params.js +94 -0
  167. package/dist/server/prerender-route-params.js.map +1 -0
  168. package/dist/server/prod-server.d.ts +3 -23
  169. package/dist/server/prod-server.js +40 -57
  170. package/dist/server/prod-server.js.map +1 -1
  171. package/dist/server/proxy-trust.d.ts +41 -0
  172. package/dist/server/proxy-trust.js +70 -0
  173. package/dist/server/proxy-trust.js.map +1 -0
  174. package/dist/server/request-pipeline.d.ts +3 -3
  175. package/dist/server/request-pipeline.js +5 -4
  176. package/dist/server/request-pipeline.js.map +1 -1
  177. package/dist/server/seed-cache.js +12 -6
  178. package/dist/server/seed-cache.js.map +1 -1
  179. package/dist/server/static-file-cache.js +1 -1
  180. package/dist/server/static-file-cache.js.map +1 -1
  181. package/dist/server/streaming-metadata.d.ts +5 -0
  182. package/dist/server/streaming-metadata.js +10 -0
  183. package/dist/server/streaming-metadata.js.map +1 -0
  184. package/dist/shims/app-router-scroll-state.d.ts +12 -0
  185. package/dist/shims/app-router-scroll-state.js +38 -0
  186. package/dist/shims/app-router-scroll-state.js.map +1 -0
  187. package/dist/shims/app-router-scroll.d.ts +14 -0
  188. package/dist/shims/app-router-scroll.js +100 -0
  189. package/dist/shims/app-router-scroll.js.map +1 -0
  190. package/dist/shims/before-interactive-context.d.ts +30 -0
  191. package/dist/shims/before-interactive-context.js +10 -0
  192. package/dist/shims/before-interactive-context.js.map +1 -0
  193. package/dist/shims/cache-runtime.d.ts +1 -1
  194. package/dist/shims/cache-runtime.js +14 -1
  195. package/dist/shims/cache-runtime.js.map +1 -1
  196. package/dist/shims/default-not-found.d.ts +12 -0
  197. package/dist/shims/default-not-found.js +61 -0
  198. package/dist/shims/default-not-found.js.map +1 -0
  199. package/dist/shims/font-local.d.ts +5 -0
  200. package/dist/shims/font-local.js +6 -2
  201. package/dist/shims/font-local.js.map +1 -1
  202. package/dist/shims/head.js +4 -4
  203. package/dist/shims/head.js.map +1 -1
  204. package/dist/shims/headers.d.ts +6 -2
  205. package/dist/shims/headers.js +64 -21
  206. package/dist/shims/headers.js.map +1 -1
  207. package/dist/shims/image.d.ts +1 -1
  208. package/dist/shims/image.js +4 -4
  209. package/dist/shims/image.js.map +1 -1
  210. package/dist/shims/internal/pages-data-target.d.ts +58 -0
  211. package/dist/shims/internal/pages-data-target.js +91 -0
  212. package/dist/shims/internal/pages-data-target.js.map +1 -0
  213. package/dist/shims/internal/pages-data-url.d.ts +42 -0
  214. package/dist/shims/internal/pages-data-url.js +73 -0
  215. package/dist/shims/internal/pages-data-url.js.map +1 -0
  216. package/dist/shims/link.js +59 -9
  217. package/dist/shims/link.js.map +1 -1
  218. package/dist/shims/metadata.d.ts +2 -1
  219. package/dist/shims/metadata.js +61 -2
  220. package/dist/shims/metadata.js.map +1 -1
  221. package/dist/shims/navigation.js +32 -9
  222. package/dist/shims/navigation.js.map +1 -1
  223. package/dist/shims/router.js +376 -77
  224. package/dist/shims/router.js.map +1 -1
  225. package/dist/shims/script.js +86 -12
  226. package/dist/shims/script.js.map +1 -1
  227. package/dist/shims/server.js +1 -0
  228. package/dist/shims/server.js.map +1 -1
  229. package/dist/shims/url-utils.d.ts +2 -1
  230. package/dist/shims/url-utils.js +15 -4
  231. package/dist/shims/url-utils.js.map +1 -1
  232. package/dist/utils/html-limited-bots.d.ts +5 -0
  233. package/dist/utils/html-limited-bots.js +15 -0
  234. package/dist/utils/html-limited-bots.js.map +1 -0
  235. package/dist/utils/query.d.ts +6 -0
  236. package/dist/utils/query.js +10 -1
  237. package/dist/utils/query.js.map +1 -1
  238. package/package.json +1 -1
@@ -46,6 +46,7 @@ type RenderAppPageHtmlStreamOptions = {
46
46
  type RenderAppPageHtmlResponseOptions = {
47
47
  clearRequestContext: () => void;
48
48
  fontLinkHeader?: string;
49
+ isEdgeRuntime?: boolean;
49
50
  middlewareHeaders?: Headers | null;
50
51
  status: number;
51
52
  } & RenderAppPageHtmlStreamOptions;
@@ -1,5 +1,6 @@
1
1
  import { VINEXT_RSC_VARY_HEADER } from "./app-rsc-cache-busting.js";
2
2
  import { mergeMiddlewareResponseHeaders } from "./middleware-response-headers.js";
3
+ import { applyEdgeRuntimeHeader } from "./app-page-response.js";
3
4
  //#region src/server/app-page-stream.ts
4
5
  function createAppPageFontData(options) {
5
6
  return {
@@ -63,6 +64,7 @@ async function renderAppPageHtmlResponse(options) {
63
64
  "Content-Type": "text/html; charset=utf-8",
64
65
  Vary: VINEXT_RSC_VARY_HEADER
65
66
  });
67
+ applyEdgeRuntimeHeader(headers, options.isEdgeRuntime);
66
68
  if (options.fontLinkHeader) headers.set("Link", options.fontLinkHeader);
67
69
  mergeMiddlewareResponseHeaders(headers, options.middlewareHeaders ?? null);
68
70
  return new Response(safeStream, {
@@ -1 +1 @@
1
- {"version":3,"file":"app-page-stream.js","names":[],"sources":["../../src/server/app-page-stream.ts"],"sourcesContent":["import type { AppPageFontPreload } from \"./app-page-execution.js\";\nimport type { ReactFormState } from \"react-dom/client\";\nimport { VINEXT_RSC_VARY_HEADER } from \"./app-rsc-cache-busting.js\";\nimport { mergeMiddlewareResponseHeaders } from \"./middleware-response-headers.js\";\nimport type { RootParams } from \"vinext/shims/root-params\";\n\nexport type AppPageFontData = {\n links: string[];\n preloads: readonly AppPageFontPreload[];\n styles: string[];\n};\n\ntype CreateAppPageFontDataOptions = {\n getLinks: () => string[];\n getPreloads: () => AppPageFontPreload[];\n getStyles: () => string[];\n};\n\nexport type AppPageSsrHandler = {\n handleSsr: (\n rscStream: ReadableStream<Uint8Array>,\n navigationContext: unknown,\n fontData: AppPageFontData,\n options?: {\n formState?: ReactFormState | null;\n scriptNonce?: string;\n basePath?: string;\n rootParams?: RootParams;\n sideStream?: ReadableStream<Uint8Array>;\n capturedRscDataRef?: { value: Promise<ArrayBuffer> | null };\n /** When true, wait for the full React tree before emitting bytes. */\n waitForAllReady?: boolean;\n },\n ) => Promise<ReadableStream<Uint8Array>>;\n};\n\ntype RenderAppPageHtmlStreamOptions = {\n fontData: AppPageFontData;\n formState?: ReactFormState | null;\n navigationContext: unknown;\n rscStream: ReadableStream<Uint8Array>;\n scriptNonce?: string;\n basePath?: string;\n rootParams?: RootParams;\n ssrHandler: AppPageSsrHandler;\n /** Pre-split side stream for fused embed+capture (#981). When set,\n * handleSsr skips its internal tee and accumulates raw RSC bytes. */\n sideStream?: ReadableStream<Uint8Array>;\n /** Out-parameter filled with accumulated raw RSC bytes after stream consumption. */\n capturedRscDataRef?: { value: Promise<ArrayBuffer> | null };\n /** When true, wait for the full React tree before emitting bytes. */\n waitForAllReady?: boolean;\n};\n\ntype RenderAppPageHtmlResponseOptions = {\n clearRequestContext: () => void;\n fontLinkHeader?: string;\n middlewareHeaders?: Headers | null;\n status: number;\n} & RenderAppPageHtmlStreamOptions;\n\ntype AppPageHtmlStreamRecoveryResult = {\n htmlStream: ReadableStream<Uint8Array> | null;\n response: Response | null;\n};\n\ntype RenderAppPageHtmlStreamWithRecoveryOptions<TSpecialError> = {\n onShellRendered?: () => void;\n renderErrorBoundaryResponse: (error: unknown) => Promise<Response | null>;\n renderHtmlStream: () => Promise<ReadableStream<Uint8Array>>;\n renderSpecialErrorResponse: (specialError: TSpecialError) => Promise<Response>;\n resolveSpecialError: (error: unknown) => TSpecialError | null;\n};\n\ntype AppPageRscErrorTracker = {\n getCapturedError: () => unknown;\n /**\n * Returns a NEXT_REDIRECT or NEXT_HTTP_ERROR_FALLBACK error captured during\n * the RSC render. Read after the SSR shell promise resolves to swap a\n * 307/404 in place of the streamed body when redirect()/notFound() throws\n * synchronously inside a route-level Suspense boundary (loading.tsx).\n */\n getCapturedSpecialError: () => unknown;\n onRenderError: (error: unknown, requestInfo: unknown, errorContext: unknown) => unknown;\n};\n\ntype ShouldRerenderAppPageWithGlobalErrorOptions = {\n capturedError: unknown;\n hasLocalBoundary: boolean;\n};\n\nexport function createAppPageFontData(options: CreateAppPageFontDataOptions): AppPageFontData {\n return {\n links: options.getLinks(),\n preloads: options.getPreloads(),\n styles: options.getStyles(),\n };\n}\n\nexport async function renderAppPageHtmlStream(\n options: RenderAppPageHtmlStreamOptions,\n): Promise<ReadableStream<Uint8Array>> {\n const ssrOptions = {\n formState: options.formState ?? null,\n scriptNonce: options.scriptNonce,\n basePath: options.basePath,\n rootParams: options.rootParams,\n sideStream: options.sideStream,\n capturedRscDataRef: options.capturedRscDataRef,\n waitForAllReady: options.waitForAllReady,\n };\n\n return options.ssrHandler.handleSsr(\n options.rscStream,\n options.navigationContext,\n options.fontData,\n ssrOptions,\n );\n}\n\n/**\n * Wraps a stream so that `onFlush` is called when the last byte has been read\n * by the downstream consumer (i.e. when the HTTP layer finishes draining the\n * response body). This is the correct place to clear per-request context,\n * because the RSC/SSR pipeline is lazy — components execute while the stream\n * is being consumed, not when the stream handle is first obtained.\n */\nexport function deferUntilStreamConsumed(\n stream: ReadableStream<Uint8Array>,\n onFlush: () => void,\n): ReadableStream<Uint8Array> {\n let called = false;\n const once = () => {\n if (!called) {\n called = true;\n onFlush();\n }\n };\n\n const cleanup = new TransformStream<Uint8Array, Uint8Array>({\n flush() {\n once();\n },\n });\n\n const piped = stream.pipeThrough(cleanup);\n\n // Wrap with a ReadableStream so we can intercept cancel() — the TransformStream\n // Transformer interface does not expose a cancel hook in the Web Streams spec.\n const reader = piped.getReader();\n return new ReadableStream<Uint8Array>({\n pull(controller) {\n return reader.read().then(\n ({ done, value }) => {\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n (error) => {\n once();\n controller.error(error);\n },\n );\n },\n cancel(reason) {\n // Stream cancelled before fully consumed (e.g. client disconnected).\n // Still clear per-request context to avoid leaks.\n once();\n return reader.cancel(reason);\n },\n });\n}\n\nexport async function renderAppPageHtmlResponse(\n options: RenderAppPageHtmlResponseOptions,\n): Promise<Response> {\n const htmlStream = await renderAppPageHtmlStream(options);\n\n // Defer clearRequestContext() until the stream is fully consumed by the HTTP\n // layer. Calling it synchronously here would race the lazy RSC/SSR pipeline:\n // components execute while the stream is being pulled, not when the handle\n // is first returned. See: https://github.com/cloudflare/vinext/issues/660\n const safeStream = deferUntilStreamConsumed(htmlStream, () => {\n options.clearRequestContext();\n });\n\n const headers = new Headers({\n \"Content-Type\": \"text/html; charset=utf-8\",\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n\n if (options.fontLinkHeader) {\n headers.set(\"Link\", options.fontLinkHeader);\n }\n\n mergeMiddlewareResponseHeaders(headers, options.middlewareHeaders ?? null);\n\n return new Response(safeStream, {\n status: options.status,\n headers,\n });\n}\n\nexport async function renderAppPageHtmlStreamWithRecovery<TSpecialError>(\n options: RenderAppPageHtmlStreamWithRecoveryOptions<TSpecialError>,\n): Promise<AppPageHtmlStreamRecoveryResult> {\n try {\n const htmlStream = await options.renderHtmlStream();\n options.onShellRendered?.();\n return {\n htmlStream,\n response: null,\n };\n } catch (error) {\n const specialError = options.resolveSpecialError(error);\n if (specialError) {\n return {\n htmlStream: null,\n response: await options.renderSpecialErrorResponse(specialError),\n };\n }\n\n const boundaryResponse = await options.renderErrorBoundaryResponse(error);\n if (boundaryResponse) {\n return {\n htmlStream: null,\n response: boundaryResponse,\n };\n }\n\n throw error;\n }\n}\n\nexport function createAppPageRscErrorTracker(\n baseOnError: (error: unknown, requestInfo: unknown, errorContext: unknown) => unknown,\n): AppPageRscErrorTracker {\n let capturedError: unknown = null;\n let capturedSpecialError: unknown = null;\n\n return {\n getCapturedError() {\n return capturedError;\n },\n getCapturedSpecialError() {\n return capturedSpecialError;\n },\n onRenderError(error, requestInfo, errorContext) {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n // Errors with a digest are signal throws (NEXT_REDIRECT,\n // NEXT_NOT_FOUND, NEXT_HTTP_ERROR_FALLBACK). They're not real\n // failures — keep the first one so the lifecycle can swap a\n // 307/404 in place of a streamed \"Switched to client rendering\"\n // body for routes with a route-level Suspense boundary.\n if (capturedSpecialError === null) {\n capturedSpecialError = error;\n }\n } else {\n capturedError = error;\n }\n return baseOnError(error, requestInfo, errorContext);\n },\n };\n}\n\nexport function shouldRerenderAppPageWithGlobalError(\n options: ShouldRerenderAppPageWithGlobalErrorOptions,\n): boolean {\n return Boolean(options.capturedError) && !options.hasLocalBoundary;\n}\n"],"mappings":";;;AA2FA,SAAgB,sBAAsB,SAAwD;CAC5F,OAAO;EACL,OAAO,QAAQ,UAAU;EACzB,UAAU,QAAQ,aAAa;EAC/B,QAAQ,QAAQ,WAAW;EAC5B;;AAGH,eAAsB,wBACpB,SACqC;CACrC,MAAM,aAAa;EACjB,WAAW,QAAQ,aAAa;EAChC,aAAa,QAAQ;EACrB,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,YAAY,QAAQ;EACpB,oBAAoB,QAAQ;EAC5B,iBAAiB,QAAQ;EAC1B;CAED,OAAO,QAAQ,WAAW,UACxB,QAAQ,WACR,QAAQ,mBACR,QAAQ,UACR,WACD;;;;;;;;;AAUH,SAAgB,yBACd,QACA,SAC4B;CAC5B,IAAI,SAAS;CACb,MAAM,aAAa;EACjB,IAAI,CAAC,QAAQ;GACX,SAAS;GACT,SAAS;;;CAIb,MAAM,UAAU,IAAI,gBAAwC,EAC1D,QAAQ;EACN,MAAM;IAET,CAAC;CAMF,MAAM,SAJQ,OAAO,YAAY,QAIb,CAAC,WAAW;CAChC,OAAO,IAAI,eAA2B;EACpC,KAAK,YAAY;GACf,OAAO,OAAO,MAAM,CAAC,MAClB,EAAE,MAAM,YAAY;IACnB,IAAI,MACF,WAAW,OAAO;SAElB,WAAW,QAAQ,MAAM;OAG5B,UAAU;IACT,MAAM;IACN,WAAW,MAAM,MAAM;KAE1B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server/app-page-stream.ts"],"sourcesContent":["import type { AppPageFontPreload } from \"./app-page-execution.js\";\nimport type { ReactFormState } from \"react-dom/client\";\nimport { VINEXT_RSC_VARY_HEADER } from \"./app-rsc-cache-busting.js\";\nimport { applyEdgeRuntimeHeader } from \"./app-page-response.js\";\nimport { mergeMiddlewareResponseHeaders } from \"./middleware-response-headers.js\";\nimport type { RootParams } from \"vinext/shims/root-params\";\n\nexport type AppPageFontData = {\n links: string[];\n preloads: readonly AppPageFontPreload[];\n styles: string[];\n};\n\ntype CreateAppPageFontDataOptions = {\n getLinks: () => string[];\n getPreloads: () => AppPageFontPreload[];\n getStyles: () => string[];\n};\n\nexport type AppPageSsrHandler = {\n handleSsr: (\n rscStream: ReadableStream<Uint8Array>,\n navigationContext: unknown,\n fontData: AppPageFontData,\n options?: {\n formState?: ReactFormState | null;\n scriptNonce?: string;\n basePath?: string;\n rootParams?: RootParams;\n sideStream?: ReadableStream<Uint8Array>;\n capturedRscDataRef?: { value: Promise<ArrayBuffer> | null };\n /** When true, wait for the full React tree before emitting bytes. */\n waitForAllReady?: boolean;\n },\n ) => Promise<ReadableStream<Uint8Array>>;\n};\n\ntype RenderAppPageHtmlStreamOptions = {\n fontData: AppPageFontData;\n formState?: ReactFormState | null;\n navigationContext: unknown;\n rscStream: ReadableStream<Uint8Array>;\n scriptNonce?: string;\n basePath?: string;\n rootParams?: RootParams;\n ssrHandler: AppPageSsrHandler;\n /** Pre-split side stream for fused embed+capture (#981). When set,\n * handleSsr skips its internal tee and accumulates raw RSC bytes. */\n sideStream?: ReadableStream<Uint8Array>;\n /** Out-parameter filled with accumulated raw RSC bytes after stream consumption. */\n capturedRscDataRef?: { value: Promise<ArrayBuffer> | null };\n /** When true, wait for the full React tree before emitting bytes. */\n waitForAllReady?: boolean;\n};\n\ntype RenderAppPageHtmlResponseOptions = {\n clearRequestContext: () => void;\n fontLinkHeader?: string;\n isEdgeRuntime?: boolean;\n middlewareHeaders?: Headers | null;\n status: number;\n} & RenderAppPageHtmlStreamOptions;\n\ntype AppPageHtmlStreamRecoveryResult = {\n htmlStream: ReadableStream<Uint8Array> | null;\n response: Response | null;\n};\n\ntype RenderAppPageHtmlStreamWithRecoveryOptions<TSpecialError> = {\n onShellRendered?: () => void;\n renderErrorBoundaryResponse: (error: unknown) => Promise<Response | null>;\n renderHtmlStream: () => Promise<ReadableStream<Uint8Array>>;\n renderSpecialErrorResponse: (specialError: TSpecialError) => Promise<Response>;\n resolveSpecialError: (error: unknown) => TSpecialError | null;\n};\n\ntype AppPageRscErrorTracker = {\n getCapturedError: () => unknown;\n /**\n * Returns a NEXT_REDIRECT or NEXT_HTTP_ERROR_FALLBACK error captured during\n * the RSC render. Read after the SSR shell promise resolves to swap a\n * 307/404 in place of the streamed body when redirect()/notFound() throws\n * synchronously inside a route-level Suspense boundary (loading.tsx).\n */\n getCapturedSpecialError: () => unknown;\n onRenderError: (error: unknown, requestInfo: unknown, errorContext: unknown) => unknown;\n};\n\ntype ShouldRerenderAppPageWithGlobalErrorOptions = {\n capturedError: unknown;\n hasLocalBoundary: boolean;\n};\n\nexport function createAppPageFontData(options: CreateAppPageFontDataOptions): AppPageFontData {\n return {\n links: options.getLinks(),\n preloads: options.getPreloads(),\n styles: options.getStyles(),\n };\n}\n\nexport async function renderAppPageHtmlStream(\n options: RenderAppPageHtmlStreamOptions,\n): Promise<ReadableStream<Uint8Array>> {\n const ssrOptions = {\n formState: options.formState ?? null,\n scriptNonce: options.scriptNonce,\n basePath: options.basePath,\n rootParams: options.rootParams,\n sideStream: options.sideStream,\n capturedRscDataRef: options.capturedRscDataRef,\n waitForAllReady: options.waitForAllReady,\n };\n\n return options.ssrHandler.handleSsr(\n options.rscStream,\n options.navigationContext,\n options.fontData,\n ssrOptions,\n );\n}\n\n/**\n * Wraps a stream so that `onFlush` is called when the last byte has been read\n * by the downstream consumer (i.e. when the HTTP layer finishes draining the\n * response body). This is the correct place to clear per-request context,\n * because the RSC/SSR pipeline is lazy — components execute while the stream\n * is being consumed, not when the stream handle is first obtained.\n */\nexport function deferUntilStreamConsumed(\n stream: ReadableStream<Uint8Array>,\n onFlush: () => void,\n): ReadableStream<Uint8Array> {\n let called = false;\n const once = () => {\n if (!called) {\n called = true;\n onFlush();\n }\n };\n\n const cleanup = new TransformStream<Uint8Array, Uint8Array>({\n flush() {\n once();\n },\n });\n\n const piped = stream.pipeThrough(cleanup);\n\n // Wrap with a ReadableStream so we can intercept cancel() — the TransformStream\n // Transformer interface does not expose a cancel hook in the Web Streams spec.\n const reader = piped.getReader();\n return new ReadableStream<Uint8Array>({\n pull(controller) {\n return reader.read().then(\n ({ done, value }) => {\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n (error) => {\n once();\n controller.error(error);\n },\n );\n },\n cancel(reason) {\n // Stream cancelled before fully consumed (e.g. client disconnected).\n // Still clear per-request context to avoid leaks.\n once();\n return reader.cancel(reason);\n },\n });\n}\n\nexport async function renderAppPageHtmlResponse(\n options: RenderAppPageHtmlResponseOptions,\n): Promise<Response> {\n const htmlStream = await renderAppPageHtmlStream(options);\n\n // Defer clearRequestContext() until the stream is fully consumed by the HTTP\n // layer. Calling it synchronously here would race the lazy RSC/SSR pipeline:\n // components execute while the stream is being pulled, not when the handle\n // is first returned. See: https://github.com/cloudflare/vinext/issues/660\n const safeStream = deferUntilStreamConsumed(htmlStream, () => {\n options.clearRequestContext();\n });\n\n const headers = new Headers({\n \"Content-Type\": \"text/html; charset=utf-8\",\n Vary: VINEXT_RSC_VARY_HEADER,\n });\n\n applyEdgeRuntimeHeader(headers, options.isEdgeRuntime);\n\n if (options.fontLinkHeader) {\n headers.set(\"Link\", options.fontLinkHeader);\n }\n\n mergeMiddlewareResponseHeaders(headers, options.middlewareHeaders ?? null);\n\n return new Response(safeStream, {\n status: options.status,\n headers,\n });\n}\n\nexport async function renderAppPageHtmlStreamWithRecovery<TSpecialError>(\n options: RenderAppPageHtmlStreamWithRecoveryOptions<TSpecialError>,\n): Promise<AppPageHtmlStreamRecoveryResult> {\n try {\n const htmlStream = await options.renderHtmlStream();\n options.onShellRendered?.();\n return {\n htmlStream,\n response: null,\n };\n } catch (error) {\n const specialError = options.resolveSpecialError(error);\n if (specialError) {\n return {\n htmlStream: null,\n response: await options.renderSpecialErrorResponse(specialError),\n };\n }\n\n const boundaryResponse = await options.renderErrorBoundaryResponse(error);\n if (boundaryResponse) {\n return {\n htmlStream: null,\n response: boundaryResponse,\n };\n }\n\n throw error;\n }\n}\n\nexport function createAppPageRscErrorTracker(\n baseOnError: (error: unknown, requestInfo: unknown, errorContext: unknown) => unknown,\n): AppPageRscErrorTracker {\n let capturedError: unknown = null;\n let capturedSpecialError: unknown = null;\n\n return {\n getCapturedError() {\n return capturedError;\n },\n getCapturedSpecialError() {\n return capturedSpecialError;\n },\n onRenderError(error, requestInfo, errorContext) {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n // Errors with a digest are signal throws (NEXT_REDIRECT,\n // NEXT_NOT_FOUND, NEXT_HTTP_ERROR_FALLBACK). They're not real\n // failures — keep the first one so the lifecycle can swap a\n // 307/404 in place of a streamed \"Switched to client rendering\"\n // body for routes with a route-level Suspense boundary.\n if (capturedSpecialError === null) {\n capturedSpecialError = error;\n }\n } else {\n capturedError = error;\n }\n return baseOnError(error, requestInfo, errorContext);\n },\n };\n}\n\nexport function shouldRerenderAppPageWithGlobalError(\n options: ShouldRerenderAppPageWithGlobalErrorOptions,\n): boolean {\n return Boolean(options.capturedError) && !options.hasLocalBoundary;\n}\n"],"mappings":";;;;AA6FA,SAAgB,sBAAsB,SAAwD;CAC5F,OAAO;EACL,OAAO,QAAQ,UAAU;EACzB,UAAU,QAAQ,aAAa;EAC/B,QAAQ,QAAQ,WAAW;EAC5B;;AAGH,eAAsB,wBACpB,SACqC;CACrC,MAAM,aAAa;EACjB,WAAW,QAAQ,aAAa;EAChC,aAAa,QAAQ;EACrB,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,YAAY,QAAQ;EACpB,oBAAoB,QA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GACL,YAAY;GACZ,UAAU,MAAM,QAAQ,2BAA2B,aAAa;GACjE;EAGH,MAAM,mBAAmB,MAAM,QAAQ,4BAA4B,MAAM;EACzE,IAAI,kBACF,OAAO;GACL,YAAY;GACZ,UAAU;GACX;EAGH,MAAM;;;AAIV,SAAgB,6BACd,aACwB;CACxB,IAAI,gBAAyB;CAC7B,IAAI,uBAAgC;CAEpC,OAAO;EACL,mBAAmB;GACjB,OAAO;;EAET,0BAA0B;GACxB,OAAO;;EAET,cAAc,OAAO,aAAa,cAAc;GAC9C,IAAI,SAAS,OAAO,UAAU,YAAY,YAAY;QAMhD,yBAAyB,MAC3B,uBAAuB;UAGzB,gBAAgB;GAElB,OAAO,YAAY,OAAO,aAAa,aAAa;;EAEvD;;AAGH,SAAgB,qCACd,SACS;CACT,OAAO,QAAQ,QAAQ,cAAc,IAAI,CAAC,QAAQ"}
@@ -21,6 +21,7 @@ type DispatchAppRouteHandlerOptions = {
21
21
  basePath?: string;
22
22
  cleanPathname: string;
23
23
  clearRequestContext: () => void;
24
+ draftModeSecret: string;
24
25
  expireSeconds?: number;
25
26
  i18n?: NextI18nConfig | null;
26
27
  isDevelopment?: boolean;
@@ -22,6 +22,7 @@ function buildRouteHandlerPageCacheTags(pathname, extraTags, routeSegments) {
22
22
  async function runInRouteHandlerRevalidationContext(options, renderFn) {
23
23
  await runWithRequestContext(createRequestContext({
24
24
  headersContext: createStaticGenerationHeadersContext({
25
+ draftModeSecret: options.draftModeSecret,
25
26
  dynamicConfig: options.dynamicConfig,
26
27
  routeKind: "route",
27
28
  routePattern: options.routePattern
@@ -92,6 +93,7 @@ async function dispatchAppRouteHandler(options) {
92
93
  runInRevalidationContext(renderFn) {
93
94
  return runInRouteHandlerRevalidationContext({
94
95
  cleanPathname: options.cleanPathname,
96
+ draftModeSecret: options.draftModeSecret,
95
97
  dynamicConfig: handler.dynamic,
96
98
  routePattern: route.pattern,
97
99
  routeSegments: route.routeSegments
@@ -117,6 +119,7 @@ async function dispatchAppRouteHandler(options) {
117
119
  cleanPathname: options.cleanPathname,
118
120
  clearRequestContext: options.clearRequestContext,
119
121
  consumeDynamicUsage,
122
+ draftModeSecret: options.draftModeSecret,
120
123
  executionContext: getRequestExecutionContext(),
121
124
  getAndClearPendingCookies,
122
125
  getCollectedFetchTags,
@@ -1 +1 @@
1
- {"version":3,"file":"app-route-handler-dispatch.js","names":[],"sources":["../../src/server/app-route-handler-dispatch.ts"],"sourcesContent":["import type { NextI18nConfig } from \"../config/next-config.js\";\nimport {\n getCollectedFetchTags,\n ensureFetchPatch,\n setCurrentFetchSoftTags,\n} from \"vinext/shims/fetch-cache\";\nimport {\n consumeDynamicUsage,\n getAndClearPendingCookies,\n getDraftModeCookieHeader,\n markDynamicUsage,\n setHeadersAccessPhase,\n} from \"vinext/shims/headers\";\nimport { setNavigationContext } from \"vinext/shims/navigation\";\nimport { getRequestExecutionContext } from \"vinext/shims/request-context\";\nimport { createRequestContext, runWithRequestContext } from \"vinext/shims/unified-request-context\";\nimport type { ISRCacheEntry } from \"./isr-cache.js\";\nimport {\n getAppRouteHandlerRevalidateSeconds,\n hasAppRouteHandlerDefaultExport,\n resolveAppRouteHandlerMethod,\n shouldReadAppRouteHandlerCache,\n type AppRouteHandlerModule,\n} from \"./app-route-handler-policy.js\";\nimport { readAppRouteHandlerCacheResponse } from \"./app-route-handler-cache.js\";\nimport {\n executeAppRouteHandler,\n type AppRouteDebugLogger,\n type AppRouteHandlerFunction,\n type AppRouteParams,\n type RouteHandlerCacheSetter,\n} from \"./app-route-handler-execution.js\";\nimport { isKnownDynamicAppRoute, isValidHTTPMethod } from \"./app-route-handler-runtime.js\";\nimport {\n applyRouteHandlerMiddlewareContext,\n type RouteHandlerMiddlewareContext,\n} from \"./app-route-handler-response.js\";\nimport { createStaticGenerationHeadersContext } from \"./app-static-generation.js\";\nimport { buildPageCacheTags } from \"./implicit-tags.js\";\nimport { makeThenableParams } from \"vinext/shims/thenable-params\";\nimport { reportRequestError } from \"./instrumentation.js\";\n\ntype AppRouteHandlerDispatchRoute = {\n pattern: string;\n routeHandler: AppRouteHandlerModule;\n routeSegments: string[];\n};\n\ntype RouteHandlerCacheGetter = (key: string) => Promise<ISRCacheEntry | null>;\ntype RouteHandlerBackgroundRegenerationErrorContext = {\n routerKind: \"App Router\";\n routePath: string;\n routeType: \"route\";\n};\ntype RouteHandlerBackgroundRegenerator = (\n key: string,\n renderFn: () => Promise<void>,\n errorContext?: RouteHandlerBackgroundRegenerationErrorContext,\n) => void;\n\ntype DispatchAppRouteHandlerOptions = {\n basePath?: string;\n cleanPathname: string;\n clearRequestContext: () => void;\n expireSeconds?: number;\n i18n?: NextI18nConfig | null;\n isDevelopment?: boolean;\n isProduction?: boolean;\n isrDebug?: AppRouteDebugLogger;\n isrGet: RouteHandlerCacheGetter;\n isrRouteKey: (pathname: string) => string;\n isrSet: RouteHandlerCacheSetter;\n middlewareContext: RouteHandlerMiddlewareContext;\n middlewareRequestHeaders?: Headers | null;\n /**\n * `null` for non-dynamic routes, matching Next.js semantics. The dispatch\n * layer threads this through to the handler context unchanged so user code\n * (`params ? await params : null`) resolves to `null`.\n */\n params: AppRouteParams | null;\n request: Request;\n route: AppRouteHandlerDispatchRoute;\n scheduleBackgroundRegeneration: RouteHandlerBackgroundRegenerator;\n searchParams: URLSearchParams;\n};\n\nfunction isAppRouteHandlerFunction(value: unknown): value is AppRouteHandlerFunction {\n return typeof value === \"function\";\n}\n\nfunction buildRouteHandlerPageCacheTags(\n pathname: string,\n extraTags: string[],\n routeSegments: string[],\n): string[] {\n return buildPageCacheTags(pathname, extraTags, routeSegments, \"route\");\n}\n\nasync function runInRouteHandlerRevalidationContext(\n options: {\n cleanPathname: string;\n dynamicConfig?: string;\n routePattern: string;\n routeSegments: string[];\n },\n renderFn: () => Promise<void>,\n): Promise<void> {\n const headersContext = createStaticGenerationHeadersContext({\n dynamicConfig: options.dynamicConfig,\n routeKind: \"route\",\n routePattern: options.routePattern,\n });\n const requestContext = createRequestContext({\n headersContext,\n executionContext: getRequestExecutionContext(),\n unstableCacheRevalidation: \"foreground\",\n });\n\n await runWithRequestContext(requestContext, async () => {\n ensureFetchPatch();\n setCurrentFetchSoftTags(\n buildRouteHandlerPageCacheTags(options.cleanPathname, [], options.routeSegments),\n );\n await renderFn();\n });\n}\n\nexport async function dispatchAppRouteHandler(\n options: DispatchAppRouteHandlerOptions,\n): Promise<Response> {\n const { route } = options;\n const handler = route.routeHandler;\n const method = options.request.method.toUpperCase();\n const revalidateSeconds = getAppRouteHandlerRevalidateSeconds(handler);\n const isDevelopment = options.isDevelopment ?? process.env.NODE_ENV === \"development\";\n const isProduction = options.isProduction ?? process.env.NODE_ENV === \"production\";\n\n if (hasAppRouteHandlerDefaultExport(handler) && isDevelopment) {\n console.error(\n \"[vinext] Detected default export in route handler \" +\n route.pattern +\n \". Export a named export for each HTTP method instead.\",\n );\n }\n\n // Reject non-standard HTTP methods before any auto-OPTIONS/405 logic.\n // Next.js returns 400 for invalid methods; vinext mirrors that behavior.\n // https://github.com/vercel/next.js/blob/canary/packages/next/src/server/route-modules/app-route/module.ts#L390-L392\n if (!isValidHTTPMethod(method)) {\n options.clearRequestContext();\n return applyRouteHandlerMiddlewareContext(\n new Response(null, { status: 400 }),\n options.middlewareContext,\n );\n }\n\n const { allowHeaderForOptions, handlerFn, isAutoHead, shouldAutoRespondToOptions } =\n resolveAppRouteHandlerMethod(handler, method);\n\n if (shouldAutoRespondToOptions) {\n options.clearRequestContext();\n return applyRouteHandlerMiddlewareContext(\n new Response(null, {\n status: 204,\n headers: { Allow: allowHeaderForOptions },\n }),\n options.middlewareContext,\n );\n }\n\n const resolvedHandlerFn = isAppRouteHandlerFunction(handlerFn) ? handlerFn : undefined;\n\n if (\n revalidateSeconds !== null &&\n shouldReadAppRouteHandlerCache({\n dynamicConfig: handler.dynamic,\n handlerFn: resolvedHandlerFn,\n isAutoHead,\n isKnownDynamic: isKnownDynamicAppRoute(route.pattern),\n isProduction,\n method,\n revalidateSeconds,\n }) &&\n resolvedHandlerFn\n ) {\n const cachedRouteResponse = await readAppRouteHandlerCacheResponse({\n basePath: options.basePath,\n buildPageCacheTags(pathname, extraTags) {\n return buildRouteHandlerPageCacheTags(pathname, extraTags, route.routeSegments);\n },\n cleanPathname: options.cleanPathname,\n clearRequestContext: options.clearRequestContext,\n consumeDynamicUsage,\n dynamicConfig: handler.dynamic,\n getCollectedFetchTags,\n handlerFn: resolvedHandlerFn,\n i18n: options.i18n,\n isAutoHead,\n isrDebug: options.isrDebug,\n isrGet: options.isrGet,\n isrRouteKey: options.isrRouteKey,\n isrSet: options.isrSet,\n markDynamicUsage,\n middlewareContext: options.middlewareContext,\n params: options.params,\n requestUrl: options.request.url,\n revalidateSearchParams: options.searchParams,\n expireSeconds: options.expireSeconds,\n revalidateSeconds,\n routePattern: route.pattern,\n runInRevalidationContext(renderFn) {\n return runInRouteHandlerRevalidationContext(\n {\n cleanPathname: options.cleanPathname,\n dynamicConfig: handler.dynamic,\n routePattern: route.pattern,\n routeSegments: route.routeSegments,\n },\n renderFn,\n );\n },\n scheduleBackgroundRegeneration(key, renderFn) {\n options.scheduleBackgroundRegeneration(key, renderFn, {\n routerKind: \"App Router\",\n routePath: route.pattern,\n routeType: \"route\",\n });\n },\n setHeadersAccessPhase,\n setNavigationContext,\n });\n if (cachedRouteResponse) {\n return cachedRouteResponse;\n }\n }\n\n if (resolvedHandlerFn) {\n return executeAppRouteHandler({\n basePath: options.basePath,\n buildPageCacheTags(pathname, extraTags) {\n return buildRouteHandlerPageCacheTags(pathname, extraTags, route.routeSegments);\n },\n cleanPathname: options.cleanPathname,\n clearRequestContext: options.clearRequestContext,\n consumeDynamicUsage,\n executionContext: getRequestExecutionContext(),\n getAndClearPendingCookies,\n getCollectedFetchTags,\n getDraftModeCookieHeader,\n handler,\n handlerFn: resolvedHandlerFn,\n i18n: options.i18n,\n isAutoHead,\n isProduction,\n isrDebug: options.isrDebug,\n isrRouteKey: options.isrRouteKey,\n isrSet: options.isrSet,\n markDynamicUsage,\n method,\n middlewareContext: options.middlewareContext,\n middlewareRequestHeaders: options.middlewareRequestHeaders,\n params: options.params === null ? null : makeThenableParams(options.params),\n reportRequestError(error, request, context) {\n void reportRequestError(error, request, context);\n },\n request: options.request,\n expireSeconds: options.expireSeconds,\n revalidateSeconds,\n routePattern: route.pattern,\n setHeadersAccessPhase,\n });\n }\n\n options.clearRequestContext();\n return applyRouteHandlerMiddlewareContext(\n new Response(null, {\n status: 405,\n }),\n options.middlewareContext,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsFA,SAAS,0BAA0B,OAAkD;CACnF,OAAO,OAAO,UAAU;;AAG1B,SAAS,+BACP,UACA,WACA,eACU;CACV,OAAO,mBAAmB,UAAU,WAAW,eAAe,QAAQ;;AAGxE,eAAe,qCACb,SAMA,UACe;CAYf,MAAM,sBANiB,qBAAqB;EAC1C,gBANqB,qCAAqC;GAC1D,eAAe,QAAQ;GACvB,WAAW;GACX,cAAc,QAAQ;GACvB,CAEe;EACd,kBAAkB,4BAA4B;EAC9C,2BAA2B;EAC5B,CAEyC,EAAE,YAAY;EACtD,kBAAkB;EAClB,wBACE,+BAA+B,QAAQ,eAAe,EAAE,EAAE,QAAQ,cAAc,CACjF;EACD,MAAM,UAAU;GAChB;;AAGJ,eAAsB,wBACpB,SACmB;CACnB,MAAM,EAAE,UAAU;CAClB,MAAM,UAAU,MAAM;CACtB,MAAM,SAAS,QAAQ,QAAQ,OAAO,aAAa;CACnD,MAAM,oBAAoB,oCAAoC,QAAQ;CACtE,MAAM,gBAAgB,QAAQ,iBAAiB,QAAQ,IAAI,aAAa;CACxE,MAAM,eAAe,QAAQ,gBAAgB,QAAQ,IAAI,aAAa;CAEtE,IAAI,gCAAgC,QAAQ,IAAI,eAC9C,QAAQ,MACN,uDACE,MAAM,UACN,wDACH;CAMH,IAAI,CAAC,kBAAkB,OAAO,EAAE;EAC9B,QAAQ,qBAAqB;EAC7B,OAAO,mCACL,IAAI,SAAS,MAAM,EAAE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AAuB;EAC5B,UAAU,QAAQ;EAClB,mBAAmB,UAAU,WAAW;GACtC,OAAO,+BAA+B,UAAU,WAAW,MAAM,cAAc;;EAEjF,eAAe,QAAQ;EACvB,qBAAqB,QAAQ;EAC7B;EACA,kBAAkB,4BAA4B;EAC9C;EACA;EACA;EACA;EACA,WAAW;EACX,MAAM,QAAQ;EACd;EACA;EACA,UAAU,QAAQ;EAClB,aAAa,QAAQ;EACrB,QAAQ,QAAQ;EAChB;EACA;EACA,mBAAmB,QAAQ;EAC3B,0BAA0B,QAAQ;EAClC,QAAQ,QAAQ,WAAW,OAAO,OAAO,mBAAmB,QAAQ,OAAO;EAC3E,mBAAmB,OAAO,SAAS,SAAS;GAC1C,mBAAwB,OAAO,SAAS,QAAQ;;EAElD,SAAS,QAAQ;EACjB,eAAe,QAAQ;EACvB;EACA,cAAc,MAAM;EACpB;EACD,CAAC;CAGJ,QAAQ,qBAAqB;CAC7B,OAAO,mCACL,IAAI,SAAS,MAAM,EACjB,QAAQ,KACT,CAAC,EACF,QAAQ,kBACT"}
1
+ {"version":3,"file":"app-route-handler-dispatch.js","names":[],"sources":["../../src/server/app-route-handler-dispatch.ts"],"sourcesContent":["import type { NextI18nConfig } from \"../config/next-config.js\";\nimport {\n getCollectedFetchTags,\n ensureFetchPatch,\n setCurrentFetchSoftTags,\n} from \"vinext/shims/fetch-cache\";\nimport {\n consumeDynamicUsage,\n getAndClearPendingCookies,\n getDraftModeCookieHeader,\n markDynamicUsage,\n setHeadersAccessPhase,\n} from \"vinext/shims/headers\";\nimport { setNavigationContext } from \"vinext/shims/navigation\";\nimport { getRequestExecutionContext } from \"vinext/shims/request-context\";\nimport { createRequestContext, runWithRequestContext } from \"vinext/shims/unified-request-context\";\nimport type { ISRCacheEntry } from \"./isr-cache.js\";\nimport {\n getAppRouteHandlerRevalidateSeconds,\n hasAppRouteHandlerDefaultExport,\n resolveAppRouteHandlerMethod,\n shouldReadAppRouteHandlerCache,\n type AppRouteHandlerModule,\n} from \"./app-route-handler-policy.js\";\nimport { readAppRouteHandlerCacheResponse } from \"./app-route-handler-cache.js\";\nimport {\n executeAppRouteHandler,\n type AppRouteDebugLogger,\n type AppRouteHandlerFunction,\n type AppRouteParams,\n type RouteHandlerCacheSetter,\n} from \"./app-route-handler-execution.js\";\nimport { isKnownDynamicAppRoute, isValidHTTPMethod } from \"./app-route-handler-runtime.js\";\nimport {\n applyRouteHandlerMiddlewareContext,\n type RouteHandlerMiddlewareContext,\n} from \"./app-route-handler-response.js\";\nimport { createStaticGenerationHeadersContext } from \"./app-static-generation.js\";\nimport { buildPageCacheTags } from \"./implicit-tags.js\";\nimport { makeThenableParams } from \"vinext/shims/thenable-params\";\nimport { reportRequestError } from \"./instrumentation.js\";\n\ntype AppRouteHandlerDispatchRoute = {\n pattern: string;\n routeHandler: AppRouteHandlerModule;\n routeSegments: string[];\n};\n\ntype RouteHandlerCacheGetter = (key: string) => Promise<ISRCacheEntry | null>;\ntype RouteHandlerBackgroundRegenerationErrorContext = {\n routerKind: \"App Router\";\n routePath: string;\n routeType: \"route\";\n};\ntype RouteHandlerBackgroundRegenerator = (\n key: string,\n renderFn: () => Promise<void>,\n errorContext?: RouteHandlerBackgroundRegenerationErrorContext,\n) => void;\n\ntype DispatchAppRouteHandlerOptions = {\n basePath?: string;\n cleanPathname: string;\n clearRequestContext: () => void;\n draftModeSecret: string;\n expireSeconds?: number;\n i18n?: NextI18nConfig | null;\n isDevelopment?: boolean;\n isProduction?: boolean;\n isrDebug?: AppRouteDebugLogger;\n isrGet: RouteHandlerCacheGetter;\n isrRouteKey: (pathname: string) => string;\n isrSet: RouteHandlerCacheSetter;\n middlewareContext: RouteHandlerMiddlewareContext;\n middlewareRequestHeaders?: Headers | null;\n /**\n * `null` for non-dynamic routes, matching Next.js semantics. The dispatch\n * layer threads this through to the handler context unchanged so user code\n * (`params ? await params : null`) resolves to `null`.\n */\n params: AppRouteParams | null;\n request: Request;\n route: AppRouteHandlerDispatchRoute;\n scheduleBackgroundRegeneration: RouteHandlerBackgroundRegenerator;\n searchParams: URLSearchParams;\n};\n\nfunction isAppRouteHandlerFunction(value: unknown): value is AppRouteHandlerFunction {\n return typeof value === \"function\";\n}\n\nfunction buildRouteHandlerPageCacheTags(\n pathname: string,\n extraTags: string[],\n routeSegments: string[],\n): string[] {\n return buildPageCacheTags(pathname, extraTags, routeSegments, \"route\");\n}\n\nasync function runInRouteHandlerRevalidationContext(\n options: {\n cleanPathname: string;\n draftModeSecret: string;\n dynamicConfig?: string;\n routePattern: string;\n routeSegments: string[];\n },\n renderFn: () => Promise<void>,\n): Promise<void> {\n const headersContext = createStaticGenerationHeadersContext({\n draftModeSecret: options.draftModeSecret,\n dynamicConfig: options.dynamicConfig,\n routeKind: \"route\",\n routePattern: options.routePattern,\n });\n const requestContext = createRequestContext({\n headersContext,\n executionContext: getRequestExecutionContext(),\n unstableCacheRevalidation: \"foreground\",\n });\n\n await runWithRequestContext(requestContext, async () => {\n ensureFetchPatch();\n setCurrentFetchSoftTags(\n buildRouteHandlerPageCacheTags(options.cleanPathname, [], options.routeSegments),\n );\n await renderFn();\n });\n}\n\nexport async function dispatchAppRouteHandler(\n options: DispatchAppRouteHandlerOptions,\n): Promise<Response> {\n const { route } = options;\n const handler = route.routeHandler;\n const method = options.request.method.toUpperCase();\n const revalidateSeconds = getAppRouteHandlerRevalidateSeconds(handler);\n const isDevelopment = options.isDevelopment ?? process.env.NODE_ENV === \"development\";\n const isProduction = options.isProduction ?? process.env.NODE_ENV === \"production\";\n\n if (hasAppRouteHandlerDefaultExport(handler) && isDevelopment) {\n console.error(\n \"[vinext] Detected default export in route handler \" +\n route.pattern +\n \". Export a named export for each HTTP method instead.\",\n );\n }\n\n // Reject non-standard HTTP methods before any auto-OPTIONS/405 logic.\n // Next.js returns 400 for invalid methods; vinext mirrors that behavior.\n // https://github.com/vercel/next.js/blob/canary/packages/next/src/server/route-modules/app-route/module.ts#L390-L392\n if (!isValidHTTPMethod(method)) {\n options.clearRequestContext();\n return applyRouteHandlerMiddlewareContext(\n new Response(null, { status: 400 }),\n options.middlewareContext,\n );\n }\n\n const { allowHeaderForOptions, handlerFn, isAutoHead, shouldAutoRespondToOptions } =\n resolveAppRouteHandlerMethod(handler, method);\n\n if (shouldAutoRespondToOptions) {\n options.clearRequestContext();\n return applyRouteHandlerMiddlewareContext(\n new Response(null, {\n status: 204,\n headers: { Allow: allowHeaderForOptions },\n }),\n options.middlewareContext,\n );\n }\n\n const resolvedHandlerFn = isAppRouteHandlerFunction(handlerFn) ? handlerFn : undefined;\n\n if (\n revalidateSeconds !== null &&\n shouldReadAppRouteHandlerCache({\n dynamicConfig: handler.dynamic,\n handlerFn: resolvedHandlerFn,\n isAutoHead,\n isKnownDynamic: isKnownDynamicAppRoute(route.pattern),\n isProduction,\n method,\n revalidateSeconds,\n }) &&\n resolvedHandlerFn\n ) {\n const cachedRouteResponse = await readAppRouteHandlerCacheResponse({\n basePath: options.basePath,\n buildPageCacheTags(pathname, extraTags) {\n return buildRouteHandlerPageCacheTags(pathname, extraTags, route.routeSegments);\n },\n cleanPathname: options.cleanPathname,\n clearRequestContext: options.clearRequestContext,\n consumeDynamicUsage,\n dynamicConfig: handler.dynamic,\n getCollectedFetchTags,\n handlerFn: resolvedHandlerFn,\n i18n: options.i18n,\n isAutoHead,\n isrDebug: options.isrDebug,\n isrGet: options.isrGet,\n isrRouteKey: options.isrRouteKey,\n isrSet: options.isrSet,\n markDynamicUsage,\n middlewareContext: options.middlewareContext,\n params: options.params,\n requestUrl: options.request.url,\n revalidateSearchParams: options.searchParams,\n expireSeconds: options.expireSeconds,\n revalidateSeconds,\n routePattern: route.pattern,\n runInRevalidationContext(renderFn) {\n return runInRouteHandlerRevalidationContext(\n {\n cleanPathname: options.cleanPathname,\n draftModeSecret: options.draftModeSecret,\n dynamicConfig: handler.dynamic,\n routePattern: route.pattern,\n routeSegments: route.routeSegments,\n },\n renderFn,\n );\n },\n scheduleBackgroundRegeneration(key, renderFn) {\n options.scheduleBackgroundRegeneration(key, renderFn, {\n routerKind: \"App Router\",\n routePath: route.pattern,\n routeType: \"route\",\n });\n },\n setHeadersAccessPhase,\n setNavigationContext,\n });\n if (cachedRouteResponse) {\n return cachedRouteResponse;\n }\n }\n\n if (resolvedHandlerFn) {\n return executeAppRouteHandler({\n basePath: options.basePath,\n buildPageCacheTags(pathname, extraTags) {\n return buildRouteHandlerPageCacheTags(pathname, extraTags, route.routeSegments);\n },\n cleanPathname: options.cleanPathname,\n clearRequestContext: options.clearRequestContext,\n consumeDynamicUsage,\n draftModeSecret: options.draftModeSecret,\n executionContext: getRequestExecutionContext(),\n getAndClearPendingCookies,\n getCollectedFetchTags,\n getDraftModeCookieHeader,\n handler,\n handlerFn: resolvedHandlerFn,\n i18n: options.i18n,\n isAutoHead,\n isProduction,\n isrDebug: options.isrDebug,\n isrRouteKey: options.isrRouteKey,\n isrSet: options.isrSet,\n markDynamicUsage,\n method,\n middlewareContext: options.middlewareContext,\n middlewareRequestHeaders: options.middlewareRequestHeaders,\n params: options.params === null ? null : makeThenableParams(options.params),\n reportRequestError(error, request, context) {\n void reportRequestError(error, request, context);\n },\n request: options.request,\n expireSeconds: options.expireSeconds,\n revalidateSeconds,\n routePattern: route.pattern,\n setHeadersAccessPhase,\n });\n }\n\n options.clearRequestContext();\n return applyRouteHandlerMiddlewareContext(\n new Response(null, {\n status: 405,\n }),\n options.middlewareContext,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuFA,SAAS,0BAA0B,OAAkD;CACnF,OAAO,OAAO,UAAU;;AAG1B,SAAS,+BACP,UACA,WACA,eACU;CACV,OAAO,mBAAmB,UAAU,WAAW,eAAe,QAAQ;;AAGxE,eAAe,qCACb,SAOA,UACe;CAaf,MAAM,sBANiB,qBAAqB;EAC1C,gBAPqB,qCAAqC;GAC1D,iBAAiB,QAAQ;GACzB,eAAe,QAAQ;GACvB,WAAW;GACX,cAAc,QAAQ;GACvB,CAEe;EACd,kBAAkB,4BAA4B;EAC9C,2BAA2B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jB,QAAQ,KACT,CAAC,EACF,QAAQ,kBACT"}
@@ -38,6 +38,7 @@ type AppRouteDebugLogger = (event: string, detail: string) => void;
38
38
  type RunAppRouteHandlerOptions = {
39
39
  basePath?: string;
40
40
  consumeDynamicUsage: AppRouteDynamicUsageFn;
41
+ draftModeSecret?: string;
41
42
  dynamicConfig?: string;
42
43
  handlerFn: AppRouteHandlerFunction;
43
44
  i18n?: NextI18nConfig | null;
@@ -7,6 +7,7 @@ import { applyRouteHandlerMiddlewareContext, applyRouteHandlerRevalidateHeader,
7
7
  function configureAppRouteStaticGenerationContext(options) {
8
8
  if (options.dynamicConfig === "force-static" || options.dynamicConfig === "error") {
9
9
  setHeadersContext(createStaticGenerationHeadersContext({
10
+ draftModeSecret: options.draftModeSecret,
10
11
  dynamicConfig: options.dynamicConfig,
11
12
  routeKind: "route",
12
13
  routePattern: options.routePattern
@@ -1 +1 @@
1
- {"version":3,"file":"app-route-handler-execution.js","names":[],"sources":["../../src/server/app-route-handler-execution.ts"],"sourcesContent":["import type { NextI18nConfig } from \"../config/next-config.js\";\nimport { setHeadersContext, type HeadersAccessPhase } from \"vinext/shims/headers\";\nimport type { ExecutionContextLike } from \"vinext/shims/request-context\";\nimport type { CachedRouteValue } from \"vinext/shims/cache\";\nimport type { NextRequest } from \"vinext/shims/server\";\nimport {\n createStaticGenerationHeadersContext,\n getAppRouteStaticGenerationErrorMessage,\n} from \"./app-static-generation.js\";\nimport {\n isPossibleAppRouteActionRequest,\n resolveAppRouteHandlerSpecialError,\n shouldApplyAppRouteHandlerRevalidateHeader,\n shouldWriteAppRouteHandlerCache,\n type AppRouteHandlerModule,\n} from \"./app-route-handler-policy.js\";\nimport {\n applyRouteHandlerMiddlewareContext,\n applyRouteHandlerRevalidateHeader,\n assertSupportedAppRouteHandlerResponse,\n buildAppRouteCacheValue,\n finalizeRouteHandlerResponse,\n markRouteHandlerCacheMiss,\n type RouteHandlerMiddlewareContext,\n} from \"./app-route-handler-response.js\";\nimport {\n createTrackedAppRouteRequest,\n markKnownDynamicAppRoute,\n} from \"./app-route-handler-runtime.js\";\n\nexport type AppRouteParams = Record<string, string | string[]>;\nexport type AppRouteDynamicUsageFn = () => boolean;\nexport type MarkAppRouteDynamicUsageFn = () => void;\n/**\n * Route handler context.\n *\n * `params` is `null` for non-dynamic routes (no `[param]` segments) so that\n * user code like `params ? await params : null` resolves to `null`, matching\n * Next.js behavior. For dynamic routes it's a thenable that resolves to the\n * matched params object.\n *\n * See: test/e2e/app-dir/app-routes/app-custom-routes.test.ts in Next.js for\n * the authoritative assertion (`expect(meta.params).toEqual(null)`).\n */\nexport type AppRouteHandlerFunction = (\n request: NextRequest,\n context: { params: AppRouteParams | null },\n) => Response | Promise<Response>;\nexport type RouteHandlerCacheSetter = (\n key: string,\n data: CachedRouteValue,\n revalidateSeconds: number,\n tags: string[],\n expireSeconds?: number,\n) => Promise<void>;\ntype AppRouteErrorReporter = (\n error: Error,\n request: { path: string; method: string; headers: Record<string, string> },\n route: { routerKind: \"App Router\"; routePath: string; routeType: \"route\" },\n) => void;\nexport type AppRouteDebugLogger = (event: string, detail: string) => void;\n\ntype RunAppRouteHandlerOptions = {\n basePath?: string;\n consumeDynamicUsage: AppRouteDynamicUsageFn;\n dynamicConfig?: string;\n handlerFn: AppRouteHandlerFunction;\n i18n?: NextI18nConfig | null;\n markDynamicUsage: MarkAppRouteDynamicUsageFn;\n middlewareRequestHeaders?: Headers | null;\n /**\n * `null` for non-dynamic routes. Passed through to the handler context\n * unchanged — callers are expected to compute this from `route.isDynamic`.\n */\n params: AppRouteParams | null;\n request: Request;\n routePattern?: string;\n setHeadersAccessPhase?: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n};\n\ntype RunAppRouteHandlerResult = {\n dynamicUsedInHandler: boolean;\n response: Response;\n};\n\ntype ExecuteAppRouteHandlerOptions = {\n buildPageCacheTags: (pathname: string, extraTags: string[]) => string[];\n clearRequestContext: () => void;\n cleanPathname: string;\n executionContext: ExecutionContextLike | null;\n getAndClearPendingCookies: () => string[];\n getCollectedFetchTags: () => string[];\n getDraftModeCookieHeader: () => string | null | undefined;\n handler: AppRouteHandlerModule;\n isAutoHead: boolean;\n isProduction: boolean;\n isrDebug?: AppRouteDebugLogger;\n isrRouteKey: (pathname: string) => string;\n isrSet: RouteHandlerCacheSetter;\n method: string;\n middlewareContext: RouteHandlerMiddlewareContext;\n reportRequestError: AppRouteErrorReporter;\n expireSeconds?: number;\n revalidateSeconds: number | null;\n routePattern: string;\n setHeadersAccessPhase: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n} & RunAppRouteHandlerOptions;\n\nfunction configureAppRouteStaticGenerationContext(options: RunAppRouteHandlerOptions): void {\n if (options.dynamicConfig === \"force-static\" || options.dynamicConfig === \"error\") {\n setHeadersContext(\n createStaticGenerationHeadersContext({\n dynamicConfig: options.dynamicConfig,\n routeKind: \"route\",\n routePattern: options.routePattern,\n }),\n );\n options.setHeadersAccessPhase?.(\"route-handler\");\n }\n}\n\nexport async function runAppRouteHandler(\n options: RunAppRouteHandlerOptions,\n): Promise<RunAppRouteHandlerResult> {\n options.consumeDynamicUsage();\n configureAppRouteStaticGenerationContext(options);\n const trackedRequest = createTrackedAppRouteRequest(options.request, {\n basePath: options.basePath,\n i18n: options.i18n,\n middlewareHeaders: options.middlewareRequestHeaders,\n onDynamicAccess() {\n options.markDynamicUsage();\n },\n requestMode:\n options.dynamicConfig === \"force-static\" || options.dynamicConfig === \"error\"\n ? options.dynamicConfig\n : \"auto\",\n staticGenerationErrorMessage(expression) {\n return getAppRouteStaticGenerationErrorMessage(options.routePattern, expression);\n },\n });\n const response = await options.handlerFn(trackedRequest.request, {\n params: options.params,\n });\n\n return {\n dynamicUsedInHandler: options.consumeDynamicUsage(),\n response,\n };\n}\n\nexport async function executeAppRouteHandler(\n options: ExecuteAppRouteHandlerOptions,\n): Promise<Response> {\n const previousHeadersPhase = options.setHeadersAccessPhase(\"route-handler\");\n\n try {\n const { dynamicUsedInHandler, response } = await runAppRouteHandler({\n ...options,\n dynamicConfig: options.handler.dynamic,\n });\n assertSupportedAppRouteHandlerResponse(response);\n const handlerSetCacheControl = response.headers.has(\"cache-control\");\n\n if (dynamicUsedInHandler) {\n markKnownDynamicAppRoute(options.routePattern);\n }\n\n if (\n shouldApplyAppRouteHandlerRevalidateHeader({\n dynamicUsedInHandler,\n handlerSetCacheControl,\n isAutoHead: options.isAutoHead,\n method: options.method,\n revalidateSeconds: options.revalidateSeconds,\n })\n ) {\n const revalidateSeconds = options.revalidateSeconds;\n if (revalidateSeconds == null) {\n throw new Error(\"Expected route handler revalidate seconds\");\n }\n applyRouteHandlerRevalidateHeader(response, revalidateSeconds, options.expireSeconds);\n }\n\n if (\n shouldWriteAppRouteHandlerCache({\n dynamicConfig: options.handler.dynamic,\n dynamicUsedInHandler,\n handlerSetCacheControl,\n isAutoHead: options.isAutoHead,\n isProduction: options.isProduction,\n method: options.method,\n revalidateSeconds: options.revalidateSeconds,\n })\n ) {\n markRouteHandlerCacheMiss(response);\n const routeClone = response.clone();\n const routeKey = options.isrRouteKey(options.cleanPathname);\n const revalidateSeconds = options.revalidateSeconds;\n if (revalidateSeconds == null) {\n throw new Error(\"Expected route handler cache revalidate seconds\");\n }\n const routeTags = options.buildPageCacheTags(\n options.cleanPathname,\n options.getCollectedFetchTags(),\n );\n const routeWritePromise = (async () => {\n try {\n const routeCacheValue = await buildAppRouteCacheValue(routeClone);\n await options.isrSet(\n routeKey,\n routeCacheValue,\n revalidateSeconds,\n routeTags,\n options.expireSeconds,\n );\n options.isrDebug?.(\"route cache written\", routeKey);\n } catch (cacheErr) {\n console.error(\"[vinext] ISR route cache write error:\", cacheErr);\n }\n })();\n options.executionContext?.waitUntil(routeWritePromise);\n }\n\n const pendingCookies = options.getAndClearPendingCookies();\n const draftCookie = options.getDraftModeCookieHeader();\n options.clearRequestContext();\n\n return applyRouteHandlerMiddlewareContext(\n finalizeRouteHandlerResponse(response, {\n pendingCookies,\n draftCookie,\n isHead: options.isAutoHead,\n }),\n options.middlewareContext,\n );\n } catch (error) {\n const pendingCookies = options.getAndClearPendingCookies();\n const draftCookie = options.getDraftModeCookieHeader();\n const specialError = resolveAppRouteHandlerSpecialError(error, options.request.url, {\n isAction: isPossibleAppRouteActionRequest(options.request),\n });\n options.clearRequestContext();\n\n if (specialError) {\n if (specialError.kind === \"redirect\") {\n return applyRouteHandlerMiddlewareContext(\n finalizeRouteHandlerResponse(\n new Response(null, {\n status: specialError.statusCode,\n headers: { Location: specialError.location },\n }),\n {\n pendingCookies,\n draftCookie,\n isHead: options.isAutoHead,\n },\n ),\n options.middlewareContext,\n );\n }\n\n return applyRouteHandlerMiddlewareContext(\n new Response(null, { status: specialError.statusCode }),\n options.middlewareContext,\n );\n }\n\n console.error(\"[vinext] Route handler error:\", error);\n options.reportRequestError(\n error instanceof Error ? error : new Error(String(error)),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n {\n routerKind: \"App Router\",\n routePath: options.routePattern,\n routeType: \"route\",\n },\n );\n\n return applyRouteHandlerMiddlewareContext(\n new Response(null, { status: 500 }),\n options.middlewareContext,\n );\n } finally {\n options.setHeadersAccessPhase(previousHeadersPhase);\n }\n}\n"],"mappings":";;;;;;AA4GA,SAAS,yCAAyC,SAA0C;CAC1F,IAAI,QAAQ,kBAAkB,kBAAkB,QAAQ,kBAAkB,SAAS;EACjF,kBACE,qCAAqC;GACnC,eAAe,QAAQ;GACvB,WAAW;GACX,cAAc,QAAQ;GACvB,CAAC,CACH;EACD,QAAQ,wBAAwB,gBAAgB;;;AAIpD,eAAsB,mBACpB,SACmC;CACnC,QAAQ,qBAAqB;CAC7B,yCAAyC,QAAQ;CACjD,MAAM,iBAAiB,6BAA6B,QAAQ,SAAS;EACnE,UAAU,QAAQ;EAClB,MAAM,QAAQ;EACd,mBAAmB,QAAQ;EAC3B,kBAAkB;GAChB,QAAQ,kBAAkB;;EAE5B,aACE,QAAQ,kBAAkB,kBAAkB,Q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QAAQ,kBACT;WACO;EACR,QAAQ,sBAAsB,qBAAqB"}
1
+ {"version":3,"file":"app-route-handler-execution.js","names":[],"sources":["../../src/server/app-route-handler-execution.ts"],"sourcesContent":["import type { NextI18nConfig } from \"../config/next-config.js\";\nimport { setHeadersContext, type HeadersAccessPhase } from \"vinext/shims/headers\";\nimport type { ExecutionContextLike } from \"vinext/shims/request-context\";\nimport type { CachedRouteValue } from \"vinext/shims/cache\";\nimport type { NextRequest } from \"vinext/shims/server\";\nimport {\n createStaticGenerationHeadersContext,\n getAppRouteStaticGenerationErrorMessage,\n} from \"./app-static-generation.js\";\nimport {\n isPossibleAppRouteActionRequest,\n resolveAppRouteHandlerSpecialError,\n shouldApplyAppRouteHandlerRevalidateHeader,\n shouldWriteAppRouteHandlerCache,\n type AppRouteHandlerModule,\n} from \"./app-route-handler-policy.js\";\nimport {\n applyRouteHandlerMiddlewareContext,\n applyRouteHandlerRevalidateHeader,\n assertSupportedAppRouteHandlerResponse,\n buildAppRouteCacheValue,\n finalizeRouteHandlerResponse,\n markRouteHandlerCacheMiss,\n type RouteHandlerMiddlewareContext,\n} from \"./app-route-handler-response.js\";\nimport {\n createTrackedAppRouteRequest,\n markKnownDynamicAppRoute,\n} from \"./app-route-handler-runtime.js\";\n\nexport type AppRouteParams = Record<string, string | string[]>;\nexport type AppRouteDynamicUsageFn = () => boolean;\nexport type MarkAppRouteDynamicUsageFn = () => void;\n/**\n * Route handler context.\n *\n * `params` is `null` for non-dynamic routes (no `[param]` segments) so that\n * user code like `params ? await params : null` resolves to `null`, matching\n * Next.js behavior. For dynamic routes it's a thenable that resolves to the\n * matched params object.\n *\n * See: test/e2e/app-dir/app-routes/app-custom-routes.test.ts in Next.js for\n * the authoritative assertion (`expect(meta.params).toEqual(null)`).\n */\nexport type AppRouteHandlerFunction = (\n request: NextRequest,\n context: { params: AppRouteParams | null },\n) => Response | Promise<Response>;\nexport type RouteHandlerCacheSetter = (\n key: string,\n data: CachedRouteValue,\n revalidateSeconds: number,\n tags: string[],\n expireSeconds?: number,\n) => Promise<void>;\ntype AppRouteErrorReporter = (\n error: Error,\n request: { path: string; method: string; headers: Record<string, string> },\n route: { routerKind: \"App Router\"; routePath: string; routeType: \"route\" },\n) => void;\nexport type AppRouteDebugLogger = (event: string, detail: string) => void;\n\ntype RunAppRouteHandlerOptions = {\n basePath?: string;\n consumeDynamicUsage: AppRouteDynamicUsageFn;\n draftModeSecret?: string;\n dynamicConfig?: string;\n handlerFn: AppRouteHandlerFunction;\n i18n?: NextI18nConfig | null;\n markDynamicUsage: MarkAppRouteDynamicUsageFn;\n middlewareRequestHeaders?: Headers | null;\n /**\n * `null` for non-dynamic routes. Passed through to the handler context\n * unchanged — callers are expected to compute this from `route.isDynamic`.\n */\n params: AppRouteParams | null;\n request: Request;\n routePattern?: string;\n setHeadersAccessPhase?: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n};\n\ntype RunAppRouteHandlerResult = {\n dynamicUsedInHandler: boolean;\n response: Response;\n};\n\ntype ExecuteAppRouteHandlerOptions = {\n buildPageCacheTags: (pathname: string, extraTags: string[]) => string[];\n clearRequestContext: () => void;\n cleanPathname: string;\n executionContext: ExecutionContextLike | null;\n getAndClearPendingCookies: () => string[];\n getCollectedFetchTags: () => string[];\n getDraftModeCookieHeader: () => string | null | undefined;\n handler: AppRouteHandlerModule;\n isAutoHead: boolean;\n isProduction: boolean;\n isrDebug?: AppRouteDebugLogger;\n isrRouteKey: (pathname: string) => string;\n isrSet: RouteHandlerCacheSetter;\n method: string;\n middlewareContext: RouteHandlerMiddlewareContext;\n reportRequestError: AppRouteErrorReporter;\n expireSeconds?: number;\n revalidateSeconds: number | null;\n routePattern: string;\n setHeadersAccessPhase: (phase: HeadersAccessPhase) => HeadersAccessPhase;\n} & RunAppRouteHandlerOptions;\n\nfunction configureAppRouteStaticGenerationContext(options: RunAppRouteHandlerOptions): void {\n if (options.dynamicConfig === \"force-static\" || options.dynamicConfig === \"error\") {\n setHeadersContext(\n createStaticGenerationHeadersContext({\n draftModeSecret: options.draftModeSecret,\n dynamicConfig: options.dynamicConfig,\n routeKind: \"route\",\n routePattern: options.routePattern,\n }),\n );\n options.setHeadersAccessPhase?.(\"route-handler\");\n }\n}\n\nexport async function runAppRouteHandler(\n options: RunAppRouteHandlerOptions,\n): Promise<RunAppRouteHandlerResult> {\n options.consumeDynamicUsage();\n configureAppRouteStaticGenerationContext(options);\n const trackedRequest = createTrackedAppRouteRequest(options.request, {\n basePath: options.basePath,\n i18n: options.i18n,\n middlewareHeaders: options.middlewareRequestHeaders,\n onDynamicAccess() {\n options.markDynamicUsage();\n },\n requestMode:\n options.dynamicConfig === \"force-static\" || options.dynamicConfig === \"error\"\n ? options.dynamicConfig\n : \"auto\",\n staticGenerationErrorMessage(expression) {\n return getAppRouteStaticGenerationErrorMessage(options.routePattern, expression);\n },\n });\n const response = await options.handlerFn(trackedRequest.request, {\n params: options.params,\n });\n\n return {\n dynamicUsedInHandler: options.consumeDynamicUsage(),\n response,\n };\n}\n\nexport async function executeAppRouteHandler(\n options: ExecuteAppRouteHandlerOptions,\n): Promise<Response> {\n const previousHeadersPhase = options.setHeadersAccessPhase(\"route-handler\");\n\n try {\n const { dynamicUsedInHandler, response } = await runAppRouteHandler({\n ...options,\n dynamicConfig: options.handler.dynamic,\n });\n assertSupportedAppRouteHandlerResponse(response);\n const handlerSetCacheControl = response.headers.has(\"cache-control\");\n\n if (dynamicUsedInHandler) {\n markKnownDynamicAppRoute(options.routePattern);\n }\n\n if (\n shouldApplyAppRouteHandlerRevalidateHeader({\n dynamicUsedInHandler,\n handlerSetCacheControl,\n isAutoHead: options.isAutoHead,\n method: options.method,\n revalidateSeconds: options.revalidateSeconds,\n })\n ) {\n const revalidateSeconds = options.revalidateSeconds;\n if (revalidateSeconds == null) {\n throw new Error(\"Expected route handler revalidate seconds\");\n }\n applyRouteHandlerRevalidateHeader(response, revalidateSeconds, options.expireSeconds);\n }\n\n if (\n shouldWriteAppRouteHandlerCache({\n dynamicConfig: options.handler.dynamic,\n dynamicUsedInHandler,\n handlerSetCacheControl,\n isAutoHead: options.isAutoHead,\n isProduction: options.isProduction,\n method: options.method,\n revalidateSeconds: options.revalidateSeconds,\n })\n ) {\n markRouteHandlerCacheMiss(response);\n const routeClone = response.clone();\n const routeKey = options.isrRouteKey(options.cleanPathname);\n const revalidateSeconds = options.revalidateSeconds;\n if (revalidateSeconds == null) {\n throw new Error(\"Expected route handler cache revalidate seconds\");\n }\n const routeTags = options.buildPageCacheTags(\n options.cleanPathname,\n options.getCollectedFetchTags(),\n );\n const routeWritePromise = (async () => {\n try {\n const routeCacheValue = await buildAppRouteCacheValue(routeClone);\n await options.isrSet(\n routeKey,\n routeCacheValue,\n revalidateSeconds,\n routeTags,\n options.expireSeconds,\n );\n options.isrDebug?.(\"route cache written\", routeKey);\n } catch (cacheErr) {\n console.error(\"[vinext] ISR route cache write error:\", cacheErr);\n }\n })();\n options.executionContext?.waitUntil(routeWritePromise);\n }\n\n const pendingCookies = options.getAndClearPendingCookies();\n const draftCookie = options.getDraftModeCookieHeader();\n options.clearRequestContext();\n\n return applyRouteHandlerMiddlewareContext(\n finalizeRouteHandlerResponse(response, {\n pendingCookies,\n draftCookie,\n isHead: options.isAutoHead,\n }),\n options.middlewareContext,\n );\n } catch (error) {\n const pendingCookies = options.getAndClearPendingCookies();\n const draftCookie = options.getDraftModeCookieHeader();\n const specialError = resolveAppRouteHandlerSpecialError(error, options.request.url, {\n isAction: isPossibleAppRouteActionRequest(options.request),\n });\n options.clearRequestContext();\n\n if (specialError) {\n if (specialError.kind === \"redirect\") {\n return applyRouteHandlerMiddlewareContext(\n finalizeRouteHandlerResponse(\n new Response(null, {\n status: specialError.statusCode,\n headers: { Location: specialError.location },\n }),\n {\n pendingCookies,\n draftCookie,\n isHead: options.isAutoHead,\n },\n ),\n options.middlewareContext,\n );\n }\n\n return applyRouteHandlerMiddlewareContext(\n new Response(null, { status: specialError.statusCode }),\n options.middlewareContext,\n );\n }\n\n console.error(\"[vinext] Route handler error:\", error);\n options.reportRequestError(\n error instanceof Error ? error : new Error(String(error)),\n {\n path: options.cleanPathname,\n method: options.request.method,\n headers: Object.fromEntries(options.request.headers.entries()),\n },\n {\n routerKind: \"App Router\",\n routePath: options.routePattern,\n routeType: \"route\",\n },\n );\n\n return applyRouteHandlerMiddlewareContext(\n new Response(null, { status: 500 }),\n options.middlewareContext,\n );\n } finally {\n options.setHeadersAccessPhase(previousHeadersPhase);\n }\n}\n"],"mappings":";;;;;;AA6GA,SAAS,yCAAyC,SAA0C;CAC1F,IAAI,QAAQ,kBAAkB,kBAAkB,QAAQ,kBAAkB,SAAS;EACjF,kBACE,qCAAqC;GACnC,iBAAiB,QAAQ;GACzB,eAAe,QAAQ;GACvB,WAAW;GACX,cAAc,QAAQ;GACvB,CAAC,CACH;EACD,QAAQ,wBAAwB,gBAAgB;;;AAIpD,eAAsB,mBACpB,SACmC;CACnC,QAAQ,qBAAqB;CAC7B,yCAAyC,QAAQ;CACjD,MAAM,iBAAiB,6BAA6B,QAAQ,SAAS;EACnE,UAAU,QAAQ;EAClB,MAAM,QAAQ;EACd,mBAAmB,QAAQ;EAC3B,kBAAkB;GAChB,QAAQ,kBAAkB;;EAE5B,aACE,QAAQ,kBAAkB,kBAAkB,QAAQ,kBAAkB,UAClE,QAAQ,gBACR;EACN,6BAA6B,YAAY;GACvC,OAAO,wCAAwC,QAAQ,cAAc,WAAW;;EAEnF,CAAC;CACF,MAAM,WAAW,MAAM,QAAQ,UAAU,eAAe,SAAS,EAC/D,QAAQ,QAAQ,QACjB,CAAC;CAEF,OAAO;EACL,sBAAsB,QAAQ,qBAAqB;EACnD;EACD;;AAGH,eAAsB,uBACpB,SACmB;CACnB,MAAM,uBAAuB,QAAQ,sBAAsB,gBAAgB;CAE3E,IAAI;EACF,MAAM,EAAE,sBAAsB,aAAa,MAAM,mBAAmB;GAClE,GAAG;GACH,eAAe,QAAQ,QAAQ;GAChC,CAAC;EACF,uCAAuC,SAAS;EAChD,M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AQ,0BAA0B;EACtD,MAAM,eAAe,mCAAmC,OAAO,QAAQ,QAAQ,KAAK,EAClF,UAAU,gCAAgC,QAAQ,QAAQ,EAC3D,CAAC;EACF,QAAQ,qBAAqB;EAE7B,IAAI,cAAc;GAChB,IAAI,aAAa,SAAS,YACxB,OAAO,mCACL,6BACE,IAAI,SAAS,MAAM;IACjB,QAAQ,aAAa;IACrB,SAAS,EAAE,UAAU,aAAa,UAAU;IAC7C,CAAC,EACF;IACE;IACA;IACA,QAAQ,QAAQ;IACjB,CACF,EACD,QAAQ,kBACT;GAGH,OAAO,mCACL,IAAI,SAAS,MAAM,EAAE,QAAQ,aAAa,YAAY,CAAC,EACvD,QAAQ,kBACT;;EAGH,QAAQ,MAAM,iCAAiC,MAAM;EACrD,QAAQ,mBACN,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC,EACzD;GACE,MAAM,QAAQ;GACd,QAAQ,QAAQ,QAAQ;GACxB,SAAS,OAAO,YAAY,QAAQ,QAAQ,QAAQ,SAAS,CAAC;GAC/D,EACD;GACE,YAAY;GACZ,WAAW,QAAQ;GACnB,WAAW;GACZ,CACF;EAED,OAAO,mCACL,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC,EACnC,QAAQ,kBACT;WACO;EACR,QAAQ,sBAAsB,qBAAqB"}
@@ -1,8 +1,8 @@
1
1
  import "./headers.js";
2
2
  import { processMiddlewareHeaders } from "./request-pipeline.js";
3
3
  import { setCacheStateHeaders } from "./cache-headers.js";
4
- import { mergeMiddlewareResponseHeaders } from "./middleware-response-headers.js";
5
4
  import { NEVER_CACHE_CONTROL, STATIC_CACHE_CONTROL, buildCachedRevalidateCacheControl } from "./cache-control.js";
5
+ import { mergeMiddlewareResponseHeaders } from "./middleware-response-headers.js";
6
6
  //#region src/server/app-route-handler-response.ts
7
7
  const APP_ROUTE_REWRITE_ERROR = "NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue.";
8
8
  const APP_ROUTE_NEXT_ERROR = "NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler";
@@ -38,6 +38,7 @@ type DispatchMatchedPageOptions<TRoute> = {
38
38
  middlewareContext: AppRscMiddlewareContext;
39
39
  mountedSlotsHeader: string | null;
40
40
  params: AppPageParams;
41
+ staticParamsValidationParams?: AppPageParams;
41
42
  rootParams?: RootParams;
42
43
  request: Request;
43
44
  route: TRoute;
@@ -115,6 +116,7 @@ type CreateAppRscHandlerOptions<TRoute extends AppRscHandlerRoute> = {
115
116
  beforeFiles: NextRewrite[];
116
117
  fallback: NextRewrite[];
117
118
  };
119
+ draftModeSecret: string;
118
120
  dispatchMatchedPage: (options: DispatchMatchedPageOptions<TRoute>) => Promise<Response>;
119
121
  dispatchMatchedRouteHandler: (options: DispatchMatchedRouteHandlerOptions<TRoute>) => Promise<Response>;
120
122
  ensureInstrumentation?: () => Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { createRequestContext, runWithRequestContext } from "../shims/unified-request-context.js";
2
2
  import { hasBasePath } from "../utils/base-path.js";
3
3
  import { getRequestExecutionContext } from "../shims/request-context.js";
4
- import { VINEXT_MW_CTX_HEADER } from "./headers.js";
4
+ import { VINEXT_MW_CTX_HEADER, VINEXT_PRERENDER_ROUTE_PARAMS_HEADER } from "./headers.js";
5
5
  import { isExternalUrl, matchRedirect, matchRewrite, proxyExternalRequest, requestContextFromRequest, sanitizeDestination } from "../config/config-matchers.js";
6
6
  import { notFoundResponse } from "./http-error-responses.js";
7
7
  import { applyConfigHeadersToResponse, cloneRequestWithHeaders, filterInternalHeaders, normalizeTrailingSlash, resolvePublicFileRoute, validateImageUrl } from "./request-pipeline.js";
@@ -10,12 +10,14 @@ import { ensureFetchPatch, setCurrentFetchSoftTags } from "../shims/fetch-cache.
10
10
  import { createRscRedirectLocation, resolveInvalidRscCacheBustingRequest, stripRscCacheBustingSearchParam, stripRscSuffix } from "./app-rsc-cache-busting.js";
11
11
  import { getScriptNonceFromHeaderSources } from "./csp.js";
12
12
  import { normalizeDefaultLocalePathname } from "./pages-i18n.js";
13
+ import { isImageOptimizationPath } from "./image-optimization.js";
14
+ import { prerenderRouteParamsPayloadMatchesRoute, readTrustedPrerenderRouteParams, serializePrerenderRouteParamsHeader } from "./prerender-route-params.js";
15
+ import { pickRootParams, setRootParams } from "../shims/root-params.js";
13
16
  import { mergeMiddlewareResponseHeaders } from "./middleware-response-headers.js";
14
- import { applyAppMiddleware } from "./app-middleware.js";
15
17
  import "./app-page-response.js";
18
+ import { applyAppMiddleware } from "./app-middleware.js";
16
19
  import { buildPageCacheTags } from "./implicit-tags.js";
17
20
  import { buildPostMwRequestContext } from "./app-post-middleware-context.js";
18
- import { pickRootParams, setRootParams } from "../shims/root-params.js";
19
21
  import { handleAppPrerenderEndpoint } from "./app-prerender-endpoints.js";
20
22
  import { flattenErrorCauses } from "../utils/error-cause.js";
21
23
  import { finalizeAppRscResponse } from "./app-rsc-response-finalizer.js";
@@ -143,7 +145,7 @@ async function handleAppRscRequest(options, request, preMiddlewareRequestContext
143
145
  }, matchPathname(cleanPathname));
144
146
  if (beforeFilesRewrite instanceof Response) return beforeFilesRewrite;
145
147
  if (beforeFilesRewrite) cleanPathname = beforeFilesRewrite;
146
- if (cleanPathname === "/_vinext/image") {
148
+ if (isImageOptimizationPath(cleanPathname)) {
147
149
  const imageUrlResult = validateImageUrl(url.searchParams.get("url"), request.url);
148
150
  if (imageUrlResult instanceof Response) return imageUrlResult;
149
151
  return Response.redirect(new URL(imageUrlResult, url.origin).href, 302);
@@ -252,19 +254,22 @@ async function handleAppRscRequest(options, request, preMiddlewareRequestContext
252
254
  return notFoundResponse({ headers });
253
255
  }
254
256
  const { route, params } = match;
257
+ const prerenderRouteParamsPayload = readTrustedPrerenderRouteParams(request);
258
+ const prerenderRouteParams = prerenderRouteParamsPayloadMatchesRoute(prerenderRouteParamsPayload, route.pattern, params) ? prerenderRouteParamsPayload.params : null;
259
+ const renderParams = prerenderRouteParams ?? params;
255
260
  options.setNavigationContext({
256
261
  pathname: canonicalPathname,
257
262
  searchParams: url.searchParams,
258
- params
263
+ params: renderParams
259
264
  });
260
- const rootParams = pickRootParams(params, route.rootParamNames);
265
+ const rootParams = pickRootParams(renderParams, route.rootParamNames);
261
266
  setRootParams(rootParams);
262
267
  if (route.routeHandler) {
263
268
  setCurrentFetchSoftTags(buildPageCacheTags(cleanPathname, [], [...route.routeSegments], "route"));
264
269
  return options.dispatchMatchedRouteHandler({
265
270
  cleanPathname,
266
271
  middlewareContext,
267
- params: route.isDynamic ? params : null,
272
+ params: route.isDynamic ? renderParams : null,
268
273
  request,
269
274
  route,
270
275
  searchParams: url.searchParams
@@ -281,7 +286,8 @@ async function handleAppRscRequest(options, request, preMiddlewareRequestContext
281
286
  isRscRequest,
282
287
  middlewareContext,
283
288
  mountedSlotsHeader,
284
- params,
289
+ params: renderParams,
290
+ staticParamsValidationParams: prerenderRouteParams === null ? void 0 : params,
285
291
  rootParams,
286
292
  request,
287
293
  route,
@@ -295,12 +301,15 @@ function createAppRscHandler(options) {
295
301
  await options.ensureInstrumentation?.();
296
302
  const mwCtx = rawRequest.headers.get(VINEXT_MW_CTX_HEADER);
297
303
  const isDataRequest = rawRequest.headers.get("x-nextjs-data") === "1";
304
+ const prerenderRouteParamsPayload = readTrustedPrerenderRouteParams(rawRequest);
298
305
  const filteredHeaders = filterInternalHeaders(rawRequest.headers);
299
306
  if (mwCtx !== null) filteredHeaders.set(VINEXT_MW_CTX_HEADER, mwCtx);
307
+ const prerenderRouteParamsHeader = serializePrerenderRouteParamsHeader(prerenderRouteParamsPayload);
308
+ if (prerenderRouteParamsHeader !== null) filteredHeaders.set(VINEXT_PRERENDER_ROUTE_PARAMS_HEADER, prerenderRouteParamsHeader);
300
309
  const request = cloneRequestWithHeaders(rawRequest, filteredHeaders);
301
310
  const executionContext = isExecutionContextLike(ctx) ? ctx : getRequestExecutionContext() ?? null;
302
311
  return runWithRequestContext(createRequestContext({
303
- headersContext: headersContextFromRequest(request),
312
+ headersContext: headersContextFromRequest(request, { draftModeSecret: options.draftModeSecret }),
304
313
  executionContext,
305
314
  unstableCacheRevalidation: "background"
306
315
  }), () => runWithPrerenderWorkUnit(async () => {
@@ -1 +1 @@
1
- {"version":3,"file":"app-rsc-handler.js","names":[],"sources":["../../src/server/app-rsc-handler.ts"],"sourcesContent":["import type {\n NextHeader,\n NextI18nConfig,\n NextRedirect,\n NextRewrite,\n} from \"../config/next-config.js\";\nimport {\n isExternalUrl,\n matchRedirect,\n matchRewrite,\n proxyExternalRequest,\n requestContextFromRequest,\n sanitizeDestination,\n type BasePathMatchState,\n} from \"../config/config-matchers.js\";\nimport { headersContextFromRequest } from \"vinext/shims/headers\";\nimport {\n NEXT_ACTION_HEADER,\n RSC_ACTION_HEADER,\n RSC_HEADER,\n VINEXT_MW_CTX_HEADER,\n} from \"./headers.js\";\nimport { ensureFetchPatch, setCurrentFetchSoftTags } from \"vinext/shims/fetch-cache\";\nimport type { ReactFormState } from \"react-dom/client\";\nimport {\n getRequestExecutionContext,\n type ExecutionContextLike,\n} from \"vinext/shims/request-context\";\nimport { pickRootParams, setRootParams, type RootParams } from \"vinext/shims/root-params\";\nimport { createRequestContext, runWithRequestContext } from \"vinext/shims/unified-request-context\";\nimport { flattenErrorCauses } from \"../utils/error-cause.js\";\nimport { hasBasePath } from \"../utils/base-path.js\";\nimport { applyAppMiddleware, type AppMiddlewareContext } from \"./app-middleware.js\";\nimport { mergeMiddlewareResponseHeaders } from \"./app-page-response.js\";\nimport { handleAppPrerenderEndpoint } from \"./app-prerender-endpoints.js\";\nimport {\n createRscRedirectLocation,\n resolveInvalidRscCacheBustingRequest,\n stripRscCacheBustingSearchParam,\n stripRscSuffix,\n} from \"./app-rsc-cache-busting.js\";\nimport { finalizeAppRscResponse } from \"./app-rsc-response-finalizer.js\";\nimport { normalizeRscRequest } from \"./app-rsc-request-normalization.js\";\nimport { normalizeDefaultLocalePathname } from \"./pages-i18n.js\";\nimport { notFoundResponse } from \"./http-error-responses.js\";\nimport { getScriptNonceFromHeaderSources } from \"./csp.js\";\nimport { buildPageCacheTags } from \"./implicit-tags.js\";\nimport { handleMetadataRouteRequest } from \"./metadata-route-response.js\";\nimport type { MiddlewareModule } from \"./middleware-runtime.js\";\nimport { runWithPrerenderWorkUnit } from \"./prerender-work-unit-setup.js\";\nimport { buildPostMwRequestContext } from \"./app-post-middleware-context.js\";\nimport type { AppRscRenderMode } from \"./app-rsc-render-mode.js\";\nimport {\n cloneRequestWithHeaders,\n filterInternalHeaders,\n applyConfigHeadersToResponse,\n normalizeTrailingSlash,\n resolvePublicFileRoute,\n validateImageUrl,\n} from \"./request-pipeline.js\";\n\ntype AppPageParams = Record<string, string | string[]>;\ntype RequestContext = ReturnType<typeof requestContextFromRequest>;\ntype MetadataRoutes = Parameters<typeof handleMetadataRouteRequest>[0][\"metadataRoutes\"];\ntype MakeThenableParams = Parameters<typeof handleMetadataRouteRequest>[0][\"makeThenableParams\"];\ntype StaticParamsMap = Parameters<typeof handleAppPrerenderEndpoint>[1][\"staticParamsMap\"];\ntype RootParamNamesMap = Parameters<\n typeof handleAppPrerenderEndpoint\n>[1][\"rootParamNamesByPattern\"];\n\ntype AppRscMiddlewareContext = AppMiddlewareContext;\n\ntype AppRscHandlerRoute = {\n isDynamic: boolean;\n page?: unknown;\n pattern: string;\n rootParamNames?: readonly string[];\n routeHandler?: unknown;\n routeSegments: readonly string[];\n};\n\ntype AppRscRouteMatch<TRoute> = {\n params: AppPageParams;\n route: TRoute;\n};\n\ntype DispatchMatchedPageOptions<TRoute> = {\n cleanPathname: string;\n formState: ReactFormState | null;\n actionError?: unknown;\n actionFailed?: boolean;\n handlerStart: number;\n interceptionContext: string | null;\n isProgressiveActionRender: boolean;\n isRscRequest: boolean;\n middlewareContext: AppRscMiddlewareContext;\n mountedSlotsHeader: string | null;\n params: AppPageParams;\n rootParams?: RootParams;\n request: Request;\n route: TRoute;\n scriptNonce?: string;\n searchParams: URLSearchParams;\n renderMode: AppRscRenderMode;\n};\n\ntype DispatchMatchedRouteHandlerOptions<TRoute> = {\n cleanPathname: string;\n middlewareContext: AppRscMiddlewareContext;\n /**\n * `null` for non-dynamic routes. Mirrors Next.js' route handler context\n * shape: user code that does `params ? await params : null` resolves to\n * `null` for routes without dynamic segments. Dynamic routes receive the\n * matched params object.\n */\n params: AppPageParams | null;\n request: Request;\n route: TRoute;\n searchParams: URLSearchParams;\n};\n\ntype HandleProgressiveActionRequestOptions = {\n actionId: string | null;\n cleanPathname: string;\n contentType: string;\n middlewareContext: AppRscMiddlewareContext;\n request: Request;\n};\n\ntype ProgressiveActionFormStateResult =\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 HandleServerActionRequestOptions = {\n actionId: string | null;\n cleanPathname: string;\n contentType: string;\n interceptionContext: string | null;\n isRscRequest: boolean;\n middlewareContext: AppRscMiddlewareContext;\n mountedSlotsHeader: string | null;\n request: Request;\n searchParams: URLSearchParams;\n};\n\ntype RenderNotFoundOptions<TRoute> = {\n isRscRequest: boolean;\n matchedParams?: AppPageParams;\n middlewareContext: AppRscMiddlewareContext;\n request: Request;\n route: TRoute | null;\n scriptNonce?: string;\n};\n\ntype RenderPagesFallbackOptions = {\n isRscRequest: boolean;\n middlewareContext: AppRscMiddlewareContext;\n request: Request;\n url: URL;\n};\n\ntype NavigationContextValue = {\n params: AppPageParams;\n pathname: string;\n searchParams: URLSearchParams;\n};\n\ntype CreateAppRscHandlerOptions<TRoute extends AppRscHandlerRoute> = {\n basePath: string;\n clearRequestContext: () => void;\n configHeaders: NextHeader[];\n configRedirects: NextRedirect[];\n configRewrites: {\n afterFiles: NextRewrite[];\n beforeFiles: NextRewrite[];\n fallback: NextRewrite[];\n };\n dispatchMatchedPage: (options: DispatchMatchedPageOptions<TRoute>) => Promise<Response>;\n dispatchMatchedRouteHandler: (\n options: DispatchMatchedRouteHandlerOptions<TRoute>,\n ) => Promise<Response>;\n ensureInstrumentation?: () => Promise<void>;\n handleProgressiveActionRequest: (\n options: HandleProgressiveActionRequestOptions,\n ) => Promise<Response | ProgressiveActionFormStateResult | null>;\n handleServerActionRequest: (\n options: HandleServerActionRequestOptions,\n ) => Promise<Response | null>;\n i18nConfig: NextI18nConfig | null;\n isMiddlewareProxy: boolean;\n loadPrerenderPagesRoutes?: () => Promise<unknown>;\n makeThenableParams: MakeThenableParams;\n matchRoute: (pathname: string) => AppRscRouteMatch<TRoute> | null;\n metadataRoutes: MetadataRoutes;\n middlewareModule: MiddlewareModule | null;\n publicFiles: ReadonlySet<string>;\n renderNotFound: (options: RenderNotFoundOptions<TRoute>) => Promise<Response | null>;\n renderPagesFallback?: (options: RenderPagesFallbackOptions) => Promise<Response | null>;\n rootParamNamesByPattern?: RootParamNamesMap;\n setNavigationContext: (context: NavigationContextValue) => void;\n staticParamsMap: StaticParamsMap;\n trailingSlash: boolean;\n validateDevRequestOrigin?: (request: Request) => Response | null;\n};\n\nfunction hasProperty<TKey extends PropertyKey>(\n value: object,\n key: TKey,\n): value is object & Record<TKey, unknown> {\n return key in value;\n}\n\nfunction isExecutionContextLike(value: unknown): value is ExecutionContextLike {\n if (!value || typeof value !== \"object\") return false;\n return hasProperty(value, \"waitUntil\") && typeof value.waitUntil === \"function\";\n}\n\n// TODO(#1333): once App Router supports `basePath: false` rules (see\n// `normalizeRscRequest` — it 404s out-of-basePath requests before they\n// reach this code), pass `hadBasePath` here and skip the prefix when\n// false, mirroring the same guard in `prod-server.ts` and `deploy.ts`.\nfunction redirectDestinationWithBasePath(destination: string, basePath: string): string {\n if (!basePath || isExternalUrl(destination) || hasBasePath(destination, basePath)) {\n return destination;\n }\n return basePath + destination;\n}\n\nasync function applyRewrite(\n options: {\n basePathState: BasePathMatchState;\n clearRequestContext: () => void;\n request: Request;\n requestContext: RequestContext;\n rewrites: NextRewrite[];\n },\n cleanPathname: string,\n): Promise<Response | string | null> {\n if (!options.rewrites.length) return null;\n\n const rewritten = matchRewrite(\n cleanPathname,\n options.rewrites,\n options.requestContext,\n options.basePathState,\n );\n if (!rewritten) return null;\n\n if (isExternalUrl(rewritten)) {\n options.clearRequestContext();\n return proxyExternalRequest(options.request, rewritten);\n }\n\n return rewritten;\n}\n\nfunction applyConfigHeadersToMiddlewareRedirect(\n response: Response,\n options: {\n basePathState: BasePathMatchState;\n configHeaders: NextHeader[];\n pathname: string;\n requestContext: RequestContext;\n },\n): Response {\n // Non-redirect middleware responses still pass through finalization, where\n // config headers are applied once. Redirects skip finalization to avoid\n // mutating immutable redirect headers, so they need the earlier header layer here.\n if (response.status < 300 || response.status >= 400) return response;\n if (!options.configHeaders.length) return response;\n\n const headers = new Headers();\n applyConfigHeadersToResponse(headers, {\n configHeaders: options.configHeaders,\n pathname: options.pathname,\n requestContext: options.requestContext,\n basePathState: options.basePathState,\n });\n\n if (!headers.entries().next().done) {\n mergeMiddlewareResponseHeaders(headers, response.headers);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n return response;\n}\n\nasync function handleAppRscRequest<TRoute extends AppRscHandlerRoute>(\n options: CreateAppRscHandlerOptions<TRoute>,\n request: Request,\n preMiddlewareRequestContext: RequestContext,\n isDataRequest: boolean,\n): Promise<Response> {\n const handlerStart = process.env.NODE_ENV !== \"production\" ? performance.now() : 0;\n\n if (process.env.NODE_ENV !== \"production\") {\n const originBlock = options.validateDevRequestOrigin?.(request);\n if (originBlock) return originBlock;\n }\n\n const normalized = normalizeRscRequest(request, options.basePath);\n if (normalized instanceof Response) return normalized;\n\n const { url, isRscRequest, interceptionContextHeader, mountedSlotsHeader, renderMode } =\n normalized;\n let { pathname, cleanPathname } = normalized;\n // Canonical (external) pathname the user requested. Middleware rewrites and\n // next.config.js rewrites mutate `cleanPathname` so internal route matching\n // can find the destination page, but hooks like `usePathname()` must reflect\n // the original URL the user sees in the address bar.\n // Matches Next.js: test/e2e/app-dir/hooks/hooks.test.ts —\n // \"should have the canonical url pathname on rewrite\"\n const canonicalPathname = cleanPathname;\n\n // The request reached this point so it was either under basePath (stripped\n // by normalizeRscRequest) or basePath is empty. In both cases the matcher\n // gating below treats default (basePath: true) rules as eligible. The App\n // Router does not yet support `basePath: false` rules — they would need a\n // pre-strip hook in normalizeRscRequest to fire. Tracked as follow-up to\n // issue #1333.\n const basePathState = { basePath: options.basePath, hadBasePath: true };\n\n const prerenderEndpointResponse = await handleAppPrerenderEndpoint(request, {\n isPrerenderEnabled() {\n return process.env.VINEXT_PRERENDER === \"1\";\n },\n loadPagesRoutes: options.loadPrerenderPagesRoutes,\n pathname,\n rootParamNamesByPattern: options.rootParamNamesByPattern,\n staticParamsMap: options.staticParamsMap,\n });\n if (prerenderEndpointResponse) return prerenderEndpointResponse;\n\n const trailingSlashRedirect = normalizeTrailingSlash(\n pathname,\n options.basePath,\n options.trailingSlash,\n url.search,\n );\n if (trailingSlashRedirect) return trailingSlashRedirect;\n\n // Default-locale path normalisation (issue #1336, item 4). Next.js\n // splices in the (domain-aware) default locale on every request that\n // arrives without a locale prefix before running config redirect / rewrite\n // / header matching. Mirrors resolve-routes.ts lines ~250-263.\n //\n // Defined once here so the same helper is reused for the redirect match\n // below, the middleware-redirect config header match further down, and the\n // post-middleware rewrite matches. `i18nConfig` and `url.hostname` are\n // request-scoped constants from this point on.\n const matchPathname = (p: string): string =>\n normalizeDefaultLocalePathname(p, options.i18nConfig, { hostname: url.hostname });\n\n const redirectPathname = matchPathname(stripRscSuffix(pathname));\n const redirect = matchRedirect(\n redirectPathname,\n options.configRedirects,\n preMiddlewareRequestContext,\n basePathState,\n );\n if (redirect) {\n const destination = sanitizeDestination(\n redirectDestinationWithBasePath(redirect.destination, options.basePath),\n );\n const location =\n isRscRequest && request.headers.get(RSC_HEADER) === \"1\"\n ? await createRscRedirectLocation(destination, request)\n : destination;\n return new Response(null, {\n status: redirect.permanent ? 308 : 307,\n headers: { Location: location },\n });\n }\n\n const rscCacheBustingRedirect = await resolveInvalidRscCacheBustingRequest({\n isRscRequest,\n request,\n });\n if (rscCacheBustingRedirect) return rscCacheBustingRedirect;\n\n const middlewareContext: AppRscMiddlewareContext = {\n headers: null,\n requestHeaders: null,\n status: null,\n };\n\n if (options.middlewareModule) {\n const middlewareResult = await applyAppMiddleware({\n basePath: options.basePath,\n cleanPathname,\n context: middlewareContext,\n i18nConfig: options.i18nConfig,\n isDataRequest,\n isProxy: options.isMiddlewareProxy,\n module: options.middlewareModule,\n request,\n trailingSlash: options.trailingSlash,\n });\n if (middlewareResult.kind === \"response\") {\n return applyConfigHeadersToMiddlewareRedirect(middlewareResult.response, {\n basePathState,\n configHeaders: options.configHeaders,\n pathname: matchPathname(cleanPathname),\n requestContext: preMiddlewareRequestContext,\n });\n }\n\n cleanPathname = middlewareResult.cleanPathname;\n if (middlewareResult.search !== null) {\n url.search = middlewareResult.search;\n }\n }\n\n const scriptNonce = getScriptNonceFromHeaderSources(request.headers, middlewareContext.headers);\n const postMiddlewareRequestContext = buildPostMwRequestContext(request);\n\n // Rewrites (beforeFiles, afterFiles, fallback) use `matchPathname` from\n // above to splice in the default locale before matching. Route matching\n // itself continues to use the un-prefixed `cleanPathname` because App\n // Router files live under `app/...` with no locale segment. See issue\n // #1336 item 4 / pages-i18n.normalizeDefaultLocalePathname.\n const beforeFilesRewrite = await applyRewrite(\n {\n basePathState,\n clearRequestContext: options.clearRequestContext,\n request,\n requestContext: postMiddlewareRequestContext,\n rewrites: options.configRewrites.beforeFiles,\n },\n matchPathname(cleanPathname),\n );\n if (beforeFilesRewrite instanceof Response) return beforeFilesRewrite;\n if (beforeFilesRewrite) cleanPathname = beforeFilesRewrite;\n\n if (cleanPathname === \"/_vinext/image\") {\n const imageUrlResult = validateImageUrl(url.searchParams.get(\"url\"), request.url);\n if (imageUrlResult instanceof Response) return imageUrlResult;\n return Response.redirect(new URL(imageUrlResult, url.origin).href, 302);\n }\n\n const metadataRouteResponse = await handleMetadataRouteRequest({\n metadataRoutes: options.metadataRoutes,\n cleanPathname,\n makeThenableParams: options.makeThenableParams,\n });\n if (metadataRouteResponse) return metadataRouteResponse;\n\n const publicFileResponse = resolvePublicFileRoute({\n cleanPathname,\n middlewareContext,\n pathname,\n publicFiles: options.publicFiles,\n request,\n });\n if (publicFileResponse) {\n options.clearRequestContext();\n return publicFileResponse;\n }\n\n if (isRscRequest) {\n stripRscCacheBustingSearchParam(url);\n }\n\n options.setNavigationContext({\n pathname: canonicalPathname,\n searchParams: url.searchParams,\n params: {},\n });\n\n const actionId =\n request.headers.get(RSC_ACTION_HEADER) ?? request.headers.get(NEXT_ACTION_HEADER);\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n const progressiveActionResult = await options.handleProgressiveActionRequest({\n actionId,\n cleanPathname,\n contentType,\n middlewareContext,\n request,\n });\n if (progressiveActionResult instanceof Response) return progressiveActionResult;\n const isProgressiveActionRender = progressiveActionResult?.kind === \"form-state\";\n const formState = isProgressiveActionRender ? progressiveActionResult.formState : null;\n const failedProgressiveActionResult =\n isProgressiveActionRender && \"actionFailed\" in progressiveActionResult\n ? progressiveActionResult\n : null;\n const actionFailed = failedProgressiveActionResult !== null;\n const actionError = failedProgressiveActionResult?.actionError;\n\n const serverActionResponse = await options.handleServerActionRequest({\n actionId,\n cleanPathname,\n contentType,\n interceptionContext: interceptionContextHeader,\n isRscRequest,\n middlewareContext,\n mountedSlotsHeader,\n request,\n searchParams: url.searchParams,\n });\n if (serverActionResponse) return serverActionResponse;\n\n let match = options.matchRoute(cleanPathname);\n if (!match || match.route.isDynamic) {\n const afterFilesRewrite = await applyRewrite(\n {\n basePathState,\n clearRequestContext: options.clearRequestContext,\n request,\n requestContext: postMiddlewareRequestContext,\n rewrites: options.configRewrites.afterFiles,\n },\n matchPathname(cleanPathname),\n );\n if (afterFilesRewrite instanceof Response) return afterFilesRewrite;\n if (afterFilesRewrite) {\n cleanPathname = afterFilesRewrite;\n match = options.matchRoute(cleanPathname);\n }\n }\n\n if (!match) {\n const fallbackRewrite = await applyRewrite(\n {\n basePathState,\n clearRequestContext: options.clearRequestContext,\n request,\n requestContext: postMiddlewareRequestContext,\n rewrites: options.configRewrites.fallback,\n },\n matchPathname(cleanPathname),\n );\n if (fallbackRewrite instanceof Response) return fallbackRewrite;\n if (fallbackRewrite) {\n cleanPathname = fallbackRewrite;\n match = options.matchRoute(cleanPathname);\n }\n }\n\n if (!match) {\n const pagesFallbackResponse = await options.renderPagesFallback?.({\n isRscRequest,\n middlewareContext,\n request,\n url,\n });\n if (pagesFallbackResponse) {\n options.clearRequestContext();\n return pagesFallbackResponse;\n }\n\n const renderedNotFoundResponse = await options.renderNotFound({\n isRscRequest,\n middlewareContext,\n request,\n route: null,\n scriptNonce,\n });\n if (renderedNotFoundResponse) return renderedNotFoundResponse;\n\n options.clearRequestContext();\n const headers = new Headers();\n mergeMiddlewareResponseHeaders(headers, middlewareContext.headers);\n return notFoundResponse({ headers });\n }\n\n const { route, params } = match;\n options.setNavigationContext({\n pathname: canonicalPathname,\n searchParams: url.searchParams,\n params,\n });\n const rootParams = pickRootParams(params, route.rootParamNames);\n setRootParams(rootParams);\n\n if (route.routeHandler) {\n setCurrentFetchSoftTags(\n buildPageCacheTags(cleanPathname, [], [...route.routeSegments], \"route\"),\n );\n return options.dispatchMatchedRouteHandler({\n cleanPathname,\n middlewareContext,\n // Non-dynamic routes report params as `null` to match Next.js. Internal\n // bookkeeping above (navigation context, root params) keeps the matched\n // object (always `{}` for non-dynamic) so `useParams()` etc. still see\n // an object shape; only the user-facing handler context surfaces null.\n params: route.isDynamic ? params : null,\n request,\n route,\n searchParams: url.searchParams,\n });\n }\n\n return options.dispatchMatchedPage({\n cleanPathname,\n formState,\n actionError,\n actionFailed,\n handlerStart,\n interceptionContext: interceptionContextHeader,\n isProgressiveActionRender,\n isRscRequest,\n middlewareContext,\n mountedSlotsHeader,\n params,\n rootParams,\n request,\n route,\n scriptNonce,\n searchParams: url.searchParams,\n renderMode,\n });\n}\n\nexport function createAppRscHandler<TRoute extends AppRscHandlerRoute>(\n options: CreateAppRscHandlerOptions<TRoute>,\n): (request: Request, ctx: unknown) => Promise<Response> {\n return async function appRscHandler(rawRequest, ctx) {\n await options.ensureInstrumentation?.();\n\n // Strip forged internal headers at the App Router request boundary.\n // Must happen BEFORE headersContextFromRequest() and\n // requestContextFromRequest() so the captured context never contains\n // attacker-controlled internal headers. This is the correct boundary\n // for pure App Router requests; in hybrid app+pages mode the connect\n // handler already filtered headers upstream and x-vinext-mw-ctx\n // (not in INTERNAL_HEADERS) carries the forwarded middleware context.\n // srvx's NodeRequestHeaders reads from rawHeaders for iteration but falls\n // back to req.headers for .get() / .has(). In the dev server we add\n // x-vinext-mw-ctx to req.headers after the Request is built, so it is\n // visible to .get() but lost when filterInternalHeaders iterates. Read it\n // BEFORE iterating so applyForwardedMiddlewareContext can skip middleware.\n const mwCtx = rawRequest.headers.get(VINEXT_MW_CTX_HEADER);\n // Capture `x-nextjs-data` before filtering — the middleware redirect\n // protocol needs to know whether the inbound request was a `_next/data`\n // fetch to emit `x-nextjs-redirect` instead of an HTTP redirect.\n const isDataRequest = rawRequest.headers.get(\"x-nextjs-data\") === \"1\";\n const filteredHeaders = filterInternalHeaders(rawRequest.headers);\n if (mwCtx !== null) {\n filteredHeaders.set(VINEXT_MW_CTX_HEADER, mwCtx);\n }\n const request = cloneRequestWithHeaders(rawRequest, filteredHeaders);\n\n const executionContext = isExecutionContextLike(ctx)\n ? ctx\n : (getRequestExecutionContext() ?? null);\n const headersContext = headersContextFromRequest(request);\n const requestContext = createRequestContext({\n headersContext,\n executionContext,\n unstableCacheRevalidation: \"background\",\n });\n\n return runWithRequestContext(requestContext, () =>\n runWithPrerenderWorkUnit(\n async () => {\n ensureFetchPatch();\n const preMiddlewareRequestContext = requestContextFromRequest(request);\n let response: Response;\n\n try {\n response = await handleAppRscRequest(\n options,\n request,\n preMiddlewareRequestContext,\n isDataRequest,\n );\n } catch (error) {\n if (process.env.NODE_ENV !== \"production\") {\n flattenErrorCauses(error);\n }\n throw error;\n }\n\n return finalizeAppRscResponse(response, request, {\n basePath: options.basePath,\n configHeaders: options.configHeaders,\n i18nConfig: options.i18nConfig,\n requestContext: preMiddlewareRequestContext,\n });\n },\n { route: () => new URL(request.url).pathname },\n ),\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAS,YACP,OACA,KACyC;CACzC,OAAO,OAAO;;AAGhB,SAAS,uBAAuB,OAA+C;CAC7E,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,OAAO,YAAY,OAAO,YAAY,IAAI,OAAO,MAAM,cAAc;;AAOvE,SAAS,gCAAgC,aAAqB,UAA0B;CACtF,IAAI,CAAC,YAAY,cAAc,YAAY,IAAI,YAAY,aAAa,SAAS,EAC/E,OAAO;CAET,OAAO,WAAW;;AAGpB,eAAe,aACb,SAOA,eACmC;CACnC,IAAI,CAAC,QAAQ,SAAS,QAAQ,OAAO;CAErC,MAAM,YAAY,aAChB,eACA,QAAQ,UACR,QAAQ,gBACR,QAAQ,cACT;CACD,IAAI,CAAC,WAAW,OAAO;CAEvB,IAAI,cAAc,UAAU,EAAE;EAC5B,QAAQ,qBAAqB;EAC7B,OAAO,qBAAqB,QAAQ,SAAS,UAAU;;CAGzD,OAAO;;AAGT,SAAS,uCACP,UACA,SAMU;CAIV,IAAI,SAAS,SAAS,OAAO,SAAS,UAAU,KAAK,OAAO;CAC5D,IAAI,CAAC,QAAQ,cAAc,QAAQ,OAAO;CAE1C,MAAM,UAAU,IAAI,SAAS;CAC7B,6BAA6B,SAAS;EACpC,eAAe,QAAQ;EACvB,UAAU,QAAQ;EAClB,gBAAgB,QAAQ;EACxB,eAAe,QAAQ;EACxB,CAAC;CAEF,IAAI,CAAC,QAAQ,SAAS,CAAC,MAAM,CAAC,MAAM;EAClC,+BAA+B,SAAS,SAAS,QAAQ;EACzD,OAAO,IAAI,SAAS,SAAS,MAAM;GACjC,QAAQ,SAAS;G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AgB,KAAK;EAClE,MAAM,kBAAkB,sBAAsB,WAAW,QAAQ;EACjE,IAAI,UAAU,MACZ,gBAAgB,IAAI,sBAAsB,MAAM;EAElD,MAAM,UAAU,wBAAwB,YAAY,gBAAgB;EAEpE,MAAM,mBAAmB,uBAAuB,IAAI,GAChD,MACC,4BAA4B,IAAI;EAQrC,OAAO,sBANgB,qBAAqB;GAC1C,gBAFqB,0BAA0B,QAEjC;GACd;GACA,2BAA2B;GAC5B,CAE0C,QACzC,yBACE,YAAY;GACV,kBAAkB;GAClB,MAAM,8BAA8B,0BAA0B,QAAQ;GACtE,IAAI;GAEJ,IAAI;IACF,WAAW,MAAM,oBACf,SACA,SACA,6BACA,cACD;YACM,OAAO;IACd,IAAI,QAAQ,IAAI,aAAa,cAC3B,mBAAmB,MAAM;IAE3B,MAAM;;GAGR,OAAO,uBAAuB,UAAU,SAAS;IAC/C,UAAU,QAAQ;IAClB,eAAe,QAAQ;IACvB,YAAY,QAAQ;IACpB,gBAAgB;IACjB,CAAC;KAEJ,EAAE,aAAa,IAAI,IAAI,QAAQ,IAAI,CAAC,UAAU,CAC/C,CACF"}
1
+ {"version":3,"file":"app-rsc-handler.js","names":[],"sources":["../../src/server/app-rsc-handler.ts"],"sourcesContent":["import type {\n NextHeader,\n NextI18nConfig,\n NextRedirect,\n NextRewrite,\n} from \"../config/next-config.js\";\nimport {\n isExternalUrl,\n matchRedirect,\n matchRewrite,\n proxyExternalRequest,\n requestContextFromRequest,\n sanitizeDestination,\n type BasePathMatchState,\n} from \"../config/config-matchers.js\";\nimport { headersContextFromRequest } from \"vinext/shims/headers\";\nimport {\n NEXT_ACTION_HEADER,\n RSC_ACTION_HEADER,\n RSC_HEADER,\n VINEXT_MW_CTX_HEADER,\n VINEXT_PRERENDER_ROUTE_PARAMS_HEADER,\n} from \"./headers.js\";\nimport { ensureFetchPatch, setCurrentFetchSoftTags } from \"vinext/shims/fetch-cache\";\nimport type { ReactFormState } from \"react-dom/client\";\nimport {\n getRequestExecutionContext,\n type ExecutionContextLike,\n} from \"vinext/shims/request-context\";\nimport { pickRootParams, setRootParams, type RootParams } from \"vinext/shims/root-params\";\nimport { createRequestContext, runWithRequestContext } from \"vinext/shims/unified-request-context\";\nimport { flattenErrorCauses } from \"../utils/error-cause.js\";\nimport { hasBasePath } from \"../utils/base-path.js\";\nimport { applyAppMiddleware, type AppMiddlewareContext } from \"./app-middleware.js\";\nimport { mergeMiddlewareResponseHeaders } from \"./app-page-response.js\";\nimport { handleAppPrerenderEndpoint } from \"./app-prerender-endpoints.js\";\nimport {\n createRscRedirectLocation,\n resolveInvalidRscCacheBustingRequest,\n stripRscCacheBustingSearchParam,\n stripRscSuffix,\n} from \"./app-rsc-cache-busting.js\";\nimport { finalizeAppRscResponse } from \"./app-rsc-response-finalizer.js\";\nimport { normalizeRscRequest } from \"./app-rsc-request-normalization.js\";\nimport { normalizeDefaultLocalePathname } from \"./pages-i18n.js\";\nimport { notFoundResponse } from \"./http-error-responses.js\";\nimport { getScriptNonceFromHeaderSources } from \"./csp.js\";\nimport { buildPageCacheTags } from \"./implicit-tags.js\";\nimport { isImageOptimizationPath } from \"./image-optimization.js\";\nimport { handleMetadataRouteRequest } from \"./metadata-route-response.js\";\nimport type { MiddlewareModule } from \"./middleware-runtime.js\";\nimport { runWithPrerenderWorkUnit } from \"./prerender-work-unit-setup.js\";\nimport { buildPostMwRequestContext } from \"./app-post-middleware-context.js\";\nimport type { AppRscRenderMode } from \"./app-rsc-render-mode.js\";\nimport {\n cloneRequestWithHeaders,\n filterInternalHeaders,\n applyConfigHeadersToResponse,\n normalizeTrailingSlash,\n resolvePublicFileRoute,\n validateImageUrl,\n} from \"./request-pipeline.js\";\nimport {\n prerenderRouteParamsPayloadMatchesRoute,\n readTrustedPrerenderRouteParams,\n serializePrerenderRouteParamsHeader,\n} from \"./prerender-route-params.js\";\n\ntype AppPageParams = Record<string, string | string[]>;\ntype RequestContext = ReturnType<typeof requestContextFromRequest>;\ntype MetadataRoutes = Parameters<typeof handleMetadataRouteRequest>[0][\"metadataRoutes\"];\ntype MakeThenableParams = Parameters<typeof handleMetadataRouteRequest>[0][\"makeThenableParams\"];\ntype StaticParamsMap = Parameters<typeof handleAppPrerenderEndpoint>[1][\"staticParamsMap\"];\ntype RootParamNamesMap = Parameters<\n typeof handleAppPrerenderEndpoint\n>[1][\"rootParamNamesByPattern\"];\n\ntype AppRscMiddlewareContext = AppMiddlewareContext;\n\ntype AppRscHandlerRoute = {\n isDynamic: boolean;\n page?: unknown;\n pattern: string;\n rootParamNames?: readonly string[];\n routeHandler?: unknown;\n routeSegments: readonly string[];\n};\n\ntype AppRscRouteMatch<TRoute> = {\n params: AppPageParams;\n route: TRoute;\n};\n\ntype DispatchMatchedPageOptions<TRoute> = {\n cleanPathname: string;\n formState: ReactFormState | null;\n actionError?: unknown;\n actionFailed?: boolean;\n handlerStart: number;\n interceptionContext: string | null;\n isProgressiveActionRender: boolean;\n isRscRequest: boolean;\n middlewareContext: AppRscMiddlewareContext;\n mountedSlotsHeader: string | null;\n params: AppPageParams;\n staticParamsValidationParams?: AppPageParams;\n rootParams?: RootParams;\n request: Request;\n route: TRoute;\n scriptNonce?: string;\n searchParams: URLSearchParams;\n renderMode: AppRscRenderMode;\n};\n\ntype DispatchMatchedRouteHandlerOptions<TRoute> = {\n cleanPathname: string;\n middlewareContext: AppRscMiddlewareContext;\n /**\n * `null` for non-dynamic routes. Mirrors Next.js' route handler context\n * shape: user code that does `params ? await params : null` resolves to\n * `null` for routes without dynamic segments. Dynamic routes receive the\n * matched params object.\n */\n params: AppPageParams | null;\n request: Request;\n route: TRoute;\n searchParams: URLSearchParams;\n};\n\ntype HandleProgressiveActionRequestOptions = {\n actionId: string | null;\n cleanPathname: string;\n contentType: string;\n middlewareContext: AppRscMiddlewareContext;\n request: Request;\n};\n\ntype ProgressiveActionFormStateResult =\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 HandleServerActionRequestOptions = {\n actionId: string | null;\n cleanPathname: string;\n contentType: string;\n interceptionContext: string | null;\n isRscRequest: boolean;\n middlewareContext: AppRscMiddlewareContext;\n mountedSlotsHeader: string | null;\n request: Request;\n searchParams: URLSearchParams;\n};\n\ntype RenderNotFoundOptions<TRoute> = {\n isRscRequest: boolean;\n matchedParams?: AppPageParams;\n middlewareContext: AppRscMiddlewareContext;\n request: Request;\n route: TRoute | null;\n scriptNonce?: string;\n};\n\ntype RenderPagesFallbackOptions = {\n isRscRequest: boolean;\n middlewareContext: AppRscMiddlewareContext;\n request: Request;\n url: URL;\n};\n\ntype NavigationContextValue = {\n params: AppPageParams;\n pathname: string;\n searchParams: URLSearchParams;\n};\n\ntype CreateAppRscHandlerOptions<TRoute extends AppRscHandlerRoute> = {\n basePath: string;\n clearRequestContext: () => void;\n configHeaders: NextHeader[];\n configRedirects: NextRedirect[];\n configRewrites: {\n afterFiles: NextRewrite[];\n beforeFiles: NextRewrite[];\n fallback: NextRewrite[];\n };\n draftModeSecret: string;\n dispatchMatchedPage: (options: DispatchMatchedPageOptions<TRoute>) => Promise<Response>;\n dispatchMatchedRouteHandler: (\n options: DispatchMatchedRouteHandlerOptions<TRoute>,\n ) => Promise<Response>;\n ensureInstrumentation?: () => Promise<void>;\n handleProgressiveActionRequest: (\n options: HandleProgressiveActionRequestOptions,\n ) => Promise<Response | ProgressiveActionFormStateResult | null>;\n handleServerActionRequest: (\n options: HandleServerActionRequestOptions,\n ) => Promise<Response | null>;\n i18nConfig: NextI18nConfig | null;\n isMiddlewareProxy: boolean;\n loadPrerenderPagesRoutes?: () => Promise<unknown>;\n makeThenableParams: MakeThenableParams;\n matchRoute: (pathname: string) => AppRscRouteMatch<TRoute> | null;\n metadataRoutes: MetadataRoutes;\n middlewareModule: MiddlewareModule | null;\n publicFiles: ReadonlySet<string>;\n renderNotFound: (options: RenderNotFoundOptions<TRoute>) => Promise<Response | null>;\n renderPagesFallback?: (options: RenderPagesFallbackOptions) => Promise<Response | null>;\n rootParamNamesByPattern?: RootParamNamesMap;\n setNavigationContext: (context: NavigationContextValue) => void;\n staticParamsMap: StaticParamsMap;\n trailingSlash: boolean;\n validateDevRequestOrigin?: (request: Request) => Response | null;\n};\n\nfunction hasProperty<TKey extends PropertyKey>(\n value: object,\n key: TKey,\n): value is object & Record<TKey, unknown> {\n return key in value;\n}\n\nfunction isExecutionContextLike(value: unknown): value is ExecutionContextLike {\n if (!value || typeof value !== \"object\") return false;\n return hasProperty(value, \"waitUntil\") && typeof value.waitUntil === \"function\";\n}\n\n// TODO(#1333): once App Router supports `basePath: false` rules (see\n// `normalizeRscRequest` — it 404s out-of-basePath requests before they\n// reach this code), pass `hadBasePath` here and skip the prefix when\n// false, mirroring the same guard in `prod-server.ts` and `deploy.ts`.\nfunction redirectDestinationWithBasePath(destination: string, basePath: string): string {\n if (!basePath || isExternalUrl(destination) || hasBasePath(destination, basePath)) {\n return destination;\n }\n return basePath + destination;\n}\n\nasync function applyRewrite(\n options: {\n basePathState: BasePathMatchState;\n clearRequestContext: () => void;\n request: Request;\n requestContext: RequestContext;\n rewrites: NextRewrite[];\n },\n cleanPathname: string,\n): Promise<Response | string | null> {\n if (!options.rewrites.length) return null;\n\n const rewritten = matchRewrite(\n cleanPathname,\n options.rewrites,\n options.requestContext,\n options.basePathState,\n );\n if (!rewritten) return null;\n\n if (isExternalUrl(rewritten)) {\n options.clearRequestContext();\n return proxyExternalRequest(options.request, rewritten);\n }\n\n return rewritten;\n}\n\nfunction applyConfigHeadersToMiddlewareRedirect(\n response: Response,\n options: {\n basePathState: BasePathMatchState;\n configHeaders: NextHeader[];\n pathname: string;\n requestContext: RequestContext;\n },\n): Response {\n // Non-redirect middleware responses still pass through finalization, where\n // config headers are applied once. Redirects skip finalization to avoid\n // mutating immutable redirect headers, so they need the earlier header layer here.\n if (response.status < 300 || response.status >= 400) return response;\n if (!options.configHeaders.length) return response;\n\n const headers = new Headers();\n applyConfigHeadersToResponse(headers, {\n configHeaders: options.configHeaders,\n pathname: options.pathname,\n requestContext: options.requestContext,\n basePathState: options.basePathState,\n });\n\n if (!headers.entries().next().done) {\n mergeMiddlewareResponseHeaders(headers, response.headers);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n return response;\n}\n\nasync function handleAppRscRequest<TRoute extends AppRscHandlerRoute>(\n options: CreateAppRscHandlerOptions<TRoute>,\n request: Request,\n preMiddlewareRequestContext: RequestContext,\n isDataRequest: boolean,\n): Promise<Response> {\n const handlerStart = process.env.NODE_ENV !== \"production\" ? performance.now() : 0;\n\n if (process.env.NODE_ENV !== \"production\") {\n const originBlock = options.validateDevRequestOrigin?.(request);\n if (originBlock) return originBlock;\n }\n\n const normalized = normalizeRscRequest(request, options.basePath);\n if (normalized instanceof Response) return normalized;\n\n const { url, isRscRequest, interceptionContextHeader, mountedSlotsHeader, renderMode } =\n normalized;\n let { pathname, cleanPathname } = normalized;\n // Canonical (external) pathname the user requested. Middleware rewrites and\n // next.config.js rewrites mutate `cleanPathname` so internal route matching\n // can find the destination page, but hooks like `usePathname()` must reflect\n // the original URL the user sees in the address bar.\n // Matches Next.js: test/e2e/app-dir/hooks/hooks.test.ts —\n // \"should have the canonical url pathname on rewrite\"\n const canonicalPathname = cleanPathname;\n\n // The request reached this point so it was either under basePath (stripped\n // by normalizeRscRequest) or basePath is empty. In both cases the matcher\n // gating below treats default (basePath: true) rules as eligible. The App\n // Router does not yet support `basePath: false` rules — they would need a\n // pre-strip hook in normalizeRscRequest to fire. Tracked as follow-up to\n // issue #1333.\n const basePathState = { basePath: options.basePath, hadBasePath: true };\n\n const prerenderEndpointResponse = await handleAppPrerenderEndpoint(request, {\n isPrerenderEnabled() {\n return process.env.VINEXT_PRERENDER === \"1\";\n },\n loadPagesRoutes: options.loadPrerenderPagesRoutes,\n pathname,\n rootParamNamesByPattern: options.rootParamNamesByPattern,\n staticParamsMap: options.staticParamsMap,\n });\n if (prerenderEndpointResponse) return prerenderEndpointResponse;\n\n const trailingSlashRedirect = normalizeTrailingSlash(\n pathname,\n options.basePath,\n options.trailingSlash,\n url.search,\n );\n if (trailingSlashRedirect) return trailingSlashRedirect;\n\n // Default-locale path normalisation (issue #1336, item 4). Next.js\n // splices in the (domain-aware) default locale on every request that\n // arrives without a locale prefix before running config redirect / rewrite\n // / header matching. Mirrors resolve-routes.ts lines ~250-263.\n //\n // Defined once here so the same helper is reused for the redirect match\n // below, the middleware-redirect config header match further down, and the\n // post-middleware rewrite matches. `i18nConfig` and `url.hostname` are\n // request-scoped constants from this point on.\n const matchPathname = (p: string): string =>\n normalizeDefaultLocalePathname(p, options.i18nConfig, { hostname: url.hostname });\n\n const redirectPathname = matchPathname(stripRscSuffix(pathname));\n const redirect = matchRedirect(\n redirectPathname,\n options.configRedirects,\n preMiddlewareRequestContext,\n basePathState,\n );\n if (redirect) {\n const destination = sanitizeDestination(\n redirectDestinationWithBasePath(redirect.destination, options.basePath),\n );\n const location =\n isRscRequest && request.headers.get(RSC_HEADER) === \"1\"\n ? await createRscRedirectLocation(destination, request)\n : destination;\n return new Response(null, {\n status: redirect.permanent ? 308 : 307,\n headers: { Location: location },\n });\n }\n\n const rscCacheBustingRedirect = await resolveInvalidRscCacheBustingRequest({\n isRscRequest,\n request,\n });\n if (rscCacheBustingRedirect) return rscCacheBustingRedirect;\n\n const middlewareContext: AppRscMiddlewareContext = {\n headers: null,\n requestHeaders: null,\n status: null,\n };\n\n if (options.middlewareModule) {\n const middlewareResult = await applyAppMiddleware({\n basePath: options.basePath,\n cleanPathname,\n context: middlewareContext,\n i18nConfig: options.i18nConfig,\n isDataRequest,\n isProxy: options.isMiddlewareProxy,\n module: options.middlewareModule,\n request,\n trailingSlash: options.trailingSlash,\n });\n if (middlewareResult.kind === \"response\") {\n return applyConfigHeadersToMiddlewareRedirect(middlewareResult.response, {\n basePathState,\n configHeaders: options.configHeaders,\n pathname: matchPathname(cleanPathname),\n requestContext: preMiddlewareRequestContext,\n });\n }\n\n cleanPathname = middlewareResult.cleanPathname;\n if (middlewareResult.search !== null) {\n url.search = middlewareResult.search;\n }\n }\n\n const scriptNonce = getScriptNonceFromHeaderSources(request.headers, middlewareContext.headers);\n const postMiddlewareRequestContext = buildPostMwRequestContext(request);\n\n // Rewrites (beforeFiles, afterFiles, fallback) use `matchPathname` from\n // above to splice in the default locale before matching. Route matching\n // itself continues to use the un-prefixed `cleanPathname` because App\n // Router files live under `app/...` with no locale segment. See issue\n // #1336 item 4 / pages-i18n.normalizeDefaultLocalePathname.\n const beforeFilesRewrite = await applyRewrite(\n {\n basePathState,\n clearRequestContext: options.clearRequestContext,\n request,\n requestContext: postMiddlewareRequestContext,\n rewrites: options.configRewrites.beforeFiles,\n },\n matchPathname(cleanPathname),\n );\n if (beforeFilesRewrite instanceof Response) return beforeFilesRewrite;\n if (beforeFilesRewrite) cleanPathname = beforeFilesRewrite;\n\n if (isImageOptimizationPath(cleanPathname)) {\n const imageUrlResult = validateImageUrl(url.searchParams.get(\"url\"), request.url);\n if (imageUrlResult instanceof Response) return imageUrlResult;\n return Response.redirect(new URL(imageUrlResult, url.origin).href, 302);\n }\n\n const metadataRouteResponse = await handleMetadataRouteRequest({\n metadataRoutes: options.metadataRoutes,\n cleanPathname,\n makeThenableParams: options.makeThenableParams,\n });\n if (metadataRouteResponse) return metadataRouteResponse;\n\n const publicFileResponse = resolvePublicFileRoute({\n cleanPathname,\n middlewareContext,\n pathname,\n publicFiles: options.publicFiles,\n request,\n });\n if (publicFileResponse) {\n options.clearRequestContext();\n return publicFileResponse;\n }\n\n if (isRscRequest) {\n stripRscCacheBustingSearchParam(url);\n }\n\n options.setNavigationContext({\n pathname: canonicalPathname,\n searchParams: url.searchParams,\n params: {},\n });\n\n const actionId =\n request.headers.get(RSC_ACTION_HEADER) ?? request.headers.get(NEXT_ACTION_HEADER);\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n const progressiveActionResult = await options.handleProgressiveActionRequest({\n actionId,\n cleanPathname,\n contentType,\n middlewareContext,\n request,\n });\n if (progressiveActionResult instanceof Response) return progressiveActionResult;\n const isProgressiveActionRender = progressiveActionResult?.kind === \"form-state\";\n const formState = isProgressiveActionRender ? progressiveActionResult.formState : null;\n const failedProgressiveActionResult =\n isProgressiveActionRender && \"actionFailed\" in progressiveActionResult\n ? progressiveActionResult\n : null;\n const actionFailed = failedProgressiveActionResult !== null;\n const actionError = failedProgressiveActionResult?.actionError;\n\n const serverActionResponse = await options.handleServerActionRequest({\n actionId,\n cleanPathname,\n contentType,\n interceptionContext: interceptionContextHeader,\n isRscRequest,\n middlewareContext,\n mountedSlotsHeader,\n request,\n searchParams: url.searchParams,\n });\n if (serverActionResponse) return serverActionResponse;\n\n let match = options.matchRoute(cleanPathname);\n if (!match || match.route.isDynamic) {\n const afterFilesRewrite = await applyRewrite(\n {\n basePathState,\n clearRequestContext: options.clearRequestContext,\n request,\n requestContext: postMiddlewareRequestContext,\n rewrites: options.configRewrites.afterFiles,\n },\n matchPathname(cleanPathname),\n );\n if (afterFilesRewrite instanceof Response) return afterFilesRewrite;\n if (afterFilesRewrite) {\n cleanPathname = afterFilesRewrite;\n match = options.matchRoute(cleanPathname);\n }\n }\n\n if (!match) {\n const fallbackRewrite = await applyRewrite(\n {\n basePathState,\n clearRequestContext: options.clearRequestContext,\n request,\n requestContext: postMiddlewareRequestContext,\n rewrites: options.configRewrites.fallback,\n },\n matchPathname(cleanPathname),\n );\n if (fallbackRewrite instanceof Response) return fallbackRewrite;\n if (fallbackRewrite) {\n cleanPathname = fallbackRewrite;\n match = options.matchRoute(cleanPathname);\n }\n }\n\n if (!match) {\n const pagesFallbackResponse = await options.renderPagesFallback?.({\n isRscRequest,\n middlewareContext,\n request,\n url,\n });\n if (pagesFallbackResponse) {\n options.clearRequestContext();\n return pagesFallbackResponse;\n }\n\n const renderedNotFoundResponse = await options.renderNotFound({\n isRscRequest,\n middlewareContext,\n request,\n route: null,\n scriptNonce,\n });\n if (renderedNotFoundResponse) return renderedNotFoundResponse;\n\n options.clearRequestContext();\n const headers = new Headers();\n mergeMiddlewareResponseHeaders(headers, middlewareContext.headers);\n return notFoundResponse({ headers });\n }\n\n const { route, params } = match;\n const prerenderRouteParamsPayload = readTrustedPrerenderRouteParams(request);\n const prerenderRouteParams = prerenderRouteParamsPayloadMatchesRoute(\n prerenderRouteParamsPayload,\n route.pattern,\n params,\n )\n ? prerenderRouteParamsPayload.params\n : null;\n const renderParams = prerenderRouteParams ?? params;\n options.setNavigationContext({\n pathname: canonicalPathname,\n searchParams: url.searchParams,\n params: renderParams,\n });\n const rootParams = pickRootParams(renderParams, route.rootParamNames);\n setRootParams(rootParams);\n\n if (route.routeHandler) {\n setCurrentFetchSoftTags(\n buildPageCacheTags(cleanPathname, [], [...route.routeSegments], \"route\"),\n );\n return options.dispatchMatchedRouteHandler({\n cleanPathname,\n middlewareContext,\n // Non-dynamic routes report params as `null` to match Next.js. Internal\n // bookkeeping above (navigation context, root params) keeps the matched\n // object (always `{}` for non-dynamic) so `useParams()` etc. still see\n // an object shape; only the user-facing handler context surfaces null.\n params: route.isDynamic ? renderParams : null,\n request,\n route,\n searchParams: url.searchParams,\n });\n }\n\n return options.dispatchMatchedPage({\n cleanPathname,\n formState,\n actionError,\n actionFailed,\n handlerStart,\n interceptionContext: interceptionContextHeader,\n isProgressiveActionRender,\n isRscRequest,\n middlewareContext,\n mountedSlotsHeader,\n params: renderParams,\n staticParamsValidationParams: prerenderRouteParams === null ? undefined : params,\n rootParams,\n request,\n route,\n scriptNonce,\n searchParams: url.searchParams,\n renderMode,\n });\n}\n\nexport function createAppRscHandler<TRoute extends AppRscHandlerRoute>(\n options: CreateAppRscHandlerOptions<TRoute>,\n): (request: Request, ctx: unknown) => Promise<Response> {\n return async function appRscHandler(rawRequest, ctx) {\n await options.ensureInstrumentation?.();\n\n // Strip forged internal headers at the App Router request boundary.\n // Must happen BEFORE headersContextFromRequest() and\n // requestContextFromRequest() so the captured context never contains\n // attacker-controlled internal headers. This is the correct boundary\n // for pure App Router requests; in hybrid app+pages mode the connect\n // handler already filtered headers upstream and x-vinext-mw-ctx\n // (not in INTERNAL_HEADERS) carries the forwarded middleware context.\n // srvx's NodeRequestHeaders reads from rawHeaders for iteration but falls\n // back to req.headers for .get() / .has(). In the dev server we add\n // x-vinext-mw-ctx to req.headers after the Request is built, so it is\n // visible to .get() but lost when filterInternalHeaders iterates. Read it\n // BEFORE iterating so applyForwardedMiddlewareContext can skip middleware.\n const mwCtx = rawRequest.headers.get(VINEXT_MW_CTX_HEADER);\n // Capture `x-nextjs-data` before filtering — the middleware redirect\n // protocol needs to know whether the inbound request was a `_next/data`\n // fetch to emit `x-nextjs-redirect` instead of an HTTP redirect.\n const isDataRequest = rawRequest.headers.get(\"x-nextjs-data\") === \"1\";\n // Read the trusted prerender route params before filtering strips the\n // route-params header (it IS in VINEXT_INTERNAL_HEADERS), then re-attach the\n // validated value below so the second read in handleAppRscRequest still sees\n // it. The secret was already verified upstream at prod-server's\n // nodeToWebRequest boundary; the surviving secret header (NOT in either\n // internal-header list) lets readTrustedPrerenderRouteParams's\n // VINEXT_PRERENDER gate pass on the reconstructed request. If the secret\n // header is ever added to VINEXT_INTERNAL_HEADERS, that second read breaks.\n const prerenderRouteParamsPayload = readTrustedPrerenderRouteParams(rawRequest);\n const filteredHeaders = filterInternalHeaders(rawRequest.headers);\n if (mwCtx !== null) {\n filteredHeaders.set(VINEXT_MW_CTX_HEADER, mwCtx);\n }\n const prerenderRouteParamsHeader = serializePrerenderRouteParamsHeader(\n prerenderRouteParamsPayload,\n );\n if (prerenderRouteParamsHeader !== null) {\n filteredHeaders.set(VINEXT_PRERENDER_ROUTE_PARAMS_HEADER, prerenderRouteParamsHeader);\n }\n const request = cloneRequestWithHeaders(rawRequest, filteredHeaders);\n\n const executionContext = isExecutionContextLike(ctx)\n ? ctx\n : (getRequestExecutionContext() ?? null);\n const headersContext = headersContextFromRequest(request, {\n draftModeSecret: options.draftModeSecret,\n });\n const requestContext = createRequestContext({\n headersContext,\n executionContext,\n unstableCacheRevalidation: \"background\",\n });\n\n return runWithRequestContext(requestContext, () =>\n runWithPrerenderWorkUnit(\n async () => {\n ensureFetchPatch();\n const preMiddlewareRequestContext = requestContextFromRequest(request);\n let response: Response;\n\n try {\n response = await handleAppRscRequest(\n options,\n request,\n preMiddlewareRequestContext,\n isDataRequest,\n );\n } catch (error) {\n if (process.env.NODE_ENV !== \"production\") {\n flattenErrorCauses(error);\n }\n throw error;\n }\n\n return finalizeAppRscResponse(response, request, {\n basePath: options.basePath,\n configHeaders: options.configHeaders,\n i18nConfig: options.i18nConfig,\n requestContext: preMiddlewareRequestContext,\n });\n },\n { route: () => new URL(request.url).pathname },\n ),\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8NA,SAAS,YACP,OACA,KACyC;CACzC,OAAO,OAAO;;AAGhB,SAAS,uBAAuB,OAA+C;CAC7E,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,OAAO,YAAY,OAAO,YAAY,IAAI,OAAO,MAAM,cAAc;;AAOvE,SAAS,gCAAgC,aAAqB,UAA0B;CACtF,IAAI,CAAC,YAAY,cAAc,YAAY,IAAI,YAAY,aAAa,SAAS,EAC/E,OAAO;CAET,OAAO,WAAW;;AAGpB,eAAe,aACb,SAOA,eACmC;CACnC,IAAI,CAAC,QAAQ,SAAS,QAAQ,OAAO;CAErC,MAAM,YAAY,aAChB,eACA,QAAQ,UACR,QAAQ,gBACR,QAAQ,cACT;CACD,IAAI,CAAC,WAAW,OAAO;CAEvB,IAAI,cAAc,UAAU,EAAE;EAC5B,QAAQ,qBAAqB;EAC7B,OAAO,qBAAqB,QAAQ,SAAS,UAAU;;CAGzD,OAAO;;AAGT,SAAS,uCACP,UACA,SAMU;CAIV,IAAI,SAAS,SAAS,OAAO,SAAS,UAAU,KAAK,OAAO;CAC5D,IAAI,CAAC,QAAQ,cAAc,QAAQ,OAAO;CAE1C,MAAM,UAAU,IAAI,SAAS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AgB;IACjB,CAAC;KAEJ,EAAE,aAAa,IAAI,IAAI,QAAQ,IAAI,CAAC,UAAU,CAC/C,CACF"}
@@ -1,12 +1,13 @@
1
1
  import { normalizePathnameForRouteMatchStrict } from "../routing/utils.js";
2
2
  import { hasBasePath, stripBasePath } from "../utils/base-path.js";
3
- import { VINEXT_CLIENT_REUSE_MANIFEST_HEADER, VINEXT_MOUNTED_SLOTS_HEADER, VINEXT_RSC_RENDER_MODE_HEADER } from "./headers.js";
3
+ import { VINEXT_CLIENT_REUSE_MANIFEST_HEADER, VINEXT_INTERCEPTION_CONTEXT_HEADER, VINEXT_MOUNTED_SLOTS_HEADER, VINEXT_RSC_RENDER_MODE_HEADER } from "./headers.js";
4
4
  import { normalizePath } from "./normalize-path.js";
5
5
  import { badRequestResponse, notFoundResponse } from "./http-error-responses.js";
6
6
  import { guardProtocolRelativeUrl } from "./request-pipeline.js";
7
7
  import { normalizeMountedSlotsHeader } from "./app-mounted-slots-header.js";
8
8
  import { APP_RSC_RENDER_MODE_NAVIGATION, parseAppRscRenderMode } from "./app-rsc-render-mode.js";
9
9
  import { stripRscSuffix } from "./app-rsc-cache-busting.js";
10
+ import { normalizeInterceptionContextHeader } from "./app-interception-context-header.js";
10
11
  import { parseClientReuseManifestHeader } from "./client-reuse-manifest.js";
11
12
  //#region src/server/app-rsc-request-normalization.ts
12
13
  /**
@@ -55,7 +56,7 @@ function normalizeRscRequest(request, basePath) {
55
56
  }
56
57
  const isRscRequest = pathname.endsWith(".rsc");
57
58
  const cleanPathname = stripRscSuffix(pathname);
58
- const interceptionContextHeader = request.headers.get("X-Vinext-Interception-Context")?.replaceAll("\0", "") || null;
59
+ const interceptionContextHeader = normalizeInterceptionContextHeader(request.headers.get(VINEXT_INTERCEPTION_CONTEXT_HEADER));
59
60
  const mountedSlotsHeader = normalizeMountedSlotsHeader(request.headers.get(VINEXT_MOUNTED_SLOTS_HEADER));
60
61
  const renderMode = isRscRequest ? parseAppRscRenderMode(request.headers.get(VINEXT_RSC_RENDER_MODE_HEADER)) : APP_RSC_RENDER_MODE_NAVIGATION;
61
62
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"app-rsc-request-normalization.js","names":[],"sources":["../../src/server/app-rsc-request-normalization.ts"],"sourcesContent":["import { normalizePath } from \"./normalize-path.js\";\nimport { normalizePathnameForRouteMatchStrict } from \"../routing/utils.js\";\nimport { guardProtocolRelativeUrl } from \"./request-pipeline.js\";\nimport { hasBasePath, stripBasePath } from \"../utils/base-path.js\";\nimport {\n VINEXT_CLIENT_REUSE_MANIFEST_HEADER,\n VINEXT_INTERCEPTION_CONTEXT_HEADER,\n VINEXT_MOUNTED_SLOTS_HEADER,\n VINEXT_RSC_RENDER_MODE_HEADER,\n} from \"./headers.js\";\nimport {\n parseClientReuseManifestHeader,\n type ClientReuseManifestParseResult,\n} from \"./client-reuse-manifest.js\";\nimport { normalizeMountedSlotsHeader } from \"./app-mounted-slots-header.js\";\nimport { stripRscSuffix } from \"./app-rsc-cache-busting.js\";\nimport {\n APP_RSC_RENDER_MODE_NAVIGATION,\n parseAppRscRenderMode,\n type AppRscRenderMode,\n} from \"./app-rsc-render-mode.js\";\nimport { badRequestResponse, notFoundResponse } from \"./http-error-responses.js\";\n\nexport { normalizeMountedSlotsHeader } from \"./app-mounted-slots-header.js\";\n\nexport type NormalizedRscRequest = {\n /** Parsed URL. Callers may mutate `url.search` after middleware runs. */\n url: URL;\n /** Normalized pathname with basePath stripped. Used for all internal routing. */\n pathname: string;\n /** Pathname with `.rsc` suffix removed. Used for route matching and navigation context. */\n cleanPathname: string;\n /** True when the request targets a canonical `.rsc` payload URL. */\n isRscRequest: boolean;\n /** Sanitized X-Vinext-Interception-Context header (null bytes stripped). null when absent. */\n interceptionContextHeader: string | null;\n /** Normalized x-vinext-mounted-slots header (deduplicated, sorted). null when absent or blank. */\n mountedSlotsHeader: string | null;\n /** Semantic RSC payload mode. HTML requests always normalize to \"navigation\". */\n renderMode: AppRscRenderMode;\n /** Disabled ClientReuseManifest hint. Never authorizes skip transport in this stage. */\n clientReuseManifest: ClientReuseManifestParseResult;\n};\n\n/**\n * Normalize an App Router RSC request.\n *\n * Performs all security-sensitive and compatibility-sensitive preprocessing before\n * route matching. The ordering of steps is security-critical — changing it introduces\n * vulnerabilities:\n *\n * 1. Parse URL\n * 2. Protocol-relative URL guard — on the raw pathname, BEFORE normalizePath collapses\n * `//` to `/`. If the guard ran after normalization, `//evil.com` → `/evil.com`\n * would bypass the check and reach the trailing-slash redirector, which echoes the\n * path into a `Location` header that browsers interpret as protocol-relative.\n * 3. Strict percent-decode each segment — throws on malformed sequences (→ 400). Must\n * run before basePath check so %2F-encoded slashes cannot create fake basePath prefixes.\n * 4. Collapse double-slashes, resolve `.` and `..` segments (normalizePath)\n * 5. basePath check + strip — 404 when pathname lacks the basePath prefix.\n * `/__vinext/` bypasses this for internal prerender endpoints.\n * 6. RSC detection: `.rsc` suffix only. RSC headers do not select payload\n * rendering at the canonical HTML URL, so caches that ignore Vary cannot\n * store Flight responses under HTML URLs.\n * 7. cleanPathname — pathname with `.rsc` suffix stripped\n * 8. Sanitize X-Vinext-Interception-Context — strip null bytes (header injection)\n * 9. Normalize x-vinext-mounted-slots — dedup and sort for canonical cache keys\n * 10. Read semantic render mode for refresh/action payload rendering\n * 11. Parse disabled ClientReuseManifest hints on canonical RSC payload requests\n *\n * @returns A 400 or 404 Response for invalid or out-of-scope inputs,\n * or a NormalizedRscRequest for valid requests.\n */\nexport function normalizeRscRequest(\n request: Request,\n basePath: string,\n): Response | NormalizedRscRequest {\n const url = new URL(request.url);\n\n // Step 2: Guard against protocol-relative open redirects on the raw pathname.\n // normalizePath (step 4) would collapse //evil.com to /evil.com, causing the\n // guard to miss it. Raw pathname must be checked first.\n const protoGuard = guardProtocolRelativeUrl(url.pathname);\n if (protoGuard) return protoGuard;\n\n // Step 3: Strict segment-wise percent-decode. Preserves encoded path delimiters\n // (%2F stays %2F) to prevent encoded slashes from acting as path separators.\n // Throws on malformed sequences like %GG — caller must return 400.\n let decoded: string;\n try {\n decoded = normalizePathnameForRouteMatchStrict(url.pathname);\n } catch {\n return badRequestResponse();\n }\n\n // Step 4: Collapse double-slashes and resolve . / .. segments.\n let pathname = normalizePath(decoded);\n\n // Step 5: basePath check and strip.\n // Skipped when basePath is empty (no basePath configured).\n // /__vinext/ prefix bypasses the check for internal prerender endpoints\n // that must be reachable regardless of basePath configuration.\n if (basePath) {\n if (!hasBasePath(pathname, basePath) && !pathname.startsWith(\"/__vinext/\")) {\n return notFoundResponse();\n }\n pathname = stripBasePath(pathname, basePath);\n }\n\n // Steps 6-7: RSC detection and cleanPathname.\n const isRscRequest = pathname.endsWith(\".rsc\");\n const cleanPathname = stripRscSuffix(pathname);\n\n // Step 8: Sanitize X-Vinext-Interception-Context.\n // Null bytes in header values can be used for injection in some HTTP stacks.\n const interceptionContextHeader =\n request.headers.get(VINEXT_INTERCEPTION_CONTEXT_HEADER)?.replaceAll(\"\\0\", \"\") || null;\n\n // Step 9: Normalize mounted-slots header for canonical cache keying.\n const mountedSlotsHeader = normalizeMountedSlotsHeader(\n request.headers.get(VINEXT_MOUNTED_SLOTS_HEADER),\n );\n const renderMode = isRscRequest\n ? parseAppRscRenderMode(request.headers.get(VINEXT_RSC_RENDER_MODE_HEADER))\n : APP_RSC_RENDER_MODE_NAVIGATION;\n const clientReuseManifest = isRscRequest\n ? parseClientReuseManifestHeader(request.headers.get(VINEXT_CLIENT_REUSE_MANIFEST_HEADER))\n : ({ kind: \"absent\" } satisfies ClientReuseManifestParseResult);\n\n return {\n clientReuseManifest,\n url,\n pathname,\n cleanPathname,\n isRscRequest,\n interceptionContextHeader,\n mountedSlotsHeader,\n renderMode,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,SAAgB,oBACd,SACA,UACiC;CACjC,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;CAKhC,MAAM,aAAa,yBAAyB,IAAI,SAAS;CACzD,IAAI,YAAY,OAAO;CAKvB,IAAI;CACJ,IAAI;EACF,UAAU,qCAAqC,IAAI,SAAS;SACtD;EACN,OAAO,oBAAoB;;CAI7B,IAAI,WAAW,cAAc,QAAQ;CAMrC,IAAI,UAAU;EACZ,IAAI,CAAC,YAAY,UAAU,SAAS,IAAI,CAAC,SAAS,WAAW,aAAa,EACxE,OAAO,kBAAkB;EAE3B,WAAW,cAAc,UAAU,SAAS;;CAI9C,MAAM,eAAe,SAAS,SAAS,OAAO;CAC9C,MAAM,gBAAgB,eAAe,SAAS;CAI9C,MAAM,4BACJ,QAAQ,QAAQ,IAAA,gCAAuC,EAAE,WAAW,MAAM,GAAG,IAAI;CAGnF,MAAM,qBAAqB,4BACzB,QAAQ,QAAQ,IAAI,4BAA4B,CACjD;CACD,MAAM,aAAa,eACf,sBAAsB,QAAQ,QAAQ,IAAI,8BAA8B,CAAC,GACzE;CAKJ,OAAO;EACL,qBAL0B,eACxB,+BAA+B,QAAQ,QAAQ,IAAI,oCAAoC,CAAC,GACvF,EAAE,MAAM,UAAU;EAIrB;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
1
+ {"version":3,"file":"app-rsc-request-normalization.js","names":[],"sources":["../../src/server/app-rsc-request-normalization.ts"],"sourcesContent":["import { normalizePath } from \"./normalize-path.js\";\nimport { normalizePathnameForRouteMatchStrict } from \"../routing/utils.js\";\nimport { guardProtocolRelativeUrl } from \"./request-pipeline.js\";\nimport { hasBasePath, stripBasePath } from \"../utils/base-path.js\";\nimport {\n VINEXT_CLIENT_REUSE_MANIFEST_HEADER,\n VINEXT_INTERCEPTION_CONTEXT_HEADER,\n VINEXT_MOUNTED_SLOTS_HEADER,\n VINEXT_RSC_RENDER_MODE_HEADER,\n} from \"./headers.js\";\nimport {\n parseClientReuseManifestHeader,\n type ClientReuseManifestParseResult,\n} from \"./client-reuse-manifest.js\";\nimport { normalizeInterceptionContextHeader } from \"./app-interception-context-header.js\";\nimport { normalizeMountedSlotsHeader } from \"./app-mounted-slots-header.js\";\nimport { stripRscSuffix } from \"./app-rsc-cache-busting.js\";\nimport {\n APP_RSC_RENDER_MODE_NAVIGATION,\n parseAppRscRenderMode,\n type AppRscRenderMode,\n} from \"./app-rsc-render-mode.js\";\nimport { badRequestResponse, notFoundResponse } from \"./http-error-responses.js\";\n\nexport { normalizeMountedSlotsHeader } from \"./app-mounted-slots-header.js\";\n\nexport type NormalizedRscRequest = {\n /** Parsed URL. Callers may mutate `url.search` after middleware runs. */\n url: URL;\n /** Normalized pathname with basePath stripped. Used for all internal routing. */\n pathname: string;\n /** Pathname with `.rsc` suffix removed. Used for route matching and navigation context. */\n cleanPathname: string;\n /** True when the request targets a canonical `.rsc` payload URL. */\n isRscRequest: boolean;\n /** Sanitized X-Vinext-Interception-Context header (null bytes stripped). null when absent. */\n interceptionContextHeader: string | null;\n /** Normalized x-vinext-mounted-slots header (deduplicated, sorted). null when absent or blank. */\n mountedSlotsHeader: string | null;\n /** Semantic RSC payload mode. HTML requests always normalize to \"navigation\". */\n renderMode: AppRscRenderMode;\n /** Disabled ClientReuseManifest hint. Never authorizes skip transport in this stage. */\n clientReuseManifest: ClientReuseManifestParseResult;\n};\n\n/**\n * Normalize an App Router RSC request.\n *\n * Performs all security-sensitive and compatibility-sensitive preprocessing before\n * route matching. The ordering of steps is security-critical — changing it introduces\n * vulnerabilities:\n *\n * 1. Parse URL\n * 2. Protocol-relative URL guard — on the raw pathname, BEFORE normalizePath collapses\n * `//` to `/`. If the guard ran after normalization, `//evil.com` → `/evil.com`\n * would bypass the check and reach the trailing-slash redirector, which echoes the\n * path into a `Location` header that browsers interpret as protocol-relative.\n * 3. Strict percent-decode each segment — throws on malformed sequences (→ 400). Must\n * run before basePath check so %2F-encoded slashes cannot create fake basePath prefixes.\n * 4. Collapse double-slashes, resolve `.` and `..` segments (normalizePath)\n * 5. basePath check + strip — 404 when pathname lacks the basePath prefix.\n * `/__vinext/` bypasses this for internal prerender endpoints.\n * 6. RSC detection: `.rsc` suffix only. RSC headers do not select payload\n * rendering at the canonical HTML URL, so caches that ignore Vary cannot\n * store Flight responses under HTML URLs.\n * 7. cleanPathname — pathname with `.rsc` suffix stripped\n * 8. Sanitize X-Vinext-Interception-Context — strip null bytes (header injection)\n * 9. Normalize x-vinext-mounted-slots — dedup and sort for canonical cache keys\n * 10. Read semantic render mode for refresh/action payload rendering\n * 11. Parse disabled ClientReuseManifest hints on canonical RSC payload requests\n *\n * @returns A 400 or 404 Response for invalid or out-of-scope inputs,\n * or a NormalizedRscRequest for valid requests.\n */\nexport function normalizeRscRequest(\n request: Request,\n basePath: string,\n): Response | NormalizedRscRequest {\n const url = new URL(request.url);\n\n // Step 2: Guard against protocol-relative open redirects on the raw pathname.\n // normalizePath (step 4) would collapse //evil.com to /evil.com, causing the\n // guard to miss it. Raw pathname must be checked first.\n const protoGuard = guardProtocolRelativeUrl(url.pathname);\n if (protoGuard) return protoGuard;\n\n // Step 3: Strict segment-wise percent-decode. Preserves encoded path delimiters\n // (%2F stays %2F) to prevent encoded slashes from acting as path separators.\n // Throws on malformed sequences like %GG — caller must return 400.\n let decoded: string;\n try {\n decoded = normalizePathnameForRouteMatchStrict(url.pathname);\n } catch {\n return badRequestResponse();\n }\n\n // Step 4: Collapse double-slashes and resolve . / .. segments.\n let pathname = normalizePath(decoded);\n\n // Step 5: basePath check and strip.\n // Skipped when basePath is empty (no basePath configured).\n // /__vinext/ prefix bypasses the check for internal prerender endpoints\n // that must be reachable regardless of basePath configuration.\n if (basePath) {\n if (!hasBasePath(pathname, basePath) && !pathname.startsWith(\"/__vinext/\")) {\n return notFoundResponse();\n }\n pathname = stripBasePath(pathname, basePath);\n }\n\n // Steps 6-7: RSC detection and cleanPathname.\n const isRscRequest = pathname.endsWith(\".rsc\");\n const cleanPathname = stripRscSuffix(pathname);\n\n // Step 8: Validate and sanitize X-Vinext-Interception-Context.\n //\n // The legitimate value is always a same-origin URL pathname (`/feed`,\n // `/photos/42`, …) emitted by the vinext browser entry. We strip null bytes\n // (header-injection defense), bound length, and require a pathname-shaped\n // value so an attacker cannot fan out unbounded distinct values into the\n // RSC / optimistic-route cache keys. See SECURITY-AUDIT-2026-05.md F-PROD-1.\n const interceptionContextHeader = normalizeInterceptionContextHeader(\n request.headers.get(VINEXT_INTERCEPTION_CONTEXT_HEADER),\n );\n\n // Step 9: Normalize mounted-slots header for canonical cache keying.\n const mountedSlotsHeader = normalizeMountedSlotsHeader(\n request.headers.get(VINEXT_MOUNTED_SLOTS_HEADER),\n );\n const renderMode = isRscRequest\n ? parseAppRscRenderMode(request.headers.get(VINEXT_RSC_RENDER_MODE_HEADER))\n : APP_RSC_RENDER_MODE_NAVIGATION;\n const clientReuseManifest = isRscRequest\n ? parseClientReuseManifestHeader(request.headers.get(VINEXT_CLIENT_REUSE_MANIFEST_HEADER))\n : ({ kind: \"absent\" } satisfies ClientReuseManifestParseResult);\n\n return {\n clientReuseManifest,\n url,\n pathname,\n cleanPathname,\n isRscRequest,\n interceptionContextHeader,\n mountedSlotsHeader,\n renderMode,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,oBACd,SACA,UACiC;CACjC,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;CAKhC,MAAM,aAAa,yBAAyB,IAAI,SAAS;CACzD,IAAI,YAAY,OAAO;CAKvB,IAAI;CACJ,IAAI;EACF,UAAU,qCAAqC,IAAI,SAAS;SACtD;EACN,OAAO,oBAAoB;;CAI7B,IAAI,WAAW,cAAc,QAAQ;CAMrC,IAAI,UAAU;EACZ,IAAI,CAAC,YAAY,UAAU,SAAS,IAAI,CAAC,SAAS,WAAW,aAAa,EACxE,OAAO,kBAAkB;EAE3B,WAAW,cAAc,UAAU,SAAS;;CAI9C,MAAM,eAAe,SAAS,SAAS,OAAO;CAC9C,MAAM,gBAAgB,eAAe,SAAS;CAS9C,MAAM,4BAA4B,mCAChC,QAAQ,QAAQ,IAAI,mCAAmC,CACxD;CAGD,MAAM,qBAAqB,4BACzB,QAAQ,QAAQ,IAAI,4BAA4B,CACjD;CACD,MAAM,aAAa,eACf,sBAAsB,QAAQ,QAAQ,IAAI,8BAA8B,CAAC,GACzE;CAKJ,OAAO;EACL,qBAL0B,eACxB,+BAA+B,QAAQ,QAAQ,IAAI,oCAAoC,CAAC,GACvF,EAAE,MAAM,UAAU;EAIrB;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}