vinext 1.3.1 → 1.4.0

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 (234) hide show
  1. package/README.md +5 -2
  2. package/THIRD_PARTY_LICENSES.md +47 -0
  3. package/dist/_virtual/_rolldown/runtime.js +3 -2
  4. package/dist/build/prerender.js +1 -1
  5. package/dist/build/report.d.ts +0 -14
  6. package/dist/build/report.js +1 -51
  7. package/dist/check.js +1 -1
  8. package/dist/cli.js +3 -0
  9. package/dist/client/dev-error-overlay.js +1 -1
  10. package/dist/client/navigation-runtime.d.ts +13 -1
  11. package/dist/client/navigation-runtime.js +1 -1
  12. package/dist/config/next-config.d.ts +19 -0
  13. package/dist/config/next-config.js +64 -1
  14. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/dbcs-codec.js +327 -0
  15. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/dbcs-data.js +123 -0
  16. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/index.js +29 -0
  17. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/internal.js +134 -0
  18. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/sbcs-codec.js +50 -0
  19. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/sbcs-data-generated.js +455 -0
  20. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/sbcs-data.js +147 -0
  21. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/big5-added.json.js +169 -0
  22. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/cp936.json.js +2584 -0
  23. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/cp949.json.js +2220 -0
  24. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/cp950.json.js +227 -0
  25. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/eucjp.json.js +425 -0
  26. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/gb18030-ranges.json.js +427 -0
  27. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/gbk-added.json.js +229 -0
  28. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/tables/shiftjis.json.js +292 -0
  29. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/utf16.js +106 -0
  30. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/encodings/utf7.js +182 -0
  31. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/lib/bom-handling.js +42 -0
  32. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/lib/extend-node.js +147 -0
  33. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/lib/index.js +94 -0
  34. package/dist/deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/lib/streams.js +95 -0
  35. package/dist/deps/.pnpm/safer-buffer@2.1.2/deps/safer-buffer/safer.js +45 -0
  36. package/dist/entries/app-rsc-entry.js +17 -48
  37. package/dist/entries/app-rsc-manifest.js +3 -4
  38. package/dist/entries/app-ssr-entry.js +1 -0
  39. package/dist/entries/pages-server-entry.js +33 -8
  40. package/dist/index.js +83 -70
  41. package/dist/init-cloudflare.d.ts +1 -3
  42. package/dist/init-cloudflare.js +10 -48
  43. package/dist/init-platform.d.ts +2 -0
  44. package/dist/init-platform.js +4 -0
  45. package/dist/plugins/extensionless-dynamic-import.js +6 -2
  46. package/dist/plugins/next-intl-catalog.d.ts +12 -0
  47. package/dist/plugins/next-intl-catalog.js +85 -0
  48. package/dist/plugins/pages-node-externals.d.ts +1 -0
  49. package/dist/plugins/pages-node-externals.js +1 -1
  50. package/dist/plugins/use-cache-callable.d.ts +1 -1
  51. package/dist/plugins/use-cache-callable.js +136 -94
  52. package/dist/routing/app-route-graph.d.ts +6 -0
  53. package/dist/routing/app-route-graph.js +9 -1
  54. package/dist/server/api-handler.js +19 -4
  55. package/dist/server/app-bfcache-identity.js +1 -1
  56. package/dist/server/app-browser-entry.js +79 -63
  57. package/dist/server/app-browser-history-controller.d.ts +5 -4
  58. package/dist/server/app-browser-history-controller.js +93 -15
  59. package/dist/server/app-browser-navigation-controller.d.ts +2 -2
  60. package/dist/server/app-browser-navigation-controller.js +1 -2
  61. package/dist/server/app-browser-rsc-redirect.js +4 -4
  62. package/dist/server/app-browser-server-action-client.d.ts +2 -0
  63. package/dist/server/app-browser-server-action-client.js +4 -3
  64. package/dist/server/app-browser-state.d.ts +2 -4
  65. package/dist/server/app-browser-state.js +9 -4
  66. package/dist/server/app-browser-supplemental-refresh.js +16 -1
  67. package/dist/server/app-browser-visible-commit.d.ts +1 -1
  68. package/dist/server/app-browser-visible-commit.js +2 -12
  69. package/dist/server/app-elements-wire.d.ts +6 -38
  70. package/dist/server/app-elements-wire.js +4 -41
  71. package/dist/server/app-elements.d.ts +2 -2
  72. package/dist/server/app-elements.js +2 -2
  73. package/dist/server/app-history-state.d.ts +2 -2
  74. package/dist/server/app-history-state.js +5 -2
  75. package/dist/server/app-mounted-layouts.d.ts +21 -0
  76. package/dist/server/app-mounted-layouts.js +67 -0
  77. package/dist/server/app-optimistic-routing.d.ts +19 -1
  78. package/dist/server/app-optimistic-routing.js +42 -2
  79. package/dist/server/app-page-boundary-render.js +7 -6
  80. package/dist/server/app-page-boundary.js +2 -2
  81. package/dist/server/app-page-cache-finalizer.d.ts +12 -1
  82. package/dist/server/app-page-cache-finalizer.js +70 -29
  83. package/dist/server/app-page-cache.d.ts +13 -1
  84. package/dist/server/app-page-cache.js +31 -9
  85. package/dist/server/app-page-dispatch.d.ts +5 -10
  86. package/dist/server/app-page-dispatch.js +84 -154
  87. package/dist/server/app-page-element-builder.d.ts +2 -2
  88. package/dist/server/app-page-element-builder.js +10 -9
  89. package/dist/server/app-page-execution.d.ts +17 -52
  90. package/dist/server/app-page-execution.js +99 -95
  91. package/dist/server/app-page-head.d.ts +13 -0
  92. package/dist/server/app-page-head.js +44 -16
  93. package/dist/server/app-page-http-access-fallback-metadata.d.ts +1 -0
  94. package/dist/server/app-page-http-access-fallback-metadata.js +2 -2
  95. package/dist/server/app-page-layout-gate.d.ts +35 -0
  96. package/dist/server/app-page-layout-gate.js +50 -0
  97. package/dist/server/app-page-params.d.ts +0 -1
  98. package/dist/server/app-page-params.js +1 -14
  99. package/dist/server/app-page-probe.d.ts +3 -21
  100. package/dist/server/app-page-probe.js +4 -37
  101. package/dist/server/app-page-render.d.ts +2 -12
  102. package/dist/server/app-page-render.js +89 -220
  103. package/dist/server/app-page-request.d.ts +1 -3
  104. package/dist/server/app-page-request.js +1 -1
  105. package/dist/server/app-page-response.js +3 -3
  106. package/dist/server/app-page-route-wiring.d.ts +13 -6
  107. package/dist/server/app-page-route-wiring.js +67 -61
  108. package/dist/server/app-page-rsc-render-status.d.ts +27 -1
  109. package/dist/server/app-page-rsc-render-status.js +121 -13
  110. package/dist/server/app-page-stream.d.ts +2 -0
  111. package/dist/server/app-page-stream.js +2 -2
  112. package/dist/server/app-pages-bridge.d.ts +4 -0
  113. package/dist/server/app-pages-bridge.js +7 -3
  114. package/dist/server/app-render-dependency.d.ts +11 -4
  115. package/dist/server/app-render-dependency.js +86 -38
  116. package/dist/server/app-request-stage-dispatch.js +1 -1
  117. package/dist/server/app-route-handler-cache.js +2 -2
  118. package/dist/server/app-route-handler-dispatch.js +14 -9
  119. package/dist/server/app-route-handler-execution.js +8 -3
  120. package/dist/server/app-route-handler-policy.d.ts +1 -1
  121. package/dist/server/app-route-handler-policy.js +3 -3
  122. package/dist/server/app-route-handler-response.js +1 -1
  123. package/dist/server/app-route-handler-runtime.js +17 -4
  124. package/dist/server/app-rsc-cache-busting.d.ts +2 -2
  125. package/dist/server/app-rsc-cache-busting.js +4 -4
  126. package/dist/server/app-rsc-error-handler.d.ts +2 -1
  127. package/dist/server/app-rsc-error-handler.js +9 -1
  128. package/dist/server/app-rsc-errors.d.ts +8 -0
  129. package/dist/server/app-rsc-errors.js +8 -1
  130. package/dist/server/app-rsc-handler.d.ts +5 -5
  131. package/dist/server/app-rsc-handler.js +30 -24
  132. package/dist/server/app-rsc-request-normalization.d.ts +0 -4
  133. package/dist/server/app-rsc-request-normalization.js +1 -4
  134. package/dist/server/app-rsc-response-finalizer.js +2 -2
  135. package/dist/server/app-rsc-response-stage.js +5 -3
  136. package/dist/server/app-server-action-execution.d.ts +3 -1
  137. package/dist/server/app-server-action-execution.js +7 -4
  138. package/dist/server/app-ssr-entry.d.ts +2 -0
  139. package/dist/server/app-ssr-entry.js +9 -8
  140. package/dist/server/app-ssr-stream.js +1 -1
  141. package/dist/server/app-visited-response-cache.d.ts +36 -1
  142. package/dist/server/app-visited-response-cache.js +46 -5
  143. package/dist/server/app-worker-stages.d.ts +25 -3
  144. package/dist/server/app-worker-stages.js +45 -6
  145. package/dist/server/artifact-compatibility.d.ts +0 -1
  146. package/dist/server/artifact-compatibility.js +1 -10
  147. package/dist/server/cache-proof.d.ts +1 -115
  148. package/dist/server/cache-proof.js +1 -544
  149. package/dist/server/cacheability-request.js +13 -8
  150. package/dist/server/dev-server.js +4 -3
  151. package/dist/server/headers.d.ts +6 -3
  152. package/dist/server/headers.js +9 -5
  153. package/dist/server/isr-cache.d.ts +8 -2
  154. package/dist/server/isr-cache.js +26 -1
  155. package/dist/server/metadata-route-response.js +32 -15
  156. package/dist/server/multi-stage.d.ts +52 -11
  157. package/dist/server/multi-stage.js +13 -1
  158. package/dist/server/navigation-planner.js +1 -1
  159. package/dist/server/pages-api-route.js +28 -19
  160. package/dist/server/pages-media-type.d.ts +21 -1
  161. package/dist/server/pages-media-type.js +69 -5
  162. package/dist/server/pages-node-compat.js +52 -27
  163. package/dist/server/pages-page-handler.js +11 -20
  164. package/dist/server/pages-request-pipeline.d.ts +8 -0
  165. package/dist/server/pages-request-pipeline.js +2 -2
  166. package/dist/server/pages-request-stage-entry.js +14 -12
  167. package/dist/server/pages-response-stage-entry.js +9 -3
  168. package/dist/server/prod-server.js +5 -1
  169. package/dist/server/request-pipeline.d.ts +6 -0
  170. package/dist/server/request-pipeline.js +21 -1
  171. package/dist/server/shared-cache-identity.d.ts +23 -0
  172. package/dist/server/shared-cache-identity.js +36 -0
  173. package/dist/server/worker-stages.d.ts +16 -3
  174. package/dist/server/worker-stages.js +23 -4
  175. package/dist/shims/cache-handler.js +2 -2
  176. package/dist/shims/cache-request-state.d.ts +17 -20
  177. package/dist/shims/cache-request-state.js +16 -21
  178. package/dist/shims/cache-runtime.js +27 -11
  179. package/dist/shims/cache.d.ts +8 -7
  180. package/dist/shims/cache.js +17 -19
  181. package/dist/shims/cacheability-classification.d.ts +2 -0
  182. package/dist/shims/cdn-cache.d.ts +22 -5
  183. package/dist/shims/client-page-root.js +2 -2
  184. package/dist/shims/dynamic.js +9 -6
  185. package/dist/shims/error-boundary.js +2 -2
  186. package/dist/shims/fetch-cache-state.d.ts +5 -1
  187. package/dist/shims/fetch-cache-state.js +1 -3
  188. package/dist/shims/fetch-cache.d.ts +2 -1
  189. package/dist/shims/fetch-cache.js +34 -24
  190. package/dist/shims/form.js +2 -2
  191. package/dist/shims/headers.d.ts +8 -23
  192. package/dist/shims/headers.js +17 -67
  193. package/dist/shims/internal/navigation-untracked.js +1 -1
  194. package/dist/shims/link.js +3 -1
  195. package/dist/shims/metadata.d.ts +23 -21
  196. package/dist/shims/metadata.js +62 -24
  197. package/dist/shims/navigation-server.js +1 -1
  198. package/dist/shims/navigation.d.ts +74 -7
  199. package/dist/shims/navigation.js +183 -29
  200. package/dist/shims/navigation.react-server.js +2 -2
  201. package/dist/shims/request-state-types.d.ts +2 -2
  202. package/dist/shims/slot.d.ts +12 -0
  203. package/dist/shims/slot.js +37 -9
  204. package/dist/shims/unified-request-context.d.ts +1 -1
  205. package/dist/shims/unified-request-context.js +2 -3
  206. package/dist/utils/cache-control-metadata.d.ts +5 -0
  207. package/dist/utils/cache-control-metadata.js +9 -1
  208. package/dist/utils/project.d.ts +2 -2
  209. package/dist/utils/project.js +3 -16
  210. package/dist/utils/regex.d.ts +5 -0
  211. package/dist/utils/regex.js +11 -1
  212. package/dist/utils/text-stream.d.ts +10 -5
  213. package/dist/utils/text-stream.js +6 -6
  214. package/package.json +2 -1
  215. package/dist/build/layout-classification-types.d.ts +0 -60
  216. package/dist/build/layout-classification-types.js +0 -1
  217. package/dist/build/layout-classification.d.ts +0 -62
  218. package/dist/build/layout-classification.js +0 -98
  219. package/dist/build/route-classification-injector.d.ts +0 -33
  220. package/dist/build/route-classification-injector.js +0 -59
  221. package/dist/build/route-classification-manifest.d.ts +0 -54
  222. package/dist/build/route-classification-manifest.js +0 -143
  223. package/dist/server/app-browser-client-reuse-manifest.d.ts +0 -11
  224. package/dist/server/app-browser-client-reuse-manifest.js +0 -101
  225. package/dist/server/app-layout-param-observation.d.ts +0 -42
  226. package/dist/server/app-layout-param-observation.js +0 -168
  227. package/dist/server/client-reuse-manifest.d.ts +0 -103
  228. package/dist/server/client-reuse-manifest.js +0 -209
  229. package/dist/server/skip-cache-proof.d.ts +0 -60
  230. package/dist/server/skip-cache-proof.js +0 -168
  231. package/dist/server/static-layout-client-reuse-proof.d.ts +0 -14
  232. package/dist/server/static-layout-client-reuse-proof.js +0 -33
  233. package/dist/utils/sorted-array.d.ts +0 -8
  234. package/dist/utils/sorted-array.js +0 -20
@@ -17,7 +17,7 @@ const VINEXT_CACHE_HEADER = "X-Vinext-Cache";
17
17
  const NEXTJS_CACHE_HEADER = "x-nextjs-cache";
18
18
  /** Next.js cache-tag metadata carried by prerendered App Router responses. */
19
19
  const NEXT_CACHE_TAGS_HEADER = "x-next-cache-tags";
20
- /** Timing metrics: `handlerStart,compileMs,renderMs`. */
20
+ /** Timing metrics: `handlerStart,compileMs,renderMs` (handlerStart is wall-clock ms). */
21
21
  const VINEXT_TIMING_HEADER = "x-vinext-timing";
22
22
  /** Matched route returned from an independently hosted response stage. */
23
23
  const VINEXT_TRACE_ROUTE_HEADER = "X-Vinext-Trace-Route";
@@ -85,8 +85,11 @@ const VINEXT_PRERENDER_RENDER_ERROR_HEADER = "x-vinext-prerender-render-error";
85
85
  const VINEXT_PRERENDER_SPECIAL_ERROR_HEADER = "x-vinext-prerender-special-error";
86
86
  /** Internal marker persisted only inside metadata-route APP_ROUTE cache values. */
87
87
  const VINEXT_METADATA_ROUTE_CACHE_HEADER = "x-vinext-metadata-route-cache";
88
- /** Disabled-by-default client hint describing already-held App Router payload entries. */
89
- const VINEXT_CLIENT_REUSE_MANIFEST_HEADER = "X-Vinext-Client-Reuse-Manifest";
88
+ /**
89
+ * Hashed identities of the layouts a client navigation already holds, so a
90
+ * render that's never stored can leave them out. Not part of the RSC cache key.
91
+ */
92
+ const VINEXT_MOUNTED_LAYOUTS_HEADER = "X-Vinext-Mounted-Layouts";
90
93
  /**
91
94
  * Side-channel signal that an RSC response (HTTP 200) encodes a `redirect()`
92
95
  * thrown during render. The header value is the redirect target (path-only
@@ -152,7 +155,8 @@ const FLIGHT_HEADERS = [
152
155
  "next-router-prefetch",
153
156
  "next-hmr-refresh",
154
157
  "next-router-segment-prefetch",
155
- "x-vinext-rsc-state-fingerprint"
158
+ "x-vinext-rsc-state-fingerprint",
159
+ "x-vinext-mounted-layouts"
156
160
  ];
157
161
  /**
158
162
  * Headers that must be stripped from external requests before any handler
@@ -192,4 +196,4 @@ const VINEXT_INTERNAL_HEADERS = [
192
196
  VINEXT_TRACE_ROUTE_HEADER.toLowerCase()
193
197
  ];
194
198
  //#endregion
195
- export { ACTION_FORWARDED_HEADER, ACTION_REDIRECT_HEADER, ACTION_REDIRECT_STATUS_HEADER, ACTION_REDIRECT_TYPE_HEADER, ACTION_REVALIDATED_HEADER, FLIGHT_HEADERS, INTERNAL_HEADERS, MIDDLEWARE_HEADER_PREFIX, MIDDLEWARE_NEXT_HEADER, MIDDLEWARE_REWRITE_HEADER, MIDDLEWARE_SET_COOKIE_HEADER, MIDDLEWARE_SKIP_HEADER, NEXTJS_ACTION_NOT_FOUND_HEADER, NEXTJS_CACHE_HEADER, NEXTJS_DEPLOYMENT_ID_HEADER, NEXT_ACTION_HEADER, NEXT_CACHE_TAGS_HEADER, NEXT_HTML_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER, NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_STALE_TIME_HEADER, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_URL_HEADER, RSC_ACTION_HEADER, RSC_HEADER, VINEXT_CACHEABILITY_PROBE_HEADER, VINEXT_CACHEABILITY_PROBE_QUERY_PARAM, VINEXT_CACHEABILITY_PROBE_ROUTE_HEADER, VINEXT_CACHE_HEADER, VINEXT_CLIENT_REUSE_MANIFEST_HEADER, VINEXT_DYNAMIC_STALE_TIME_HEADER, VINEXT_EXPECTED_WORKER_VERSION_HEADER, VINEXT_INTERCEPTION_CONTEXT_HEADER, VINEXT_INTERCEPTION_ID_HEADER, VINEXT_INTERNAL_HEADERS, VINEXT_METADATA_ROUTE_CACHE_HEADER, VINEXT_MOUNTED_SLOTS_HEADER, VINEXT_MW_CTX_HEADER, VINEXT_PARAMS_HEADER, VINEXT_PRERENDER_CACHE_LIFE_HEADER, VINEXT_PRERENDER_METADATA_ROUTES_PATH, VINEXT_PRERENDER_PAGES_STATIC_PATHS_PATH, VINEXT_PRERENDER_READINESS_HEADER, VINEXT_PRERENDER_READINESS_PATH, VINEXT_PRERENDER_RENDER_ERROR_HEADER, VINEXT_PRERENDER_REWRITTEN_HEADER, VINEXT_PRERENDER_ROUTE_PARAMS_HEADER, VINEXT_PRERENDER_SECRET_HEADER, VINEXT_PRERENDER_SPECIAL_ERROR_HEADER, VINEXT_PRERENDER_SPECULATIVE_HEADER, VINEXT_PRERENDER_STATIC_PARAMS_PATH, VINEXT_RENDERED_PATH_AND_SEARCH_HEADER, VINEXT_REVALIDATED_CACHE_TAG_HEADER, VINEXT_REVALIDATE_HEADER, VINEXT_REVALIDATE_HOST_HEADER, VINEXT_RSC_COMPLETION_METADATA_HEADER, VINEXT_RSC_MARKER_HEADER, VINEXT_RSC_REDIRECT_HEADER, VINEXT_RSC_REDIRECT_TYPE_HEADER, VINEXT_RSC_RENDER_MODE_HEADER, VINEXT_RSC_STATE_FINGERPRINT_HEADER, VINEXT_RSC_VARY_HEADER, VINEXT_SPECIAL_ERROR_STATUS_HEADER, VINEXT_STALE_TIME_PENDING_HEADER, VINEXT_TIMING_HEADER, VINEXT_TRACE_BUFFERED_BODY_HEADER, VINEXT_TRACE_ERROR_HEADER, VINEXT_TRACE_ROUTE_HEADER, isVinextRscVaryField };
199
+ export { ACTION_FORWARDED_HEADER, ACTION_REDIRECT_HEADER, ACTION_REDIRECT_STATUS_HEADER, ACTION_REDIRECT_TYPE_HEADER, ACTION_REVALIDATED_HEADER, FLIGHT_HEADERS, INTERNAL_HEADERS, MIDDLEWARE_HEADER_PREFIX, MIDDLEWARE_NEXT_HEADER, MIDDLEWARE_REWRITE_HEADER, MIDDLEWARE_SET_COOKIE_HEADER, MIDDLEWARE_SKIP_HEADER, NEXTJS_ACTION_NOT_FOUND_HEADER, NEXTJS_CACHE_HEADER, NEXTJS_DEPLOYMENT_ID_HEADER, NEXT_ACTION_HEADER, NEXT_CACHE_TAGS_HEADER, NEXT_HTML_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER, NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_STALE_TIME_HEADER, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_URL_HEADER, RSC_ACTION_HEADER, RSC_HEADER, VINEXT_CACHEABILITY_PROBE_HEADER, VINEXT_CACHEABILITY_PROBE_QUERY_PARAM, VINEXT_CACHEABILITY_PROBE_ROUTE_HEADER, VINEXT_CACHE_HEADER, VINEXT_DYNAMIC_STALE_TIME_HEADER, VINEXT_EXPECTED_WORKER_VERSION_HEADER, VINEXT_INTERCEPTION_CONTEXT_HEADER, VINEXT_INTERCEPTION_ID_HEADER, VINEXT_INTERNAL_HEADERS, VINEXT_METADATA_ROUTE_CACHE_HEADER, VINEXT_MOUNTED_LAYOUTS_HEADER, VINEXT_MOUNTED_SLOTS_HEADER, VINEXT_MW_CTX_HEADER, VINEXT_PARAMS_HEADER, VINEXT_PRERENDER_CACHE_LIFE_HEADER, VINEXT_PRERENDER_METADATA_ROUTES_PATH, VINEXT_PRERENDER_PAGES_STATIC_PATHS_PATH, VINEXT_PRERENDER_READINESS_HEADER, VINEXT_PRERENDER_READINESS_PATH, VINEXT_PRERENDER_RENDER_ERROR_HEADER, VINEXT_PRERENDER_REWRITTEN_HEADER, VINEXT_PRERENDER_ROUTE_PARAMS_HEADER, VINEXT_PRERENDER_SECRET_HEADER, VINEXT_PRERENDER_SPECIAL_ERROR_HEADER, VINEXT_PRERENDER_SPECULATIVE_HEADER, VINEXT_PRERENDER_STATIC_PARAMS_PATH, VINEXT_RENDERED_PATH_AND_SEARCH_HEADER, VINEXT_REVALIDATED_CACHE_TAG_HEADER, VINEXT_REVALIDATE_HEADER, VINEXT_REVALIDATE_HOST_HEADER, VINEXT_RSC_COMPLETION_METADATA_HEADER, VINEXT_RSC_MARKER_HEADER, VINEXT_RSC_REDIRECT_HEADER, VINEXT_RSC_REDIRECT_TYPE_HEADER, VINEXT_RSC_RENDER_MODE_HEADER, VINEXT_RSC_STATE_FINGERPRINT_HEADER, VINEXT_RSC_VARY_HEADER, VINEXT_SPECIAL_ERROR_STATUS_HEADER, VINEXT_STALE_TIME_PENDING_HEADER, VINEXT_TIMING_HEADER, VINEXT_TRACE_BUFFERED_BODY_HEADER, VINEXT_TRACE_ERROR_HEADER, VINEXT_TRACE_ROUTE_HEADER, isVinextRscVaryField };
@@ -1,7 +1,7 @@
1
- import { OnRequestErrorContext } from "./instrumentation.js";
2
- import { PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER } from "../utils/protocol-headers.js";
3
1
  import { RenderObservation } from "./cache-proof.js";
4
2
  import { AppRscRenderMode } from "./app-rsc-render-mode.js";
3
+ import { OnRequestErrorContext } from "./instrumentation.js";
4
+ import { PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER } from "../utils/protocol-headers.js";
5
5
  import { normalizeMountedSlotsHeader } from "./app-mounted-slots-header.js";
6
6
  import { CacheControlMetadata, CacheHandlerValue, CachedAppPageValue, CachedPagesValue, IncrementalCacheValue } from "../shims/cache-handler.js";
7
7
  import { getRevalidateSecret, isOnDemandRevalidateRequest, isRevalidateSecret } from "./revalidation-request.js";
@@ -68,6 +68,12 @@ export declare function isrSetPrerenderedAppPage(key: string, data: CachedAppPag
68
68
  }): Promise<void>;
69
69
  /** Coalesce same-key synchronous on-demand revalidations. */
70
70
  export declare function coalesceOnDemandRevalidation<T>(key: string, renderFn: () => Promise<T>): Promise<T>;
71
+ /**
72
+ * Coalesce same-key on-demand revalidations whose render answers with a
73
+ * Response, or null for no match. Every caller gets its own copy of the one
74
+ * render's response. `method` is the request method the response answers.
75
+ */
76
+ export declare function coalesceOnDemandResponse<R extends Response | null>(key: string, method: string, renderFn: () => Promise<R>): Promise<R>;
71
77
  /**
72
78
  * Trigger a background regeneration for a cache key.
73
79
  *
@@ -101,6 +101,31 @@ function coalesceOnDemandRevalidation(key, renderFn) {
101
101
  return promise;
102
102
  }
103
103
  /**
104
+ * Coalesce same-key on-demand revalidations whose render answers with a
105
+ * Response, or null for no match. Every caller gets its own copy of the one
106
+ * render's response. `method` is the request method the response answers.
107
+ */
108
+ async function coalesceOnDemandResponse(key, method, renderFn) {
109
+ const snapshot = await coalesceOnDemandRevalidation(key, async () => {
110
+ const response = await renderFn();
111
+ if (!response) return null;
112
+ const hasBody = method !== "HEAD" && response.status !== 204 && response.status !== 205 && response.status !== 304;
113
+ if (!hasBody) await response.body?.cancel();
114
+ return {
115
+ body: hasBody ? new Uint8Array(await response.arrayBuffer()) : null,
116
+ headers: [...response.headers.entries()],
117
+ status: response.status,
118
+ statusText: response.statusText
119
+ };
120
+ });
121
+ if (!snapshot) return null;
122
+ return new Response(snapshot.body?.slice() ?? null, {
123
+ headers: snapshot.headers,
124
+ status: snapshot.status,
125
+ statusText: snapshot.statusText
126
+ });
127
+ }
128
+ /**
104
129
  * Trigger a background regeneration for a cache key.
105
130
  *
106
131
  * If a regeneration for this key is already in progress, this is a no-op.
@@ -247,4 +272,4 @@ function appIsrRouteKey(pathname) {
247
272
  return appIsrCacheKey(pathname, pathname !== "/" && pathname.endsWith("/") ? "route:trailing-slash" : "route");
248
273
  }
249
274
  //#endregion
250
- export { PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER, appIsrCacheKey, appIsrFallbackShellHtmlKey, appIsrFallbackShellKey, appIsrHtmlKey, appIsrRouteKey, appIsrRscKey, buildAppPageCacheValue, buildPagesCacheValue, coalesceOnDemandRevalidation, getRevalidateSecret, isOnDemandRevalidateRequest, isRevalidateSecret, isrCacheControl, isrCacheKey, isrGet, isrSet, isrSetPrerenderedAppPage, normalizeMountedSlotsHeader, pagesIsrCacheKey, resolveRouteExpireSeconds, triggerBackgroundRegeneration };
275
+ export { PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER, appIsrCacheKey, appIsrFallbackShellHtmlKey, appIsrFallbackShellKey, appIsrHtmlKey, appIsrRouteKey, appIsrRscKey, buildAppPageCacheValue, buildPagesCacheValue, coalesceOnDemandResponse, coalesceOnDemandRevalidation, getRevalidateSecret, isOnDemandRevalidateRequest, isRevalidateSecret, isrCacheControl, isrCacheKey, isrGet, isrSet, isrSetPrerenderedAppPage, normalizeMountedSlotsHeader, pagesIsrCacheKey, resolveRouteExpireSeconds, triggerBackgroundRegeneration };
@@ -8,16 +8,16 @@ import { runInWorkStoreScope } from "../shims/internal/work-store-scope.js";
8
8
  import { beginRouteCacheability, markRouteCacheabilityExplicitResponsePolicy, markRouteCacheabilityResponseBodyComplete, recordRouteCacheability } from "../shims/cacheability-classification.js";
9
9
  import { NEVER_CACHE_CONTROL, applyCdnResponseHeaders, hasCdnResponsePolicy } from "./cache-control.js";
10
10
  import { buildAppRouteMissIsrCacheControl } from "./isr-decision.js";
11
- import { isrCacheControl } from "./isr-cache.js";
11
+ import { coalesceOnDemandResponse, isrCacheControl } from "./isr-cache.js";
12
12
  import { resolveClientStaleTimeSeconds } from "../utils/cache-control-metadata.js";
13
13
  import { isRenderDynamicLatched } from "../shims/internal/headers-state.js";
14
14
  import { getActiveDraftModeState, getHeadersContext, hasDraftModeCookieHeader, replaceHeadersContext } from "../shims/headers.js";
15
- import { _consumeRequestScopedCacheLife } from "../shims/cache-request-state.js";
15
+ import { _consumeRequestScopedCacheLife, _isOnDemandRevalidate } from "../shims/cache-request-state.js";
16
16
  import { ensureFetchPatch, getCollectedFetchTags, setCurrentFetchSoftTags } from "../shims/fetch-cache.js";
17
17
  import { isValidMetadataImageId, manifestToJson, matchMetadataRoutePattern, robotsToText, sitemapToXml } from "./metadata-routes.js";
18
- import { applyPrerenderCacheLifeHeader, applyPrerenderCacheTagsHeader } from "./prerender-cache-life-header.js";
19
- import { canonicalizeAppPageParams } from "./app-page-segment-state.js";
20
18
  import { buildAppRouteCacheValue, buildRouteHandlerCachedResponse } from "./app-route-handler-response.js";
19
+ import { canonicalizeAppPageParams } from "./app-page-segment-state.js";
20
+ import { applyPrerenderCacheLifeHeader, applyPrerenderCacheTagsHeader } from "./prerender-cache-life-header.js";
21
21
  import { buildPageCacheTags } from "./implicit-tags.js";
22
22
  import { createStaticGenerationHeadersContext } from "./app-static-generation.js";
23
23
  import { completeAppRouteHandlerResponse } from "./app-route-handler-execution.js";
@@ -165,7 +165,7 @@ async function captureRenderedMetadataRoute(response, route, cleanPathname) {
165
165
  ...observedCacheLife,
166
166
  revalidate: frameworkRevalidate
167
167
  };
168
- const cacheable = (response.status < 400 || response.status === 404) && completed && !isRenderDynamicLatched() && !getActiveDraftModeState() && !hasDraftModeCookieHeader() && route.module?.dynamic !== "force-dynamic" && frameworkRevalidate > 0 && !response.headers.has("set-cookie");
168
+ const cacheable = (_isOnDemandRevalidate() || response.status < 400 || response.status === 404) && completed && !isRenderDynamicLatched() && !getActiveDraftModeState() && !hasDraftModeCookieHeader() && route.module?.dynamic !== "force-dynamic" && frameworkRevalidate > 0 && !response.headers.has("set-cookie");
169
169
  const cacheControl = cacheable ? buildAppRouteMissIsrCacheControl(frameworkRevalidate, cacheLife?.expire) : NEVER_CACHE_CONTROL;
170
170
  if (isUserResponse && !hasUserPolicy) {
171
171
  response = new Response(response.body, {
@@ -231,12 +231,34 @@ async function runMetadataRouteRegeneration(options, route, render, routeKey, pr
231
231
  await closeAfterResponse(requestContext);
232
232
  }
233
233
  }
234
+ /** The outer ISR key for a matched metadata route, or null if it's never cached. */
235
+ function getOuterMetadataCacheKey(options, route) {
236
+ if (!isOuterMetadataCacheEnabled() || !options.isrRouteKey || getActiveDraftModeState() || hasDraftModeCookieHeader() || route.module?.dynamic === "force-dynamic" || route.module?.revalidate === 0) return null;
237
+ return options.isrRouteKey(options.cleanPathname);
238
+ }
239
+ /**
240
+ * Renders a matched metadata route that wasn't served from the cache, and
241
+ * stores it. Concurrent on-demand revalidations of one entry share a single
242
+ * render, as Next.js batches ResponseCache work by its key and
243
+ * isOnDemandRevalidate.
244
+ */
245
+ async function renderMetadataRouteMiss(options, route, render, cachedEntry) {
246
+ const renderAndStore = async () => {
247
+ const rendered = await render();
248
+ if (!rendered) return null;
249
+ await writeMetadataRouteMiss(options, route, rendered, cachedEntry);
250
+ return rendered.response;
251
+ };
252
+ const routeKey = _isOnDemandRevalidate() ? getOuterMetadataCacheKey(options, route) : null;
253
+ if (routeKey === null || !options.isrSet) return renderAndStore();
254
+ return coalesceOnDemandResponse(routeKey, "GET", renderAndStore);
255
+ }
234
256
  async function readMatchedPrerenderedMetadataRouteResponse(options, route, render) {
235
- if (!isOuterMetadataCacheEnabled() || !options.isrGet || !options.isrRouteKey || getActiveDraftModeState() || hasDraftModeCookieHeader() || route.module?.dynamic === "force-dynamic" || route.module?.revalidate === 0) return {
257
+ const routeKey = getOuterMetadataCacheKey(options, route);
258
+ if (routeKey === null || !options.isrGet || _isOnDemandRevalidate()) return {
236
259
  cachedEntry: null,
237
260
  response: null
238
261
  };
239
- const routeKey = options.isrRouteKey(options.cleanPathname);
240
262
  let cached;
241
263
  try {
242
264
  cached = await options.isrGet(routeKey);
@@ -495,11 +517,8 @@ async function handleMetadataRouteRequest(options) {
495
517
  };
496
518
  const cached = await readMatchedPrerenderedMetadataRouteResponse(options, route, render);
497
519
  if (cached.response) return cached.response;
498
- const rendered = await render();
499
- if (rendered) {
500
- await writeMetadataRouteMiss(options, route, rendered, cached.cachedEntry);
501
- return rendered.response;
502
- }
520
+ const response = await renderMetadataRouteMiss(options, route, render, cached.cachedEntry);
521
+ if (response) return response;
503
522
  }
504
523
  continue;
505
524
  }
@@ -533,9 +552,7 @@ async function handleMetadataRouteRequest(options) {
533
552
  });
534
553
  if (dynamicParamsResponse) return dynamicParamsResponse;
535
554
  }
536
- const rendered = await render();
537
- await writeMetadataRouteMiss(options, route, rendered, cached.cachedEntry);
538
- return rendered.response;
555
+ return renderMetadataRouteMiss(options, route, render, cached.cachedEntry);
539
556
  }
540
557
  return null;
541
558
  }
@@ -1,5 +1,14 @@
1
1
  import { CacheabilityRepresentation } from "./cacheability-manifest.js";
2
2
  //#region src/server/multi-stage.d.ts
3
+ /**
4
+ * The origin a shared cache identity names in place of the request's. Next.js
5
+ * keys its response cache by pathname, so one stored response answers every
6
+ * host an app serves. `.invalid` never resolves, so no configured domain or
7
+ * host condition can match it when the identity is replayed.
8
+ */
9
+ export declare const VINEXT_CACHE_IDENTITY_ORIGIN = "https://cache-identity.vinext.invalid";
10
+ /** Name `origin` in place of a dispatch URL's origin in a shared cache identity. */
11
+ export declare function withCacheIdentityOrigin(requestUrl: string, origin?: string): string;
3
12
  /** Whether a response-stage cache must reject a field it did not key itself by. */
4
13
  export declare function hasUnsupportedResponseStageVary(headers: Headers, keyedRequestHeaders?: Iterable<string>): boolean;
5
14
  /**
@@ -41,26 +50,58 @@ export type VinextResponseStageDispatchOptions = {
41
50
  */
42
51
  regeneratesStoredEntry?: boolean;
43
52
  /**
44
- * Query-free identity of a shared App page GET/HEAD dispatch, supplied only
45
- * to adapters that declare `responseStageCacheIdentity: "query-free"` and
46
- * require completed-response admission. A transport given one partitions
53
+ * Shared cache identity of an App Router GET/HEAD dispatch, or of a Pages
54
+ * page the build found static (getStaticProps or none), supplied only to
55
+ * adapters that declare a `responseStageCacheIdentity` and require
56
+ * completed-response admission. A transport given one partitions
47
57
  * its baseline lookup and stored entry by this request's method and complete
48
58
  * URL plus these complete serialized props, instead of the dispatched request
49
- * and props, and replays this identity for background regeneration.
59
+ * and props, and replays this identity for background regeneration, or the
60
+ * dispatched request and props when `regenerateFromDispatch` is set.
50
61
  * Everything else in the contract above still applies.
51
62
  *
52
- * The identity drops the user query from the URL and `resolvedUrl`, keeping
63
+ * The identity names `VINEXT_CACHE_IDENTITY_ORIGIN` in place of the
64
+ * request's origin, in its URL and its `requestOrigin`, so one stored
65
+ * response answers every host, as Next.js's pathname-keyed response cache
66
+ * does. That is safe only because completed-response admission refuses a
67
+ * response whose render used a dynamic API, which every App Router read of
68
+ * the request's host is. Core omits the identity for bypassed dispatches.
69
+ *
70
+ * A Pages page identity instead names the configured i18n domain the
71
+ * request's host selects, as vinext's Pages ISR key keeps the domain, and
72
+ * the cache identity origin for every other host. A page without
73
+ * getStaticProps whose page or `_app` getInitialProps turns out to run is
74
+ * refused admission, because its props say the entry is shared across
75
+ * hosts. A getStaticProps page's `_app` getInitialProps shares its entry,
76
+ * as in Next.js, which keys it by path.
77
+ *
78
+ * Under `responseStageCacheIdentity: "query-free"`, an App page identity
79
+ * also drops the user query from the URL and `resolvedUrl`, keeping
53
80
  * framework representation selectors: the `.rsc` suffix, the render mode,
54
- * and, for RSC requests only, the one validated `_rsc` value. That is safe only because completed-response
55
- * admission refuses a cacheable App page response unless its render proved
56
- * it never read `searchParams`. The dispatched request still carries the real
57
- * query for the render itself. Core omits the identity when a `next.config`
58
- * public cache policy applies (cached per full URL, as Next.js CDN caching
59
- * is), and for bypassed, interception, and mounted-slot dispatches.
81
+ * and, for RSC requests only, the one validated `_rsc` value. That is safe
82
+ * only because completed-response admission refuses a cacheable App page
83
+ * response unless its render proved it never read `searchParams`. The
84
+ * dispatched request still carries the real query for the render itself. A
85
+ * page identity keeps the query when a `next.config` public cache policy
86
+ * applies (cached per full URL, as Next.js CDN caching is), and for
87
+ * interception and mounted-slot dispatches.
60
88
  */
61
89
  cacheIdentity?: {
62
90
  props: unknown;
91
+ /**
92
+ * Set when the identity dropped the user query. A transport stores a
93
+ * page's other part from one render only under such an identity: one
94
+ * that keeps the query is cached per full URL, and stores its own part.
95
+ */
96
+ queryFree?: true;
63
97
  request: Request;
98
+ /**
99
+ * Regenerate from the dispatched request and props. A getStaticProps
100
+ * page's custom `_app` getInitialProps receives the request, host
101
+ * included, so a Pages page regenerates from a real request, as in
102
+ * Next.js, never from the identity's synthetic origin.
103
+ */
104
+ regenerateFromDispatch?: true;
64
105
  };
65
106
  };
66
107
  export type VinextCacheabilityProbeMode = "probe" | "identity";
@@ -1,8 +1,20 @@
1
1
  //#region src/server/multi-stage.ts
2
+ /**
3
+ * The origin a shared cache identity names in place of the request's. Next.js
4
+ * keys its response cache by pathname, so one stored response answers every
5
+ * host an app serves. `.invalid` never resolves, so no configured domain or
6
+ * host condition can match it when the identity is replayed.
7
+ */
8
+ const VINEXT_CACHE_IDENTITY_ORIGIN = "https://cache-identity.vinext.invalid";
9
+ /** Name `origin` in place of a dispatch URL's origin in a shared cache identity. */
10
+ function withCacheIdentityOrigin(requestUrl, origin = VINEXT_CACHE_IDENTITY_ORIGIN) {
11
+ const url = new URL(requestUrl);
12
+ return `${origin}${url.pathname}${url.search}`;
13
+ }
2
14
  /** Whether a response-stage cache must reject a field it did not key itself by. */
3
15
  function hasUnsupportedResponseStageVary(headers, keyedRequestHeaders = []) {
4
16
  const keyedFields = new Set([...keyedRequestHeaders].map((name) => name.trim().toLowerCase()).filter(Boolean));
5
17
  return (headers.get("Vary") ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean).some((name) => name === "*" || !keyedFields.has(name));
6
18
  }
7
19
  //#endregion
8
- export { hasUnsupportedResponseStageVary };
20
+ export { VINEXT_CACHE_IDENTITY_ORIGIN, hasUnsupportedResponseStageVary, withCacheIdentityOrigin };
@@ -1,9 +1,9 @@
1
1
  import { stripBasePath } from "../utils/base-path.js";
2
2
  import { splitPathnameForRouteMatch } from "../routing/utils.js";
3
3
  import { matchRoutePattern, matchRoutePatternPrefix, matchRoutePatternWithOptionalDynamicSegments } from "../routing/route-pattern.js";
4
+ import { resolveHardNavigationTargetFromRscResponse, resolveRscCompatibilityNavigationDecision } from "./app-rsc-cache-busting.js";
4
5
  import { AppElementsWire, compareAppElementsSlotIds } from "./app-elements-wire.js";
5
6
  import "./app-elements.js";
6
- import { resolveHardNavigationTargetFromRscResponse, resolveRscCompatibilityNavigationDecision } from "./app-rsc-cache-busting.js";
7
7
  import { resolveRscRedirectLifecycleHop, resolveStreamedRscRedirectLifecycleHop } from "./app-browser-rsc-redirect.js";
8
8
  import { NavigationTraceReasonCodes, createNavigationLifecycleTraceFields, createNavigationTrace } from "./navigation-trace.js";
9
9
  import { verifyOperationTokenForCacheReuse } from "./operation-token.js";
@@ -30,6 +30,17 @@ function isEdgeApiRouteModule(module) {
30
30
  function isNodeApiRouteModule(module) {
31
31
  return typeof module.default === "function" && !isEdgeApiRuntime(resolveModuleRuntime(module));
32
32
  }
33
+ function withInitialResponseHeaders(response, initialResponseHeaders) {
34
+ if (!initialResponseHeaders || !initialResponseHeaders.keys().next().value) return response;
35
+ const headers = new Headers(initialResponseHeaders);
36
+ for (const [name, value] of response.headers) if (name !== "set-cookie") headers.set(name, value);
37
+ for (const cookie of response.headers.getSetCookie()) headers.append("Set-Cookie", cookie);
38
+ return new Response(response.body, {
39
+ headers,
40
+ status: response.status,
41
+ statusText: response.statusText
42
+ });
43
+ }
33
44
  async function handlePagesApiRoute(options) {
34
45
  const run = async () => {
35
46
  const response = await _handlePagesApiRoute(options);
@@ -51,22 +62,10 @@ async function _handlePagesApiRoute(options) {
51
62
  skipTrailingSlashRedirect: options.nextConfig.skipTrailingSlashRedirect
52
63
  } } : void 0);
53
64
  const response = await tracePagesApiHandler(route.pattern, () => handler(nextRequest));
54
- if (response instanceof Response) {
55
- const finalized = finalizeEdgeApiResponse(response, options.edgeRuntime ?? "worker");
56
- if (!options.initialResponseHeaders || !options.initialResponseHeaders.keys().next().value) return finalized;
57
- const headers = new Headers(options.initialResponseHeaders);
58
- for (const [name, value] of finalized.headers) if (name.toLowerCase() !== "set-cookie") headers.set(name, value);
59
- const finalizedCookies = finalized.headers.getSetCookie();
60
- for (const cookie of finalizedCookies) headers.append("Set-Cookie", cookie);
61
- return new Response(finalized.body, {
62
- headers,
63
- status: finalized.status,
64
- statusText: finalized.statusText
65
- });
66
- }
65
+ if (response instanceof Response) return withInitialResponseHeaders(finalizeEdgeApiResponse(response, options.edgeRuntime ?? "worker"), options.initialResponseHeaders);
67
66
  throw new Error("Edge API route did not return a Response");
68
67
  }
69
- if (!isNodeApiRouteModule(route.module)) return new Response("API route does not export a default function", { status: 500 });
68
+ if (!isNodeApiRouteModule(route.module)) return withInitialResponseHeaders(new Response("API route does not export a default function", { status: 500 }), options.initialResponseHeaders);
70
69
  const handler = route.module.default;
71
70
  const query = buildPagesApiQuery(options.url, params);
72
71
  const bodyParserConfig = resolveBodyParserConfig(route.module.config);
@@ -92,8 +91,12 @@ async function _handlePagesApiRoute(options) {
92
91
  if (!res.writableEnded) markVinextStreamedApiResponse(response);
93
92
  return response;
94
93
  };
95
- const destroyAfterHandlerError = (error) => {
94
+ const settleHandlerError = (error) => {
96
95
  const normalizedError = error instanceof Error ? error : new Error(String(error));
96
+ if (!res.headersSent) return {
97
+ type: "error",
98
+ error: normalizedError
99
+ };
97
100
  res.destroy(normalizedError);
98
101
  throw normalizedError;
99
102
  };
@@ -101,22 +104,28 @@ async function _handlePagesApiRoute(options) {
101
104
  type: "response",
102
105
  response
103
106
  }));
104
- const handlerCompletion = Promise.resolve().then(() => tracePagesApiHandler(route.pattern, () => handler(req, res), { recordErrors: options.edgeRuntime !== "node" })).then(() => ({ type: "handler" }), destroyAfterHandlerError);
107
+ const handlerCompletion = Promise.resolve().then(() => tracePagesApiHandler(route.pattern, () => handler(req, res), { recordErrors: options.edgeRuntime !== "node" })).then(() => ({ type: "handler" }), settleHandlerError);
105
108
  const firstSettled = await Promise.race([responseReady, handlerCompletion]);
106
109
  if (firstSettled.type === "response") {
107
110
  const handlerLifecycle = handlerCompletion.then(completeHandler, (error) => options.reportRequestError?.(error, route.pattern));
108
111
  getRequestExecutionContext()?.waitUntil(handlerLifecycle);
109
112
  return finalizeResponse(firstSettled.response);
110
113
  }
114
+ if (firstSettled.type === "error") {
115
+ await options.reportRequestError?.(firstSettled.error, route.pattern);
116
+ res.statusCode = 500;
117
+ res.end("Internal Server Error");
118
+ return finalizeResponse(await responsePromise);
119
+ }
111
120
  completeHandler();
112
121
  return finalizeResponse(await responsePromise);
113
122
  } catch (error) {
114
- if (error instanceof PagesBodyParseError) return new Response(error.message, {
123
+ if (error instanceof PagesBodyParseError) return withInitialResponseHeaders(new Response(error.message, {
115
124
  status: error.statusCode,
116
125
  statusText: error.message
117
- });
126
+ }), options.initialResponseHeaders);
118
127
  await options.reportRequestError?.(error instanceof Error ? error : new Error(String(error)), route.pattern);
119
- return internalServerErrorResponse();
128
+ return withInitialResponseHeaders(internalServerErrorResponse(), options.initialResponseHeaders);
120
129
  }
121
130
  }
122
131
  //#endregion
@@ -9,6 +9,26 @@ export declare class PagesBodyParseError extends Error {
9
9
  readonly statusCode: number;
10
10
  constructor(message: string, statusCode: number);
11
11
  }
12
- export declare function getMediaType(contentType: string | null | undefined): string;
13
12
  export declare function isJsonMediaType(mediaType: string): boolean;
13
+ /** A `TextDecoder`-shaped decoder for one request body. */
14
+ export type PagesBodyDecoder = {
15
+ decode(input?: Uint8Array, options?: {
16
+ stream?: boolean;
17
+ }): string;
18
+ };
19
+ /**
20
+ * Resolve the media type and body decoder for a Pages API request, matching
21
+ * Next.js `parseBody()`: a malformed Content-Type is treated as `text/plain`,
22
+ * the body is decoded with its `charset` (UTF-8 by default), and a charset that
23
+ * can't be decoded is rejected with `400 Invalid body`.
24
+ *
25
+ * Next.js decodes through raw-body with iconv-lite 0.4, which vinext bundles
26
+ * at the same version. It is loaded only for non-UTF-8 charsets: `TextDecoder`
27
+ * decodes UTF-8 identically, BOM stripping included, and keeps iconv-lite's
28
+ * encoding tables out of the startup path.
29
+ */
30
+ export declare function createPagesBodyDecoder(contentType: string | null | undefined): Promise<{
31
+ mediaType: string;
32
+ decoder: PagesBodyDecoder;
33
+ }>;
14
34
  //#endregion
@@ -1,3 +1,5 @@
1
+ import { __toESM } from "../_virtual/_rolldown/runtime.js";
2
+ import { Buffer } from "node:buffer";
1
3
  //#region src/server/pages-media-type.ts
2
4
  /**
3
5
  * Shared media-type helpers and body-parse error for Pages API routes.
@@ -13,12 +15,74 @@ var PagesBodyParseError = class extends Error {
13
15
  this.name = "PagesBodyParseError";
14
16
  }
15
17
  };
16
- function getMediaType(contentType) {
17
- const [type] = (contentType ?? "text/plain").split(";");
18
- return type?.trim().toLowerCase() || "text/plain";
19
- }
20
18
  function isJsonMediaType(mediaType) {
21
19
  return mediaType === "application/json" || mediaType === "application/ld+json";
22
20
  }
21
+ const TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
22
+ const PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
23
+ const QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
24
+ function parseContentType(header) {
25
+ let index = header.indexOf(";");
26
+ const type = (index === -1 ? header : header.slice(0, index)).trim();
27
+ if (!TYPE_REGEXP.test(type)) return null;
28
+ let charset;
29
+ if (index !== -1) {
30
+ const paramRegexp = new RegExp(PARAM_REGEXP);
31
+ paramRegexp.lastIndex = index;
32
+ let match;
33
+ while (match = paramRegexp.exec(header)) {
34
+ if (match.index !== index) return null;
35
+ index += match[0].length;
36
+ if (match[1].toLowerCase() !== "charset") continue;
37
+ const value = match[2];
38
+ charset = value.startsWith("\"") ? value.slice(1, -1).replace(QESC_REGEXP, "$1") : value;
39
+ }
40
+ if (index !== header.length) return null;
41
+ }
42
+ return {
43
+ mediaType: type.toLowerCase(),
44
+ charset
45
+ };
46
+ }
47
+ function iconvBodyDecoder(decoder) {
48
+ return { decode(input, options) {
49
+ let text = input ? decoder.write(Buffer.from(input.buffer, input.byteOffset, input.byteLength)) : "";
50
+ if (!options?.stream) text += decoder.end() || "";
51
+ return text;
52
+ } };
53
+ }
54
+ /**
55
+ * Resolve the media type and body decoder for a Pages API request, matching
56
+ * Next.js `parseBody()`: a malformed Content-Type is treated as `text/plain`,
57
+ * the body is decoded with its `charset` (UTF-8 by default), and a charset that
58
+ * can't be decoded is rejected with `400 Invalid body`.
59
+ *
60
+ * Next.js decodes through raw-body with iconv-lite 0.4, which vinext bundles
61
+ * at the same version. It is loaded only for non-UTF-8 charsets: `TextDecoder`
62
+ * decodes UTF-8 identically, BOM stripping included, and keeps iconv-lite's
63
+ * encoding tables out of the startup path.
64
+ */
65
+ async function createPagesBodyDecoder(contentType) {
66
+ const parsed = contentType && parseContentType(contentType) || {
67
+ mediaType: "text/plain",
68
+ charset: void 0
69
+ };
70
+ const charset = parsed.charset || "utf-8";
71
+ if (charset.toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "") === "utf8") return {
72
+ mediaType: parsed.mediaType,
73
+ decoder: new TextDecoder()
74
+ };
75
+ const iconv = (await import("../deps/.pnpm/iconv-lite@0.4.24/deps/iconv-lite/lib/index.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1))).default;
76
+ let decoder;
77
+ try {
78
+ decoder = iconv.getDecoder(charset);
79
+ } catch {
80
+ throw new PagesBodyParseError("Invalid body", 400);
81
+ }
82
+ return {
83
+ mediaType: parsed.mediaType,
84
+ decoder: iconvBodyDecoder(decoder)
85
+ };
86
+ }
23
87
  //#endregion
24
- export { PagesBodyParseError, getMediaType, isJsonMediaType };
88
+ export { PagesBodyParseError, createPagesBodyDecoder, isJsonMediaType };
@@ -2,11 +2,11 @@ import { parseCookieHeader } from "../utils/parse-cookie.js";
2
2
  import { getRequestExecutionContext } from "../shims/request-context.js";
3
3
  import { readStreamAsTextWithLimit } from "../utils/text-stream.js";
4
4
  import { DEFAULT_PAGES_API_BODY_SIZE_LIMIT } from "./pages-body-parser-config.js";
5
- import { PagesBodyParseError, getMediaType, isJsonMediaType } from "./pages-media-type.js";
5
+ import { PagesBodyParseError, createPagesBodyDecoder, isJsonMediaType } from "./pages-media-type.js";
6
6
  import { performOnDemandRevalidate } from "./pages-revalidate.js";
7
7
  import { clearPagesPreviewData, getPagesPreviewState, setPagesDraftMode, setPagesPreviewData } from "./pages-preview.js";
8
8
  import { decode } from "node:querystring";
9
- import { Readable, Writable } from "node:stream";
9
+ import { Readable, Stream, Writable } from "node:stream";
10
10
  //#region src/server/pages-node-compat.ts
11
11
  const MAX_PAGES_API_BODY_SIZE = DEFAULT_PAGES_API_BODY_SIZE_LIMIT;
12
12
  const NO_BODY_RESPONSE_STATUSES = /* @__PURE__ */ new Set([
@@ -26,11 +26,17 @@ function validateAppendedHeader(name, value) {
26
26
  if (INVALID_HEADER_VALUE_CHAR_PATTERN.test(String(item))) throw createNodeTypeError("ERR_INVALID_CHAR", `Invalid character in header content ["${name}"]`);
27
27
  }
28
28
  }
29
- async function readPagesRequestBodyWithLimit(request, maxBytes) {
30
- if (!request.body) return "";
31
- return readStreamAsTextWithLimit(request.body, maxBytes, () => {
29
+ /** The decoded body, or undefined when the request carried no body bytes. */
30
+ async function readPagesRequestBodyWithLimit(request, maxBytes, decoder) {
31
+ if (!request.body) return;
32
+ let byteLength = 0;
33
+ const text = await readStreamAsTextWithLimit(request.body, maxBytes, () => {
32
34
  throw new PagesBodyParseError("Request body too large", 413);
33
- });
35
+ }, { decode(input, options) {
36
+ byteLength += input?.byteLength ?? 0;
37
+ return decoder.decode(input, options);
38
+ } });
39
+ return byteLength > 0 ? text : void 0;
34
40
  }
35
41
  /**
36
42
  * Read and parse a Pages Router API request body for the Workers/prod path.
@@ -43,16 +49,16 @@ async function readPagesRequestBodyWithLimit(request, maxBytes) {
43
49
  * @see https://nextjs.org/docs/pages/building-your-application/routing/api-routes#custom-config
44
50
  */
45
51
  async function parsePagesApiBody(request, maxBytes = MAX_PAGES_API_BODY_SIZE) {
52
+ const { mediaType, decoder } = await createPagesBodyDecoder(request.headers.get("content-type"));
46
53
  if (Number.parseInt(request.headers.get("content-length") || "0", 10) > maxBytes) throw new PagesBodyParseError("Request body too large", 413);
47
- let rawBody = "";
54
+ let rawBody;
48
55
  try {
49
- rawBody = await readPagesRequestBodyWithLimit(request, maxBytes);
56
+ rawBody = await readPagesRequestBodyWithLimit(request, maxBytes, decoder);
50
57
  } catch (err) {
51
58
  if (err instanceof PagesBodyParseError) throw err;
52
59
  throw new PagesBodyParseError("Request body too large", 413);
53
60
  }
54
- const mediaType = getMediaType(request.headers.get("content-type"));
55
- if (!rawBody) return isJsonMediaType(mediaType) ? {} : mediaType === "application/x-www-form-urlencoded" ? decode(rawBody) : void 0;
61
+ if (!rawBody) return isJsonMediaType(mediaType) ? {} : mediaType === "application/x-www-form-urlencoded" ? decode("") : rawBody;
56
62
  if (isJsonMediaType(mediaType)) try {
57
63
  return JSON.parse(rawBody);
58
64
  } catch {
@@ -61,24 +67,34 @@ async function parsePagesApiBody(request, maxBytes = MAX_PAGES_API_BODY_SIZE) {
61
67
  if (mediaType === "application/x-www-form-urlencoded") return decode(rawBody);
62
68
  return rawBody;
63
69
  }
64
- async function* requestBodyChunks(request) {
65
- if (!request.body || request.bodyUsed) return;
66
- const reader = request.body.getReader();
67
- try {
68
- for (;;) {
69
- const { value, done } = await reader.read();
70
- if (done) return;
71
- yield Buffer.from(value.buffer, value.byteOffset, value.byteLength);
72
- }
73
- } finally {
74
- try {
75
- await reader.cancel();
76
- } catch {}
77
- reader.releaseLock();
78
- }
79
- }
80
70
  function createRequestReadable(request) {
81
- return Readable.from(requestBodyChunks(request), { objectMode: false });
71
+ const body = request.bodyUsed ? null : request.body;
72
+ let reader;
73
+ return new Readable({
74
+ read() {
75
+ if (!body) {
76
+ this.push(null);
77
+ return;
78
+ }
79
+ reader ??= body.getReader();
80
+ reader.read().then(({ value, done }) => {
81
+ if (this.destroyed) return;
82
+ if (done) {
83
+ this.push(null);
84
+ return;
85
+ }
86
+ this.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
87
+ }, (error) => this.destroy(error));
88
+ },
89
+ destroy(error, callback) {
90
+ const cancelled = reader ? reader.cancel(error ?? void 0) : body?.cancel(error ?? void 0);
91
+ if (!cancelled) {
92
+ callback(error);
93
+ return;
94
+ }
95
+ cancelled.then(() => callback(error), () => callback(error));
96
+ }
97
+ });
82
98
  }
83
99
  function parsePagesRequestCookies(cookieHeader) {
84
100
  return parseCookieHeader(Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader);
@@ -189,6 +205,15 @@ var PagesResponseStream = class extends Writable {
189
205
  this.end(JSON.stringify(data));
190
206
  }
191
207
  send(data) {
208
+ if (NO_BODY_RESPONSE_STATUSES.has(this.resStatusCode)) {
209
+ this.end();
210
+ return;
211
+ }
212
+ if (data instanceof Stream) {
213
+ if (!this.resHeaders["content-type"]) this.resHeaders["content-type"] = "application/octet-stream";
214
+ data.pipe(this);
215
+ return;
216
+ }
192
217
  if (Buffer.isBuffer(data)) {
193
218
  if (!this.resHeaders["content-type"]) this.resHeaders["content-type"] = "application/octet-stream";
194
219
  this.resHeaders["content-length"] = String(data.length);