agmon 0.1.1 → 0.1.3

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 (233) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/app-path-routes-manifest.json +7 -0
  3. package/.next/build/chunks/[root-of-the-server]__05i36w1t4lzaf._.js +502 -0
  4. package/.next/build/chunks/[root-of-the-server]__05i36w1t4lzaf._.js.map +11 -0
  5. package/.next/build/chunks/[root-of-the-server]__1kki86fknkq7y._.js +190 -0
  6. package/.next/build/chunks/[root-of-the-server]__1kki86fknkq7y._.js.map +8 -0
  7. package/.next/build/chunks/[turbopack-node]_transforms_postcss_ts_1gfkiq9iz8yb8._.js +13 -0
  8. package/.next/build/chunks/[turbopack-node]_transforms_postcss_ts_1gfkiq9iz8yb8._.js.map +5 -0
  9. package/.next/build/chunks/[turbopack]_runtime.js +1056 -0
  10. package/.next/build/chunks/[turbopack]_runtime.js.map +11 -0
  11. package/.next/build/chunks/node_modules_20v-8wlfss9m1._.js +7314 -0
  12. package/.next/build/chunks/node_modules_20v-8wlfss9m1._.js.map +47 -0
  13. package/.next/build/chunks/pool_entry-[turbopack-node]_transforms_postcss_ts_0tp-k2vy8nj6i._.js +6 -0
  14. package/.next/build/chunks/pool_entry-[turbopack-node]_transforms_postcss_ts_0tp-k2vy8nj6i._.js.map +5 -0
  15. package/.next/build/package.json +1 -0
  16. package/.next/build-manifest.json +54 -0
  17. package/.next/export-marker.json +6 -0
  18. package/.next/fallback-build-manifest.json +15 -0
  19. package/.next/images-manifest.json +68 -0
  20. package/.next/next-minimal-server.js.nft.json +1 -0
  21. package/.next/next-server.js.nft.json +1 -0
  22. package/.next/package.json +1 -0
  23. package/.next/prerender-manifest.json +97 -0
  24. package/.next/required-server-files.js +366 -0
  25. package/.next/required-server-files.json +366 -0
  26. package/.next/routes-manifest.json +75 -0
  27. package/.next/server/app/_global-error/page/app-paths-manifest.json +3 -0
  28. package/.next/server/app/_global-error/page/build-manifest.json +21 -0
  29. package/.next/server/app/_global-error/page/next-font-manifest.json +6 -0
  30. package/.next/server/app/_global-error/page/react-loadable-manifest.json +1 -0
  31. package/.next/server/app/_global-error/page/server-reference-manifest.json +4 -0
  32. package/.next/server/app/_global-error/page.js +10 -0
  33. package/.next/server/app/_global-error/page.js.map +5 -0
  34. package/.next/server/app/_global-error/page.js.nft.json +1 -0
  35. package/.next/server/app/_global-error/page_client-reference-manifest.js +3 -0
  36. package/.next/server/app/_global-error.html +1 -0
  37. package/.next/server/app/_global-error.meta +30 -0
  38. package/.next/server/app/_global-error.rsc +18 -0
  39. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +23 -0
  40. package/.next/server/app/_global-error.segments/_full.segment.rsc +18 -0
  41. package/.next/server/app/_global-error.segments/_tree.segment.rsc +2 -0
  42. package/.next/server/app/_not-found/page/app-paths-manifest.json +3 -0
  43. package/.next/server/app/_not-found/page/build-manifest.json +21 -0
  44. package/.next/server/app/_not-found/page/next-font-manifest.json +6 -0
  45. package/.next/server/app/_not-found/page/react-loadable-manifest.json +1 -0
  46. package/.next/server/app/_not-found/page/server-reference-manifest.json +4 -0
  47. package/.next/server/app/_not-found/page.js +12 -0
  48. package/.next/server/app/_not-found/page.js.map +5 -0
  49. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  50. package/.next/server/app/_not-found/page_client-reference-manifest.js +3 -0
  51. package/.next/server/app/_not-found.html +1 -0
  52. package/.next/server/app/_not-found.meta +35 -0
  53. package/.next/server/app/_not-found.rsc +22 -0
  54. package/.next/server/app/_not-found.segments/_full.segment.rsc +22 -0
  55. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +28 -0
  56. package/.next/server/app/_not-found.segments/_tree.segment.rsc +4 -0
  57. package/.next/server/app/api/traces/stream/route/app-paths-manifest.json +3 -0
  58. package/.next/server/app/api/traces/stream/route/build-manifest.json +12 -0
  59. package/.next/server/app/api/traces/stream/route/server-reference-manifest.json +4 -0
  60. package/.next/server/app/api/traces/stream/route.js +7 -0
  61. package/.next/server/app/api/traces/stream/route.js.map +5 -0
  62. package/.next/server/app/api/traces/stream/route.js.nft.json +1 -0
  63. package/.next/server/app/api/traces/stream/route_client-reference-manifest.js +3 -0
  64. package/.next/server/app/api/version/route/app-paths-manifest.json +3 -0
  65. package/.next/server/app/api/version/route/build-manifest.json +12 -0
  66. package/.next/server/app/api/version/route/server-reference-manifest.json +4 -0
  67. package/.next/server/app/api/version/route.js +7 -0
  68. package/.next/server/app/api/version/route.js.map +5 -0
  69. package/.next/server/app/api/version/route.js.nft.json +1 -0
  70. package/.next/server/app/api/version/route_client-reference-manifest.js +3 -0
  71. package/.next/server/app/index.html +1 -0
  72. package/.next/server/app/index.meta +29 -0
  73. package/.next/server/app/index.rsc +29 -0
  74. package/.next/server/app/index.segments/__PAGE__.segment.rsc +34 -0
  75. package/.next/server/app/index.segments/_full.segment.rsc +29 -0
  76. package/.next/server/app/index.segments/_tree.segment.rsc +3 -0
  77. package/.next/server/app/page/app-paths-manifest.json +3 -0
  78. package/.next/server/app/page/build-manifest.json +21 -0
  79. package/.next/server/app/page/next-font-manifest.json +6 -0
  80. package/.next/server/app/page/react-loadable-manifest.json +1 -0
  81. package/.next/server/app/page/server-reference-manifest.json +4 -0
  82. package/.next/server/app/page.js +13 -0
  83. package/.next/server/app/page.js.map +5 -0
  84. package/.next/server/app/page.js.nft.json +1 -0
  85. package/.next/server/app/page_client-reference-manifest.js +3 -0
  86. package/.next/server/app-paths-manifest.json +7 -0
  87. package/.next/server/chunks/[externals]__0bwf06g0pqv3h._.js +3 -0
  88. package/.next/server/chunks/[externals]__0bwf06g0pqv3h._.js.map +1 -0
  89. package/.next/server/chunks/[externals]__1p2j9_5g429uh._.js +3 -0
  90. package/.next/server/chunks/[externals]__1p2j9_5g429uh._.js.map +1 -0
  91. package/.next/server/chunks/[root-of-the-server]__04an4kw4xcc5l._.js +5 -0
  92. package/.next/server/chunks/[root-of-the-server]__04an4kw4xcc5l._.js.map +1 -0
  93. package/.next/server/chunks/[root-of-the-server]__1s6v8mz-nanm-._.js +5 -0
  94. package/.next/server/chunks/[root-of-the-server]__1s6v8mz-nanm-._.js.map +1 -0
  95. package/.next/server/chunks/[root-of-the-server]__20xfs4y2ipcvv._.js +320 -0
  96. package/.next/server/chunks/[root-of-the-server]__20xfs4y2ipcvv._.js.map +1 -0
  97. package/.next/server/chunks/[turbopack]_runtime.js +937 -0
  98. package/.next/server/chunks/[turbopack]_runtime.js.map +10 -0
  99. package/.next/server/chunks/_next-internal_server_app_api_traces_stream_route_actions_07rmicxgds803.js +3 -0
  100. package/.next/server/chunks/_next-internal_server_app_api_traces_stream_route_actions_07rmicxgds803.js.map +1 -0
  101. package/.next/server/chunks/_next-internal_server_app_api_version_route_actions_0kbx30hro8e93.js +3 -0
  102. package/.next/server/chunks/_next-internal_server_app_api_version_route_actions_0kbx30hro8e93.js.map +1 -0
  103. package/.next/server/chunks/ssr/1q96_modules_pixi_js_lib_rendering_renderers_canvas_CanvasRenderer_mjs_1xntzghggpb51._.js +3 -0
  104. package/.next/server/chunks/ssr/1q96_modules_pixi_js_lib_rendering_renderers_canvas_CanvasRenderer_mjs_1xntzghggpb51._.js.map +1 -0
  105. package/.next/server/chunks/ssr/1q96_modules_pixi_js_lib_rendering_renderers_gpu_WebGPURenderer_mjs_00tc9jrf-ft1_._.js +76 -0
  106. package/.next/server/chunks/ssr/1q96_modules_pixi_js_lib_rendering_renderers_gpu_WebGPURenderer_mjs_00tc9jrf-ft1_._.js.map +1 -0
  107. package/.next/server/chunks/ssr/[root-of-the-server]__08zgqq_38tv57._.js +3 -0
  108. package/.next/server/chunks/ssr/[root-of-the-server]__08zgqq_38tv57._.js.map +1 -0
  109. package/.next/server/chunks/ssr/[root-of-the-server]__0aa2929udndo-._.js +3 -0
  110. package/.next/server/chunks/ssr/[root-of-the-server]__0aa2929udndo-._.js.map +1 -0
  111. package/.next/server/chunks/ssr/[root-of-the-server]__0ayw3c9e93kvf._.js +3 -0
  112. package/.next/server/chunks/ssr/[root-of-the-server]__0ayw3c9e93kvf._.js.map +1 -0
  113. package/.next/server/chunks/ssr/[root-of-the-server]__0ojpb-dtuk3-q._.js +3 -0
  114. package/.next/server/chunks/ssr/[root-of-the-server]__0ojpb-dtuk3-q._.js.map +1 -0
  115. package/.next/server/chunks/ssr/[root-of-the-server]__0py1t7q9ntzgc._.js +3 -0
  116. package/.next/server/chunks/ssr/[root-of-the-server]__0py1t7q9ntzgc._.js.map +1 -0
  117. package/.next/server/chunks/ssr/[root-of-the-server]__1cf6qt9agg_9-._.js +14 -0
  118. package/.next/server/chunks/ssr/[root-of-the-server]__1cf6qt9agg_9-._.js.map +1 -0
  119. package/.next/server/chunks/ssr/[root-of-the-server]__1e1_fmeab1ca7._.js +3 -0
  120. package/.next/server/chunks/ssr/[root-of-the-server]__1e1_fmeab1ca7._.js.map +1 -0
  121. package/.next/server/chunks/ssr/[root-of-the-server]__1w2vu9hh0h02y._.js +3 -0
  122. package/.next/server/chunks/ssr/[root-of-the-server]__1w2vu9hh0h02y._.js.map +1 -0
  123. package/.next/server/chunks/ssr/[turbopack]_runtime.js +937 -0
  124. package/.next/server/chunks/ssr/[turbopack]_runtime.js.map +10 -0
  125. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0zi5s8-psc_d2.js +3 -0
  126. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0zi5s8-psc_d2.js.map +1 -0
  127. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0pt47yrisjoev.js +3 -0
  128. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0pt47yrisjoev.js.map +1 -0
  129. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_0hhsz1jew5ls7.js +3 -0
  130. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_0hhsz1jew5ls7.js.map +1 -0
  131. package/.next/server/chunks/ssr/node_modules_01xbj_9zg44kw._.js +33 -0
  132. package/.next/server/chunks/ssr/node_modules_01xbj_9zg44kw._.js.map +1 -0
  133. package/.next/server/chunks/ssr/node_modules_0a548_llmwce7._.js +23 -0
  134. package/.next/server/chunks/ssr/node_modules_0a548_llmwce7._.js.map +1 -0
  135. package/.next/server/chunks/ssr/node_modules_0gxlxpuufujz9._.js +33 -0
  136. package/.next/server/chunks/ssr/node_modules_0gxlxpuufujz9._.js.map +1 -0
  137. package/.next/server/chunks/ssr/node_modules_next_dist_0janj0i6dqko7._.js +6 -0
  138. package/.next/server/chunks/ssr/node_modules_next_dist_0janj0i6dqko7._.js.map +1 -0
  139. package/.next/server/chunks/ssr/node_modules_next_dist_1hgv5i-pr1hza._.js +3 -0
  140. package/.next/server/chunks/ssr/node_modules_next_dist_1hgv5i-pr1hza._.js.map +1 -0
  141. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0wpq8j32_ibz4._.js +3 -0
  142. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0wpq8j32_ibz4._.js.map +1 -0
  143. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0symwr9mbf-fh.js +3 -0
  144. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0symwr9mbf-fh.js.map +1 -0
  145. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0q-w892nagajq.js +3 -0
  146. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0q-w892nagajq.js.map +1 -0
  147. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0l_sp0xky89qu.js +3 -0
  148. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0l_sp0xky89qu.js.map +1 -0
  149. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0aymk_x8-bu4q.js +3 -0
  150. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0aymk_x8-bu4q.js.map +1 -0
  151. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_19--w_z4y02i7.js +3 -0
  152. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_19--w_z4y02i7.js.map +1 -0
  153. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1qjycfedgh109.js +3 -0
  154. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1qjycfedgh109.js.map +1 -0
  155. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0hcyh9uzlz7ci._.js +3 -0
  156. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0hcyh9uzlz7ci._.js.map +1 -0
  157. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0k3f3soanqdoq._.js +3 -0
  158. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0k3f3soanqdoq._.js.map +1 -0
  159. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0ovgsftn-uvbz._.js +3 -0
  160. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0ovgsftn-uvbz._.js.map +1 -0
  161. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0xa24fqr5c5qi._.js +5 -0
  162. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0xa24fqr5c5qi._.js.map +1 -0
  163. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0zrftay3kjup7._.js +5 -0
  164. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_0zrftay3kjup7._.js.map +1 -0
  165. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_1z4lgkg_w-7fr._.js +208 -0
  166. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_1z4lgkg_w-7fr._.js.map +1 -0
  167. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_1zjkoj2kc4hm-._.js +3 -0
  168. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_1zjkoj2kc4hm-._.js.map +1 -0
  169. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_environment-browser_browserAll_mjs_0xb_t3dj4ad1f._.js +16 -0
  170. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_environment-browser_browserAll_mjs_0xb_t3dj4ad1f._.js.map +1 -0
  171. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_filters_Filter_mjs_0luksfw8ekifi._.js +3 -0
  172. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_filters_Filter_mjs_0luksfw8ekifi._.js.map +1 -0
  173. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_filters_init_mjs_1o5fmm_m60v_s._.js +3 -0
  174. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_filters_init_mjs_1o5fmm_m60v_s._.js.map +1 -0
  175. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_1fkio2phhfvow._.js +196 -0
  176. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_1fkio2phhfvow._.js.map +1 -0
  177. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_1n1q7aum4i7zo._.js +196 -0
  178. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_1n1q7aum4i7zo._.js.map +1 -0
  179. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_renderers_10vpvx1o7svnk._.js +3 -0
  180. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_renderers_10vpvx1o7svnk._.js.map +1 -0
  181. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_renderers_gl_WebGLRenderer_mjs_1hlux44jh7dk-._.js +153 -0
  182. package/.next/server/chunks/ssr/node_modules_pixi_js_lib_rendering_renderers_gl_WebGLRenderer_mjs_1hlux44jh7dk-._.js.map +1 -0
  183. package/.next/server/chunks/ssr/src_app_page_1vqfk0-j72fp6.js +3 -0
  184. package/.next/server/chunks/ssr/src_app_page_1vqfk0-j72fp6.js.map +1 -0
  185. package/.next/server/functions-config-manifest.json +4 -0
  186. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  187. package/.next/server/middleware-build-manifest.js +54 -0
  188. package/.next/server/middleware-manifest.json +6 -0
  189. package/.next/server/next-font-manifest.js +1 -0
  190. package/.next/server/next-font-manifest.json +6 -0
  191. package/.next/server/pages/404.html +1 -0
  192. package/.next/server/pages/500.html +1 -0
  193. package/.next/server/pages-manifest.json +4 -0
  194. package/.next/server/prefetch-hints.json +34 -0
  195. package/.next/server/preview-props.json +5 -0
  196. package/.next/server/server-reference-manifest.js +1 -0
  197. package/.next/server/server-reference-manifest.json +5 -0
  198. package/.next/static/chunks/0_9x2udu0iodw.js +1 -0
  199. package/.next/static/chunks/0cz1d0mv5g_q7.js +1 -0
  200. package/.next/static/chunks/0umf92h1sb77c.js +1 -0
  201. package/.next/static/chunks/10om7oix6wjze.js +1 -0
  202. package/.next/static/chunks/1780fh11o7pze.js +1 -0
  203. package/.next/static/chunks/1cldmiyw3ya18.js +21 -0
  204. package/.next/static/chunks/1unuqfq-vfqtp.js +1 -0
  205. package/.next/static/chunks/2-vsu_pt58kse.js +3 -0
  206. package/.next/static/chunks/2drjv1ti9t4pg.js +1 -0
  207. package/.next/static/chunks/2hgsvrrwu57--.css +1 -0
  208. package/.next/static/chunks/2ogvir8krwwhf.js +1 -0
  209. package/.next/static/chunks/2tc54fmsk8v8q.js +1 -0
  210. package/.next/static/chunks/304ue7hvto0o0.js +206 -0
  211. package/.next/static/chunks/31gve42sn75--.js +1 -0
  212. package/.next/static/chunks/32kizm_7q94vd.js +194 -0
  213. package/.next/static/chunks/33bap0u4zwgab.js +74 -0
  214. package/.next/static/chunks/3c4xol65z2da2.js +22 -0
  215. package/.next/static/chunks/3cfn99dbrcvvp.js +31 -0
  216. package/.next/static/chunks/3d6xc1eemxy82.js +1 -0
  217. package/.next/static/chunks/3ycr8gfnsg-xv.js +151 -0
  218. package/.next/static/chunks/3ytt3vrdhke9u.js +14 -0
  219. package/.next/static/chunks/turbopack-3-ry682tkyiqk.js +1 -0
  220. package/.next/static/cy2F4S28h_-YWqCOuE_ul/_buildManifest.js +11 -0
  221. package/.next/static/cy2F4S28h_-YWqCOuE_ul/_clientMiddlewareManifest.js +1 -0
  222. package/.next/static/cy2F4S28h_-YWqCOuE_ul/_ssgManifest.js +1 -0
  223. package/.next/trace +1 -0
  224. package/.next/trace-build +1 -0
  225. package/.next/types/cache-life.d.ts +114 -0
  226. package/.next/types/root-params.d.ts +3 -0
  227. package/.next/types/routes.d.ts +74 -0
  228. package/.next/types/validator.ts +17 -0
  229. package/bin/cli.js +24 -6
  230. package/package.json +6 -6
  231. package/src/app/api/traces/stream/route.js +2 -2
  232. package/src/app/layout.js +1 -1
  233. package/src/app/page.js +6 -19
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../node_modules/next/dist/compiled/%40edge-runtime/cookies/index.js","../../../../node_modules/next/dist/esm/server/create-deduped-by-callsite-server-error-logger.js","../../../../node_modules/next/dist/esm/server/request/params.js","../../../../node_modules/next/dist/esm/server/app-render/vary-params.js","../../../../node_modules/next/dist/esm/client/components/static-generation-bailout.js","../../../../node_modules/next/dist/esm/server/lib/params-utils.js","../../../../node_modules/next/dist/esm/server/request/utils.js","../../../../node_modules/next/dist/esm/server/request/search-params.js","../../../../node_modules/next/dist/esm/client/components/client-page.js","../../../../node_modules/next/src/client/components/client-segment.tsx","../../../../node_modules/next/dist/esm/client/components/server-async-storage.js","../../../../node_modules/next/dist/esm/client/components/http-access-fallback/error-boundary.js","../../../../node_modules/next/dist/esm/client/components/http-access-fallback/http-access-fallback.js","../../../../node_modules/next/dist/esm/client/components/navigation-untracked.js","../../../../node_modules/next/dist/esm/client/components/is-next-router-error.js","../../../../node_modules/next/dist/esm/client/components/handle-isr-error.js","../../../../node_modules/next/dist/esm/client/components/error-boundary.js","../../../../node_modules/next/dist/esm/client/components/layout-router.js","../../../../node_modules/next/dist/esm/shared/lib/lazy-dynamic/react-browser-bailout.js","../../../../node_modules/next/dist/esm/client/components/readonly-url-search-params.js","../../../../node_modules/next/dist/esm/client/components/redirect-boundary.js","../../../../node_modules/next/dist/esm/client/components/instant-validation/boundary.js","../../../../node_modules/next/dist/esm/client/components/redirect-status-code.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/create-router-cache-key.js","../../../../node_modules/next/dist/esm/server/app-render/dynamic-rendering-client.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/is-bot.js","../../../../node_modules/next/dist/esm/client/components/bfcache-state-manager.js","../../../../node_modules/next/dist/esm/client/components/navigation.react-server.js","../../../../node_modules/next/dist/esm/client/components/redirect-error.js","../../../../node_modules/next/dist/esm/client/components/navigation.js","../../../../node_modules/next/dist/esm/client/components/nav-failure-handler.js","../../../../node_modules/next/dist/esm/client/components/unresolved-thenable.js","../../../../node_modules/next/dist/esm/client/components/unstable-rethrow.js","../../../../node_modules/next/dist/esm/client/components/redirect.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/disable-smooth-scroll.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/html-bots.js","../../../../node_modules/next/dist/esm/server/app-render/instant-validation/boundary-impl.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/create-segment-key.js","../../../../node_modules/next/src/client/components/render-from-template-context.tsx","../../../../node_modules/next/dist/esm/client/navigation-build-id.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/fetch-server-response.js","../../../../node_modules/next/dist/esm/client/components/use-action-queue.js","../../../../node_modules/next/dist/esm/client/app-find-source-map-url.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/set-cache-busting-search-param.js","../../../../node_modules/next/dist/esm/shared/lib/deployment-id.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/create-href-from-url.js","../../../../node_modules/next/dist/esm/lib/constants.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/router-reducer-types.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/fetch.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/cache-busting-search-param.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/cache-key.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/lru.js","../../../../node_modules/next/dist/esm/client/flight-data-helpers.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/types.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/vary-path.js","../../../../node_modules/next/dist/esm/client/components/links.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/bfcache.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/reducers/navigate-reducer.js","../../../../node_modules/next/dist/esm/shared/lib/app-router-types.js","../../../../node_modules/next/dist/esm/shared/lib/rsc-transport.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/scheduler.js","../../../../node_modules/next/dist/esm/shared/lib/hash.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/decode-server-response.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/cache.js","../../../../node_modules/next/dist/esm/shared/lib/segment-cache/vary-params-decoding.js","../../../../node_modules/next/dist/esm/client/sequential-call-server.js","../../../../node_modules/next/dist/esm/client/components/render-tree.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/navigation-testing-lock.js","../../../../node_modules/next/dist/esm/client/components/app-router-state.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/optimistic-routes.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/cache-map.js","../../../../node_modules/next/dist/esm/shared/lib/segment.js","../../../../node_modules/next/dist/esm/shared/lib/segment-cache/segment-value-encoding.js","../../../../node_modules/next/dist/esm/client/components/app-router-headers.js","../../../../node_modules/next/dist/esm/client/remove-base-path.js","../../../../node_modules/next/dist/esm/client/has-base-path.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/parse-path.js","../../../../node_modules/next/dist/esm/client/route-params.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/path-has-prefix.js","../../../../node_modules/next/src/lib/framework/boundary-components.tsx","../../../../node_modules/next/src/lib/framework/boundary-constants.tsx","../../../../node_modules/next/src/lib/metadata/generate/icon-mark.tsx","../../../../node_modules/next/dist/esm/server/web/spec-extension/cookies.js","../../../../node_modules/next/dist/esm/server/app-render/instant-validation/instant-validation-error.js","../../../../node_modules/next/dist/esm/shared/lib/action-revalidation-kind.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/parse-relative-url.js","../../../../node_modules/next/dist/esm/server/web/spec-extension/adapters/request-cookies.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/interception-routes.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/get-segment-param.js","../../../../node_modules/next/dist/esm/server/web/spec-extension/adapters/headers.js","../../../../node_modules/next/dist/esm/server/app-render/instant-validation/instant-samples.js","../../../../node_modules/next/dist/esm/server/app-render/dynamic-rendering.js","../../../../node_modules/next/dist/esm/client/components/hooks-server-context.js","../../../../node_modules/next/dist/esm/server/dynamic-rendering-utils.js","../../../../node_modules/next/dist/esm/server/app-render/instant-validation/boundary-constants.js","../../../../node_modules/next/dist/esm/server/app-render/staged-rendering.js","../../../../node_modules/next/dist/esm/server/app-render/segment-config/ensure-static.js","../../../../node_modules/next/dist/esm/shared/lib/utils/reflect-utils.js","../../../../node_modules/next/dist/esm/server/web/spec-extension/adapters/reflect.js","../../../../node_modules/next/src/shared/lib/invariant-error.ts","../../../../node_modules/next/src/shared/lib/promise-with-resolvers.ts","../../../../node_modules/next/src/shared/lib/router/utils/querystring.ts","../../../../node_modules/next/src/server/route-modules/app-page/vendored/contexts/app-router-context.ts","../../../../node_modules/next/src/server/route-modules/app-page/vendored/contexts/hooks-client-context.ts","../../../../node_modules/next/src/server/route-modules/app-page/vendored/contexts/server-inserted-html.ts","../../../../node_modules/next/src/server/route-modules/app-page/vendored/ssr/react-dom.ts","../../../../node_modules/next/src/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.ts"],"sourcesContent":["\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/index.ts\nvar src_exports = {};\n__export(src_exports, {\n RequestCookies: () => RequestCookies,\n ResponseCookies: () => ResponseCookies,\n parseCookie: () => parseCookie,\n parseSetCookie: () => parseSetCookie,\n stringifyCookie: () => stringifyCookie\n});\nmodule.exports = __toCommonJS(src_exports);\n\n// src/serialize.ts\nfunction stringifyCookie(c) {\n var _a;\n const attrs = [\n \"path\" in c && c.path && `Path=${c.path}`,\n \"expires\" in c && (c.expires || c.expires === 0) && `Expires=${(typeof c.expires === \"number\" ? new Date(c.expires) : c.expires).toUTCString()}`,\n \"maxAge\" in c && typeof c.maxAge === \"number\" && `Max-Age=${c.maxAge}`,\n \"domain\" in c && c.domain && `Domain=${c.domain}`,\n \"secure\" in c && c.secure && \"Secure\",\n \"httpOnly\" in c && c.httpOnly && \"HttpOnly\",\n \"sameSite\" in c && c.sameSite && `SameSite=${c.sameSite}`,\n \"partitioned\" in c && c.partitioned && \"Partitioned\",\n \"priority\" in c && c.priority && `Priority=${c.priority}`\n ].filter(Boolean);\n const stringified = `${c.name}=${encodeURIComponent((_a = c.value) != null ? _a : \"\")}`;\n return attrs.length === 0 ? stringified : `${stringified}; ${attrs.join(\"; \")}`;\n}\nfunction parseCookie(cookie) {\n const map = /* @__PURE__ */ new Map();\n for (const pair of cookie.split(/; */)) {\n if (!pair)\n continue;\n const splitAt = pair.indexOf(\"=\");\n if (splitAt === -1) {\n map.set(pair, \"true\");\n continue;\n }\n const [key, value] = [pair.slice(0, splitAt), pair.slice(splitAt + 1)];\n try {\n map.set(key, decodeURIComponent(value != null ? value : \"true\"));\n } catch {\n }\n }\n return map;\n}\nfunction parseSetCookie(setCookie) {\n if (!setCookie) {\n return void 0;\n }\n const [[name, value], ...attributes] = parseCookie(setCookie);\n const {\n domain,\n expires,\n httponly,\n maxage,\n path,\n samesite,\n secure,\n partitioned,\n priority\n } = Object.fromEntries(\n attributes.map(([key, value2]) => [\n key.toLowerCase().replace(/-/g, \"\"),\n value2\n ])\n );\n const cookie = {\n name,\n value: decodeURIComponent(value),\n domain,\n ...expires && { expires: new Date(expires) },\n ...httponly && { httpOnly: true },\n ...typeof maxage === \"string\" && { maxAge: Number(maxage) },\n path,\n ...samesite && { sameSite: parseSameSite(samesite) },\n ...secure && { secure: true },\n ...priority && { priority: parsePriority(priority) },\n ...partitioned && { partitioned: true }\n };\n return compact(cookie);\n}\nfunction compact(t) {\n const newT = {};\n for (const key in t) {\n if (t[key]) {\n newT[key] = t[key];\n }\n }\n return newT;\n}\nvar SAME_SITE = [\"strict\", \"lax\", \"none\"];\nfunction parseSameSite(string) {\n string = string.toLowerCase();\n return SAME_SITE.includes(string) ? string : void 0;\n}\nvar PRIORITY = [\"low\", \"medium\", \"high\"];\nfunction parsePriority(string) {\n string = string.toLowerCase();\n return PRIORITY.includes(string) ? string : void 0;\n}\nfunction splitCookiesString(cookiesString) {\n if (!cookiesString)\n return [];\n var cookiesStrings = [];\n var pos = 0;\n var start;\n var ch;\n var lastComma;\n var nextStart;\n var cookiesSeparatorFound;\n function skipWhitespace() {\n while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n pos += 1;\n }\n return pos < cookiesString.length;\n }\n function notSpecialChar() {\n ch = cookiesString.charAt(pos);\n return ch !== \"=\" && ch !== \";\" && ch !== \",\";\n }\n while (pos < cookiesString.length) {\n start = pos;\n cookiesSeparatorFound = false;\n while (skipWhitespace()) {\n ch = cookiesString.charAt(pos);\n if (ch === \",\") {\n lastComma = pos;\n pos += 1;\n skipWhitespace();\n nextStart = pos;\n while (pos < cookiesString.length && notSpecialChar()) {\n pos += 1;\n }\n if (pos < cookiesString.length && cookiesString.charAt(pos) === \"=\") {\n cookiesSeparatorFound = true;\n pos = nextStart;\n cookiesStrings.push(cookiesString.substring(start, lastComma));\n start = pos;\n } else {\n pos = lastComma + 1;\n }\n } else {\n pos += 1;\n }\n }\n if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n cookiesStrings.push(cookiesString.substring(start, cookiesString.length));\n }\n }\n return cookiesStrings;\n}\n\n// src/request-cookies.ts\nvar RequestCookies = class {\n constructor(requestHeaders) {\n /** @internal */\n this._parsed = /* @__PURE__ */ new Map();\n this._headers = requestHeaders;\n const header = requestHeaders.get(\"cookie\");\n if (header) {\n const parsed = parseCookie(header);\n for (const [name, value] of parsed) {\n this._parsed.set(name, { name, value });\n }\n }\n }\n [Symbol.iterator]() {\n return this._parsed[Symbol.iterator]();\n }\n /**\n * The amount of cookies received from the client\n */\n get size() {\n return this._parsed.size;\n }\n get(...args) {\n const name = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return this._parsed.get(name);\n }\n getAll(...args) {\n var _a;\n const all = Array.from(this._parsed);\n if (!args.length) {\n return all.map(([_, value]) => value);\n }\n const name = typeof args[0] === \"string\" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;\n return all.filter(([n]) => n === name).map(([_, value]) => value);\n }\n has(name) {\n return this._parsed.has(name);\n }\n set(...args) {\n const [name, value] = args.length === 1 ? [args[0].name, args[0].value] : args;\n const map = this._parsed;\n map.set(name, { name, value });\n this._headers.set(\n \"cookie\",\n Array.from(map).map(([_, value2]) => stringifyCookie(value2)).join(\"; \")\n );\n return this;\n }\n /**\n * Delete the cookies matching the passed name or names in the request.\n */\n delete(names) {\n const map = this._parsed;\n const result = !Array.isArray(names) ? map.delete(names) : names.map((name) => map.delete(name));\n this._headers.set(\n \"cookie\",\n Array.from(map).map(([_, value]) => stringifyCookie(value)).join(\"; \")\n );\n return result;\n }\n /**\n * Delete all the cookies in the cookies in the request.\n */\n clear() {\n this.delete(Array.from(this._parsed.keys()));\n return this;\n }\n /**\n * Format the cookies in the request as a string for logging\n */\n [Symbol.for(\"edge-runtime.inspect.custom\")]() {\n return `RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;\n }\n toString() {\n return [...this._parsed.values()].map((v) => `${v.name}=${encodeURIComponent(v.value)}`).join(\"; \");\n }\n};\n\n// src/response-cookies.ts\nvar ResponseCookies = class {\n constructor(responseHeaders) {\n /** @internal */\n this._parsed = /* @__PURE__ */ new Map();\n var _a, _b, _c;\n this._headers = responseHeaders;\n const setCookie = (_c = (_b = (_a = responseHeaders.getSetCookie) == null ? void 0 : _a.call(responseHeaders)) != null ? _b : responseHeaders.get(\"set-cookie\")) != null ? _c : [];\n const cookieStrings = Array.isArray(setCookie) ? setCookie : splitCookiesString(setCookie);\n for (const cookieString of cookieStrings) {\n const parsed = parseSetCookie(cookieString);\n if (parsed)\n this._parsed.set(parsed.name, parsed);\n }\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-get CookieStore#get} without the Promise.\n */\n get(...args) {\n const key = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return this._parsed.get(key);\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-getAll CookieStore#getAll} without the Promise.\n */\n getAll(...args) {\n var _a;\n const all = Array.from(this._parsed.values());\n if (!args.length) {\n return all;\n }\n const key = typeof args[0] === \"string\" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;\n return all.filter((c) => c.name === key);\n }\n has(name) {\n return this._parsed.has(name);\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-set CookieStore#set} without the Promise.\n */\n set(...args) {\n const [name, value, cookie] = args.length === 1 ? [args[0].name, args[0].value, args[0]] : args;\n const map = this._parsed;\n map.set(name, normalizeCookie({ name, value, ...cookie }));\n replace(map, this._headers);\n return this;\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-delete CookieStore#delete} without the Promise.\n */\n delete(...args) {\n const [name, options] = typeof args[0] === \"string\" ? [args[0]] : [args[0].name, args[0]];\n return this.set({ ...options, name, value: \"\", expires: /* @__PURE__ */ new Date(0) });\n }\n [Symbol.for(\"edge-runtime.inspect.custom\")]() {\n return `ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;\n }\n toString() {\n return [...this._parsed.values()].map(stringifyCookie).join(\"; \");\n }\n};\nfunction replace(bag, headers) {\n headers.delete(\"set-cookie\");\n for (const [, value] of bag) {\n const serialized = stringifyCookie(value);\n headers.append(\"set-cookie\", serialized);\n }\n}\nfunction normalizeCookie(cookie = { name: \"\", value: \"\" }) {\n if (typeof cookie.expires === \"number\") {\n cookie.expires = new Date(cookie.expires);\n }\n if (cookie.maxAge) {\n cookie.expires = new Date(Date.now() + cookie.maxAge * 1e3);\n }\n if (cookie.path === null || cookie.path === void 0) {\n cookie.path = \"/\";\n }\n return cookie;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n RequestCookies,\n ResponseCookies,\n parseCookie,\n parseSetCookie,\n stringifyCookie\n});\n","import * as React from 'react';\nconst errorRef = {\n current: null\n};\n// React.cache is currently only available in canary/experimental React channels.\nconst cache = typeof React.cache === 'function' ? React.cache : (fn)=>fn;\n// When Cache Components is enabled, we record these as errors so that they\n// are captured by the dev overlay as it's more critical to fix these\n// when enabled.\nconst logErrorOrWarn = process.env.__NEXT_CACHE_COMPONENTS ? console.error : console.warn;\n// We don't want to dedupe across requests.\n// The developer might've just attempted to fix the warning so we should warn again if it still happens.\nconst flushCurrentErrorIfNew = cache(// eslint-disable-next-line @typescript-eslint/no-unused-vars -- cache key\n(key)=>{\n try {\n logErrorOrWarn(errorRef.current);\n } finally{\n errorRef.current = null;\n }\n});\n/**\n * Creates a function that logs an error message that is deduped by the userland\n * callsite.\n * This requires no indirection between the call of this function and the userland\n * callsite i.e. there's only a single library frame above this.\n * Do not use on the Client where sourcemaps and ignore listing might be enabled.\n * Only use that for warnings need a fix independent of the callstack.\n *\n * @param getMessage\n * @returns\n */ export function createDedupedByCallsiteServerErrorLoggerDev(getMessage) {\n return function logDedupedError(...args) {\n const message = getMessage(...args);\n if (process.env.NODE_ENV !== 'production') {\n var _stack;\n const callStackFrames = (_stack = new Error().stack) == null ? void 0 : _stack.split('\\n');\n if (callStackFrames === undefined || callStackFrames.length < 4) {\n logErrorOrWarn(message);\n } else {\n // Error:\n // logDedupedError\n // asyncApiBeingAccessedSynchronously\n // <userland callsite>\n // TODO: This breaks if sourcemaps with ignore lists are enabled.\n const key = callStackFrames[4];\n errorRef.current = message;\n flushCurrentErrorIfNew(key);\n }\n } else {\n logErrorOrWarn(message);\n }\n };\n}\n\n//# sourceMappingURL=create-deduped-by-callsite-server-error-logger.js.map","import { workAsyncStorage } from '../app-render/work-async-storage.external';\nimport { createVaryingParams, getMetadataVaryParamsAccumulator } from '../app-render/vary-params';\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect';\nimport { workUnitAsyncStorage, throwInvariantForMissingStore } from '../app-render/work-unit-async-storage.external';\nimport { InvariantError } from '../../shared/lib/invariant-error';\nimport { describeStringPropertyAccess, wellKnownProperties } from '../../shared/lib/utils/reflect-utils';\nimport { makeDevtoolsIOAwarePromise, makeFallbackParamsHangingPromise, makePromiseFromTrigger, trackFallbackParamsAccessed, RENDER_STAGES_BY_DATA_KIND, trackPromiseUsed, trackIncompatibleShellContent } from '../dynamic-rendering-utils';\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger';\nimport { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external';\nimport { isEmptyParams, hasFallbackRouteParams, allParamsAreRootParams } from '../lib/params-utils';\nexport function createParamsFromClient(underlyingParams) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized');\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null;\n return createStaticPrerenderParams(underlyingParams, null, workStore, workUnitStore, varyParamsAccumulator);\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError('createParamsFromClient should not be called in cache contexts.');\n case 'prerender-runtime':\n throw new InvariantError('createParamsFromClient should not be called in a runtime prerender.');\n case 'build-time-generator':\n throw new InvariantError(`createParamsFromClient should not be called inside ${workUnitStore.functionName}.`);\n case 'validation-client':\n {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(underlyingParams, workStore, workUnitStore.validationSamples);\n }\n return makeUntrackedParams(underlyingParams);\n }\n case 'request':\n {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(underlyingParams, workStore, workUnitStore.validationSamples);\n }\n if (process.env.NODE_ENV === 'development') {\n const stagedFallbackParams = workUnitStore.stagedFallbackParams;\n const userspaceParams = underlyingParams;\n return createRenderParamsInDev(underlyingParams, userspaceParams, stagedFallbackParams, workStore, workUnitStore);\n } else {\n return createRenderParamsInProd(underlyingParams);\n }\n }\n default:\n workUnitStore;\n }\n }\n throwInvariantForMissingStore();\n}\nexport function createServerParamsForMetadata(underlyingParams, optionalCatchAllParamName) {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator();\n return createServerParamsForServerSegment(underlyingParams, optionalCatchAllParamName, metadataVaryParamsAccumulator);\n}\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(underlyingParams, varyParamsAccumulator = null) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized');\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-legacy':\n return createStaticPrerenderParams(underlyingParams, null, workStore, workUnitStore, varyParamsAccumulator);\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError('createServerParamsForRoute should not be called in client contexts.');\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError('createServerParamsForRoute should not be called in cache contexts.');\n case 'build-time-generator':\n throw new InvariantError(`createServerParamsForRoute should not be called inside ${workUnitStore.functionName}.`);\n case 'prerender-runtime':\n {\n throw new InvariantError('createServerParamsForRoute should not be called in runtime prerenders.');\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const stagedFallbackParams = workUnitStore.stagedFallbackParams;\n const userspaceParams = underlyingParams;\n return createRenderParamsInDev(underlyingParams, userspaceParams, stagedFallbackParams, workStore, workUnitStore);\n } else {\n return createRenderParamsInProd(underlyingParams);\n }\n default:\n workUnitStore;\n }\n }\n throwInvariantForMissingStore();\n}\nexport function createServerParamsForServerSegment(underlyingParams, optionalCatchAllParamName, varyParamsAccumulator) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized');\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator);\n case 'validation-client':\n throw new InvariantError('createServerParamsForServerSegment should not be called in client contexts.');\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError('createServerParamsForServerSegment should not be called in cache contexts.');\n case 'build-time-generator':\n throw new InvariantError(`createServerParamsForServerSegment should not be called inside ${workUnitStore.functionName}.`);\n case 'prerender-runtime':\n return createRuntimePrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator);\n case 'request':\n {\n return createRenderParamsForPage(workStore, workUnitStore, underlyingParams, optionalCatchAllParamName, varyParamsAccumulator);\n }\n default:\n workUnitStore;\n }\n }\n throwInvariantForMissingStore();\n}\nexport function createPrerenderParamsForClientSegment(underlyingParams) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Missing workStore in createPrerenderParamsForClientSegment');\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams;\n if (fallbackParams) {\n for(let key in underlyingParams){\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(workUnitStore.renderSignal, workStore.route, '`params`', workUnitStore);\n }\n }\n }\n break;\n case 'validation-client':\n throw new InvariantError('createPrerenderParamsForClientSegment should not be called in validation contexts.');\n break;\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError('createPrerenderParamsForClientSegment should not be called in cache contexts.');\n case 'build-time-generator':\n throw new InvariantError(`createPrerenderParamsForClientSegment should not be called inside ${workUnitStore.functionName}.`);\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n break;\n default:\n workUnitStore;\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams);\n}\nfunction createStaticPrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, prerenderStore, varyParamsAccumulator) {\n switch(prerenderStore.type){\n case 'prerender':\n {\n let userspaceParams = underlyingParams;\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(varyParamsAccumulator, underlyingParams, optionalCatchAllParamName);\n }\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams);\n }\n const fallbackParams = prerenderStore.fallbackRouteParams;\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore);\n }\n // All params are static.\n const { stagedRendering } = prerenderStore;\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticUrlData.static;\n return stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams);\n }\n }\n return makeUntrackedParams(userspaceParams);\n }\n case 'prerender-client':\n {\n const fallbackParams = prerenderStore.fallbackRouteParams;\n if (fallbackParams) {\n for(const key in underlyingParams){\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(underlyingParams, workStore, prerenderStore);\n }\n }\n }\n break;\n }\n case 'prerender-legacy':\n break;\n default:\n prerenderStore;\n }\n let userspaceParams = underlyingParams;\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(varyParamsAccumulator, underlyingParams, optionalCatchAllParamName);\n }\n return makeUntrackedParams(userspaceParams);\n}\nfunction createRuntimePrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator) {\n let userspaceParams = underlyingParams;\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(varyParamsAccumulator, underlyingParams, optionalCatchAllParamName);\n }\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams);\n }\n // Root params are allowed in shells, so we allow them to resolve without a delay.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams);\n }\n // Non-root params are URL data, and we need to recover a param-less session shell,\n // so we delay all params until the PrefetchRuntime stage (even if they're static)\n const paramsStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData;\n const { stagedRendering } = workUnitStore;\n if (!stagedRendering) {\n // If there's no stage controller, we're in a prospective runtime prerender.\n // Make sure we don't unblock content that won't be reached in the final prerender.\n if (workUnitStore.finalStage < paramsStage) {\n return makeHangingParams(underlyingParams, workStore, workUnitStore);\n } else {\n return makeUntrackedParams(userspaceParams);\n }\n }\n // If params don't resolve in this prerender, caches need to treat them as a hanging input.\n if (stagedRendering.finalStage && stagedRendering.finalStage < paramsStage) {\n return makeHangingParams(underlyingParams, workStore, workUnitStore);\n } else {\n return stagedRendering.delayUntilStage(paramsStage, 'params', userspaceParams);\n }\n}\nfunction createRenderParamsForPage(workStore, workUnitStore, underlyingParams, optionalCatchAllParamName, varyParamsAccumulator) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore;\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams;\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(underlyingParams, workStore, validationSamples);\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(varyParamsAccumulator, userspaceParams, optionalCatchAllParamName);\n }\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(workStore, workUnitStore, stagedRendering, asyncApiPromises, underlyingParams, userspaceParams);\n }\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const stagedFallbackParams = workUnitStore.stagedFallbackParams;\n return createRenderParamsInDev(underlyingParams, userspaceParams, stagedFallbackParams, workStore, workUnitStore);\n } else {\n return createRenderParamsInProd(userspaceParams);\n }\n}\nfunction createStagedRenderParams(workStore, workUnitStore, stagedRendering, asyncApiPromises, underlyingParams, userspaceParams) {\n const promise = createStagedRenderParamsImpl(workUnitStore, stagedRendering, asyncApiPromises, underlyingParams, userspaceParams);\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(underlyingParams, promise, workStore);\n } else {\n return promise;\n }\n}\nfunction createStagedRenderParamsImpl(workUnitStore, stagedRendering, asyncApiPromises, /** The actual param values, without any instrumentation */ underlyingParams, /** The params object to return to userspace, possibly wrapped in a proxy */ userspaceParams) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams);\n }\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.stagedFallbackParams)) {\n return createParamsPromiseFromTrigger(asyncApiPromises.sharedParamsParent, userspaceParams);\n }\n // All params are static.\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsRuntimeShell`.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticUrlData[workUnitStore.needsRuntimeShell ? 'runtime' : 'static'];\n const promise = stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams);\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(promise, trackIncompatibleShellContent.bind(null, workUnitStore, 'static `params`'));\n } else {\n return promise;\n }\n }\n return makeUntrackedParams(userspaceParams);\n}\nfunction createParamsPromiseFromTrigger(trigger, userspaceParams) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise = new Promise((resolve, reject)=>{\n trigger.then(()=>resolve(userspaceParams), reject);\n });\n promise.catch(noop);\n // @ts-expect-error\n promise.displayName = 'params';\n return promise;\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams);\n }\n}\nfunction noop() {}\nfunction createServerParamsProxyForInstantValidation(underlyingParams, workStore, validationSamples) {\n const { createExhaustiveParamsProxy } = require('../app-render/instant-validation/instant-samples');\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}));\n return createExhaustiveParamsProxy(underlyingParams, declaredParams, workStore.route);\n}\nfunction createClientParamsInInstantValidation(underlyingParams, workStore, validationSamples) {\n const { createExhaustiveParamsProxy } = require('../app-render/instant-validation/instant-samples');\n const declaredParams = new Set(Object.keys((validationSamples == null ? void 0 : validationSamples.params) ?? {}));\n const proxiedUnderlying = createExhaustiveParamsProxy(underlyingParams, declaredParams, workStore.route);\n return Promise.resolve(proxiedUnderlying);\n}\nfunction createRenderParamsInProd(userspaceParams) {\n return makeUntrackedParams(userspaceParams);\n}\nfunction createRenderParamsInDev(underlyingParams, userpaceParams, stagedFallbackParams, workStore, requestStore) {\n return makeDynamicallyTrackedParamsWithDevWarnings(underlyingParams, userpaceParams, hasFallbackRouteParams(underlyingParams, stagedFallbackParams), workStore, requestStore);\n}\nconst CachedParams = new WeakMap();\nconst fallbackParamsProxyHandler = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver);\n return ({\n [prop]: (...args)=>{\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore, '`params`');\n }\n abortOnDynamicAccess('fallback-params', new Error(`Accessed fallback \\`params\\` during prerendering.`));\n return new Proxy(originalMethod.apply(target, args), fallbackParamsProxyHandler);\n }\n })[prop];\n }\n return ReflectAdapter.get(target, prop, receiver);\n }\n};\nfunction makeHangingParams(underlyingParams, workStore, prerenderStore) {\n const cachedParams = CachedParams.get(underlyingParams);\n if (cachedParams) {\n return cachedParams;\n }\n const promise = new Proxy(makeFallbackParamsHangingPromise(prerenderStore.renderSignal, workStore.route, '`params`', // Passing `null` for the store disables tracking of params usage.\n // Caches need the additional logic from `fallbackParamsProxyHandler`,\n // so we track params usage there instead.\n null), fallbackParamsProxyHandler);\n CachedParams.set(underlyingParams, promise);\n return promise;\n}\nfunction makeUntrackedParams(underlyingParams) {\n const cachedParams = CachedParams.get(underlyingParams);\n if (cachedParams) {\n return cachedParams;\n }\n const promise = Promise.resolve(underlyingParams);\n CachedParams.set(underlyingParams, promise);\n return promise;\n}\nfunction makeDynamicallyTrackedParamsWithDevWarnings(underlyingParams, userspaceParams, hasFallbackParams, workStore, requestStore) {\n const cachedParams = CachedParams.get(underlyingParams);\n if (cachedParams) {\n return cachedParams;\n }\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams ? makeDevtoolsIOAwarePromise(userspaceParams, requestStore, RENDER_STAGES_BY_DATA_KIND.runtimeUrlData) : Promise.resolve(userspaceParams);\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(underlyingParams, promise, workStore);\n CachedParams.set(underlyingParams, proxiedPromise);\n return proxiedPromise;\n}\nfunction instrumentParamsPromiseWithDevWarnings(underlyingParams, promise, workStore) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set();\n Object.keys(underlyingParams).forEach((prop)=>{\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop);\n }\n });\n return new Proxy(promise, {\n get (target, prop, receiver) {\n if (typeof prop === 'string') {\n if (// We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)) {\n const expression = describeStringPropertyAccess('params', prop);\n warnForSyncAccess(workStore.route, expression);\n }\n }\n return ReflectAdapter.get(target, prop, receiver);\n },\n set (target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop);\n }\n return ReflectAdapter.set(target, prop, value, receiver);\n },\n ownKeys (target) {\n const expression = '`...params` or similar expression';\n warnForSyncAccess(workStore.route, expression);\n return Reflect.ownKeys(target);\n }\n });\n}\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(createParamsAccessError);\nfunction createParamsAccessError(route, expression) {\n const prefix = route ? `Route \"${route}\" ` : 'This route ';\n return new Error(`${prefix}used ${expression}. ` + `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` + `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`);\n}\n\n//# sourceMappingURL=params.js.map","import { getVaryParamsAccumulator, workUnitAsyncStorage } from './work-unit-async-storage.external';\nimport { SEARCH_PARAMS_VARY_ID } from '../../shared/lib/segment-cache/vary-params-decoding';\n/**\n * Accumulates vary params for a single segment (or for metadata/rootParams).\n *\n * A VaryParamsAccumulator is an `AsyncIterable<VaryParamId>` that can be serialized\n * by React Flight. As params are accessed during render, each newly-seen param\n * name is `add`ed, which yields it into the Flight stream immediately. After\n * rendering, call `close()` (via `finishAccumulatingVaryParams`) to end the\n * iteration.\n *\n * Because each access is flushed into the stream as it happens, the set of\n * accessed params is built up incrementally, with no step at the end of the\n * render that has to run for the client to read anything. If the prerender is\n * aborted by sync I/O, the params yielded before the abort are already in the\n * stream — and they're exactly the params the partial response depends on.\n * This mirrors how `StaleTimeIterable` works (see stale-time.ts).\n *\n * Each name is emitted at most once: `add` dedupes against the set of\n * already-yielded names, so the stream never contains a duplicate.\n *\n * NOTE: like `StaleTimeIterable`, this supports a single concurrent iteration\n * (Flight iterates it exactly once). The shared empty singleton below is the\n * only instance referenced by more than one segment, and it only ever yields\n * \"done\", so concurrent iteration of it is safe.\n */ export class VaryParamsAccumulator {\n /**\n * Records that a param was accessed. Yields the name into the stream the\n * first time it's seen; subsequent accesses of the same name are no-ops.\n */ add(id) {\n if (this._done || this._seen.has(id)) {\n return;\n }\n this._seen.add(id);\n if (this._resolve !== null) {\n this._resolve({\n value: id,\n done: false\n });\n this._resolve = null;\n } else {\n this._buffer.push(id);\n }\n }\n /** Ends the iteration. Best-effort: if skipped (e.g. on a sync-I/O abort),\n * the consumer simply reads the params yielded so far. */ close() {\n if (this._done) {\n return;\n }\n this._done = true;\n if (this._resolve !== null) {\n this._resolve({\n value: undefined,\n done: true\n });\n this._resolve = null;\n }\n }\n [Symbol.asyncIterator]() {\n return {\n next: ()=>{\n if (this._buffer.length > 0) {\n return Promise.resolve({\n value: this._buffer.shift(),\n done: false\n });\n }\n if (this._done) {\n return Promise.resolve({\n value: undefined,\n done: true\n });\n }\n return new Promise((resolve)=>{\n this._resolve = resolve;\n });\n }\n };\n }\n constructor(){\n this._resolve = null;\n this._done = false;\n this._buffer = [];\n // The set of param names already yielded. Doubles as the dedupe guard so the\n // same name is never emitted twice.\n this._seen = new Set();\n }\n}\n/**\n * A singleton accumulator that's already closed with no params. Use this for\n * segments where we know upfront that no params will be accessed, such as\n * client components or segments without user code.\n *\n * Benefits:\n * - No need to accumulate or close later\n * - Resilient: reads as an empty set even if other tracking fails\n * - Memory efficient: reuses the same object\n *\n * It's never added to `ResponseVaryParamsAccumulator.segments` (callers pass it\n * directly), so `finishAccumulatingVaryParams` doesn't touch it.\n */ export const emptyVaryParamsAccumulator = new VaryParamsAccumulator();\nemptyVaryParamsAccumulator.close();\nexport function createResponseVaryParamsAccumulator() {\n // Create the head and rootParams accumulators as top-level fields.\n // Segment accumulators are added to the segments set as they are created.\n const head = new VaryParamsAccumulator();\n const rootParams = new VaryParamsAccumulator();\n const segments = new Set();\n return {\n head,\n rootParams,\n segments\n };\n}\n/**\n * Allocates a new VaryParamsAccumulator and adds it to the response accumulator\n * associated with the current WorkUnitStore.\n *\n * Returns an iterable that yields the segment's vary params as they're\n * accessed. The iterable can be passed directly to React Flight for\n * serialization.\n */ export function createVaryParamsAccumulator() {\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (!workUnitStore) {\n return null;\n }\n const responseAccumulator = getVaryParamsAccumulator(workUnitStore);\n if (!responseAccumulator) {\n return null;\n }\n const accumulator = new VaryParamsAccumulator();\n responseAccumulator.segments.add(accumulator);\n return accumulator;\n}\nexport function getMetadataVaryParamsAccumulator() {\n var _getVaryParamsAccumulator;\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (!workUnitStore) {\n return null;\n }\n return ((_getVaryParamsAccumulator = getVaryParamsAccumulator(workUnitStore)) == null ? void 0 : _getVaryParamsAccumulator.head) ?? null;\n}\n// The metadata and viewport are always delivered in a single payload, so they\n// don't need to be tracked separately. This may change in the future, but for\n// now this is just an alias.\nexport const getViewportVaryParamsAccumulator = getMetadataVaryParamsAccumulator;\n/**\n * Returns the response-level root params iterable for serialization. Root\n * params are emitted once at the top level (not folded into every segment);\n * the client unions them into each segment's set.\n */ export function getRootParamsVaryParamsAccumulator() {\n var _getVaryParamsAccumulator;\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (!workUnitStore) {\n return null;\n }\n return ((_getVaryParamsAccumulator = getVaryParamsAccumulator(workUnitStore)) == null ? void 0 : _getVaryParamsAccumulator.rootParams) ?? null;\n}\n/**\n * Records that a param was accessed. Adds the param name to the accumulator.\n */ export function accumulateVaryParam(accumulator, id) {\n accumulator.add(id);\n}\n/**\n * Records a root param access.\n */ export function accumulateRootVaryParam(paramName) {\n const rootParamsAccumulator = getRootParamsVaryParamsAccumulator();\n if (rootParamsAccumulator !== null) {\n accumulateVaryParam(rootParamsAccumulator, paramName);\n }\n}\nexport function createVaryingParams(accumulator, originalParamsObject, optionalCatchAllParamName) {\n if (optionalCatchAllParamName !== null) {\n // When there's an optional catch-all param with no value (e.g.,\n // [[...slug]] at /), the param doesn't exist as a property on the params\n // object. Use a Proxy to track all param access — both existing params\n // and the missing optional param — including enumeration patterns like\n // Object.keys(), spread, for...in, and `in` checks.\n return new Proxy(originalParamsObject, {\n get (target, prop, receiver) {\n if (typeof prop === 'string') {\n if (prop === optionalCatchAllParamName || Object.prototype.hasOwnProperty.call(target, prop)) {\n accumulateVaryParam(accumulator, prop);\n }\n }\n return Reflect.get(target, prop, receiver);\n },\n has (target, prop) {\n if (prop === optionalCatchAllParamName) {\n accumulateVaryParam(accumulator, optionalCatchAllParamName);\n }\n return Reflect.has(target, prop);\n },\n ownKeys (target) {\n // Enumerating the params object means the user's code may depend on\n // which params are present, so conservatively track the optional\n // param as accessed.\n accumulateVaryParam(accumulator, optionalCatchAllParamName);\n return Reflect.ownKeys(target);\n }\n });\n }\n // When there's no optional catch-all, all params exist as properties on the\n // object, so we can use defineProperty getters instead of a Proxy. This is\n // faster because the engine can optimize property access on regular objects\n // more aggressively than Proxy trap calls.\n const underlyingParamsWithVarying = {};\n for(const paramName in originalParamsObject){\n Object.defineProperty(underlyingParamsWithVarying, paramName, {\n get () {\n accumulateVaryParam(accumulator, paramName);\n return originalParamsObject[paramName];\n },\n enumerable: true\n });\n }\n return underlyingParamsWithVarying;\n}\nexport function createVaryingSearchParams(accumulator, originalSearchParamsObject) {\n // Search params have no fixed schema, so any access — missing-key reads, `in`\n // checks, or enumeration — must register as varying. A Proxy is required\n // (rather than per-property getters) so that enumeration of an empty\n // searchParams object still triggers a vary. All accesses bucket into the\n // single search params id; the segment is keyed by the whole query string.\n // TODO: Split into per-param tracking if the cache key evolves.\n return new Proxy(originalSearchParamsObject, {\n get (target, prop, receiver) {\n if (typeof prop === 'string') {\n accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID);\n }\n return Reflect.get(target, prop, receiver);\n },\n has (target, prop) {\n if (typeof prop === 'string') {\n accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID);\n }\n return Reflect.has(target, prop);\n },\n ownKeys (target) {\n accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID);\n return Reflect.ownKeys(target);\n }\n });\n}\n/**\n * Closes all accumulators in a ResponseVaryParamsAccumulator, ending their\n * iterables. Call this after rendering is complete.\n *\n * This does NOT merge root params into each segment — root params are\n * serialized separately (at the top level of the response) and unioned in by\n * the client. And it's best-effort: if it's skipped because the render was\n * aborted by sync I/O, the consumer just reads the params each iterable yielded\n * before the abort.\n *\n * If we can't track vary params (e.g., legacy prerender), simply don't call\n * this function - the client treats a missing iterable as \"unknown\" vary\n * params.\n */ export function finishAccumulatingVaryParams(responseAccumulator) {\n responseAccumulator.head.close();\n responseAccumulator.rootParams.close();\n for (const segmentAccumulator of responseAccumulator.segments){\n segmentAccumulator.close();\n }\n}\n\n//# sourceMappingURL=vary-params.js.map","const NEXT_STATIC_GEN_BAILOUT = 'NEXT_STATIC_GEN_BAILOUT';\nexport class StaticGenBailoutError extends Error {\n constructor(...args){\n super(...args), this.code = NEXT_STATIC_GEN_BAILOUT;\n }\n}\nexport function isStaticGenBailoutError(error) {\n if (typeof error !== 'object' || error === null || !('code' in error)) {\n return false;\n }\n return error.code === NEXT_STATIC_GEN_BAILOUT;\n}\n\n//# sourceMappingURL=static-generation-bailout.js.map","export function allParamsAreRootParams(underlyingParams, rootParams) {\n for(const paramName in underlyingParams){\n if (!Object.hasOwn(rootParams, paramName)) {\n return false;\n }\n }\n return true;\n}\nexport function isEmptyParams(params) {\n for(const _paramKey in params){\n return false;\n }\n return true;\n}\nexport function hasFallbackRouteParams(underlyingParams, fallbackParams) {\n if (fallbackParams) {\n for(let key in underlyingParams){\n if (fallbackParams.has(key)) {\n return true;\n }\n }\n }\n return false;\n}\n\n//# sourceMappingURL=params-utils.js.map","import { StaticGenBailoutError } from '../../client/components/static-generation-bailout';\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external';\nimport { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external';\nimport { createSearchParamsInUseCacheError } from '../use-cache/use-cache-messages';\nexport function throwWithStaticGenerationBailoutErrorWithDynamicError(route, expression) {\n throw new StaticGenBailoutError(`Route ${route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);\n}\nexport function throwForSearchParamsAccessInUseCache(workStore, constructorOpt) {\n const error = createSearchParamsInUseCacheError(workStore.route);\n Error.captureStackTrace(error, constructorOpt);\n workStore.invalidDynamicUsageError ??= error;\n throw error;\n}\nexport function isRequestApiAllowedInCurrentPhase(workUnitStore) {\n switch(workUnitStore.phase){\n case 'action':\n case 'render':\n {\n // The request is still in progress. The API may be disallowed for other reasons,\n // but not because of phase.\n return true;\n }\n case 'after':\n {\n // The request has finished.\n // If we're in a Route Handler or a Server Action,\n // request APIs can be called everywhere, even in after().\n const actionStore = actionAsyncStorage.getStore();\n if (actionStore && (actionStore.isAppRoute || actionStore.isAction)) {\n return true;\n }\n const afterTaskStore = afterTaskAsyncStorage.getStore();\n if (afterTaskStore) {\n // We're in an `after` callback. Request APIs are callable if\n // the `after()` call happened in an action phase:\n // - in a Route Handler\n // - in a Server Action's body (but not the render after)\n //\n // TODO(after): Is it even possible to have `phase === 'action'` but no `actionStore`?\n // We should revisit this setup and simplify this.\n return afterTaskStore.rootTaskSpawnPhase === 'action';\n }\n // Otherwise, we must be in a page, in the `after` phase.\n // We don't allow calling request APIs here because we'd miss\n // them during prerendering and wouldn't know that the page is dynamic.\n return false;\n }\n }\n}\n\n//# sourceMappingURL=utils.js.map","import { workAsyncStorage } from '../app-render/work-async-storage.external';\nimport { createVaryingSearchParams, getMetadataVaryParamsAccumulator } from '../app-render/vary-params';\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect';\nimport { throwToInterruptStaticGeneration, annotateDynamicAccess } from '../app-render/dynamic-rendering';\nimport { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external';\nimport { workUnitAsyncStorage, throwInvariantForMissingStore } from '../app-render/work-unit-async-storage.external';\nimport { InvariantError } from '../../shared/lib/invariant-error';\nimport { makeDevtoolsIOAwarePromise, makeURLDataHangingPromise, makePromiseFromTrigger, trackURLDataAccessed, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils';\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger';\nimport { describeStringPropertyAccess, describeHasCheckingStringProperty, wellKnownProperties } from '../../shared/lib/utils/reflect-utils';\nimport { throwWithStaticGenerationBailoutErrorWithDynamicError, throwForSearchParamsAccessInUseCache } from './utils';\nexport function createSearchParamsFromClient(underlyingSearchParams) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized');\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore);\n case 'prerender-runtime':\n throw new InvariantError('createSearchParamsFromClient should not be called in a runtime prerender.');\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError('createSearchParamsFromClient should not be called in cache contexts.');\n case 'build-time-generator':\n throw new InvariantError(`createSearchParamsFromClient should not be called inside ${workUnitStore.functionName}.`);\n case 'validation-client':\n {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(underlyingSearchParams, workStore, workUnitStore);\n }\n return makeUntrackedSearchParams(underlyingSearchParams);\n }\n case 'request':\n return createRenderSearchParams(underlyingSearchParams, workStore, workUnitStore);\n default:\n workUnitStore;\n }\n }\n throwInvariantForMissingStore();\n}\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(underlyingSearchParams) {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator();\n return createServerSearchParamsForServerPage(underlyingSearchParams, metadataVaryParamsAccumulator);\n}\nexport function createServerSearchParamsForServerPage(underlyingSearchParams, varyParamsAccumulator) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized');\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore);\n case 'validation-client':\n throw new InvariantError('createServerSearchParamsForServerPage should not be called in a client validation.');\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError('createServerSearchParamsForServerPage should not be called in cache contexts.');\n case 'build-time-generator':\n throw new InvariantError(`createServerSearchParamsForServerPage should not be called inside ${workUnitStore.functionName}.`);\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(underlyingSearchParams, workStore, workUnitStore, varyParamsAccumulator);\n case 'request':\n return createRenderSearchParams(underlyingSearchParams, workStore, workUnitStore);\n default:\n workUnitStore;\n }\n }\n throwInvariantForMissingStore();\n}\nexport function createPrerenderSearchParamsForClientPage() {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized');\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({});\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeURLDataHangingPromise(workUnitStore.renderSignal, workStore.route, '`searchParams`', workUnitStore);\n case 'validation-client':\n throw new InvariantError('createPrerenderSearchParamsForClientPage should not be called in a client validation.');\n case 'prerender-runtime':\n throw new InvariantError('createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.');\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError('createPrerenderSearchParamsForClientPage should not be called in cache contexts.');\n case 'build-time-generator':\n throw new InvariantError(`createPrerenderSearchParamsForClientPage should not be called inside ${workUnitStore.functionName}.`);\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({});\n default:\n workUnitStore;\n }\n }\n throwInvariantForMissingStore();\n}\nfunction createStaticPrerenderSearchParams(workStore, prerenderStore) {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({});\n }\n switch(prerenderStore.type){\n case 'prerender':\n case 'prerender-client':\n {\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore);\n }\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore);\n default:\n return prerenderStore;\n }\n}\nfunction createRuntimePrerenderSearchParams(underlyingSearchParams, workStore, workUnitStore, varyParamsAccumulator) {\n const userspaceSearchParams = varyParamsAccumulator !== null ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams) : underlyingSearchParams;\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData;\n const { stagedRendering } = workUnitStore;\n if (!stagedRendering) {\n // If there's no stage controller, we're in a prospective runtime prerender.\n // Make sure we don't unblock content that won't be reached in the final prerender.\n if (workUnitStore.finalStage < searchParamsStage) {\n return makeHangingSearchParams(workStore, workUnitStore);\n } else {\n return makeUntrackedSearchParams(userspaceSearchParams);\n }\n }\n // If search params don't resolve in this prerender, caches need to treat them as a hanging input.\n if (stagedRendering.finalStage && stagedRendering.finalStage < searchParamsStage) {\n return makeHangingSearchParams(workStore, workUnitStore);\n } else {\n return stagedRendering.delayUntilStage(searchParamsStage, 'searchParams', userspaceSearchParams);\n }\n}\nfunction createRenderSearchParams(underlyingSearchParams, workStore, requestStore) {\n const { asyncApiPromises, validationSamples } = requestStore;\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams;\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(workStore, validationSamples, underlyingSearchParams);\n }\n return createStagedRenderSearchParams(workStore, asyncApiPromises, underlyingSearchParams, userspaceSearchParams);\n }\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({});\n }\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(underlyingSearchParams, workStore, requestStore);\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams);\n }\n}\nfunction createStagedRenderSearchParams(workStore, asyncApiPromises, underlyingSearchParams, userspaceSearchParams) {\n const trigger = asyncApiPromises.sharedSearchParamsParent;\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise((resolve, reject)=>{\n trigger.then(()=>resolve(userspaceSearchParams), reject);\n });\n // @ts-expect-error\n promise.displayName = 'searchParams';\n promise.catch(ignoreReject);\n return instrumentSearchParamsPromiseWithDevWarnings(underlyingSearchParams, promise, workStore);\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams);\n }\n}\nfunction createSearchParamsProxyForInstantValidation(workStore, validationSamples, underlyingSearchParams) {\n const { createExhaustiveSearchParamsProxy } = require('../app-render/instant-validation/instant-samples');\n const declaredKeys = new Set(Object.keys(validationSamples.searchParams ?? {}));\n return createExhaustiveSearchParamsProxy(underlyingSearchParams, declaredKeys, workStore.route);\n}\nconst CachedSearchParams = new WeakMap();\nconst CachedSearchParamsForUseCache = new WeakMap();\nfunction makeHangingSearchParams(workStore, prerenderStore) {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore);\n if (cachedSearchParams) {\n return cachedSearchParams;\n }\n const promise = makeURLDataHangingPromise(prerenderStore.renderSignal, workStore.route, '`searchParams`', // Passing `null` for the store disables tracking of params usage.\n // We want accesses of chained promises to be tracked as well.\n // TODO: The custom tracking seems unnecessary, we should standardize it\n null);\n const trackSearchParamsAccessed = ()=>{\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore();\n trackURLDataAccessed(workUnitStore ?? prerenderStore, '`searchParams`');\n };\n const proxyHandler = {\n get (target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver);\n }\n switch(prop){\n case 'then':\n case 'catch':\n case 'finally':\n {\n const originalMethod = ReflectAdapter.get(target, prop, receiver);\n return ({\n [prop]: (...args)=>{\n const expression = '`await searchParams`, `searchParams.then`, or similar';\n trackSearchParamsAccessed();\n annotateDynamicAccess(expression, prerenderStore);\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n abortOnDynamicAccess('runtime', new Error('Accessed `searchParams` during prerendering.'));\n return new Proxy(originalMethod.apply(target, args), proxyHandler);\n }\n })[prop];\n }\n case 'status':\n {\n const expression = '`use(searchParams)`, `searchParams.status`, or similar';\n trackSearchParamsAccessed();\n annotateDynamicAccess(expression, prerenderStore);\n return ReflectAdapter.get(target, prop, receiver);\n }\n default:\n {\n return ReflectAdapter.get(target, prop, receiver);\n }\n }\n }\n };\n const proxiedPromise = new Proxy(promise, proxyHandler);\n CachedSearchParams.set(prerenderStore, proxiedPromise);\n return proxiedPromise;\n}\nfunction makeErroringSearchParams(workStore, prerenderStore) {\n const cachedSearchParams = CachedSearchParams.get(workStore);\n if (cachedSearchParams) {\n return cachedSearchParams;\n }\n const underlyingSearchParams = {};\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams);\n const proxiedPromise = new Proxy(promise, {\n get (target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver);\n }\n if (typeof prop === 'string' && prop === 'then') {\n const expression = '`await searchParams`, `searchParams.then`, or similar';\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(workStore.route, expression);\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(expression, workStore, prerenderStore);\n }\n }\n return ReflectAdapter.get(target, prop, receiver);\n }\n });\n CachedSearchParams.set(workStore, proxiedPromise);\n return proxiedPromise;\n}\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */ export function makeErroringSearchParamsForUseCache() {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized');\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore);\n if (cachedSearchParams) {\n return cachedSearchParams;\n }\n const promise = Promise.resolve({});\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver);\n }\n if (typeof prop === 'string' && (prop === 'then' || !wellKnownProperties.has(prop))) {\n throwForSearchParamsAccessInUseCache(workStore, get);\n }\n return ReflectAdapter.get(target, prop, receiver);\n }\n });\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise);\n return proxiedPromise;\n}\nfunction makeUntrackedSearchParams(underlyingSearchParams) {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams);\n if (cachedSearchParams) {\n return cachedSearchParams;\n }\n const promise = Promise.resolve(underlyingSearchParams);\n CachedSearchParams.set(underlyingSearchParams, promise);\n return promise;\n}\nfunction makeUntrackedSearchParamsWithDevWarnings(underlyingSearchParams, workStore, requestStore) {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams);\n if (cachedSearchParams) {\n return cachedSearchParams;\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(underlyingSearchParams, workStore, requestStore);\n CachedSearchParams.set(requestStore, promise);\n return promise;\n}\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(underlyingSearchParams, workStore, requestStore) {\n const promiseInitialized = {\n current: false\n };\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(underlyingSearchParams, workStore, promiseInitialized);\n const promise = makeDevtoolsIOAwarePromise(proxiedUnderlying, requestStore, RENDER_STAGES_BY_DATA_KIND.runtimeUrlData);\n promise.then(()=>{\n promiseInitialized.current = true;\n }, // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the PrefetchRuntime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject);\n return instrumentSearchParamsPromiseWithDevWarnings(underlyingSearchParams, promise, workStore);\n}\nfunction ignoreReject() {}\nfunction instrumentSearchParamsObjectWithDevWarnings(underlyingSearchParams, workStore, promiseInitialized) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get (target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop);\n throwWithStaticGenerationBailoutErrorWithDynamicError(workStore.route, expression);\n }\n }\n return ReflectAdapter.get(target, prop, receiver);\n },\n has (target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty('searchParams', prop);\n throwWithStaticGenerationBailoutErrorWithDynamicError(workStore.route, expression);\n }\n }\n return Reflect.has(target, prop);\n },\n ownKeys (target) {\n if (workStore.dynamicShouldError) {\n const expression = '`{...searchParams}`, `Object.keys(searchParams)`, or similar';\n throwWithStaticGenerationBailoutErrorWithDynamicError(workStore.route, expression);\n }\n return Reflect.ownKeys(target);\n }\n });\n}\nfunction instrumentSearchParamsPromiseWithDevWarnings(underlyingSearchParams, promise, workStore) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set();\n Object.keys(underlyingSearchParams).forEach((prop)=>{\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop);\n }\n });\n return new Proxy(promise, {\n get (target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`';\n throwWithStaticGenerationBailoutErrorWithDynamicError(workStore.route, expression);\n }\n if (typeof prop === 'string') {\n if (!wellKnownProperties.has(prop) && (proxiedProperties.has(prop) || // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)) {\n const expression = describeStringPropertyAccess('searchParams', prop);\n warnForSyncAccess(workStore.route, expression);\n }\n }\n return ReflectAdapter.get(target, prop, receiver);\n },\n set (target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop);\n }\n return Reflect.set(target, prop, value, receiver);\n },\n has (target, prop) {\n if (typeof prop === 'string') {\n if (!wellKnownProperties.has(prop) && (proxiedProperties.has(prop) || // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)) {\n const expression = describeHasCheckingStringProperty('searchParams', prop);\n warnForSyncAccess(workStore.route, expression);\n }\n }\n return Reflect.has(target, prop);\n },\n ownKeys (target) {\n const expression = '`Object.keys(searchParams)` or similar';\n warnForSyncAccess(workStore.route, expression);\n return Reflect.ownKeys(target);\n }\n });\n}\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(createSearchAccessError);\nfunction createSearchAccessError(route, expression) {\n const prefix = route ? `Route \"${route}\" ` : 'This route ';\n return new Error(`${prefix}used ${expression}. ` + `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` + `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`);\n}\nfunction createClientSearchParamsInValidation(underlyingSearchParams, workStore, workUnitStore) {\n var _workUnitStore_validationSamples;\n const { createExhaustiveSearchParamsProxy } = require('../app-render/instant-validation/instant-samples');\n const declaredKeys = new Set(Object.keys(((_workUnitStore_validationSamples = workUnitStore.validationSamples) == null ? void 0 : _workUnitStore_validationSamples.searchParams) ?? {}));\n underlyingSearchParams = createExhaustiveSearchParamsProxy(underlyingSearchParams, declaredKeys, workStore.route);\n return Promise.resolve(underlyingSearchParams);\n}\n\n//# sourceMappingURL=search-params.js.map","'use client';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime';\nimport { use } from 'react';\nimport { urlSearchParamsToParsedUrlQuery } from '../route-params';\nimport { SearchParamsContext } from '../../shared/lib/hooks-client-context.shared-runtime';\nimport { createClientParams, createClientSearchParams } from './client-boundary-params';\n/**\n * When the Page is a client component we send the params and searchParams to this client wrapper\n * where they are turned into dynamically tracked values before being passed to the actual Page component.\n *\n * additionally we may send promises representing the params and searchParams. We don't ever use these passed\n * values but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations.\n * It is up to the caller to decide if the promises are needed.\n */ export function ClientPageRoot({ Component, serverProvidedParams }) {\n let searchParams;\n let params;\n if (serverProvidedParams !== null) {\n searchParams = serverProvidedParams.searchParams;\n params = serverProvidedParams.params;\n } else {\n // When Cache Components is enabled, the server does not pass the params as\n // props; they are parsed on the client and passed via context.\n const layoutRouterContext = use(LayoutRouterContext);\n params = layoutRouterContext !== null ? layoutRouterContext.parentParams : {};\n // This is an intentional behavior change: when Cache Components is enabled,\n // client segments receive the \"canonical\" search params, not the\n // rewritten ones. Users should either call useSearchParams directly or pass\n // the rewritten ones in from a Server Component.\n // TODO: Log a deprecation error when this object is accessed\n searchParams = urlSearchParamsToParsedUrlQuery(use(SearchParamsContext));\n }\n const clientSearchParams = createClientSearchParams(searchParams);\n const clientParams = createClientParams(params);\n return /*#__PURE__*/ _jsx(Component, {\n params: clientParams,\n searchParams: clientSearchParams\n });\n}\n\n//# sourceMappingURL=client-page.js.map","'use client'\n\nimport type { Params } from '../../server/request/params'\nimport { LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime'\nimport { use } from 'react'\nimport { createClientParams } from './client-boundary-params'\n\n/**\n * When the Page is a client component we send the params to this client wrapper\n * where they are turned into dynamically tracked values before being passed to the actual Segment component.\n *\n * additionally we may send a promise representing params. We don't ever use this passed\n * value but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations\n * such as when cacheComponents is enabled. It is up to the caller to decide if the promises are needed.\n */\nexport function ClientSegmentRoot({\n Component,\n slots,\n serverProvidedParams,\n}: {\n Component: React.ComponentType<any>\n slots: { [key: string]: React.ReactNode }\n serverProvidedParams: null | {\n params: Params\n promises: Array<Promise<any>> | null\n }\n}) {\n let params: Params\n if (serverProvidedParams !== null) {\n params = serverProvidedParams.params\n } else {\n // When Cache Components is enabled, the server does not pass the params\n // as props; they are parsed on the client and passed via context.\n const layoutRouterContext = use(LayoutRouterContext)\n params =\n layoutRouterContext !== null ? layoutRouterContext.parentParams : {}\n }\n\n const clientParams = createClientParams(params)\n\n return <Component {...slots} params={clientParams} />\n}\n","// Client-safe access to the server-only async-storage singletons. On the\n// server these re-export the real storages; in the browser bundle this module\n// is aliased to `./server-async-storage.browser` (see\n// scripts/generate-browser-variant-aliases.mjs), which exports `undefined`\n// stubs so the AsyncLocalStorage modules are never bundled into the client.\n// Consumers must guard usage so the stubs are not dereferenced in the browser.\nexport { actionAsyncStorage } from '../../server/app-render/action-async-storage.external';\nexport { workAsyncStorage } from '../../server/app-render/work-async-storage.external';\nexport { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external';\n\n//# sourceMappingURL=server-async-storage.js.map","'use client';\nimport { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from \"react/jsx-runtime\";\n/**\n * HTTPAccessFallbackBoundary is a boundary that catches errors and renders a\n * fallback component for HTTP errors.\n *\n * It receives the status code, and determine if it should render fallbacks for few HTTP 4xx errors.\n *\n * e.g. 404\n * 404 represents not found, and the fallback component pair contains the component and its styles.\n *\n */ import React, { useContext } from 'react';\nimport { useUntrackedPathname } from '../navigation-untracked';\nimport { HTTPAccessErrorStatus, getAccessFallbackHTTPStatus, getAccessFallbackErrorTypeByStatus, isHTTPAccessFallbackError } from './http-access-fallback';\nimport { MissingSlotContext } from '../../../shared/lib/app-router-context.shared-runtime';\nclass HTTPAccessFallbackErrorBoundary extends React.Component {\n constructor(props){\n super(props);\n this.state = {\n triggeredStatus: undefined,\n previousPathname: props.pathname\n };\n }\n componentDidCatch() {\n if (process.env.NODE_ENV === 'development' && this.props.missingSlots && this.props.missingSlots.size > 0 && // A missing children slot is the typical not-found case, so no need to warn\n !this.props.missingSlots.has('children')) {\n const { warnOnce } = require('../../../shared/lib/utils/warn-once');\n let warningMessage = 'No default component was found for a parallel route rendered on this page. Falling back to nearest NotFound boundary.\\n' + 'Learn more: https://nextjs.org/docs/app/building-your-application/routing/parallel-routes#defaultjs\\n\\n';\n const formattedSlots = Array.from(this.props.missingSlots).sort((a, b)=>a.localeCompare(b)).map((slot)=>`@${slot}`).join(', ');\n warningMessage += 'Missing slots: ' + formattedSlots;\n warnOnce(warningMessage);\n }\n }\n static getDerivedStateFromError(error) {\n if (isHTTPAccessFallbackError(error)) {\n const httpStatus = getAccessFallbackHTTPStatus(error);\n return {\n triggeredStatus: httpStatus\n };\n }\n // Re-throw if error is not for 404\n throw error;\n }\n static getDerivedStateFromProps(props, state) {\n /**\n * Handles reset of the error boundary when a navigation happens.\n * Ensures the error boundary does not stay enabled when navigating to a new page.\n * Approach of setState in render is safe as it checks the previous pathname and then overrides\n * it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders\n */ if (props.pathname !== state.previousPathname && state.triggeredStatus) {\n return {\n triggeredStatus: undefined,\n previousPathname: props.pathname\n };\n }\n return {\n triggeredStatus: state.triggeredStatus,\n previousPathname: props.pathname\n };\n }\n render() {\n const { notFound, forbidden, unauthorized, children } = this.props;\n const { triggeredStatus } = this.state;\n const errorComponents = {\n [HTTPAccessErrorStatus.NOT_FOUND]: notFound,\n [HTTPAccessErrorStatus.FORBIDDEN]: forbidden,\n [HTTPAccessErrorStatus.UNAUTHORIZED]: unauthorized\n };\n if (triggeredStatus) {\n const isNotFound = triggeredStatus === HTTPAccessErrorStatus.NOT_FOUND && notFound;\n const isForbidden = triggeredStatus === HTTPAccessErrorStatus.FORBIDDEN && forbidden;\n const isUnauthorized = triggeredStatus === HTTPAccessErrorStatus.UNAUTHORIZED && unauthorized;\n // If there's no matched boundary in this layer, keep throwing the error by rendering the children\n if (!(isNotFound || isForbidden || isUnauthorized)) {\n return children;\n }\n return /*#__PURE__*/ _jsxs(_Fragment, {\n children: [\n /*#__PURE__*/ _jsx(\"meta\", {\n name: \"robots\",\n content: \"noindex\"\n }),\n process.env.NODE_ENV === 'development' && /*#__PURE__*/ _jsx(\"meta\", {\n name: \"boundary-next-error\",\n content: getAccessFallbackErrorTypeByStatus(triggeredStatus)\n }),\n errorComponents[triggeredStatus]\n ]\n });\n }\n return children;\n }\n}\nexport function HTTPAccessFallbackBoundary({ notFound, forbidden, unauthorized, children }) {\n // When we're rendering the missing params shell, this will return null. This\n // is because we won't be rendering any not found boundaries or error\n // boundaries for the missing params shell. When this runs on the client\n // (where these error can occur), we will get the correct pathname.\n const pathname = useUntrackedPathname();\n const missingSlots = useContext(MissingSlotContext);\n const hasErrorFallback = !!(notFound || forbidden || unauthorized);\n if (hasErrorFallback) {\n return /*#__PURE__*/ _jsx(HTTPAccessFallbackErrorBoundary, {\n pathname: pathname,\n notFound: notFound,\n forbidden: forbidden,\n unauthorized: unauthorized,\n missingSlots: missingSlots,\n children: children\n });\n }\n return /*#__PURE__*/ _jsx(_Fragment, {\n children: children\n });\n}\n\n//# sourceMappingURL=error-boundary.js.map","export const HTTPAccessErrorStatus = {\n NOT_FOUND: 404,\n FORBIDDEN: 403,\n UNAUTHORIZED: 401\n};\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus));\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK';\n/**\n * Checks an error to determine if it's an error generated by\n * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.\n *\n * @param error the error that may reference a HTTP access error\n * @returns true if the error is a HTTP access error\n */ export function isHTTPAccessFallbackError(error) {\n if (typeof error !== 'object' || error === null || !('digest' in error) || typeof error.digest !== 'string') {\n return false;\n }\n const [prefix, httpStatus] = error.digest.split(';');\n return prefix === HTTP_ERROR_FALLBACK_ERROR_CODE && ALLOWED_CODES.has(Number(httpStatus));\n}\nexport function getAccessFallbackHTTPStatus(error) {\n const httpStatus = error.digest.split(';')[1];\n return Number(httpStatus);\n}\nexport function getAccessFallbackErrorTypeByStatus(status) {\n switch(status){\n case 401:\n return 'unauthorized';\n case 403:\n return 'forbidden';\n case 404:\n return 'not-found';\n default:\n return;\n }\n}\n\n//# sourceMappingURL=http-access-fallback.js.map","import { useContext } from 'react';\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime';\nimport { workUnitAsyncStorage } from './server-async-storage';\n/**\n * This checks to see if the current render has any unknown route parameters that\n * would cause the pathname to be dynamic. It's used to trigger a different\n * render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */ function hasFallbackRouteParams() {\n // The AsyncLocalStorage module is kept out of the client bundle via the\n // `./server-async-storage` browser alias; the guard ensures the stub is never\n // dereferenced in the browser.\n if (typeof window === 'undefined') {\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (!workUnitStore) return false;\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n const fallbackParams = workUnitStore.fallbackRouteParams;\n return fallbackParams ? fallbackParams.size > 0 : false;\n case 'prerender-legacy':\n case 'request':\n case 'prerender-runtime':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break;\n default:\n workUnitStore;\n }\n return false;\n }\n return false;\n}\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */ export function useUntrackedPathname() {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null;\n }\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext);\n}\n\n//# sourceMappingURL=navigation-untracked.js.map","import { isHTTPAccessFallbackError } from './http-access-fallback/http-access-fallback';\nimport { isRedirectError } from './redirect-error';\n/**\n * Returns true if the error is a navigation signal error. These errors are\n * thrown by user code to perform navigation operations and interrupt the React\n * render.\n */ export function isNextRouterError(error) {\n return isRedirectError(error) || isHTTPAccessFallbackError(error);\n}\n\n//# sourceMappingURL=is-next-router-error.js.map","import { workUnitAsyncStorage } from './server-async-storage';\n// if we are revalidating we want to re-throw the error so the\n// function crashes so we can maintain our previous cache\n// instead of caching the error page\nexport function handleISRError({ error }) {\n if (!workUnitAsyncStorage) {\n return;\n }\n const store = workUnitAsyncStorage.getStore();\n switch(store?.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n if (error) {\n console.error(error);\n }\n throw error;\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n case undefined:\n return;\n default:\n store;\n }\n}\n\n//# sourceMappingURL=handle-isr-error.js.map","'use client';\nimport { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from \"react/jsx-runtime\";\nimport React, { startTransition } from 'react';\nimport { useUntrackedPathname } from './navigation-untracked';\nimport { isNextRouterError } from './is-next-router-error';\nimport { handleHardNavError } from './nav-failure-handler';\nimport { handleISRError } from './handle-isr-error';\nimport { isBot } from '../../shared/lib/router/utils/is-bot';\nimport { AppRouterContext } from '../../shared/lib/app-router-context.shared-runtime';\nconst isBotUserAgent = typeof window !== 'undefined' && isBot(window.navigator.userAgent);\nexport class ErrorBoundaryHandler extends React.Component {\n static{\n this.contextType = AppRouterContext;\n }\n constructor(props){\n super(props), this.reset = ()=>{\n this.setState({\n error: null\n });\n }, this.retry = ()=>{\n startTransition(()=>{\n this.context?.refresh();\n this.reset();\n });\n };\n this.state = {\n error: null,\n previousPathname: this.props.pathname\n };\n }\n static getDerivedStateFromError(thrownValue) {\n if (isNextRouterError(thrownValue)) {\n // Re-throw if an expected internal Next.js router error occurs\n // this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)\n throw thrownValue;\n }\n return {\n error: {\n thrownValue\n }\n };\n }\n static getDerivedStateFromProps(props, state) {\n const { error } = state;\n // if we encounter an error while\n // a navigation is pending we shouldn't render\n // the error boundary and instead should fallback\n // to a hard navigation to attempt recovering\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n if (error && handleHardNavError(error.thrownValue)) {\n // clear error so we don't render anything\n return {\n error: null,\n previousPathname: props.pathname\n };\n }\n }\n /**\n * Handles reset of the error boundary when a navigation happens.\n * Ensures the error boundary does not stay enabled when navigating to a new page.\n * Approach of setState in render is safe as it checks the previous pathname and then overrides\n * it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders\n */ if (props.pathname !== state.previousPathname && state.error) {\n return {\n error: null,\n previousPathname: props.pathname\n };\n }\n return {\n error: state.error,\n previousPathname: props.pathname\n };\n }\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render() {\n //When it's bot request, segment level error boundary will keep rendering the children,\n // the final error will be caught by the root error boundary and determine wether need to apply graceful degrade.\n if (this.state.error && !isBotUserAgent) {\n const thrownValue = this.state.error.thrownValue;\n handleISRError({\n error: thrownValue\n });\n return /*#__PURE__*/ _jsxs(_Fragment, {\n children: [\n this.props.errorStyles,\n this.props.errorScripts,\n /*#__PURE__*/ _jsx(this.props.errorComponent, {\n // TODO(NAR-804): Docs say this is an Error object, but we don't guarantee that\n error: thrownValue,\n reset: this.reset,\n retry: this.retry\n })\n ]\n });\n }\n return this.props.children;\n }\n}\n/**\n * Handles errors through `getDerivedStateFromError`.\n * Renders the provided error component and provides a way to `reset` the error boundary state.\n */ /**\n * Renders error boundary with the provided \"errorComponent\" property as the fallback.\n * If no \"errorComponent\" property is provided it renders the children without an error boundary.\n */ export function ErrorBoundary({ errorComponent, errorStyles, errorScripts, children }) {\n // When we're rendering the missing params shell, this will return null. This\n // is because we won't be rendering any not found boundaries or error\n // boundaries for the missing params shell. When this runs on the client\n // (where these errors can occur), we will get the correct pathname.\n const pathname = useUntrackedPathname();\n if (errorComponent) {\n return /*#__PURE__*/ _jsx(ErrorBoundaryHandler, {\n pathname: pathname,\n errorComponent: errorComponent,\n errorStyles: errorStyles,\n errorScripts: errorScripts,\n children: children\n });\n }\n return /*#__PURE__*/ _jsx(_Fragment, {\n children: children\n });\n}\n\n//# sourceMappingURL=error-boundary.js.map","'use client';\nimport { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from \"react/jsx-runtime\";\nimport React, { Activity, Fragment, useContext, use, Suspense, useDeferredValue, useLayoutEffect } from 'react';\nimport { LayoutRouterContext, GlobalLayoutRouterContext, TemplateContext } from '../../shared/lib/app-router-context.shared-runtime';\nimport { unresolvedThenable } from './unresolved-thenable';\nimport { ErrorBoundary } from './error-boundary';\nimport { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll';\nimport { RedirectBoundary } from './redirect-boundary';\nimport { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary';\nimport { InstantValidationBoundaryContext, RenderValidationBoundaryAtThisLevel } from './instant-validation/boundary';\nimport { createSegmentKey } from './router-reducer/create-segment-key';\nimport { useRouterBFCache } from './bfcache-state-manager';\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths';\nimport { NavigationPromisesContext } from '../../shared/lib/hooks-client-context.shared-runtime';\nimport { getParamValueFromCacheKey } from '../route-params';\nimport { isDeferredRsc } from './render-tree';\n/**\n * Resolve the root scroll padding used by the viewport check.\n *\n * Computed lengths serialize as pixels, but percentages remain relative to\n * the scrollport. Preserve the existing behavior for values that still\n * contain unresolved CSS math.\n */ function getScrollPaddingTopInPixels(htmlElement, viewportHeight) {\n const scrollPaddingTop = getComputedStyle(htmlElement).scrollPaddingTop;\n const value = Number.parseFloat(scrollPaddingTop);\n if (!Number.isFinite(value) || value < 0) {\n return 0;\n }\n if (scrollPaddingTop.endsWith('px')) {\n return value;\n }\n if (scrollPaddingTop.endsWith('%')) {\n return value / 100 * viewportHeight;\n }\n return 0;\n}\n/**\n * Check where the top corner of the HTMLElement is relative to the usable\n * viewport.\n *\n * Scroll padding is resolved lazily so an empty Fragment does not trigger a\n * computed style read. The caller caches the value for the second check.\n */ function getScrollTargetState(instance, viewportHeight, getScrollPaddingTop) {\n const rects = instance.getClientRects();\n if (rects.length === 0) {\n return 0;\n }\n let elementTop = Number.POSITIVE_INFINITY;\n for(let i = 0; i < rects.length; i++){\n const rect = rects[i];\n if (rect.top < elementTop) {\n elementTop = rect.top;\n }\n }\n return elementTop >= getScrollPaddingTop() && elementTop <= viewportHeight ? 1 : 2;\n}\n/**\n * Find the DOM node for a hash fragment.\n * If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior.\n * If the hash fragment is an id, the page has to scroll to the element with that id.\n * If the hash fragment is a name, the page has to scroll to the first element with that name.\n */ function getHashFragmentDomNode(hashFragment) {\n // If the hash fragment is `top` the page has to scroll to the top of the page.\n if (hashFragment === 'top') {\n return document.body;\n }\n // If the hash fragment is an id, the page has to scroll to the element with that id.\n return document.getElementById(hashFragment) ?? // If the hash fragment is a name, the page has to scroll to the first element with that name.\n document.getElementsByName(hashFragment)[0] ?? null;\n}\n/**\n * Uses Fragment refs for scrolling.\n * Does not focus the first host descendant.\n */ function InnerScrollHandler(props) {\n const childrenRef = React.useRef(null);\n useLayoutEffect(()=>{\n const { scrollRef: scrollHandlerRef, renderTree } = props;\n const scrollRef = scrollHandlerRef.forceScroll ? scrollHandlerRef.scrollRef : renderTree.data.scrollRef;\n if (scrollRef === null || !scrollRef.current) return;\n let instance = null;\n const hashFragment = scrollHandlerRef.hashFragment;\n if (hashFragment) {\n instance = getHashFragmentDomNode(hashFragment);\n if (instance === null) {\n // A missing hash target is still a handled scroll intent. Do not\n // fall back to the route Fragment or leave the intent pending.\n scrollRef.current = false;\n scrollHandlerRef.onlyHashChange = false;\n scrollHandlerRef.hashFragment = null;\n return;\n }\n } else {\n instance = childrenRef.current;\n }\n // If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree.\n if (instance === null) {\n return;\n }\n let didHandleScroll = false;\n disableSmoothScrollDuringRouteTransition(()=>{\n const htmlElement = document.documentElement;\n let viewportHeight = null;\n let initialTargetState = null;\n let scrollPaddingTop = null;\n const getScrollPaddingTop = ()=>{\n if (scrollPaddingTop === null) {\n // Reuse the style and layout update from the geometry read.\n scrollPaddingTop = getScrollPaddingTopInPixels(htmlElement, viewportHeight);\n }\n return scrollPaddingTop;\n };\n if (!hashFragment) {\n // Store the current viewport height because reading `clientHeight` causes a reflow,\n // and it won't change during this function.\n viewportHeight = htmlElement.clientHeight;\n initialTargetState = getScrollTargetState(instance, viewportHeight, getScrollPaddingTop);\n // An empty Fragment is not a scroll target. In particular, avoid\n // React's sibling fallback and leave the scroll signal available\n // for another changed segment.\n if (initialTargetState === 0) {\n return;\n }\n }\n didHandleScroll = true;\n // Mark as scrolled so no other segment scrolls for this navigation.\n scrollRef.current = false;\n // This handler intentionally leaves focus untouched; resetting focus on\n // navigation is deferred.\n // In case of hash scroll, we only need to scroll the element into view\n if (hashFragment) {\n instance.scrollIntoView();\n return;\n }\n // If the element's top edge is already in the viewport, exit early.\n if (initialTargetState === 1) {\n return;\n }\n // Otherwise, try scrolling go the top of the document to be backward compatible with pages\n // scrollIntoView() called on `<html/>` element scrolls horizontally on chrome and firefox (that shouldn't happen)\n // We could use it to scroll horizontally following RTL but that also seems to be broken - it will always scroll left\n // scrollLeft = 0 also seems to ignore RTL and manually checking for RTL is too much hassle so we will scroll just vertically\n htmlElement.scrollTop = 0;\n // Scroll to domNode if domNode is not in viewport when scrolled to top of document\n if (getScrollTargetState(instance, viewportHeight, getScrollPaddingTop) === 2) {\n // Scroll into view doesn't scroll horizontally by default when not needed\n instance.scrollIntoView();\n }\n }, {\n // We will force layout by querying domNode position\n dontForceLayout: true,\n onlyHashChange: scrollHandlerRef.onlyHashChange\n });\n if (!didHandleScroll) {\n return;\n }\n // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`\n scrollHandlerRef.onlyHashChange = false;\n scrollHandlerRef.hashFragment = null;\n }, // Used to run on every commit. We may be able to be smarter about this\n // but be prepared for lots of manual testing.\n undefined);\n return /*#__PURE__*/ _jsx(Fragment, {\n ref: childrenRef,\n children: props.children\n });\n}\nfunction ScrollHandler({ children, renderTree }) {\n const context = useContext(GlobalLayoutRouterContext);\n if (!context) {\n throw new Error('invariant global layout router not mounted');\n }\n return /*#__PURE__*/ _jsx(InnerScrollHandler, {\n scrollRef: context.scrollRef,\n renderTree: renderTree,\n children: children\n });\n}\n/**\n * InnerLayoutRouter handles rendering the provided segment based on the cache.\n */ function InnerLayoutRouter({ tree, segmentPath, debugNameContext, renderTree, params, url, isActive }) {\n const context = useContext(GlobalLayoutRouterContext);\n const parentNavPromises = useContext(NavigationPromisesContext);\n if (!context) {\n throw new Error('invariant global layout router not mounted');\n }\n // `rsc` represents the renderable node for this segment.\n // If this segment has a `prefetchRsc`, it's the statically prefetched data.\n // We should use that on initial render instead of `rsc`. Then we'll switch\n // to `rsc` when the dynamic response streams in.\n //\n // If no prefetch data is available, then we go straight to rendering `rsc`.\n const resolvedPrefetchRsc = renderTree.data.prefetchRsc !== null ? renderTree.data.prefetchRsc : renderTree.data.rsc;\n // We use `useDeferredValue` to handle switching between the prefetched and\n // final values. The second argument is returned on initial render, then it\n // re-renders with the first argument.\n const rsc = useDeferredValue(renderTree.data.rsc, resolvedPrefetchRsc);\n // `rsc` is either a React node or a promise for a React node, except we\n // special case `null` to represent that this segment's data is missing. If\n // it's a promise, we need to unwrap it so we can determine whether or not the\n // data is missing.\n let resolvedRsc;\n if (isDeferredRsc(rsc)) {\n const unwrappedRsc = use(rsc);\n if (unwrappedRsc === null) {\n // If the promise was resolved to `null`, it means the data for this\n // segment was not returned by the server. Suspend indefinitely. When this\n // happens, the router is responsible for triggering a new state update to\n // un-suspend this segment.\n use(unresolvedThenable);\n }\n resolvedRsc = unwrappedRsc;\n } else {\n // This is not a deferred RSC promise. Don't need to unwrap it.\n if (rsc === null) {\n use(unresolvedThenable);\n }\n resolvedRsc = rsc;\n }\n // In dev, we create a NavigationPromisesContext containing the instrumented promises that provide\n // `useSelectedLayoutSegment` and `useSelectedLayoutSegments`.\n // Promises are cached outside of render to survive suspense retries.\n let navigationPromises = null;\n if (process.env.NODE_ENV !== 'production') {\n const { createNestedLayoutNavigationPromises } = require('./navigation-devtools');\n navigationPromises = createNestedLayoutNavigationPromises(tree, parentNavPromises);\n }\n let children = resolvedRsc;\n if (navigationPromises) {\n children = /*#__PURE__*/ _jsx(NavigationPromisesContext.Provider, {\n value: navigationPromises,\n children: resolvedRsc\n });\n }\n children = // The layout router context narrows down tree and childNodes at each level.\n /*#__PURE__*/ _jsx(LayoutRouterContext.Provider, {\n value: {\n parentTree: tree,\n parentRenderTree: renderTree,\n parentSegmentPath: segmentPath,\n parentParams: params,\n // This is always set to null as we enter a child segment. It's\n // populated by LoadingBoundaryProvider the next time we reach a\n // loading boundary.\n parentLoadingData: null,\n debugNameContext: debugNameContext,\n // TODO-APP: overriding of url for parallel routes\n url: url,\n isActive: isActive\n },\n children: children\n });\n return children;\n}\nexport function LoadingBoundaryProvider({ loading, children }) {\n // Provides the data needed to render a loading.tsx boundary, via context.\n //\n // loading.tsx creates a Suspense boundary around each of a layout's child\n // slots. (Might be bit confusing to think about the data flow, but: if\n // loading.tsx and layout.tsx are in the same directory, they are assigned\n // to the same render tree.)\n //\n // This provider component does not render the Suspense boundary directly;\n // that's handled by LoadingBoundary.\n //\n // TODO: For simplicity, we should combine this provider with LoadingBoundary\n // and render the Suspense boundary directly. The only real benefit of doing\n // it separately is so that when there are multiple parallel routes, we only\n // send the boundary data once, rather than once per child. But that's a\n // negligible benefit and can be achieved via caching instead.\n const parentContext = use(LayoutRouterContext);\n if (parentContext === null) {\n return children;\n }\n // All values except for parentLoadingData are the same as the parent context.\n return /*#__PURE__*/ _jsx(LayoutRouterContext.Provider, {\n value: {\n parentTree: parentContext.parentTree,\n parentRenderTree: parentContext.parentRenderTree,\n parentSegmentPath: parentContext.parentSegmentPath,\n parentParams: parentContext.parentParams,\n parentLoadingData: loading,\n debugNameContext: parentContext.debugNameContext,\n url: parentContext.url,\n isActive: parentContext.isActive\n },\n children: children\n });\n}\n/**\n * Renders suspense boundary with the provided \"loading\" property as the fallback.\n * If no loading property is provided it renders the children without a suspense boundary.\n */ function LoadingBoundary({ name, loading, children }) {\n // TODO: For LoadingBoundary, and the other built-in boundary types, don't\n // wrap in an extra function component if no user-defined boundary is\n // provided. In other words, inline this conditional wrapping logic into\n // the parent component. More efficient and keeps unnecessary junk out of\n // the component stack.\n if (loading !== null) {\n const loadingRsc = loading[0];\n const loadingStyles = loading[1];\n const loadingScripts = loading[2];\n return /*#__PURE__*/ _jsx(Suspense, {\n name: name,\n fallback: /*#__PURE__*/ _jsxs(_Fragment, {\n children: [\n loadingStyles,\n loadingScripts,\n loadingRsc\n ]\n }),\n children: children\n });\n }\n return /*#__PURE__*/ _jsx(_Fragment, {\n children: children\n });\n}\n/**\n * OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments.\n * It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes.\n */ export default function OuterLayoutRouter({ parallelRouterKey, error, errorStyles, errorScripts, templateStyles, templateScripts, template, notFound, forbidden, unauthorized, segmentViewBoundaries }) {\n const context = useContext(LayoutRouterContext);\n if (!context) {\n throw new Error('invariant expected layout router to be mounted');\n }\n const { parentTree, parentRenderTree, parentSegmentPath, parentParams, parentLoadingData, url, isActive, debugNameContext } = context;\n // Get the render tree for this segment by reading it from the parent segment's\n // child map.\n const parentTreeSegment = parentTree[0];\n const segmentPath = parentSegmentPath === null ? // path. This has led to a bunch of special cases scattered throughout\n // the code. We should clean this up.\n [\n parallelRouterKey\n ] : parentSegmentPath.concat([\n parentTreeSegment,\n parallelRouterKey\n ]);\n // The \"state\" key of a segment is the one passed to React. In the browser it\n // represents the identity of the UI tree. Whenever the state key changes,\n // the tree is recreated and the state is reset. In the App Router model,\n // search params do not cause state to be lost, so two segments with the same\n // segment path but different search params should have the same state key.\n // On the server, the key describes the segment's structure instead, so it\n // stays the same when unknown params become known during HTML resume.\n //\n // Whether the data can be reused is tracked separately, by the segment\n // cache's vary paths.\n const activeTree = parentTree[1][parallelRouterKey];\n const activeRenderTree = parentRenderTree.slots?.get(parallelRouterKey);\n if (activeTree === undefined || activeRenderTree === undefined) {\n // Could not find a matching segment. The client tree is inconsistent with\n // the server tree. Suspend indefinitely; the router will have already\n // detected the inconsistency when handling the server response, and\n // triggered a refresh of the page to recover.\n use(unresolvedThenable);\n }\n let maybeValidationBoundaryId = null;\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {\n maybeValidationBoundaryId = use(InstantValidationBoundaryContext);\n }\n const activeSegment = activeTree[0];\n const activeStateKey = createSegmentKey(activeSegment);\n // At each level of the route tree, not only do we render the currently\n // active segment — we also render the last N segments that were active at\n // this level inside a hidden <Activity> boundary, to preserve their state\n // if or when the user navigates to them again.\n //\n // bfcacheEntry is a linked list of FlightRouterStates.\n let bfcacheEntry = useRouterBFCache(activeTree, activeRenderTree, activeStateKey);\n let children = [];\n do {\n const tree = bfcacheEntry.tree;\n const renderTree = bfcacheEntry.renderTree;\n const stateKey = bfcacheEntry.stateKey;\n const segment = tree[0];\n /*\n - Error boundary\n - Only renders error boundary if error component is provided.\n - Rendered for each segment to ensure they have their own error state.\n - When gracefully degrade for bots, skip rendering error boundary.\n - Loading boundary\n - Only renders suspense boundary if loading components is provided.\n - Rendered for each segment to ensure they have their own loading state.\n - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.\n */ let segmentBoundaryTriggerNode = null;\n let segmentViewStateNode = null;\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentBoundaryTriggerNode, SegmentViewStateNode } = require('../../next-devtools/userspace/app/segment-explorer-node');\n const pagePrefix = normalizeAppPath(url);\n segmentViewStateNode = /*#__PURE__*/ _jsx(SegmentViewStateNode, {\n page: pagePrefix\n }, pagePrefix);\n segmentBoundaryTriggerNode = /*#__PURE__*/ _jsx(_Fragment, {\n children: /*#__PURE__*/ _jsx(SegmentBoundaryTriggerNode, {})\n });\n }\n let params = parentParams;\n if (Array.isArray(segment)) {\n // This segment contains a route param. Accumulate these as we traverse\n // down the router tree. The result represents the set of params that\n // the layout/page components are permitted to access below this point.\n const paramName = segment[0];\n const paramCacheKey = segment[1];\n const paramType = segment[2];\n const paramValue = getParamValueFromCacheKey(paramCacheKey, paramType);\n if (paramValue !== null) {\n params = {\n ...parentParams,\n [paramName]: paramValue\n };\n }\n }\n const debugName = getBoundaryDebugNameFromSegment(segment);\n // `debugNameContext` represents the nearest non-\"virtual\" parent segment.\n // `getBoundaryDebugNameFromSegment` returns undefined for virtual segments.\n // So if `debugName` is undefined, the context is passed through unchanged.\n const childDebugNameContext = debugName ?? debugNameContext;\n // In practical terms, clicking this name in the Suspense DevTools\n // should select the child slots of that layout.\n //\n // So the name we apply to the Activity boundary is actually based on\n // the nearest parent segments.\n //\n // We skip over \"virtual\" parents, i.e. ones inserted by Next.js that\n // don't correspond to application-defined code.\n const isVirtual = debugName === undefined;\n const debugNameToDisplay = isVirtual ? undefined : debugNameContext;\n let templateValue = /*#__PURE__*/ _jsxs(ScrollHandler, {\n renderTree: renderTree,\n children: [\n /*#__PURE__*/ _jsx(ErrorBoundary, {\n errorComponent: error,\n errorStyles: errorStyles,\n errorScripts: errorScripts,\n children: /*#__PURE__*/ _jsx(LoadingBoundary, {\n name: debugNameToDisplay,\n // TODO: The loading module data for a segment is stored on the\n // parent, then applied to each of that parent segment's\n // parallel route slots. In the simple case where there's only\n // one parallel route (the `children` slot), this is no\n // different from if the loading module data were stored on the\n // child directly. But I'm not sure this actually makes sense\n // when there are multiple parallel routes. It's not a huge\n // issue because you always have the option to define a narrower\n // loading boundary for a particular slot. But this sort of\n // smells like an implementation accident to me.\n loading: parentLoadingData,\n children: /*#__PURE__*/ _jsx(HTTPAccessFallbackBoundary, {\n notFound: notFound,\n forbidden: forbidden,\n unauthorized: unauthorized,\n children: /*#__PURE__*/ _jsxs(RedirectBoundary, {\n children: [\n /*#__PURE__*/ _jsx(InnerLayoutRouter, {\n url: url,\n tree: tree,\n params: params,\n renderTree: renderTree,\n segmentPath: segmentPath,\n debugNameContext: childDebugNameContext,\n isActive: isActive && stateKey === activeStateKey\n }),\n segmentBoundaryTriggerNode\n ]\n })\n })\n })\n }),\n segmentViewStateNode\n ]\n });\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS && typeof maybeValidationBoundaryId === 'string') {\n templateValue = /*#__PURE__*/ _jsx(RenderValidationBoundaryAtThisLevel, {\n id: maybeValidationBoundaryId,\n children: templateValue\n });\n }\n let child = /*#__PURE__*/ _jsxs(TemplateContext.Provider, {\n value: templateValue,\n children: [\n templateStyles,\n templateScripts,\n template\n ]\n }, stateKey);\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentStateProvider } = require('../../next-devtools/userspace/app/segment-explorer-node');\n child = /*#__PURE__*/ _jsxs(SegmentStateProvider, {\n children: [\n child,\n segmentViewBoundaries\n ]\n }, stateKey);\n }\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n child = /*#__PURE__*/ _jsx(Activity, {\n name: debugNameToDisplay,\n mode: stateKey === activeStateKey ? 'visible' : 'hidden',\n children: child\n }, stateKey);\n }\n children.push(child);\n bfcacheEntry = bfcacheEntry.next;\n }while (bfcacheEntry !== null);\n return children;\n}\nfunction getBoundaryDebugNameFromSegment(segment) {\n if (segment === '/') {\n // Reached the root\n return '/';\n }\n if (typeof segment === 'string') {\n if (isVirtualLayout(segment)) {\n return undefined;\n } else {\n return segment + '/';\n }\n }\n const paramCacheKey = segment[1];\n return paramCacheKey + '/';\n}\nfunction isVirtualLayout(segment) {\n return(// This is inserted by the loader. Uses double-underscore convention\n // (like __PAGE__ and __DEFAULT__) to avoid collisions with\n // user-defined route groups.\n segment === '(__SLOT__)');\n}\n\n//# sourceMappingURL=layout-router.js.map","// This module is bundled separately into user code and the precompiled App\n// Router runtime. Use the global symbol registry so both copies recognize the\n// same browser bailout reason.\nconst REACT_BROWSER_BAILOUT_REASON = Symbol.for('next.browser-bailout-reason');\nexport function createReactBrowserBailoutReason(reason) {\n return {\n $$typeof: REACT_BROWSER_BAILOUT_REASON,\n reason\n };\n}\nexport function getReactBrowserBailoutReason(error) {\n const cause = error?.cause;\n return cause?.$$typeof === REACT_BROWSER_BAILOUT_REASON ? cause.reason : undefined;\n}\nexport function isNextBrowserBailoutError(error) {\n return getReactBrowserBailoutReason(error) !== undefined;\n}\n\n//# sourceMappingURL=react-browser-bailout.js.map","/**\n * ReadonlyURLSearchParams implementation shared between client and server.\n * This file is intentionally not marked as 'use client' or 'use server'\n * so it can be imported by both environments.\n */ /** @internal */ class ReadonlyURLSearchParamsError extends Error {\n constructor(){\n super('Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams');\n }\n}\n/**\n * A read-only version of URLSearchParams that throws errors when mutation methods are called.\n * This ensures that the URLSearchParams returned by useSearchParams() cannot be mutated.\n */ export class ReadonlyURLSearchParams extends URLSearchParams {\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ append() {\n throw new ReadonlyURLSearchParamsError();\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ delete() {\n throw new ReadonlyURLSearchParamsError();\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ set() {\n throw new ReadonlyURLSearchParamsError();\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */ sort() {\n throw new ReadonlyURLSearchParamsError();\n }\n}\n\n//# sourceMappingURL=readonly-url-search-params.js.map","'use client';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport React, { useEffect } from 'react';\nimport { useRouter } from './navigation';\nimport { getRedirectTypeFromError, getURLFromRedirectError } from './redirect';\nimport { isRedirectError } from './redirect-error';\nfunction HandleRedirect({ redirect, reset, redirectType }) {\n const router = useRouter();\n useEffect(()=>{\n React.startTransition(()=>{\n if (redirectType === 'push') {\n router.push(redirect, {});\n } else {\n router.replace(redirect, {});\n }\n reset();\n });\n }, [\n redirect,\n redirectType,\n reset,\n router\n ]);\n return null;\n}\nexport class RedirectErrorBoundary extends React.Component {\n constructor(props){\n super(props);\n this.state = {\n redirect: null,\n redirectType: null\n };\n }\n static getDerivedStateFromError(error) {\n if (isRedirectError(error)) {\n const url = getURLFromRedirectError(error);\n const redirectType = getRedirectTypeFromError(error);\n if ('handled' in error) {\n // The redirect was already handled. We'll still catch the redirect error\n // so that we can remount the subtree, but we don't actually need to trigger the\n // router.push.\n return {\n redirect: null,\n redirectType: null\n };\n }\n return {\n redirect: url,\n redirectType\n };\n }\n // Re-throw if error is not for redirect\n throw error;\n }\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render() {\n const { redirect, redirectType } = this.state;\n if (redirect !== null && redirectType !== null) {\n return /*#__PURE__*/ _jsx(HandleRedirect, {\n redirect: redirect,\n redirectType: redirectType,\n reset: ()=>this.setState({\n redirect: null\n })\n });\n }\n return this.props.children;\n }\n}\nexport function RedirectBoundary({ children }) {\n const router = useRouter();\n return /*#__PURE__*/ _jsx(RedirectErrorBoundary, {\n router: router,\n children: children\n });\n}\n\n//# sourceMappingURL=redirect-boundary.js.map","'use client';\n// We can't fork a `use client` boundary based on node-client vs browser-client.\n// We need to fork one level deeper.\nexport { InstantValidationBoundaryContext, PlaceValidationBoundaryBelowThisLevel, RenderValidationBoundaryAtThisLevel, SlotMarker } from './impl';\n\n//# sourceMappingURL=boundary.js.map","export var RedirectStatusCode = /*#__PURE__*/ function(RedirectStatusCode) {\n RedirectStatusCode[RedirectStatusCode[\"SeeOther\"] = 303] = \"SeeOther\";\n RedirectStatusCode[RedirectStatusCode[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n RedirectStatusCode[RedirectStatusCode[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n return RedirectStatusCode;\n}({});\n\n//# sourceMappingURL=redirect-status-code.js.map","export function createRouterCacheKey(segment) {\n // if the segment is an array, it means it's a dynamic segment\n // for example, ['lang', 'en', 'd']. We need to convert it to a string to store it as a cache node key.\n if (Array.isArray(segment)) {\n return `${segment[0]}|${segment[1]}|${segment[2]}`;\n }\n return segment;\n}\n\n//# sourceMappingURL=create-router-cache-key.js.map","import React from 'react';\nimport { browser } from 'react-dom';\nimport { throwForMissingRequestStore, workUnitAsyncStorage } from './work-unit-async-storage.external';\nimport { workAsyncStorage } from '../app-render/work-async-storage.external';\nimport { ClientHookDynamicError, makeClientHookHangingPromise } from '../dynamic-rendering-utils';\nimport { InvariantError } from '../../shared/lib/invariant-error';\nimport { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';\nimport { createReactBrowserBailoutReason } from '../../shared/lib/lazy-dynamic/react-browser-bailout';\nconst getUseSearchParamsBailoutReason = createReactBrowserBailoutReason.bind(null, 'useSearchParams()');\n// TODO(veil): This module is separated from `dynamic-rendering.ts` as a workaround.\n// When these hooks were part of `dynamic-rendering.ts, the source location of these\n// `React.use()` calls would show up in Webpack snapshots in `client-hook-abort-reasons.test.ts`,\n// which makes changes to the surrounding file needlessly churn the snapshots.\n// Until the ignore-listing is fixed, we can make this less annoying by keeping these hooks in a separate file.\nexport function useDynamicRouteParams(expression) {\n const workStore = workAsyncStorage.getStore();\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workStore && workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender-client':\n {\n const fallbackParams = workUnitStore.fallbackRouteParams;\n if (fallbackParams && fallbackParams.size > 0) {\n // We are in a prerender with cacheComponents semantics. We are going to\n // hang here and never resolve. This will cause the currently\n // rendering component to effectively be a dynamic hole.\n React.use(makeClientHookHangingPromise(workUnitStore.renderSignal, new ClientHookDynamicError(workStore.route, expression)));\n }\n break;\n }\n case 'prerender':\n throw new InvariantError(`\\`${expression}\\` was called from a Server Component. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`);\n case 'validation-client':\n {\n break;\n }\n case 'prerender-runtime':\n throw new InvariantError(`\\`${expression}\\` was called during a runtime prerender. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`);\n case 'cache':\n case 'private-cache':\n throw new InvariantError(`\\`${expression}\\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`);\n case 'build-time-generator':\n throw new InvariantError(`\\`${expression}\\` was called in \\`${workUnitStore.functionName}\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`);\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n break;\n default:\n workUnitStore;\n }\n }\n}\nexport function useDynamicSearchParams(expression) {\n const workStore = workAsyncStorage.getStore();\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (!workStore) {\n // We assume pages router context and just return\n return;\n }\n if (!workUnitStore) {\n throwForMissingRequestStore(expression);\n }\n switch(workUnitStore.type){\n case 'validation-client':\n // During instant validation we try to behave as close to client as possible,\n // so this shouldn't hang during SSR.\n return;\n case 'prerender-client':\n {\n React.use(makeClientHookHangingPromise(workUnitStore.renderSignal, new ClientHookDynamicError(workStore.route, expression)));\n break;\n }\n case 'prerender-legacy':\n {\n if (workStore.forceStatic) {\n return;\n }\n if (process.env.__NEXT_EXPERIMENTAL_REACT_BROWSER_BAILOUT) {\n // @ts-expect-error TODO: Update @types/react-dom to include the reason argument.\n React.use(browser(getUseSearchParamsBailoutReason));\n return;\n } else {\n throw new BailoutToCSRError(expression);\n }\n }\n case 'prerender':\n case 'prerender-runtime':\n throw new InvariantError(`\\`${expression}\\` was called from a Server Component. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`);\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n throw new InvariantError(`\\`${expression}\\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`);\n case 'build-time-generator':\n throw new InvariantError(`\\`${expression}\\` was called in \\`${workUnitStore.functionName}\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`);\n case 'request':\n return;\n default:\n workUnitStore;\n }\n}\n\n//# sourceMappingURL=dynamic-rendering-client.js.map","import { HTML_LIMITED_BOT_UA_RE } from './html-bots';\n// Bot crawler that will spin up a headless browser and execute JS.\n// Only the main Googlebot search crawler executes JavaScript, not other Google crawlers.\n// x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers\n// This regex specifically matches \"Googlebot\" but NOT \"Mediapartners-Google\", \"AdsBot-Google\", etc.\nconst HEADLESS_BROWSER_BOT_UA_RE = /Googlebot(?!-)|Googlebot$/i;\nexport const HTML_LIMITED_BOT_UA_RE_STRING = HTML_LIMITED_BOT_UA_RE.source;\nexport { HTML_LIMITED_BOT_UA_RE };\nfunction isDomBotUA(userAgent) {\n return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent);\n}\nfunction isHtmlLimitedBotUA(userAgent) {\n return HTML_LIMITED_BOT_UA_RE.test(userAgent);\n}\nexport function isBot(userAgent) {\n return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent);\n}\nexport function getBotType(userAgent) {\n if (isDomBotUA(userAgent)) {\n return 'dom';\n }\n if (isHtmlLimitedBotUA(userAgent)) {\n return 'html';\n }\n return undefined;\n}\n\n//# sourceMappingURL=is-bot.js.map","import { useState } from 'react';\n// When the flag is disabled, only track the currently active tree\nconst MAX_BF_CACHE_ENTRIES = process.env.__NEXT_CACHE_COMPONENTS ? 3 : 1;\n/**\n * Keeps track of the most recent N trees (FlightRouterStates) that were active\n * at a certain segment level. E.g. for a segment \"/a/b/[param]\", this hook\n * tracks the last N param values that the router rendered for N.\n *\n * The result of this hook precisely determines the number and order of\n * trees that are rendered in parallel at their segment level.\n *\n * The purpose of this cache is to we can preserve the React and DOM state of\n * some number of inactive trees, by rendering them in an <Activity> boundary.\n * That means it would not make sense for the the lifetime of the cache to be\n * any longer than the lifetime of the React tree; e.g. if the hook were\n * unmounted, then the React tree would be, too. So, we use React state to\n * manage it.\n *\n * Each entry retains its render tree, including its RSC data. This hook\n * determines which trees should have their React and DOM state preserved\n * by <Activity>.\n */ export function useRouterBFCache(activeTree, activeRenderTree, activeStateKey) {\n // The currently active entry. The entries form a linked list, sorted in\n // order of most recently active. This allows us to reuse parts of the list\n // without cloning, unless there's a reordering or removal.\n // TODO: Once we start tracking back/forward history at each route level,\n // we should use the history order instead. In other words, when traversing\n // to an existing entry as a result of a popstate event, we should maintain\n // the existing order instead of moving it to the front of the list. I think\n // an initial implementation of this could be to pass an incrementing id\n // to history.pushState/replaceState, then use that here for ordering.\n const [prevActiveEntry, setPrevActiveEntry] = useState(()=>{\n const initialEntry = {\n tree: activeTree,\n renderTree: activeRenderTree,\n stateKey: activeStateKey,\n next: null\n };\n return initialEntry;\n });\n if (prevActiveEntry.tree === activeTree) {\n // Fast path. The active tree hasn't changed, so we can reuse the\n // existing state.\n return prevActiveEntry;\n }\n // The route tree changed. Note that this doesn't mean that the tree changed\n // *at this level* — the change may be due to a child route. Either way, we\n // need to either add or update the router tree in the bfcache.\n //\n // The rest of the code looks more complicated than it actually is because we\n // can't mutate the state in place; we have to copy-on-write.\n // Create a new entry for the active cache key. This is the head of the new\n // linked list.\n const newActiveEntry = {\n tree: activeTree,\n renderTree: activeRenderTree,\n stateKey: activeStateKey,\n next: null\n };\n // We need to append the old list onto the new list. If the head of the new\n // list was already present in the cache, then we'll need to clone everything\n // that came before it. Then we can reuse the rest.\n let n = 1;\n let oldEntry = prevActiveEntry;\n let clonedEntry = newActiveEntry;\n while(oldEntry !== null && n < MAX_BF_CACHE_ENTRIES){\n if (oldEntry.stateKey === activeStateKey) {\n // Fast path. This entry in the old list that corresponds to the key that\n // is now active. We've already placed a clone of this entry at the front\n // of the new list. We can reuse the rest of the old list without cloning.\n // NOTE: We don't need to worry about eviction in this case because we\n // haven't increased the size of the cache, and we assume the max size\n // is constant across renders. If we were to change it to a dynamic limit,\n // then the implementation would need to account for that.\n clonedEntry.next = oldEntry.next;\n break;\n } else {\n // Clone the entry and append it to the list.\n n++;\n const entry = {\n tree: oldEntry.tree,\n renderTree: oldEntry.renderTree,\n stateKey: oldEntry.stateKey,\n next: null\n };\n clonedEntry.next = entry;\n clonedEntry = entry;\n }\n oldEntry = oldEntry.next;\n }\n setPrevActiveEntry(newActiveEntry);\n return newActiveEntry;\n}\n\n//# sourceMappingURL=bfcache-state-manager.js.map","import { ReadonlyURLSearchParams } from './readonly-url-search-params';\nexport function unstable_isUnrecognizedActionError() {\n throw new Error('`unstable_isUnrecognizedActionError` can only be used on the client.');\n}\nexport { redirect, permanentRedirect } from './redirect';\nexport { notFound } from './not-found';\nexport { forbidden } from './forbidden';\nexport { unauthorized } from './unauthorized';\nexport { unstable_rethrow } from './unstable-rethrow';\nexport { ReadonlyURLSearchParams };\nexport const RedirectType = {\n push: 'push',\n replace: 'replace'\n};\n\n//# sourceMappingURL=navigation.react-server.js.map","import { RedirectStatusCode } from './redirect-status-code';\nexport const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT';\n/**\n * Checks an error to determine if it's an error generated by the\n * `redirect(url)` helper.\n *\n * @param error the error that may reference a redirect error\n * @returns true if the error is a redirect error\n */ export function isRedirectError(error) {\n if (typeof error !== 'object' || error === null || !('digest' in error) || typeof error.digest !== 'string') {\n return false;\n }\n const digest = error.digest.split(';');\n const [errorCode, type] = digest;\n const destination = digest.slice(2, -2).join(';');\n const status = digest.at(-2);\n const statusCode = Number(status);\n return errorCode === REDIRECT_ERROR_CODE && (type === 'replace' || type === 'push') && typeof destination === 'string' && !isNaN(statusCode) && statusCode in RedirectStatusCode;\n}\n\n//# sourceMappingURL=redirect-error.js.map","import React, { useContext, useMemo, use } from 'react';\nimport { AppRouterContext, LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime';\nimport { SearchParamsContext, PathnameContext, PathParamsContext, NavigationPromisesContext, ReadonlyURLSearchParams } from '../../shared/lib/hooks-client-context.shared-runtime';\nimport { computeSelectedLayoutSegment, getSelectedLayoutSegmentPath } from '../../shared/lib/segment';\nimport { useDynamicRouteParams, useDynamicSearchParams } from './navigation-dynamic-rendering';\nconst { instrumentParamsForClientValidation, instrumentSearchParamsForClientValidation, expectCompleteParamsInClientValidation } = process.env.__NEXT_CACHE_COMPONENTS ? require('./instant-samples') : {};\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you *read* the current URL's search parameters.\n *\n * Learn more about [`URLSearchParams` on MDN](https://developer.mozilla.org/docs/Web/API/URLSearchParams)\n *\n * @example\n * ```ts\n * \"use client\"\n * import { useSearchParams } from 'next/navigation'\n *\n * export default function Page() {\n * const searchParams = useSearchParams()\n * searchParams.get('foo') // returns 'bar' when ?foo=bar\n * // ...\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useSearchParams`](https://nextjs.org/docs/app/api-reference/functions/use-search-params)\n */ // Client components API\nexport function useSearchParams() {\n useDynamicSearchParams?.('useSearchParams()');\n const searchParams = useContext(SearchParamsContext);\n // In the case where this is `null`, the compat types added in\n // `next-env.d.ts` will add a new overload that changes the return type to\n // include `null`.\n const readonlySearchParams = useMemo(()=>{\n if (!searchParams) {\n // When the router is not ready in pages, we won't have the search params\n // available.\n return null;\n }\n return new ReadonlyURLSearchParams(searchParams);\n }, [\n searchParams\n ]);\n // During build-time instant validation, wrap with an proxy\n // so that accessing undeclared search params throws an error.\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS && readonlySearchParams) {\n return instrumentSearchParamsForClientValidation(readonlySearchParams);\n }\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext);\n if (navigationPromises) {\n return use(navigationPromises.searchParams);\n }\n }\n return readonlySearchParams;\n}\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read the current URL's pathname.\n *\n * @example\n * ```ts\n * \"use client\"\n * import { usePathname } from 'next/navigation'\n *\n * export default function Page() {\n * const pathname = usePathname() // returns \"/dashboard\" on /dashboard?foo=bar\n * // ...\n * }\n * ```\n *\n * Read more: [Next.js Docs: `usePathname`](https://nextjs.org/docs/app/api-reference/functions/use-pathname)\n */ // Client components API\nexport function usePathname() {\n useDynamicRouteParams?.('usePathname()');\n // In the case where this is `null`, the compat types added in `next-env.d.ts`\n // will add a new overload that changes the return type to include `null`.\n const pathname = useContext(PathnameContext);\n // During build-time instant validation, error if fallback params exist\n // because usePathname() can't return a sensible value without all params.\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS && pathname) {\n expectCompleteParamsInClientValidation('usePathname()');\n return pathname;\n }\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext);\n if (navigationPromises) {\n return use(navigationPromises.pathname);\n }\n }\n return pathname;\n}\n// Client components API\nexport { ServerInsertedHTMLContext, useServerInsertedHTML } from '../../shared/lib/server-inserted-html.shared-runtime';\n/**\n *\n * This hook allows you to programmatically change routes inside [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components).\n *\n * @example\n * ```ts\n * \"use client\"\n * import { useRouter } from 'next/navigation'\n *\n * export default function Page() {\n * const router = useRouter()\n * // ...\n * router.push('/dashboard') // Navigate to /dashboard\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useRouter`](https://nextjs.org/docs/app/api-reference/functions/use-router)\n */ // Client components API\nexport function useRouter() {\n const router = useContext(AppRouterContext);\n if (router === null) {\n throw new Error('invariant expected app router to be mounted');\n }\n // Read the bfcacheId of the closest CacheNode and merge it into the\n // returned router instance. This is contextual: callers in a shared\n // layout get the layout's id; callers in a leaf segment get the leaf's.\n // The id is stored on the CacheNode as a number and materialized as a\n // string here. The format mirrors React's `useId()` (e.g. `_r_0_`) with\n // a `b` prefix, so the id can be safely concatenated with other keys\n // without collision.\n const layout = useContext(LayoutRouterContext);\n const bfcacheIdNumber = layout?.parentRenderTree.data.bfcacheId ?? 0;\n return useMemo(()=>({\n back: router.back,\n forward: router.forward,\n refresh: router.refresh,\n hmrRefresh: router.hmrRefresh,\n push: router.push,\n replace: router.replace,\n prefetch: router.prefetch,\n experimental_gesturePush: router.experimental_gesturePush,\n bfcacheId: '_b_' + bfcacheIdNumber + '_'\n }), [\n router,\n bfcacheIdNumber\n ]);\n}\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read a route's dynamic params filled in by the current URL.\n *\n * @example\n * ```ts\n * \"use client\"\n * import { useParams } from 'next/navigation'\n *\n * export default function Page() {\n * // on /dashboard/[team] where pathname is /dashboard/nextjs\n * const { team } = useParams() // team === \"nextjs\"\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useParams`](https://nextjs.org/docs/app/api-reference/functions/use-params)\n */ // Client components API\nexport function useParams() {\n useDynamicRouteParams?.('useParams()');\n const params = useContext(PathParamsContext);\n // During build-time instant validation, wrap with a proxy\n // so that accessing undeclared params throws an error.\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS && params) {\n return instrumentParamsForClientValidation(params);\n }\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext);\n if (navigationPromises) {\n return use(navigationPromises.params);\n }\n }\n return params;\n}\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read the active route segments **below** the Layout it is called from.\n *\n * @example\n * ```ts\n * 'use client'\n *\n * import { useSelectedLayoutSegments } from 'next/navigation'\n *\n * export default function ExampleClientComponent() {\n * const segments = useSelectedLayoutSegments()\n *\n * return (\n * <ul>\n * {segments.map((segment, index) => (\n * <li key={index}>{segment}</li>\n * ))}\n * </ul>\n * )\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useSelectedLayoutSegments`](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments)\n */ // Client components API\nexport function useSelectedLayoutSegments(parallelRouteKey = 'children') {\n useDynamicRouteParams?.('useSelectedLayoutSegments()');\n const context = useContext(LayoutRouterContext);\n // @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts\n if (!context) return null;\n // During build-time instant validation, error if fallback params exist\n // because useSelectedLayoutSegments() can't return a sensible value without all params.\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS && context) {\n expectCompleteParamsInClientValidation('useSelectedLayoutSegments()');\n }\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext);\n if (navigationPromises) {\n const promise = navigationPromises.selectedLayoutSegmentsPromises?.get(parallelRouteKey);\n if (promise) {\n // We should always have a promise here, but if we don't, it's not worth erroring over.\n // We just won't be able to instrument it, but can still provide the value.\n return use(promise);\n }\n }\n }\n return getSelectedLayoutSegmentPath(context.parentTree, parallelRouteKey);\n}\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read the active route segment **one level below** the Layout it is called from.\n *\n * @example\n * ```ts\n * 'use client'\n * import { useSelectedLayoutSegment } from 'next/navigation'\n *\n * export default function ExampleClientComponent() {\n * const segment = useSelectedLayoutSegment()\n *\n * return <p>Active segment: {segment}</p>\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useSelectedLayoutSegment`](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment)\n */ // Client components API\nexport function useSelectedLayoutSegment(parallelRouteKey = 'children') {\n useDynamicRouteParams?.('useSelectedLayoutSegment()');\n const navigationPromises = useContext(NavigationPromisesContext);\n const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey);\n // During build-time instant validation, error if fallback params exist\n // because useSelectedLayoutSegment() can't return a sensible value without all params.\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {\n expectCompleteParamsInClientValidation('useSelectedLayoutSegment()');\n }\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && navigationPromises && 'use' in React) {\n const promise = navigationPromises.selectedLayoutSegmentPromises?.get(parallelRouteKey);\n if (promise) {\n // We should always have a promise here, but if we don't, it's not worth erroring over.\n // We just won't be able to instrument it, but can still provide the value.\n return use(promise);\n }\n }\n return computeSelectedLayoutSegment(selectedLayoutSegments, parallelRouteKey);\n}\nexport { unstable_isUnrecognizedActionError } from './unrecognized-action-error';\n// Shared components APIs\nexport { // We need the same class that was used to instantiate the context value\n// Otherwise instanceof checks will fail in usercode\nReadonlyURLSearchParams, };\nexport { notFound, forbidden, unauthorized, redirect, permanentRedirect, RedirectType, unstable_rethrow } from './navigation.react-server';\n\n//# sourceMappingURL=navigation.js.map","import { useEffect } from 'react';\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url';\nexport function handleHardNavError(error) {\n if (typeof window !== 'undefined' && window.next.__pendingUrl && createHrefFromUrl(new URL(window.location.href)) !== createHrefFromUrl(window.next.__pendingUrl)) {\n console.error(`Error occurred during navigation, falling back to hard navigation`, error);\n window.location.href = window.next.__pendingUrl.toString();\n return true;\n }\n return false;\n}\nexport function useNavFailureHandler() {\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n // this if is only for DCE of the feature flag not conditional\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(()=>{\n const uncaughtExceptionHandler = (evt)=>{\n const error = 'reason' in evt ? evt.reason : evt.error;\n // if we have an unhandled exception/rejection during\n // a navigation we fall back to a hard navigation to\n // attempt recovering to a good state\n handleHardNavError(error);\n };\n window.addEventListener('unhandledrejection', uncaughtExceptionHandler);\n window.addEventListener('error', uncaughtExceptionHandler);\n return ()=>{\n window.removeEventListener('error', uncaughtExceptionHandler);\n window.removeEventListener('unhandledrejection', uncaughtExceptionHandler);\n };\n }, []);\n }\n}\n\n//# sourceMappingURL=nav-failure-handler.js.map","/**\n * Create a \"Thenable\" that does not resolve. This is used to suspend indefinitely when data is not available yet.\n */ export const unresolvedThenable = {\n then: ()=>{}\n};\n\n//# sourceMappingURL=unresolved-thenable.js.map","import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils';\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';\nimport { isNextRouterError } from './is-next-router-error';\nimport { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering';\nimport { isDynamicServerError } from './hooks-server-context';\n/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * In the browser bundle this module is aliased to `./unstable-rethrow.browser`, which performs a\n * subset of these checks (the server-only ones can never occur in the browser). This default\n * module holds the full server logic and is used on every server runtime (Node, edge) and in any\n * context where the alias does not apply.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */ export function unstable_rethrow(error) {\n if (isNextRouterError(error) || isBailoutToCSRError(error) || isDynamicServerError(error) || isHangingPromiseRejectionError(error) || isPrerenderInterruptedError(error)) {\n throw error;\n }\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause);\n }\n}\n\n//# sourceMappingURL=unstable-rethrow.js.map","import { RedirectStatusCode } from './redirect-status-code';\nimport { isRedirectError, REDIRECT_ERROR_CODE } from './redirect-error';\nimport { actionAsyncStorage } from './server-async-storage';\nexport function getRedirectError(url, type, statusCode = RedirectStatusCode.TemporaryRedirect) {\n const error = new Error(REDIRECT_ERROR_CODE);\n error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};`;\n return error;\n}\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 307 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n * - In a Server Action, type defaults to 'push' and 'replace' elsewhere.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */ export function redirect(/** The URL to redirect to */ url, type) {\n type ??= actionAsyncStorage?.getStore()?.isAction ? 'push' : 'replace';\n throw getRedirectError(url, type, RedirectStatusCode.TemporaryRedirect);\n}\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 308 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */ export function permanentRedirect(/** The URL to redirect to */ url, type = 'replace') {\n throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect);\n}\nexport function getURLFromRedirectError(error) {\n if (!isRedirectError(error)) return null;\n // Slices off the beginning of the digest that contains the code and the\n // separating ';'.\n return error.digest.split(';').slice(2, -2).join(';');\n}\nexport function getRedirectTypeFromError(error) {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error');\n }\n return error.digest.split(';', 2)[1];\n}\nexport function getRedirectStatusCodeFromError(error) {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error');\n }\n return Number(error.digest.split(';').at(-2));\n}\n\n//# sourceMappingURL=redirect.js.map","/**\n * Run function with `scroll-behavior: auto` applied to `<html/>`.\n * This css change will be reverted after the function finishes.\n */ export function disableSmoothScrollDuringRouteTransition(fn, options = {}) {\n // if only the hash is changed, we don't need to disable smooth scrolling\n // we only care to prevent smooth scrolling when navigating to a new page to avoid jarring UX\n if (options.onlyHashChange) {\n fn();\n return;\n }\n const htmlElement = document.documentElement;\n const hasDataAttribute = htmlElement.dataset.scrollBehavior === 'smooth';\n if (!hasDataAttribute) {\n // Warn if smooth scrolling is detected but no data attribute is present\n if (process.env.NODE_ENV === 'development' && getComputedStyle(htmlElement).scrollBehavior === 'smooth') {\n const { warnOnce } = require('../../utils/warn-once');\n warnOnce('Detected `scroll-behavior: smooth` on the `<html>` element. To disable smooth scrolling during route transitions, ' + 'add `data-scroll-behavior=\"smooth\"` to your <html> element. ' + 'Learn more: https://nextjs.org/docs/messages/missing-data-scroll-behavior');\n }\n // No smooth scrolling configured, run directly without style manipulation\n fn();\n return;\n }\n // Proceed with temporarily disabling smooth scrolling\n const existing = htmlElement.style.scrollBehavior;\n htmlElement.style.scrollBehavior = 'auto';\n if (!options.dontForceLayout) {\n // In Chrome-based browsers we need to force reflow before calling `scrollTo`.\n // Otherwise it will not pickup the change in scrollBehavior\n // More info here: https://github.com/vercel/next.js/issues/40719#issuecomment-1336248042\n htmlElement.getClientRects();\n }\n fn();\n htmlElement.style.scrollBehavior = existing;\n}\n\n//# sourceMappingURL=disable-smooth-scroll.js.map","// This regex contains the bots that we need to do a blocking render for and can't safely stream the response\n// due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent.\n// Note: The pattern [\\w-]+-Google captures all Google crawlers with \"-Google\" suffix (e.g., Mediapartners-Google, AdsBot-Google, Storebot-Google)\n// as well as crawlers starting with \"Google-\" (e.g., Google-PageRenderer, Google-InspectionTool)\nexport const HTML_LIMITED_BOT_UA_RE = /[\\w-]+-Google|Google-[\\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight/i;\n\n//# sourceMappingURL=html-bots.js.map","/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */ // Do not put a \"use client\" directive here. Import this module via the shim in\n// `packages/next/src/client/components/instant-validation/boundary.tsx` instead.\n// 'use client'\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { createContext } from 'react';\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants';\nimport { InvariantError } from '../../../shared/lib/invariant-error';\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external';\nif (typeof window !== 'undefined') {\n throw new InvariantError('Instant validation boundaries should never appear in browser bundles.');\n}\nfunction getValidationBoundaryTracking() {\n const store = workUnitAsyncStorage.getStore();\n if (!store) return null;\n switch(store.type){\n case 'validation-client':\n return store.boundaryState;\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break;\n default:\n store;\n }\n return null;\n}\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [INSTANT_VALIDATION_BOUNDARY_NAME]: function({ id, children }) {\n // Track which boundaries we actually managed to render.\n const state = getValidationBoundaryTracking();\n if (state === null) {\n throw new InvariantError('Missing boundary tracking state');\n }\n state.renderedIds.add(id);\n return children;\n }\n};\nexport const InstantValidationBoundaryContext = /*#__PURE__*/ createContext(null);\nexport function PlaceValidationBoundaryBelowThisLevel({ id, children }) {\n return(// OuterLayoutRouter will see this and render a `RenderValidationBoundaryAtThisLevel`.\n /*#__PURE__*/ _jsx(InstantValidationBoundaryContext, {\n value: id,\n children: children\n }));\n}\nexport function RenderValidationBoundaryAtThisLevel({ id, children }) {\n // We got a boundaryId from the context. Clear the context so that the children don't render another boundary.\n return /*#__PURE__*/ _jsx(InstantValidationBoundary, {\n id: id,\n children: /*#__PURE__*/ _jsx(InstantValidationBoundaryContext, {\n value: null,\n children: children\n })\n });\n}\nconst InstantValidationBoundary = // We use slice(0) to trick the bundler into not inlining/minifying the function\n// so it retains the name inferred from the namespace object\nNameSpace[INSTANT_VALIDATION_BOUNDARY_NAME.slice(0)];\n// Slot marker component for attributing validation errors to the\n// correct config when a boundary spans multiple parallel slots.\n// Renders a dynamically-named inner component so the slot index\n// appears in the SSR component stack (__next_instant_slot_N__).\nconst slotMarkerCache = new Map();\nexport function SlotMarker({ name, children }) {\n let Marker = slotMarkerCache.get(name);\n if (!Marker) {\n const ns = {\n [name]: function({ children: c }) {\n return c;\n }\n };\n Marker = ns[name];\n slotMarkerCache.set(name, Marker);\n }\n return /*#__PURE__*/ _jsx(Marker, {\n children: children\n });\n}\n\n//# sourceMappingURL=boundary-impl.js.map","import { createRouterCacheKey } from './create-router-cache-key';\n// React uses these keys to find suspended subtrees when resuming HTML. They\n// must be the same before and after route params and search params are known.\n// The browser uses the concrete keys instead, so navigation still resets or\n// preserves state as appropriate. Its bundle uses create-segment-key.browser.ts.\n// React keys are not embedded in the HTML.\nexport function createSegmentKey(segment) {\n if (Array.isArray(segment)) {\n return `${segment[0]}|${segment[2]}`;\n }\n return createRouterCacheKey(segment);\n}\n// TODO: To model this more accurately, we should use React.optimisticKey\n// instead. Perhaps a separate Fragment that wraps around the Head:\n// <Fragment key={headKey}> where headKey is React.optimisticKey during\n// SSR. We should do this for all fallback param values.\nexport function createHeadKey(varyPath) {\n // The head's vary path starts with its request key: the route structure,\n // with param names but no values.\n return varyPath.value;\n}\n\n//# sourceMappingURL=create-segment-key.js.map","'use client'\n\nimport React, { useContext, type JSX } from 'react'\nimport { TemplateContext } from '../../shared/lib/app-router-context.shared-runtime'\n\nexport default function RenderFromTemplateContext(): JSX.Element {\n const children = useContext(TemplateContext)\n return <>{children}</>\n}\n","// This gets assigned as a side-effect during app initialization. Because it\n// represents the build used to create the JS bundle, it should never change\n// after being set, so we store it in a global variable.\n//\n// When performing RSC requests, if the incoming data has a different build ID,\n// we perform an MPA navigation/refresh to load the updated build and ensure\n// that the client and server in sync.\n//\n// Starts as an empty string. In practice, because setNavigationBuildId is called during initialization\n// before hydration starts, this will always get reassigned to the actual ID before it's ever needed\n// by a navigation. If for some reasons it didn't, due to a bug or race condition, then on\n// navigation the build comparision would fail and trigger an MPA navigation.\n//\n// Note that this can also be initialized with the deployment id instead (if available). So it's not\n// the same as \"the build id\", but we are running out of alternative names for \"build id or\n// deployment id\".\nlet globalBuildId = '';\nexport function setNavigationBuildId(buildId) {\n globalBuildId = buildId;\n}\nexport function getNavigationBuildId() {\n return globalBuildId;\n}\n\n//# sourceMappingURL=navigation-build-id.js.map","'use client';\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromReadableStream as createFromReadableStreamBrowser, createFromFetch as createFromFetchBrowser } from 'react-server-dom-webpack/client';\nimport { InvariantError } from '../../../shared/lib/invariant-error';\nimport { fetch } from '../segment-cache/fetch';\nimport { NEXT_ROUTER_STATE_TREE_HEADER, NEXT_RSC_UNION_QUERY, NEXT_URL, RSC_HEADER, RSC_CONTENT_TYPE_HEADER, NEXT_HMR_REFRESH_HEADER, NEXT_DID_POSTPONE_HEADER, NEXT_HTML_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER } from '../app-router-headers';\nimport { callServer } from '../../app-call-server';\nimport { findSourceMapURL } from '../../app-find-source-map-url';\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers';\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param';\nimport { urlToUrlWithoutFlightMarker } from '../../route-params';\nimport { getDeploymentId } from '../../../shared/lib/deployment-id';\nimport { getNavigationBuildId } from '../../navigation-build-id';\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants';\nimport { stripIsPartialByte, bufferPrefetchResponseBody } from '../segment-cache/cache';\nimport { UnknownDynamicStaleTime } from '../segment-cache/bfcache';\nconst createFromReadableStream = createFromReadableStreamBrowser;\nconst createFromFetch = createFromFetchBrowser;\nlet createDebugChannel;\nif (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = require('../../dev/debug-channel').createDebugChannel;\n}\nfunction doMpaNavigation(url) {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString();\n}\nlet isPageUnloading = false;\nif (typeof window !== 'undefined') {\n // Track when the page is unloading, e.g. due to reloading the page or\n // performing hard navigations. This allows us to suppress error logging when\n // the browser cancels in-flight requests during page unload.\n window.addEventListener('pagehide', ()=>{\n isPageUnloading = true;\n });\n // Reset the flag on pageshow, e.g. when navigating back and the JavaScript\n // execution context is restored by the browser.\n window.addEventListener('pageshow', ()=>{\n isPageUnloading = false;\n });\n}\n/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */ export async function fetchServerResponse(url, options) {\n const { flightRouterState, nextUrl } = options;\n const headers = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(flightRouterState, options.isHmrRefresh)\n };\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1';\n }\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl;\n }\n // In static export mode, we need to modify the URL to request the .txt file,\n // but we should preserve the original URL for the canonical URL and error handling.\n const originalUrl = url;\n try {\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n // In \"output: export\" mode, we can't rely on headers to distinguish\n // between HTML and RSC requests. Instead, we append an extra prefix\n // to the request.\n url = new URL(url);\n if (url.pathname.endsWith('/')) {\n url.pathname += 'index.txt';\n } else {\n url.pathname += '.txt';\n }\n }\n }\n // During a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise. Navigations\n // only ever receive live-render responses (per-segment prefetch\n // responses, which omit some fields, are decoded by the segment cache\n // instead), so the decode is typed as the live-render variant.\n const res = await createFetch(url, headers, 'auto', true, options.signal);\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } = require('../offline');\n notifyOnline();\n }\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url));\n const canonicalUrl = res.redirected ? responseUrl : originalUrl;\n const contentType = res.headers.get('content-type') || '';\n const interception = !!res.headers.get('vary')?.includes(NEXT_URL);\n const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER);\n let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER);\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n if (!isFlightResponse) {\n isFlightResponse = contentType.startsWith('text/plain');\n }\n }\n }\n // If fetch returns something different than flight response handle it like a mpa navigation\n // If the fetch was not 200, we also handle it like a mpa navigation\n if (!isFlightResponse || !res.ok || !res.body) {\n // in case the original URL came with a hash, preserve it before redirecting to the new URL\n if (url.hash) {\n responseUrl.hash = url.hash;\n }\n return doMpaNavigation(responseUrl.toString());\n }\n // We may navigate to a page that requires a different Webpack runtime.\n // In prod, every page will have the same Webpack runtime.\n // In dev, the Webpack runtime is minimal for each page.\n // We need to ensure the Webpack runtime is updated before executing client-side JS of the new page.\n // TODO: This needs to happen in the Flight Client.\n // Or Webpack needs to include the runtime update in the Flight response as\n // a blocking script.\n if (process.env.NODE_ENV !== 'production' && !process.env.TURBOPACK) {\n await require('../../dev/hot-reloader/app/hot-reloader-app').waitForWebpackRuntimeHotUpdate();\n }\n // This request passed `true` to `shouldImmediatelyDecode`, so the Flight\n // response promise is always initialized.\n const flightResponsePromise = res.flightResponsePromise;\n const [flightResponse, cacheData] = await Promise.all([\n flightResponsePromise,\n res.cacheData\n ]);\n if ((res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !== getNavigationBuildId()) {\n // The server build does not match the client build.\n return doMpaNavigation(res.url);\n }\n if (flightResponse.n !== undefined) {\n // The server responded with an MPA navigation URL instead of a\n // SPA payload.\n return doMpaNavigation(flightResponse.n);\n }\n const staticStageResponse = cacheData !== null ? await resolveStaticStageResponse(cacheData, flightResponse, headers) : null;\n return {\n transportData: flightResponse.t ?? null,\n canonicalUrl: canonicalUrl,\n // TODO: We should be able to read this from the rewrite header, not the\n // Flight response. Theoretically they should always agree, but there are\n // currently some cases where it's incorrect for interception routes. We\n // can always trust the value in the response body. However, per-segment\n // prefetch responses don't embed the value in the body; they rely on the\n // header alone. So we need to investigate why the header is sometimes\n // wrong for interception routes.\n renderedSearch: flightResponse.q,\n couldBeIntercepted: interception,\n supportsPerSegmentPrefetching: flightResponse.S,\n postponed,\n // The dynamicStaleTime is only present in the response body when\n // a page exports unstable_dynamicStaleTime and this is a dynamic render.\n // When absent (UnknownDynamicStaleTime), the client falls back to the\n // global DYNAMIC_STALETIME_MS. The value is in seconds.\n dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,\n isResponsePartial: cacheData !== null ? cacheData.isResponsePartial : false,\n staticStageResponse,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n revealAfter: flightResponse._revealAfter ?? null\n };\n } catch (err) {\n if (options.signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request.\n // Rethrow so the caller treats it as canceled, rather than logging a\n // failure or falling back to an MPA navigation.\n throw err;\n }\n // If the fetch rejected due to a network error, wait for connectivity\n // to be restored and then retry. checkOfflineError returns true for\n // network errors (and starts the polling loop); returns false for\n // intentional aborts/timeouts, which fall through to the MPA fallback.\n //\n // Note: when the user navigates multiple times while offline, each\n // navigation queues a separate retry here. Once connectivity returns,\n // all pending retries resume simultaneously. This is mitigated in PR 3\n // by reusing back-forward cache entries during offline navigation, which\n // avoids issuing new fetches in the first place.\n if (process.env.__NEXT_USE_OFFLINE && !isPageUnloading) {\n const { checkOfflineError, getOffline, waitForConnection } = require('../offline');\n if (checkOfflineError(err)) {\n const offline = getOffline();\n if (offline !== null) {\n await waitForConnection(offline);\n }\n return fetchServerResponse(url, options);\n }\n }\n if (!isPageUnloading) {\n console.error(`Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`, err);\n }\n // If fetch fails handle it like a mpa navigation\n // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.\n // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.\n return originalUrl.toString();\n }\n}\n/**\n * Strips the leading isPartial byte from an RSC navigation response and\n * clones the body for segment cache extraction.\n *\n * When cache components is enabled, the server prepends a single byte:\n * '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped\n * before Flight decoding because it's not valid RSC data. The body is\n * cloned before Flight can consume it so the clone is available for later use.\n *\n * When cache components is disabled, returns the original response with\n * cacheData: null.\n */ export async function processFetch(response) {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (!response.body) {\n throw new InvariantError('Expected RSC navigation response to have a body');\n }\n const { stream, isPartial } = await stripIsPartialByte(response.body);\n let responseStream;\n let cacheData;\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n // Three readers needed: the main Flight decoder, the static-stage\n // extractor, and the shell-stage extractor. Tee twice.\n const [stream1, rest] = stream.tee();\n const [staticBodyClone, shellBodyClone] = rest.tee();\n responseStream = stream1;\n cacheData = {\n isResponsePartial: isPartial,\n staticBodyClone,\n shellBodyClone\n };\n } else {\n responseStream = stream;\n cacheData = {\n isResponsePartial: isPartial\n };\n }\n const strippedResponse = new Response(responseStream, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText\n });\n // The Response constructor doesn't preserve `url` or `redirected` from\n // the original. We need both: `url` for React DevTools and `redirected`\n // for the redirect replay logic below.\n Object.defineProperty(strippedResponse, 'url', {\n value: response.url\n });\n Object.defineProperty(strippedResponse, 'redirected', {\n value: response.redirected\n });\n return {\n response: strippedResponse,\n cacheData\n };\n }\n return {\n response,\n cacheData: null\n };\n}\n/**\n * Resolves the static stage response from the raw `processFetch` outputs and\n * the decoded flight response, for writing into the segment cache. The\n * resolved response's partiality is the whole response's partiality\n * (`cacheData.isResponsePartial`): a complete response is resolved whole, a\n * partial one as its truncated static-stage prefix.\n *\n * - Fully static: use the decoded flight response as-is, no truncation needed.\n * - Not fully static + `l` field: truncate the body clone at the static stage\n * byte boundary and decode.\n * - Otherwise: no cache-worthy data.\n */ async function resolveStaticStageResponse(cacheData, flightResponse, headers) {\n const { isResponsePartial, staticBodyClone } = cacheData;\n if (staticBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n staticBodyClone.cancel();\n return flightResponse;\n }\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const staticStageByteLength = await flightResponse.l;\n if (staticStageByteLength === 0) {\n staticBodyClone.cancel();\n return null;\n }\n return decodeStageUntilBoundary(staticBodyClone, staticStageByteLength, headers);\n }\n // No caching — cancel the unused clone.\n staticBodyClone.cancel();\n }\n return null;\n}\n/**\n * Resolves the shell stage of a prerender response:\n *\n * - `a === undefined` (server didn't emit shell stage info) or no shell body\n * clone: no shell exists — returns null.\n * - `a` resolves to `null`: the shell IS the main response — returns\n * `flightResponse` itself (callers compare by reference).\n * - `a` resolves to a number: the shell is a strict prefix of the response —\n * returns a separate Flight decode of the byte prefix.\n */ export async function resolveShellStageResponse(cacheData, flightResponse, headers) {\n const { shellBodyClone } = cacheData;\n if (!shellBodyClone) {\n return null;\n }\n if (flightResponse.a === undefined) {\n // The render wasn't staged — no shell exists.\n shellBodyClone.cancel();\n return null;\n }\n const shellByteLength = await flightResponse.a;\n if (shellByteLength === 0) {\n shellBodyClone.cancel();\n return null;\n }\n if (shellByteLength === null) {\n // The shell IS the full response (no shell/full split). Return the full\n // response itself — callers detect this case by reference equality —\n // rather than collapsing it into null, which would lose the distinction\n // from \"no shell exists\". This mirrors the convention of the per-segment\n // prefetch fetch (see fetchAndWritePerSegmentPrefetchResponse in cache.ts).\n shellBodyClone.cancel();\n return flightResponse;\n }\n return decodeStageUntilBoundary(shellBodyClone, shellByteLength, headers);\n}\n/**\n * Truncates and buffers a Flight stream clone at the given byte boundary and\n * decodes the prefix as an optional Flight payload. Returns null if extraction\n * fails or the root does not resolve before the next task. The caller can still\n * use the full response.\n */ export async function decodeStageUntilBoundary(responseBodyClone, byteLength, headers) {\n try {\n const buffer = await bufferPrefetchResponseBody(responseBodyClone, byteLength);\n const response = decodeBufferedStage(buffer, headers);\n // The caller already has the full response root, but this prefix may omit\n // rows that the root needs. Bound this optional extraction so it cannot\n // hold up the full response. This deadline applies to the outer root, not\n // to Client Components that continue loading through lazy references.\n return await new Promise((resolve)=>{\n const timeout = setTimeout(()=>resolve(null), 0);\n response.then((root)=>{\n clearTimeout(timeout);\n resolve(root);\n }, ()=>{\n clearTimeout(timeout);\n resolve(null);\n });\n });\n } catch {\n return null;\n }\n}\n/**\n * Decodes already-buffered Flight response bytes as a stage payload. A\n * \"stage\" is a prefix of the staged server render — see `RenderStage` in\n * packages/next/src/server/app-render/staged-rendering.ts. The\n * bytes are delivered to Flight as a single chunk so all rows are processed\n * synchronously in one call — required for the thenable-status reads that\n * scope a response's late-resolving metadata (vary params, isPartial, ...)\n * to this decode.\n */ export function decodeBufferedStage(buffer, headers) {\n const stream = new ReadableStream({\n start (controller) {\n controller.enqueue(buffer);\n controller.close();\n }\n });\n return createFromNextReadableStream(stream, headers, {\n allowPartialStream: true\n });\n}\n// When an HMR refresh can be superseded, we decode its Flight response through\n// a wrapper stream we can close on abort. Closing the stream (rather than\n// letting the aborted fetch error it) makes React's Flight client mark\n// unresolved rows as halted: they suspend during render instead of rejecting,\n// so a superseded request never surfaces an error on an already-committed tree.\n// Because the stream is closed, there's also no unclosed-stream GC-root leak\n// (see #89610). The wrapper is created synchronously here so that the decode\n// starts at the same point `createFromNextFetch` would, preserving the\n// server-latency debug timing.\nfunction createHaltingFlightResponse(fetchPromise, headers, signal) {\n let closed = false;\n let reader = null;\n const wrapper = new ReadableStream({\n start (controller) {\n const onAbort = ()=>{\n closed = true;\n try {\n controller.close();\n } catch {\n // The controller may already be closed; nothing to do.\n }\n if (reader !== null) {\n reader.cancel().catch(()=>{});\n }\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, {\n once: true\n });\n }\n },\n async pull (controller) {\n if (closed) {\n return;\n }\n if (reader === null) {\n let response;\n try {\n response = await fetchPromise;\n } catch (err) {\n // We don't inspect `err`. If the request was superseded, `onAbort`\n // already ran synchronously (abort listeners fire during\n // `signal.abort()`, before this rejection microtask), so `closed` is\n // true and the controller is already closed — erroring it would\n // throw, and a superseded request's failure is moot regardless of its\n // cause. Only a genuine, non-superseded failure reaches here with\n // `closed` still false; that is the case we surface.\n if (!closed) {\n controller.error(err);\n }\n return;\n }\n if (closed) {\n // Aborted while awaiting the response. The `fetch` abort tears down\n // an in-flight request, but if it had already completed we still hold\n // an unread body; release it so it isn't left dangling.\n response.body?.cancel().catch(()=>{});\n return;\n }\n const body = response.body;\n if (body === null) {\n controller.close();\n return;\n }\n reader = body.getReader();\n }\n try {\n const { done, value } = await reader.read();\n if (closed) {\n return;\n }\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (err) {\n // Same as the fetch catch above: once superseded (`closed`) the\n // controller is already closed and the outcome is moot, so we swallow\n // the rejection unconditionally; only a real, non-superseded read\n // failure (`closed` still false) is surfaced.\n if (!closed) {\n controller.error(err);\n }\n }\n }\n });\n // React attaches `_debugInfo` to the returned promise at runtime.\n return createFromNextReadableStream(wrapper, headers, {\n allowPartialStream: true\n });\n}\n// Selects the Flight decode strategy: a halting wrapper for cancellable HMR\n// refreshes, otherwise the standard fetch-based decode. Gated to the dev server\n// (where HMR runs) so the wrapper is eliminated from production and\n// `--debug-prerender` bundles regardless of the flag.\nfunction decodeFlightResponse(fetchPromise, headers, signal) {\n if (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION && signal) {\n return createHaltingFlightResponse(fetchPromise, headers, signal);\n }\n return createFromNextFetch(fetchPromise, headers);\n}\nexport async function createFetch(url, headers, fetchPriority, shouldImmediatelyDecode, signal) {\n // TODO: In output: \"export\" mode, the headers do nothing. Omit them (and the\n // cache busting search param) from the request so they're\n // maximally cacheable.\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority;\n }\n const deploymentId = getDeploymentId();\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId;\n }\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r;\n }\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto.getRandomValues(new Uint32Array(1))[0].toString(16);\n }\n const fetchOptions = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal\n };\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url);\n await setCacheBustingSearchParam(fetchUrl, headers);\n let processed = fetch(fetchUrl, fetchOptions).then(processFetch);\n let fetchPromise = processed.then(({ response })=>response);\n // Immediately pass the fetch promise to the Flight client so that the debug\n // info includes the latency from the client to the server. The internal timer\n // in React starts as soon as `createFromFetch` is called.\n //\n // The only case where we don't do this is during a prefetch, because a\n // top-level prefetch response never blocks a navigation; if it hasn't already\n // been written into the cache by the time the navigation happens, the router\n // will go straight to a dynamic request.\n let flightResponsePromise = shouldImmediatelyDecode ? decodeFlightResponse(fetchPromise, headers, signal) : null;\n let browserResponse = await fetchPromise;\n // If the server responds with a redirect (e.g. 307), and the redirected\n // location does not contain the cache busting search param set in the\n // original request, the response is likely invalid — when following the\n // redirect, the browser forwards the request headers, but since the cache\n // busting search param is missing, the server will reject the request due to\n // a mismatch.\n //\n // Ideally, we would be able to intercept the redirect response and perform it\n // manually, instead of letting the browser automatically follow it, but this\n // is not allowed by the fetch API.\n //\n // So instead, we must \"replay\" the redirect by fetching the new location\n // again, but this time we'll append the cache busting search param to prevent\n // a mismatch.\n //\n // TODO: We can optimize Next.js's built-in middleware APIs by returning a\n // custom status code, to prevent the browser from automatically following it.\n //\n // This does not affect Server Action-based redirects; those are encoded\n // differently, as part of the Flight body. It only affects redirects that\n // occur in a middleware or a third-party proxy.\n let redirected = browserResponse.redirected;\n if (process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS) {\n // This is to prevent a redirect loop. Same limit used by Chrome.\n const MAX_REDIRECTS = 20;\n for(let n = 0; n < MAX_REDIRECTS; n++){\n if (!browserResponse.redirected) {\n break;\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl);\n if (responseUrl.origin !== fetchUrl.origin) {\n break;\n }\n if (responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) === fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)) {\n break;\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl);\n await setCacheBustingSearchParam(fetchUrl, headers);\n processed = fetch(fetchUrl, fetchOptions).then(processFetch);\n fetchPromise = processed.then(({ response })=>response);\n flightResponsePromise = shouldImmediatelyDecode ? decodeFlightResponse(fetchPromise, headers, signal) : null;\n browserResponse = await fetchPromise;\n // We just performed a manual redirect, so this is now true.\n redirected = true;\n }\n }\n // Remove the cache busting search param from the response URL, to prevent it\n // from leaking outside of this function.\n const responseUrl = new URL(browserResponse.url, fetchUrl);\n responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY);\n const rscResponse = {\n url: responseUrl.href,\n // This is true if any redirects occurred, either automatically by the\n // browser, or manually by us. So it's different from\n // `browserResponse.redirected`, which only tells us whether the browser\n // followed a redirect, and only for the last response in the chain.\n redirected,\n // These can be copied from the last browser response we received. We\n // intentionally only expose the subset of fields that are actually used\n // elsewhere in the codebase.\n ok: browserResponse.ok,\n headers: browserResponse.headers,\n body: browserResponse.body,\n status: browserResponse.status,\n // This is the exact promise returned by `createFromFetch`. It contains\n // debug information that we need to transfer to any derived promises that\n // are later rendered by React.\n flightResponsePromise: flightResponsePromise,\n cacheData: processed.then(({ cacheData })=>cacheData)\n };\n return rscResponse;\n}\nexport function createFromNextReadableStream(flightStream, requestHeaders, options) {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n unstable_allowPartialStream: options?.allowPartialStream\n });\n}\nfunction createFromNextFetch(promiseForResponse, requestHeaders) {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders)\n });\n}\n\n//# sourceMappingURL=fetch-server-response.js.map","import React, { use, useMemo, useOptimistic } from 'react';\nimport { isThenable } from '../../shared/lib/is-thenable';\nimport { ACTION_REFRESH } from './router-reducer/router-reducer-types';\n// The app router state lives outside of React, so we can import the dispatch\n// method directly wherever we need it, rather than passing it around via props\n// or context.\nlet dispatch = null;\n/**\n * Called when the instant navigation test lock is released. If the router\n * is initialized, dispatches a soft refresh to fetch dynamic data. If not\n * (e.g. the lock was released before hydration finished), falls back to a\n * hard reload.\n */ export function refreshOnInstantNavigationUnlock() {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n if (dispatch !== null) {\n dispatch({\n type: ACTION_REFRESH,\n bypassCacheInvalidation: true\n });\n } else {\n window.location.reload();\n }\n }\n}\nexport function dispatchAppRouterAction(action) {\n if (dispatch === null) {\n throw new Error('Internal Next.js error: Router action dispatched before initialization.');\n }\n dispatch(action);\n}\n// Optimistic state setter for experimental_gesturePush. Only should be used\n// during a gesture transition.\nlet setGestureRouterState = null;\nexport function dispatchGestureState(state) {\n if (setGestureRouterState === null) {\n throw new Error('Internal Next.js error: Router action dispatched before initialization.');\n }\n setGestureRouterState(state);\n}\nconst __DEV__ = process.env.NODE_ENV !== 'production';\nconst promisesWithDebugInfo = __DEV__ ? new WeakMap() : null;\nexport function useActionQueue(actionQueue) {\n const [canonicalState, setState] = React.useState(actionQueue.state);\n // Wrap the canonical state in useOptimistic to support\n // experimental_gesturePush. During a gesture transition, this returns a fork\n // of the router state that represents the eventual target if/when the gesture\n // completes. Otherwise it returns the canonical state.\n const [state, setGesture] = useOptimistic(canonicalState);\n if (typeof window !== 'undefined') {\n setGestureRouterState = setGesture;\n }\n // Because of a known issue that requires to decode Flight streams inside the\n // render phase, we have to be a bit clever and assign the dispatch method to\n // a module-level variable upon initialization. The useState hook in this\n // module only exists to synchronize state that lives outside of React.\n // Ideally, what we'd do instead is pass the state as a prop to root.render;\n // this is conceptually how we're modeling the app router state, despite the\n // weird implementation details.\n let nextDispatch;\n if (process.env.NODE_ENV !== 'production') {\n const { useAppDevRenderingIndicator } = require('../../next-devtools/userspace/use-app-dev-rendering-indicator');\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const appDevRenderingIndicator = useAppDevRenderingIndicator();\n nextDispatch = (action)=>{\n appDevRenderingIndicator(()=>{\n actionQueue.dispatch(action, setState);\n });\n };\n } else {\n nextDispatch = (action)=>actionQueue.dispatch(action, setState);\n }\n if (typeof window !== 'undefined') {\n dispatch = nextDispatch;\n }\n // When navigating to a non-prefetched route, then App Router state will be\n // blocked until the server responds. We need to transfer the `_debugInfo`\n // from the underlying Flight response onto the top-level promise that is\n // passed to React (via `use`) so that the latency is accurately represented\n // in the React DevTools.\n const stateWithDebugInfo = useMemo(()=>{\n if (!__DEV__) {\n return state;\n }\n if (isThenable(state)) {\n // useMemo can't be used to cache a Promise since the memoized value is thrown\n // away when we suspend. So we use a WeakMap to cache the Promise with debug info.\n let promiseWithDebugInfo = promisesWithDebugInfo.get(state);\n if (promiseWithDebugInfo === undefined) {\n const debugInfo = [];\n promiseWithDebugInfo = Promise.resolve(state).then((asyncState)=>{\n if (asyncState.debugInfo !== null) {\n debugInfo.push(...asyncState.debugInfo);\n }\n return asyncState;\n });\n promiseWithDebugInfo._debugInfo = debugInfo;\n promisesWithDebugInfo.set(state, promiseWithDebugInfo);\n }\n return promiseWithDebugInfo;\n }\n return state;\n }, [\n state\n ]);\n return isThenable(stateWithDebugInfo) ? use(stateWithDebugInfo) : stateWithDebugInfo;\n}\n\n//# sourceMappingURL=use-action-queue.js.map","const basePath = process.env.__NEXT_ROUTER_BASEPATH || '';\nconst pathname = `${basePath}/__nextjs_source-map`;\nexport const findSourceMapURL = // Source maps are only served by the dev server.\nprocess.env.__NEXT_DEV_SERVER ? function findSourceMapURL(filename) {\n if (filename === '') {\n return null;\n }\n if (filename.startsWith(document.location.origin) && filename.includes('/_next/static')) {\n // This is a request for a client chunk. This can only happen when\n // using Turbopack. In this case, since we control how those source\n // maps are generated, we can safely assume that the sourceMappingURL\n // is relative to the filename, with an added `.map` extension. The\n // browser can just request this file, and it gets served through the\n // normal dev server, without the need to route this through\n // the `/__nextjs_source-map` dev middleware.\n return `${filename}.map`;\n }\n const url = new URL(pathname, document.location.origin);\n url.searchParams.set('filename', filename);\n return url.href;\n} : undefined;\n\n//# sourceMappingURL=app-find-source-map-url.js.map","'use client';\nimport { computeCacheBustingSearchParam, computeLegacyCacheBustingSearchParam } from '../../../shared/lib/router/utils/cache-busting-search-param';\nimport { NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_URL, NEXT_RSC_UNION_QUERY } from '../app-router-headers';\nasync function computeClientCacheBustingSearchParam(headers) {\n if (typeof globalThis.crypto?.subtle?.digest === 'function') {\n return computeCacheBustingSearchParam(headers[NEXT_ROUTER_PREFETCH_HEADER], headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER], headers[NEXT_ROUTER_STATE_TREE_HEADER], headers[NEXT_URL]);\n }\n return computeLegacyCacheBustingSearchParam(headers[NEXT_ROUTER_PREFETCH_HEADER], headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER], headers[NEXT_ROUTER_STATE_TREE_HEADER], headers[NEXT_URL]);\n}\n/**\n * Mutates the provided URL by adding a cache-busting search parameter for CDNs that don't\n * support custom headers. This helps avoid caching conflicts by making each request unique.\n *\n * Rather than relying on the Vary header which some CDNs ignore, we append a search param\n * to create a unique URL that forces a fresh request.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * Note: This function mutates the input URL directly and resolves once the\n * cache-busting value has been computed and applied.\n *\n * TODO: Since we need to use a search param anyway, we could simplify by removing the custom\n * headers approach entirely and just use search params.\n */ export const setCacheBustingSearchParam = async (url, headers)=>{\n const uniqueCacheKey = await computeClientCacheBustingSearchParam(headers);\n setCacheBustingSearchParamWithHash(url, uniqueCacheKey);\n};\n/**\n * Sets a cache-busting search parameter on a URL using a provided hash value.\n *\n * This function performs the same logic as `setCacheBustingSearchParam` but accepts\n * a pre-computed hash instead of computing it from headers.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * hash: \"abc123\"\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * If the hash is empty, we will set `_rsc` search param without a value.\n * Like this: https://example.com/path?query=1&_rsc\n *\n * Note: This function mutates the input URL directly and does not return anything.\n */ export const setCacheBustingSearchParamWithHash = (url, hash)=>{\n /**\n * Note that we intentionally do not use `url.searchParams.set` here:\n *\n * const url = new URL('https://example.com/search?q=custom%20spacing');\n * url.searchParams.set('_rsc', 'abc123');\n * console.log(url.toString()); // Outputs: https://example.com/search?q=custom+spacing&_rsc=abc123\n * ^ <--- this is causing confusion\n * This is in fact intended based on https://url.spec.whatwg.org/#interface-urlsearchparams, but\n * we want to preserve the %20 as %20 if that's what the user passed in, hence the custom\n * logic below.\n */ const existingSearch = url.search;\n const rawQuery = existingSearch.startsWith('?') ? existingSearch.slice(1) : existingSearch;\n // Always remove any existing cache busting param and add a fresh one to ensure\n // we have the correct value based on current request headers\n const pairs = rawQuery.split('&').filter((pair)=>pair && !pair.startsWith(`${NEXT_RSC_UNION_QUERY}=`));\n if (hash.length > 0) {\n pairs.push(`${NEXT_RSC_UNION_QUERY}=${hash}`);\n } else {\n pairs.push(`${NEXT_RSC_UNION_QUERY}`);\n }\n url.search = pairs.length ? `?${pairs.join('&')}` : '';\n};\n\n//# sourceMappingURL=set-cache-busting-search-param.js.map","let deploymentId;\nif (typeof window !== 'undefined') {\n deploymentId = document.documentElement.dataset.dplId;\n // Immediately remove the attribute to prevent hydration errors (the dplId was inserted into the\n // HTML only), React isn't aware of it at all.\n document.documentElement.removeAttribute('data-dpl-id');\n} else {\n // Client side: replaced with globalThis.NEXT_DEPLOYMENT_ID\n // Server side: left as is or replaced with a string or replaced with false\n deploymentId = process.env.NEXT_DEPLOYMENT_ID || undefined;\n}\nexport function getDeploymentId() {\n return deploymentId;\n}\nexport function getDeploymentIdQuery(ampersand = false) {\n let id = getDeploymentId();\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`;\n }\n return '';\n}\nexport function getAssetToken() {\n return process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS ? undefined : process.env.NEXT_DEPLOYMENT_ID;\n}\nexport function getAssetTokenQuery(ampersand = false) {\n let id = getAssetToken();\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`;\n }\n return '';\n}\n\n//# sourceMappingURL=deployment-id.js.map","export function createHrefFromUrl(url, includeHash = true) {\n return url.pathname + url.search + (includeHash ? url.hash : '');\n}\n\n//# sourceMappingURL=create-href-from-url.js.map","export const TEXT_PLAIN_CONTENT_TYPE_HEADER = 'text/plain';\nexport const HTML_CONTENT_TYPE_HEADER = 'text/html; charset=utf-8';\nexport const JSON_CONTENT_TYPE_HEADER = 'application/json; charset=utf-8';\nexport const NEXT_QUERY_PARAM_PREFIX = 'nxtP';\nexport const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI';\nexport const MATCHED_PATH_HEADER = 'x-matched-path';\nexport const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate';\nexport const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER = 'x-prerender-revalidate-if-generated';\nexport const RSC_SEGMENTS_DIR_SUFFIX = '.segments';\nexport const RSC_SEGMENT_SUFFIX = '.segment.rsc';\nexport const RSC_SUFFIX = '.rsc';\nexport const ACTION_SUFFIX = '.action';\nexport const NEXT_DATA_SUFFIX = '.json';\nexport const NEXT_META_SUFFIX = '.meta';\nexport const NEXT_BODY_SUFFIX = '.body';\nexport const NEXT_NAV_DEPLOYMENT_ID_HEADER = 'x-nextjs-deployment-id';\nexport const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags';\nexport const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags';\nexport const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER = 'x-next-revalidate-tag-token';\nexport const NEXT_RESUME_HEADER = 'next-resume';\nexport const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length';\n// if these change make sure we update the related\n// documentation as well\nexport const NEXT_CACHE_TAG_MAX_ITEMS = 128;\nexport const NEXT_CACHE_TAG_MAX_LENGTH = 256;\nexport const NEXT_CACHE_SOFT_TAG_MAX_LENGTH = 1024;\nexport const NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_';\nexport const NEXT_CACHE_ROOT_PARAM_TAG_ID = '_N_RP_';\n// in seconds\nexport const CACHE_ONE_YEAR_SECONDS = 31536000;\n// in seconds, represents revalidate=false. I.e. never revaliate.\n// We use this value since it can be represented as a V8 SMI for optimal performance.\n// It can also be serialized as JSON if it ever leaks accidentally as an actual value.\nexport const INFINITE_CACHE = 0xfffffffe;\n// Patterns to detect middleware files\nexport const MIDDLEWARE_FILENAME = 'middleware';\nexport const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`;\n// Patterns to detect proxy files (replacement for middleware)\nexport const PROXY_FILENAME = 'proxy';\nexport const PROXY_LOCATION_REGEXP = `(?:src/)?${PROXY_FILENAME}`;\n// Pattern to detect instrumentation hooks file\nexport const INSTRUMENTATION_HOOK_FILENAME = 'instrumentation';\n// Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path,\n// we have to use a private alias\nexport const PAGES_DIR_ALIAS = 'private-next-pages';\nexport const DOT_NEXT_ALIAS = 'private-dot-next';\nexport const ROOT_DIR_ALIAS = 'private-next-root-dir';\nexport const APP_DIR_ALIAS = 'private-next-app-dir';\nexport const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy';\nexport const RSC_ACTION_VALIDATE_ALIAS = 'private-next-rsc-action-validate';\nexport const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-server-reference';\nexport const RSC_CACHE_WRAPPER_ALIAS = 'private-next-rsc-cache-wrapper';\nexport const RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS = 'private-next-rsc-track-dynamic-import';\nexport const RSC_ACTION_ENCRYPTION_ALIAS = 'private-next-rsc-action-encryption';\nexport const RSC_ACTION_CLIENT_WRAPPER_ALIAS = 'private-next-rsc-action-client-wrapper';\nexport const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`;\nexport const SSG_GET_INITIAL_PROPS_CONFLICT = `You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps`;\nexport const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.`;\nexport const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`;\nexport const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props`;\nexport const SERVER_PROPS_EXPORT_ERROR = `pages with \\`getServerSideProps\\` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export`;\nexport const GSP_NO_RETURNED_VALUE = 'Your `getStaticProps` function did not return an object. Did you forget to add a `return`?';\nexport const GSSP_NO_RETURNED_VALUE = 'Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?';\nexport const UNSTABLE_REVALIDATE_RENAME_ERROR = 'The `unstable_revalidate` property is available for general use.\\n' + 'Please use `revalidate` instead.';\nexport const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member`;\nexport const NON_STANDARD_NODE_ENV = `You are using a non-standard \"NODE_ENV\" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env`;\nexport const SSG_FALLBACK_EXPORT_ERROR = `Pages with \\`fallback\\` enabled in \\`getStaticPaths\\` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export`;\nexport const ESLINT_DEFAULT_DIRS = [\n 'app',\n 'pages',\n 'components',\n 'lib',\n 'src'\n];\nexport const SERVER_RUNTIME = {\n edge: 'edge',\n experimentalEdge: 'experimental-edge',\n nodejs: 'nodejs'\n};\nexport const WEB_SOCKET_MAX_RECONNECTIONS = 12;\n/**\n * The names of the webpack layers. These layers are the primitives for the\n * webpack chunks.\n */ const WEBPACK_LAYERS_NAMES = {\n /**\n * The layer for the shared code between the client and server bundles.\n */ shared: 'shared',\n /**\n * The layer for server-only runtime and picking up `react-server` export conditions.\n * Including app router RSC pages and app router custom routes and metadata routes.\n */ reactServerComponents: 'rsc',\n /**\n * Server Side Rendering layer for app (ssr).\n */ serverSideRendering: 'ssr',\n /**\n * The browser client bundle layer for actions.\n */ actionBrowser: 'action-browser',\n /**\n * The Node.js bundle layer for the API routes.\n */ apiNode: 'api-node',\n /**\n * The Edge Lite bundle layer for the API routes.\n */ apiEdge: 'api-edge',\n /**\n * The layer for the middleware code.\n */ middleware: 'middleware',\n /**\n * The layer for the instrumentation hooks.\n */ instrument: 'instrument',\n /**\n * The layer for assets on the edge.\n */ edgeAsset: 'edge-asset',\n /**\n * The browser client bundle layer for App directory.\n */ appPagesBrowser: 'app-pages-browser',\n /**\n * The browser client bundle layer for Pages directory.\n */ pagesDirBrowser: 'pages-dir-browser',\n /**\n * The Edge Lite bundle layer for Pages directory.\n */ pagesDirEdge: 'pages-dir-edge',\n /**\n * The Node.js bundle layer for Pages directory.\n */ pagesDirNode: 'pages-dir-node'\n};\nconst WEBPACK_LAYERS = {\n ...WEBPACK_LAYERS_NAMES,\n GROUP: {\n builtinReact: [\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.actionBrowser\n ],\n serverOnly: [\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.actionBrowser,\n WEBPACK_LAYERS_NAMES.instrument,\n WEBPACK_LAYERS_NAMES.middleware\n ],\n neutralTarget: [\n // pages api\n WEBPACK_LAYERS_NAMES.apiNode,\n WEBPACK_LAYERS_NAMES.apiEdge\n ],\n clientOnly: [\n WEBPACK_LAYERS_NAMES.serverSideRendering,\n WEBPACK_LAYERS_NAMES.appPagesBrowser\n ],\n bundled: [\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.actionBrowser,\n WEBPACK_LAYERS_NAMES.serverSideRendering,\n WEBPACK_LAYERS_NAMES.appPagesBrowser,\n WEBPACK_LAYERS_NAMES.shared,\n WEBPACK_LAYERS_NAMES.instrument,\n WEBPACK_LAYERS_NAMES.middleware\n ],\n appPages: [\n // app router pages and layouts\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.serverSideRendering,\n WEBPACK_LAYERS_NAMES.appPagesBrowser,\n WEBPACK_LAYERS_NAMES.actionBrowser\n ]\n }\n};\nconst WEBPACK_RESOURCE_QUERIES = {\n edgeSSREntry: '__next_edge_ssr_entry__',\n metadata: '__next_metadata__',\n metadataRoute: '__next_metadata_route__',\n metadataImageMeta: '__next_metadata_image_meta__'\n};\nexport { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES };\n\n//# sourceMappingURL=constants.js.map","export const ACTION_REFRESH = 'refresh';\nexport const ACTION_NAVIGATE = 'navigate';\nexport const ACTION_RESTORE = 'restore';\nexport const ACTION_SERVER_PATCH = 'server-patch';\nexport const ACTION_HMR_REFRESH = 'hmr-refresh';\nexport const ACTION_SERVER_ACTION = 'server-action';\n/**\n * PrefetchKind defines the type of prefetching that should be done.\n * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.\n * - `full` - prefetch the page data fully.\n */ export var PrefetchKind = /*#__PURE__*/ function(PrefetchKind) {\n PrefetchKind[\"AUTO\"] = \"auto\";\n PrefetchKind[\"FULL\"] = \"full\";\n return PrefetchKind;\n}({});\n/**\n * Controls the scroll behavior for a navigation.\n */ export var ScrollBehavior = /*#__PURE__*/ function(ScrollBehavior) {\n /** Use per-node ScrollRef to decide whether to scroll. */ ScrollBehavior[ScrollBehavior[\"Default\"] = 0] = \"Default\";\n /** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */ ScrollBehavior[ScrollBehavior[\"NoScroll\"] = 1] = \"NoScroll\";\n return ScrollBehavior;\n}({});\n\n//# sourceMappingURL=router-reducer-types.js.map","import { getPreLockFetch } from './navigation-testing-lock';\n/**\n * Internal `fetch` used by the Next.js client router.\n *\n * When the Instant Navigation Testing API is enabled, the navigation lock may\n * install a blocking override on `window.fetch` for the duration of a lock\n * scope. To let internal fetches bypass the lock, callers go through a wrapper\n * that falls back to the pre-lock fetch captured at lock-acquire time.\n *\n * When the testing API is not enabled, this calls window.fetch directly.\n */ function fetchInternal(input, init) {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const preLockFetch = getPreLockFetch();\n if (preLockFetch !== null) {\n return preLockFetch(input, init);\n }\n }\n return fetch(input, init);\n}\nexport { fetchInternal as fetch };\n\n//# sourceMappingURL=fetch.js.map","import { hexHash } from '../../hash';\nconst CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12;\nconst textEncoder = new TextEncoder();\nfunction encodeCacheBustingSearchParam(bytes) {\n let binary = '';\n for(let i = 0; i < bytes.length; i++){\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\nfunction normalizeCacheBustingInput(value) {\n if (value === undefined) {\n return '0';\n }\n return Array.isArray(value) ? value.join(',') : value;\n}\nfunction createCacheBustingSearchParamInput(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader) {\n if ((prefetchHeader === undefined || prefetchHeader === '0') && segmentPrefetchHeader === undefined && stateTreeHeader === undefined && nextUrlHeader === undefined) {\n return null;\n }\n return [\n prefetchHeader ?? '0',\n normalizeCacheBustingInput(segmentPrefetchHeader),\n normalizeCacheBustingInput(stateTreeHeader),\n normalizeCacheBustingInput(nextUrlHeader)\n ].join(',');\n}\nasync function computeCacheBustingSearchParamFromInput(input) {\n // Truncate SHA-256 to 96 bits to keep `_rsc` compact\n const digest = await globalThis.crypto.subtle.digest('SHA-256', textEncoder.encode(input));\n return encodeCacheBustingSearchParam(new Uint8Array(digest).subarray(0, CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES));\n}\nexport async function computeCacheBustingSearchParam(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader) {\n const input = createCacheBustingSearchParamInput(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader);\n if (input === null) {\n return '';\n }\n return computeCacheBustingSearchParamFromInput(input);\n}\nexport function computeLegacyCacheBustingSearchParam(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader) {\n const input = createCacheBustingSearchParamInput(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader);\n if (input === null) {\n return '';\n }\n return hexHash(input);\n}\n\n//# sourceMappingURL=cache-busting-search-param.js.map","// TypeScript trick to simulate opaque types, like in Flow.\nexport function createCacheKey(originalHref, nextUrl) {\n const originalUrl = new URL(originalHref);\n const cacheKey = {\n pathname: originalUrl.pathname,\n search: originalUrl.search,\n nextUrl: nextUrl\n };\n return cacheKey;\n}\n/**\n * Splits a pathname into its non-empty parts. Equivalent to\n * `pathname.split('/').filter((p) => p !== '')` — empty tokens produced by\n * leading, trailing, or consecutive slashes are skipped.\n *\n * We use a manual loop instead of `split` + `filter` because\n * `String.prototype.split` can return arrays with either the packed or holey\n * elements kind depending on internal fast paths, and `filter`/`slice`\n * propagate the kind. Mixing holey and packed arrays at the same call sites\n * makes downstream array method loads (`slice`, `join`, `length`) polymorphic\n * and causes repeated \"wrong map\" deoptimizations in hot route-matching code.\n * Pushing into an array literal guarantees a packed elements kind.\n */ export function splitPathnameIntoParts(pathname) {\n const parts = [];\n let start = 0;\n for(let i = 0; i < pathname.length; i++){\n if (pathname.charCodeAt(i) === 47 /* '/' */ ) {\n if (i > start) {\n parts.push(pathname.slice(start, i));\n }\n start = i + 1;\n }\n }\n if (start < pathname.length) {\n parts.push(pathname.slice(start));\n }\n return parts;\n}\n\n//# sourceMappingURL=cache-key.js.map","import { deleteMapEntry } from './cache-map';\nimport { pingPrefetchScheduler } from './scheduler';\n// We use an LRU for memory management. We must update this whenever we add or\n// remove a new cache entry, or when an entry changes size.\nlet head = null;\nlet lruSize = 0;\n// TODO: I chose the max size somewhat arbitrarily. Consider setting this based\n// on navigator.deviceMemory, or some other heuristic. We should make this\n// customizable via the Next.js config, too.\nconst maxLruSize = 50 * 1024 * 1024 // 50 MB\n;\nexport function lruPut(node) {\n if (head === node) {\n // Already at the head\n return;\n }\n const prev = node.prev;\n const next = node.next;\n if (next === null || prev === null) {\n // This is an insertion\n lruSize += node.size;\n // Whenever we add an entry, we need to check if we've exceeded the\n // max size. We don't evict entries immediately; they're evicted later in\n // an asynchronous task.\n ensureCleanupIsScheduled();\n } else {\n // This is a move. Remove from its current position.\n prev.next = next;\n next.prev = prev;\n }\n // Move to the front of the list\n if (head === null) {\n // This is the first entry\n node.prev = node;\n node.next = node;\n } else {\n // Add to the front of the list\n const tail = head.prev;\n node.prev = tail;\n // In practice, this is never null, but that isn't encoded in the type\n if (tail !== null) {\n tail.next = node;\n }\n node.next = head;\n head.prev = node;\n }\n head = node;\n}\nexport function updateLruSize(node, newNodeSize) {\n // This is a separate function from `put` so that we can resize the entry\n // regardless of whether it's currently being tracked by the LRU.\n const prevNodeSize = node.size;\n node.size = newNodeSize;\n if (node.next === null) {\n // This entry is not currently being tracked by the LRU.\n return;\n }\n // Update the total LRU size\n lruSize = lruSize - prevNodeSize + newNodeSize;\n ensureCleanupIsScheduled();\n}\nexport function deleteFromLru(deleted) {\n const next = deleted.next;\n const prev = deleted.prev;\n if (next !== null && prev !== null) {\n lruSize -= deleted.size;\n deleted.next = null;\n deleted.prev = null;\n // Remove from the list\n if (head === deleted) {\n // Update the head\n if (next === head) {\n // This was the last entry\n head = null;\n } else {\n head = next;\n prev.next = next;\n next.prev = prev;\n }\n } else {\n prev.next = next;\n next.prev = prev;\n }\n } else {\n // Already deleted\n }\n}\nfunction ensureCleanupIsScheduled() {\n if (lruSize <= maxLruSize) {\n return;\n }\n // To schedule cleanup, ping the prefetch scheduler. At the end of its work\n // loop, once there are no queued tasks and no in-progress requests, it will\n // call cleanup().\n pingPrefetchScheduler();\n}\nexport function cleanup() {\n if (lruSize <= maxLruSize) {\n return;\n }\n // Evict entries until we're at 90% capacity. We can assume this won't\n // infinite loop because even if `maxLruSize` were 0, eventually\n // `deleteFromLru` sets `head` to `null` when we run out entries.\n const ninetyPercentMax = maxLruSize * 0.9;\n while(lruSize > ninetyPercentMax && head !== null){\n const tail = head.prev;\n // In practice, this is never null, but that isn't encoded in the type\n if (tail !== null) {\n // Delete the entry from the map. In turn, this will remove it from\n // the LRU.\n deleteMapEntry(tail);\n }\n }\n}\n\n//# sourceMappingURL=lru.js.map","import { getCacheKeyForDynamicParam, parseDynamicParamFromURLPart, doesStaticSegmentAppearInURL, getRenderedPathname, getRenderedSearch } from './route-params';\nimport { createHrefFromUrl } from './components/router-reducer/create-href-from-url';\nexport function createInitialRSCPayloadFromFallbackPrerender(response, fallbackInitialRSCPayload) {\n // This is a static fallback page. In order to hydrate the page, we need to\n // parse the client params from the URL, but to account for the possibility\n // that the page was rewritten, we need to check the response headers\n // for x-nextjs-rewritten-path or x-nextjs-rewritten-query headers. Since\n // we can't access the headers of the initial document response, the client\n // performs a fetch request to the current location. Since it's possible that\n // the fetch request will be dynamically rewritten to a different path than\n // the initial document, this fetch request delivers _all_ the hydration data\n // for the page; it was not inlined into the document, like it normally\n // would be.\n //\n // TODO: Consider treating the case where fetch is rewritten to a different\n // path from the document as a special deopt case. We should optimistically\n // assume this won't happen, inline the data into the document, and perform\n // a minimal request (like a HEAD or range request) to verify that the\n // response matches. Tricky to get right because we need to account for\n // all the different deployment environments we support, like output:\n // \"export\" mode, where we currently don't assume that custom response\n // headers are present.\n // Patch the transport tree sent by the server with the correct params\n // parsed from the URL + response object.\n const renderedPathname = getRenderedPathname(response);\n const renderedSearch = getRenderedSearch(response);\n const canonicalUrl = createHrefFromUrl(new URL(location.href));\n const fallbackTransportData = fallbackInitialRSCPayload.t;\n const payload = {\n c: canonicalUrl.split('/'),\n q: renderedSearch,\n i: fallbackInitialRSCPayload.i,\n t: {\n t: fillInFallbackTransportTree(fallbackTransportData.t, renderedPathname.split('/').filter((part)=>part !== ''), 0),\n h: fallbackTransportData.h\n },\n m: fallbackInitialRSCPayload.m,\n G: fallbackInitialRSCPayload.G,\n S: fallbackInitialRSCPayload.S\n };\n if (fallbackInitialRSCPayload.b) {\n payload.b = fallbackInitialRSCPayload.b;\n }\n return payload;\n}\n/**\n * A fallback prerender is rendered without concrete param values. Fill them\n * in by parsing the rendered pathname, so the hydrated tree has the same\n * identity a direct render of this URL would have.\n */ function fillInFallbackTransportTree(node, pathnameParts, pathnamePartsIndex) {\n const originalSegment = node.s;\n let newSegment;\n let doesAppearInURL;\n if (typeof originalSegment === 'string') {\n newSegment = originalSegment;\n doesAppearInURL = doesStaticSegmentAppearInURL(originalSegment);\n } else {\n const paramValue = parseDynamicParamFromURLPart(originalSegment.t, pathnameParts, pathnamePartsIndex);\n newSegment = {\n n: originalSegment.n,\n t: originalSegment.t,\n k: getCacheKeyForDynamicParam(paramValue),\n s: originalSegment.s\n };\n doesAppearInURL = true;\n }\n // Only increment the index if the segment appears in the URL. If it's a\n // \"virtual\" segment, like a route group, it remains the same.\n const childPathnamePartsIndex = doesAppearInURL ? pathnamePartsIndex + 1 : pathnamePartsIndex;\n const children = node.c;\n let newChildren;\n if (children !== undefined) {\n newChildren = new Map();\n for (const [parallelRouteKey, childNode] of children){\n newChildren.set(parallelRouteKey, fillInFallbackTransportTree(childNode, pathnameParts, childPathnamePartsIndex));\n }\n }\n const newNode = {\n s: newSegment,\n d: node.d\n };\n if (node.h !== undefined) {\n newNode.h = node.h;\n }\n if (newChildren !== undefined) {\n newNode.c = newChildren;\n }\n return newNode;\n}\nexport function getNextFlightSegmentPath(flightSegmentPath) {\n // Since `FlightSegmentPath` is a repeated tuple of `Segment` and `ParallelRouteKey`, we slice off two items\n // to get the next segment path.\n return flightSegmentPath.slice(2);\n}\n/**\n * This function is used to prepare the flight router state for the request.\n * It removes markers that are not needed by the server, and are purely used\n * for stashing state on the client.\n * @param flightRouterState - The flight router state to prepare.\n * @param isHmrRefresh - Whether this is an HMR refresh request.\n * @returns The prepared flight router state.\n */ export function prepareFlightRouterStateForRequest(flightRouterState, isHmrRefresh) {\n // HMR requests need the complete, unmodified state for proper functionality\n if (isHmrRefresh) {\n return encodeURIComponent(JSON.stringify(flightRouterState));\n }\n return encodeURIComponent(JSON.stringify(stripClientOnlyDataFromFlightRouterState(flightRouterState)));\n}\n/**\n * Recursively strips client-only data from FlightRouterState while preserving\n * server-needed information for proper rendering decisions.\n */ function stripClientOnlyDataFromFlightRouterState(flightRouterState) {\n const [segment, parallelRoutes, _refreshState, refreshMarker, prefetchHints] = flightRouterState;\n // Strip client-only data from the segment\n const cleanedSegment = stripClientOnlyDataFromSegment(segment);\n // Recursively process parallel routes\n const cleanedParallelRoutes = {};\n for (const [key, childState] of Object.entries(parallelRoutes)){\n cleanedParallelRoutes[key] = stripClientOnlyDataFromFlightRouterState(childState);\n }\n const result = [\n cleanedSegment,\n cleanedParallelRoutes\n ];\n if (refreshMarker) {\n result[2] = null // null slightly more compact than undefined\n ;\n result[3] = refreshMarker;\n }\n // Append optional fields if present\n if (prefetchHints !== undefined) {\n result[4] = prefetchHints;\n }\n // Leave out the page's search params. They're only used by the client, and\n // request headers may be forwarded through redirects.\n return result;\n}\n/**\n * Strips client-only data from segments:\n * - staticSiblings from dynamic segment tuples (only needed for client-side\n * prefetch reuse decisions)\n */ function stripClientOnlyDataFromSegment(segment) {\n if (typeof segment === 'string') {\n return segment;\n }\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n // Strip staticSiblings (4th element) since server doesn't need it\n const [paramName, paramCacheKey, paramType] = segment;\n return [\n paramName,\n paramCacheKey,\n paramType,\n null\n ];\n}\n\n//# sourceMappingURL=flight-data-helpers.js.map","/**\n * Shared types and constants for the Segment Cache.\n */ export var NavigationResultTag = /*#__PURE__*/ function(NavigationResultTag) {\n NavigationResultTag[NavigationResultTag[\"MPA\"] = 0] = \"MPA\";\n NavigationResultTag[NavigationResultTag[\"Success\"] = 1] = \"Success\";\n NavigationResultTag[NavigationResultTag[\"NoOp\"] = 2] = \"NoOp\";\n NavigationResultTag[NavigationResultTag[\"Async\"] = 3] = \"Async\";\n return NavigationResultTag;\n}({});\n/**\n * The priority of the prefetch task. Higher numbers are higher priority.\n */ export var PrefetchPriority = /*#__PURE__*/ function(PrefetchPriority) {\n /**\n * Assigned to the most recently hovered/touched link. Special network\n * bandwidth is reserved for this task only. There's only ever one Intent-\n * priority task at a time; when a new Intent task is scheduled, the previous\n * one is bumped down to Default.\n */ PrefetchPriority[PrefetchPriority[\"Intent\"] = 2] = \"Intent\";\n /**\n * The default priority for prefetch tasks.\n */ PrefetchPriority[PrefetchPriority[\"Default\"] = 1] = \"Default\";\n /**\n * Assigned to tasks when they spawn non-blocking background work, like\n * revalidating a partially cached entry to see if more data is available.\n */ PrefetchPriority[PrefetchPriority[\"Background\"] = 0] = \"Background\";\n return PrefetchPriority;\n}({});\nexport var FetchStrategy = /*#__PURE__*/ function(FetchStrategy) {\n // Deliberately ordered so we can easily compare two segments\n // and determine if one segment is \"more specific\" than another\n // (i.e. if it's likely that it contains more data). See\n // canNewFetchStrategyProvideMoreContent in cache.ts for what each tier can\n // contain relative to the others.\n //\n // Full and LoadingBoundary belong to the non-Partial-Prefetching regime:\n // they're only relevant in modes where the staging concepts (shell tiers,\n // runtime prefetches) don't apply. They sit on this single ordered ladder\n // as an accepted convenience, because cross-regime comparisons exist\n // (e.g. canNewFetchStrategyProvideMoreContent).\n //\n // These numeric values are client-internal and never cross the wire — the\n // `next-router-prefetch` request header values are mapped explicitly in\n // fetchSegmentPrefetchesUsingRuntimeRequest (cache.ts) — so the members can\n // be renumbered freely as long as the relative order is preserved.\n FetchStrategy[FetchStrategy[\"LoadingBoundary\"] = 0] = \"LoadingBoundary\";\n // The shell-stage variant extracted from a static per-segment prefetch\n // response: every segment's param-dependent content is reduced to pending\n // references that render as the param fallback, keyed at the shell vary\n // paths (only root params kept concrete). The Shell PHASE that issues\n // these requests targets the conceptual App Shell; the strategy itself is\n // just this mechanical truncation and keying. Less complete than\n // RuntimeShell — a static response can't include content that depends on\n // session data (cookies, headers) — and less complete than PPR at concrete\n // paths, which includes prerendered param-dependent content.\n FetchStrategy[FetchStrategy[\"StaticShell\"] = 1] = \"StaticShell\";\n FetchStrategy[FetchStrategy[\"RuntimeShell\"] = 2] = \"RuntimeShell\";\n FetchStrategy[FetchStrategy[\"PPR\"] = 3] = \"PPR\";\n FetchStrategy[FetchStrategy[\"PPRRuntime\"] = 4] = \"PPRRuntime\";\n FetchStrategy[FetchStrategy[\"Full\"] = 5] = \"Full\";\n return FetchStrategy;\n}({});\n\n//# sourceMappingURL=types.js.map","import { FetchStrategy } from './types';\nimport { Fallback } from './cache-map';\nimport { readVaryParams, SEARCH_PARAMS_VARY_ID } from '../../../shared/lib/segment-cache/vary-params-decoding';\nexport function getRouteVaryPath(pathname, search, nextUrl) {\n // requestKey -> searchParams -> nextUrl\n const varyPath = {\n id: null,\n value: pathname,\n isRootParam: false,\n parent: {\n id: SEARCH_PARAMS_VARY_ID,\n value: search,\n isRootParam: false,\n parent: {\n id: null,\n value: nextUrl,\n isRootParam: false,\n parent: null\n }\n }\n };\n return varyPath;\n}\nexport function getFulfilledRouteVaryPath(pathname, search, nextUrl, couldBeIntercepted) {\n // This is called when a route's data is fulfilled. The cache entry will be\n // re-keyed based on which inputs the response varies by.\n // requestKey -> searchParams -> nextUrl\n const varyPath = {\n id: null,\n value: pathname,\n isRootParam: false,\n parent: {\n id: SEARCH_PARAMS_VARY_ID,\n value: search,\n isRootParam: false,\n parent: {\n id: null,\n value: couldBeIntercepted ? nextUrl : Fallback,\n isRootParam: false,\n parent: null\n }\n }\n };\n return varyPath;\n}\nexport function appendLayoutVaryPath(parentPath, cacheKey, paramName, isRootParam) {\n const varyPathPart = {\n id: paramName,\n value: cacheKey,\n isRootParam,\n parent: parentPath\n };\n return varyPathPart;\n}\nexport function finalizeVaryPath(requestKey, // Non-null when the segment varies on search params: the search entry is\n// spliced in between the request key and the path params. Fallback keys an\n// entry that is reusable across all search strings.\nsearchParams, partialVaryPath) {\n // requestKey -> [searchParams] -> pathParams\n let parent = partialVaryPath;\n if (searchParams !== null) {\n parent = {\n id: SEARCH_PARAMS_VARY_ID,\n value: searchParams,\n isRootParam: false,\n parent: partialVaryPath\n };\n }\n const varyPath = {\n id: null,\n value: requestKey,\n isRootParam: false,\n parent\n };\n return varyPath;\n}\nexport function getPartialVaryPath(finalizedVaryPath) {\n // This is the inverse of finalizeVaryPath: strip the request key, and the\n // search params entry if there is one.\n const parent = finalizedVaryPath.parent;\n if (parent !== null && parent.id === SEARCH_PARAMS_VARY_ID) {\n return parent.parent;\n }\n return parent;\n}\nexport function getSegmentVaryPathForRequest(fetchStrategy, tree) {\n // This is used for storing pending requests in the cache. We want to choose\n // the most generic vary path based on the strategy used to fetch it, i.e.\n // static/PPR versus runtime prefetching, so that it can be reused as much\n // as possible.\n //\n // We may be able to re-key the response to something even more generic once\n // we receive it — for example, if the server tells us that the response\n // doesn't vary on a particular param — but even before we send the request,\n // we know some params are reusable based on the fetch strategy alone. For\n // example, a static prefetch will never vary on search params.\n //\n // The original vary path with all the params filled in is stored on the\n // route tree object. We will clone this one to create a new vary path\n // where certain params are replaced with Fallback.\n //\n // This result of this function is not stored anywhere. It's only used to\n // access the cache a single time.\n //\n // TODO: Rather than create a new list object just to access the cache, the\n // plan is to add the concept of a \"vary mask\". This will represent all the\n // params that can be treated as Fallback. (Or perhaps the inverse.)\n const originalVaryPath = tree.varyPath;\n if (fetchStrategy === FetchStrategy.RuntimeShell || fetchStrategy === FetchStrategy.StaticShell) {\n // Both shell strategies produce the App Shell variant of a segment —\n // RuntimeShell via a runtime render with non-root params omitted,\n // StaticShell by truncating a static per-segment response at the shell\n // byte boundary. Either way, the resulting entry is reusable across all\n // concrete values of the non-root params, so we key it at the precomputed\n // shell vary path (every non-root param substituted with Fallback; root\n // params keep their concrete value).\n return tree.shellVaryPath;\n }\n // The vary path includes a search params entry only when the segment varies\n // on search params.\n const searchParamsVaryPath = originalVaryPath.parent;\n if (searchParamsVaryPath !== null && searchParamsVaryPath.id === SEARCH_PARAMS_VARY_ID) {\n // Only a runtime prefetch will include search params in the vary path.\n // Static prefetches never include search params, so they can be reused\n // across all possible search param values.\n const doesVaryOnSearchParams = fetchStrategy === FetchStrategy.Full || fetchStrategy === FetchStrategy.PPRRuntime;\n if (!doesVaryOnSearchParams) {\n // The response from the the server will not vary on search params.\n // Rebuild the vary path with the search params replaced by Fallback.\n //\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with Fallback\n return finalizeVaryPath(originalVaryPath.value, Fallback, getPartialVaryPath(originalVaryPath));\n }\n }\n // The request does vary on search params. We don't need to modify anything.\n return originalVaryPath;\n}\nexport function cloneVaryPathWithNewSearchParams(originalVaryPath, newSearch) {\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with newSearch\n const searchParamsVaryPath = originalVaryPath.parent;\n if (searchParamsVaryPath === null || searchParamsVaryPath.id !== SEARCH_PARAMS_VARY_ID) {\n // No search params entry; nothing to replace.\n return originalVaryPath;\n }\n return finalizeVaryPath(originalVaryPath.value, newSearch, getPartialVaryPath(originalVaryPath));\n}\n/**\n * Returns the rendered value of the vary path's search params entry when the\n * vary path has one with a concrete value, null otherwise. Only a segment that\n * varies on search params carries the entry; on every other vary path, and on\n * one whose search params entry is Fallback, this is null.\n */ export function getRenderedSearchFromVaryPath(varyPath) {\n let node = varyPath;\n while(node !== null){\n if (node.id === SEARCH_PARAMS_VARY_ID) {\n const search = node.value;\n if (typeof search === 'string') {\n return search;\n }\n return null;\n }\n node = node.parent;\n }\n return null;\n}\n/**\n * The kind of param change between two vary paths for the same segment. A path\n * param change takes precedence, because path params are part of\n * LayoutRouter's React key: the segment remounts either way.\n */ export var ParamsChange = /*#__PURE__*/ function(ParamsChange) {\n ParamsChange[ParamsChange[\"None\"] = 0] = \"None\";\n ParamsChange[ParamsChange[\"SearchParams\"] = 1] = \"SearchParams\";\n ParamsChange[ParamsChange[\"PathParam\"] = 2] = \"PathParam\";\n return ParamsChange;\n}({});\nexport function compareParams(currentVaryPath, nextVaryPath) {\n // Both vary paths are for the same segment, so they list the same params in\n // the same order. Walk them together. This includes params inherited from\n // parent layouts, since those may have changed, too.\n let current = currentVaryPath;\n let next = nextVaryPath;\n let change = 0;\n while(current !== null && next !== null){\n if (current.value !== next.value) {\n const id = current.id;\n if (id === null) {\n // The request key. Callers check that the route structure matches\n // first, so it's always the same.\n } else if (id === SEARCH_PARAMS_VARY_ID) {\n change = 1;\n } else {\n return 2;\n }\n }\n current = current.parent;\n next = next.parent;\n }\n return change;\n}\nexport function didReadChangedParam(currentVaryPath, nextVaryPath, varyParams) {\n // Returns true if the output rendered with `currentVaryPath` read a param\n // whose value is different in `nextVaryPath`. `varyParams` is the set of\n // params the output read, or null if we don't know.\n //\n // Same traversal as compareParams. Only read the set if a param changed.\n let current = currentVaryPath;\n let next = nextVaryPath;\n let total = null;\n while(current !== null && next !== null){\n if (current.value !== next.value) {\n const id = current.id;\n if (id === null) {\n // The request key. Callers check that the route structure matches\n // first, so it's always the same.\n } else {\n if (total === null) {\n if (varyParams === null) {\n // We don't know. Assume it read the param.\n return true;\n }\n total = readVaryParams(varyParams);\n if (total === null) {\n // The render hasn't finished, or it aborted. Assume it read the\n // param.\n return true;\n }\n }\n if (total.has(id)) {\n return true;\n }\n }\n }\n current = current.parent;\n next = next.parent;\n }\n return false;\n}\nexport function getFulfilledSegmentVaryPath(original, varyParams) {\n // Re-keys a segment's vary path based on which params the segment actually\n // depends on. Params that are NOT in the varyParams set are replaced with\n // Fallback, allowing the cache entry to be reused across different values of\n // those params.\n // This is called when a segment is fulfilled with data from the server. The\n // varyParams set comes from the server and indicates which params were\n // accessed during rendering.\n const clone = {\n id: original.id,\n // If the id is null, this node is not a param (e.g., it's a request key).\n // If the id is in the varyParams set, keep the original value.\n // Otherwise, replace with Fallback to make it reusable.\n value: original.id === null || varyParams.has(original.id) ? original.value : Fallback,\n isRootParam: original.isRootParam,\n parent: original.parent === null ? null : getFulfilledSegmentVaryPath(original.parent, varyParams)\n };\n return clone;\n}\nexport function getShellSegmentVaryPath(original) {\n // Re-keys a segment's vary path to identify the \"App Shell\" entry for this\n // segment position — a reusable loading state that can be served for any\n // concrete navigation to this segment. The shell is rendered with params\n // omitted, with one exception: root params (path params at or above the root\n // layout) may be accessed during the shell render, so the shell varies on\n // them. Accordingly, we keep the concrete value of structural nodes (request\n // keys, etc.) and root param nodes, and replace every other param node (non-\n // root path params and search params) with Fallback.\n const clone = {\n id: original.id,\n value: original.id === null || original.isRootParam === true ? original.value : Fallback,\n isRootParam: original.isRootParam,\n parent: original.parent === null ? null : getShellSegmentVaryPath(original.parent)\n };\n return clone;\n}\n\n//# sourceMappingURL=vary-path.js.map","import { FetchStrategy, PrefetchPriority } from './segment-cache/types';\nimport { createCacheKey } from './segment-cache/cache-key';\nimport { schedulePrefetchTask as scheduleSegmentPrefetchTask, cancelPrefetchTask, reschedulePrefetchTask, isPrefetchTaskDirty } from './segment-cache/scheduler';\nimport { startTransition } from 'react';\n// Tracks the most recently navigated link instance. When null, indicates\n// the current navigation was not initiated by a link click.\nlet linkForMostRecentNavigation = null;\n// Status object indicating link is pending\nexport const PENDING_LINK_STATUS = {\n pending: true\n};\n// Status object indicating link is idle\nexport const IDLE_LINK_STATUS = {\n pending: false\n};\n// Updates the loading state when navigating between links\n// - Resets the previous link's loading state\n// - Sets the new link's loading state\n// - Updates tracking of current navigation\nexport function setLinkForCurrentNavigation(link) {\n startTransition(()=>{\n linkForMostRecentNavigation?.setOptimisticLinkStatus(IDLE_LINK_STATUS);\n link?.setOptimisticLinkStatus(PENDING_LINK_STATUS);\n linkForMostRecentNavigation = link;\n });\n}\n// Unmounts the current link instance from navigation tracking\nexport function unmountLinkForCurrentNavigation(link) {\n if (linkForMostRecentNavigation === link) {\n linkForMostRecentNavigation = null;\n }\n}\n/**\n * Returns the link instance that initiated the most recent navigation.\n * Returns null if the navigation was not initiated by a link click.\n *\n * Used by the Instant Navigation Testing API in dev mode to match the\n * fetch strategy of the link during cache-miss navigations.\n */ export function getLinkForCurrentNavigation() {\n return linkForMostRecentNavigation;\n}\n// Use a WeakMap to associate a Link instance with its DOM element. This is\n// used by the IntersectionObserver to track the link's visibility.\nconst prefetchable = typeof WeakMap === 'function' ? new WeakMap() : new Map();\n// A Set of the currently visible links. We re-prefetch visible links after a\n// cache invalidation, or when the current URL changes. It's a separate data\n// structure from the WeakMap above because only the visible links need to\n// be enumerated.\nconst prefetchableAndVisible = new Set();\n// A single IntersectionObserver instance shared by all <Link> components.\nconst observer = typeof IntersectionObserver === 'function' ? new IntersectionObserver(handleIntersect, {\n rootMargin: '200px'\n}) : null;\nfunction observeVisibility(element, instance) {\n const existingInstance = prefetchable.get(element);\n if (existingInstance !== undefined) {\n // This shouldn't happen because each <Link> component should have its own\n // anchor tag instance, but it's defensive coding to avoid a memory leak in\n // case there's a logical error somewhere else.\n unmountPrefetchableInstance(element);\n }\n // Only track prefetchable links that have a valid prefetch URL\n prefetchable.set(element, instance);\n if (observer !== null) {\n observer.observe(element);\n }\n}\nfunction coercePrefetchableUrl(href) {\n if (typeof window !== 'undefined') {\n const { createPrefetchURL } = // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require\n require('./app-router-utils');\n try {\n return createPrefetchURL(href);\n } catch {\n // createPrefetchURL sometimes throws an error if an invalid URL is\n // provided, though I'm not sure if it's actually necessary.\n // TODO: Consider removing the throw from the inner function, or change it\n // to reportError. Or maybe the error isn't even necessary for automatic\n // prefetches, just navigations.\n const reportErrorFn = typeof reportError === 'function' ? reportError : console.error;\n reportErrorFn(`Cannot prefetch '${href}' because it cannot be converted to a URL.`);\n return null;\n }\n } else {\n return null;\n }\n}\nexport function mountLinkInstance(element, href, router, fetchStrategy, prefetchEnabled, setOptimisticLinkStatus, ownerStack) {\n if (prefetchEnabled) {\n const prefetchURL = coercePrefetchableUrl(href);\n if (prefetchURL !== null) {\n const instance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus,\n ownerStack\n };\n // We only observe the link's visibility if it's prefetchable. For\n // example, this excludes links to external URLs.\n observeVisibility(element, instance);\n return instance;\n }\n }\n // If the link is not prefetchable, we still create an instance so we can\n // track its optimistic state (i.e. useLinkStatus).\n const instance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: null,\n setOptimisticLinkStatus,\n ownerStack\n };\n return instance;\n}\nexport function mountFormInstance(element, href, router, fetchStrategy) {\n const prefetchURL = coercePrefetchableUrl(href);\n if (prefetchURL === null) {\n // This href is not prefetchable, so we don't track it.\n // TODO: We currently observe/unobserve a form every time its href changes.\n // For Links, this isn't a big deal because the href doesn't usually change,\n // but for forms it's extremely common. We should optimize this.\n return;\n }\n const instance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus: null\n };\n observeVisibility(element, instance);\n}\nexport function unmountPrefetchableInstance(element) {\n const instance = prefetchable.get(element);\n if (instance !== undefined) {\n prefetchable.delete(element);\n prefetchableAndVisible.delete(instance);\n const prefetchTask = instance.prefetchTask;\n if (prefetchTask !== null) {\n cancelPrefetchTask(prefetchTask);\n }\n }\n if (observer !== null) {\n observer.unobserve(element);\n }\n}\nfunction handleIntersect(entries) {\n // Process the entries in reverse order. The prefetch scheduler assigns the\n // highest priority to the most recently scheduled task, so whichever link we\n // schedule *last* wins. When multiple links enter the viewport at once (e.g.\n // on initial load), the observer reports them in document order, so iterating\n // in reverse means the link nearest the top of the document is scheduled last\n // and therefore prioritized. The topmost link isn't guaranteed to be the most\n // important, but as a default heuristic it's more reasonable than prioritizing\n // whichever link happens to be lowest in the document.\n for(let i = entries.length - 1; i >= 0; i--){\n const entry = entries[i];\n // Some extremely old browsers or polyfills don't reliably support\n // isIntersecting so we check intersectionRatio instead. (Do we care? Not\n // really. But whatever this is fine.)\n const isVisible = entry.intersectionRatio > 0;\n onLinkVisibilityChanged(entry.target, isVisible);\n }\n}\nexport function onLinkVisibilityChanged(element, isVisible) {\n if (process.env.NODE_ENV !== 'production') {\n // Prefetching on viewport is disabled in development for performance\n // reasons, because it requires compiling the target page.\n // TODO: Investigate re-enabling this.\n return;\n }\n const instance = prefetchable.get(element);\n if (instance === undefined) {\n return;\n }\n instance.isVisible = isVisible;\n if (isVisible) {\n prefetchableAndVisible.add(instance);\n } else {\n prefetchableAndVisible.delete(instance);\n }\n rescheduleLinkPrefetch(instance, PrefetchPriority.Default);\n}\nexport function onNavigationIntent(element, unstable_upgradeToDynamicPrefetch) {\n const instance = prefetchable.get(element);\n if (instance === undefined) {\n return;\n }\n // Prefetch the link on hover/touchstart.\n if (instance !== undefined) {\n if (process.env.__NEXT_DYNAMIC_ON_HOVER && unstable_upgradeToDynamicPrefetch) {\n // Switch to a full prefetch\n instance.fetchStrategy = FetchStrategy.Full;\n }\n rescheduleLinkPrefetch(instance, PrefetchPriority.Intent);\n }\n}\nfunction rescheduleLinkPrefetch(instance, priority) {\n // Ensures that app-router-instance is not compiled in the server bundle\n if (typeof window !== 'undefined') {\n const existingPrefetchTask = instance.prefetchTask;\n if (!instance.isVisible) {\n // Cancel any in-progress prefetch task. (If it already finished then this\n // is a no-op.)\n if (existingPrefetchTask !== null) {\n cancelPrefetchTask(existingPrefetchTask);\n }\n // We don't need to reset the prefetchTask to null upon cancellation; an\n // old task object can be rescheduled with reschedulePrefetchTask. This is a\n // micro-optimization but also makes the code simpler (don't need to\n // worry about whether an old task object is stale).\n return;\n }\n const { getCurrentAppRouterState } = // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require\n require('./app-router-instance');\n const appRouterState = getCurrentAppRouterState();\n if (appRouterState !== null) {\n if (existingPrefetchTask === null) {\n // Initiate a prefetch task.\n const nextUrl = appRouterState.nextUrl;\n const cacheKey = createCacheKey(instance.prefetchHref, nextUrl);\n instance.prefetchTask = scheduleSegmentPrefetchTask(cacheKey, appRouterState.root, instance.fetchStrategy, priority, null, null // navigationLockPrefetch\n );\n } else {\n // We already have an old task object that we can reschedule. This is\n // effectively the same as canceling the old task and creating a new one.\n reschedulePrefetchTask(existingPrefetchTask, appRouterState.root, instance.fetchStrategy, priority);\n }\n }\n }\n}\nexport function pingVisibleLinks(nextUrl, root) {\n // For each currently visible link, cancel the existing prefetch task (if it\n // exists) and schedule a new one. This is effectively the same as if all the\n // visible links left and then re-entered the viewport.\n //\n // This is called when the Next-Url or the active cache tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n for (const instance of prefetchableAndVisible){\n const task = instance.prefetchTask;\n if (task !== null && !isPrefetchTaskDirty(task, nextUrl, root)) {\n continue;\n }\n // Something changed. Cancel the existing prefetch task and schedule a\n // new one.\n if (task !== null) {\n cancelPrefetchTask(task);\n }\n const cacheKey = createCacheKey(instance.prefetchHref, nextUrl);\n instance.prefetchTask = scheduleSegmentPrefetchTask(cacheKey, root, instance.fetchStrategy, PrefetchPriority.Default, null, null // navigationLockPrefetch\n );\n }\n}\n\n//# sourceMappingURL=links.js.map","import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer';\n/**\n * Sentinel value indicating that no per-page dynamic stale time was provided.\n * When this is the dynamicStaleTime, the default DYNAMIC_STALETIME_MS is used.\n */ export const UnknownDynamicStaleTime = -1;\n/**\n * Converts a dynamic stale time (in seconds, as sent by the server in the `d`\n * field of the Flight response) to an absolute staleAt timestamp. When the\n * value is unknown, falls back to the global DYNAMIC_STALETIME_MS.\n */ export function computeDynamicStaleAt(now, dynamicStaleTimeSeconds) {\n return dynamicStaleTimeSeconds !== UnknownDynamicStaleTime ? now + dynamicStaleTimeSeconds * 1000 : now + DYNAMIC_STALETIME_MS;\n}\nimport { setInCacheMap, getFromCacheMap, EntryStatus, createCacheMap } from './cache-map';\nconst bfcacheMap = createCacheMap();\nlet currentBfCacheVersion = 0;\nexport function invalidateBfCache() {\n if (typeof window === 'undefined') {\n return;\n }\n currentBfCacheVersion++;\n}\nexport function writeToBFCache(now, varyPath, cacheNode, dynamicStaleAt) {\n if (typeof window === 'undefined') {\n return;\n }\n const entry = {\n rsc: cacheNode.rsc,\n prefetchRsc: cacheNode.prefetchRsc,\n varyParams: cacheNode.varyParams,\n bfcacheId: cacheNode.bfcacheId,\n ref: null,\n // TODO: This is just a heuristic. Getting the actual size of the segment\n // isn't feasible because it's part of a larger streaming response. The\n // LRU will still evict it, we just won't have a fully accurate total\n // LRU size. However, we'll probably remove the size tracking from the LRU\n // entirely and use memory pressure events instead.\n size: 100,\n navigatedAt: now,\n // A back/forward navigation will disregard the stale time. This field is\n // only relevant when staleTimes.dynamic is enabled or unstable_dynamicStaleTime\n // is exported by a page.\n staleAt: dynamicStaleAt,\n version: currentBfCacheVersion,\n status: EntryStatus.Fulfilled\n };\n const isRevalidation = false;\n setInCacheMap(bfcacheMap, varyPath, entry, isRevalidation);\n}\n/**\n * Patches the entry written for a segment before its dynamic response\n * arrived, with what the response filled in on the segment's CacheNode: the\n * per-page stale time from `unstable_dynamicStaleTime` (authoritative over\n * the default DYNAMIC_STALETIME_MS the entry was written with) and the\n * source of the params its data depends on. The entry shares the node's\n * deferred `rsc` promise, which the response resolves in place. Only the entry\n * that shares the node's `rsc` is updated; a refresh may have replaced the\n * entry at the same vary path, and that entry belongs to the newer node.\n *\n * TODO: This function exists because the entry gets `rsc` when it is written\n * but the stale time and vary params only later, through a second write that\n * has to find the entry again. The response should fill in all three as one\n * unit: make the pending CacheNode itself the thenable (like DeferredRsc, but\n * for the whole node) with an explicit pending → fulfilled/rejected\n * transition, so the entry holds the node and observes its resolution\n * directly, with nothing to look up or patch afterwards.\n */ export function updateBFCacheEntryFromDynamicResponse(varyPath, cacheNode, newStaleAt) {\n if (typeof window === 'undefined') {\n return;\n }\n const isRevalidation = false;\n // Read with staleness bypass (-1) so we can update even stale entries\n const entry = getFromCacheMap(-1, currentBfCacheVersion, bfcacheMap, varyPath, isRevalidation, false);\n if (entry !== null && entry.rsc === cacheNode.rsc) {\n entry.staleAt = newStaleAt;\n entry.varyParams = cacheNode.varyParams;\n }\n}\nexport function readFromBFCache(varyPath) {\n if (typeof window === 'undefined') {\n return null;\n }\n const isRevalidation = false;\n return getFromCacheMap(// During a back/forward navigation, it doesn't matter how stale the data\n // might be. Pass -1 instead of the actual current time to bypass\n // staleness checks.\n -1, currentBfCacheVersion, bfcacheMap, varyPath, isRevalidation, false);\n}\nexport function readFromBFCacheDuringRegularNavigation(now, varyPath) {\n if (typeof window === 'undefined') {\n return null;\n }\n const isRevalidation = false;\n return getFromCacheMap(now, currentBfCacheVersion, bfcacheMap, varyPath, isRevalidation, false);\n}\n\n//# sourceMappingURL=bfcache.js.map","import { completeHardNavigation, navigate as navigateUsingSegmentCache } from '../../app-router-state';\nimport { getStaleTimeMs } from '../../segment-cache/cache';\nimport { FreshnessPolicy } from '../../render-tree';\n// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)\n// and default to 5 minutes (static) / 0 seconds (dynamic)\nexport const DYNAMIC_STALETIME_MS = Number(process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME) * 1000;\nexport const STATIC_STALETIME_MS = getStaleTimeMs(Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME));\nexport function navigateReducer(state, action) {\n const { url, isExternalUrl, navigateType, scrollBehavior } = action;\n if (isExternalUrl) {\n return completeHardNavigation(state, url, navigateType);\n }\n // Handles case where `<meta http-equiv=\"refresh\">` tag is present,\n // which will trigger an MPA navigation.\n if (document.getElementById('__next-page-redirect')) {\n return completeHardNavigation(state, url, navigateType);\n }\n // Temporary glue code between the router reducer and the new navigation\n // implementation. Eventually we'll rewrite the router reducer to a\n // state machine.\n const currentUrl = new URL(state.canonicalUrl, location.origin);\n const currentRenderedSearch = state.renderedSearch;\n return navigateUsingSegmentCache(state, url, currentUrl, currentRenderedSearch, state.root, state.tree, state.nextUrl, FreshnessPolicy.Default, scrollBehavior, navigateType);\n}\n\n//# sourceMappingURL=navigate-reducer.js.map","/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */ export var PrefetchHint = /*#__PURE__*/ function(PrefetchHint) {\n // NOTE: The 0b00001 bit was previously HasRuntimePrefetch (prefetch:\n // 'allow-runtime'). Partial Prefetching allows using runtime requests\n // for every segment, so the bit was removed. Do not reuse it without\n // considering caches populated by older builds.\n // This segment or one of its descendants opts into Partial Prefetching, i.e.\n // uses the two-phase (Shell then Speculative) prefetch flow. Set when\n // `prefetch` is 'partial' (including the default implied by the global\n // `partialPrefetching` config). Propagates upward so the root segment\n // reflects the entire subtree.\n //\n // Partial Prefetching routes may use runtime requests for both shells\n // and prefetches. They *may* be optimized to a use a static request\n // if no runtime data was accessed during the prerender.\n // However, If the route has `ensureStatic` configured to \"shell\", \"prefetch\",\n // or \"navigation\", we *must* use static requests for the shell (and possibly the\n // prefetch).\n // Both of these cases are signalled to the scheduler via the\n // `ShouldAttemptStatic{Shell,Prefetch}` hints and the `needsRuntimeRequest`\n // promise.\n PrefetchHint[PrefetchHint[\"SubtreeHasPartialPrefetching\"] = 2] = \"SubtreeHasPartialPrefetching\";\n // This segment itself has a loading.tsx boundary.\n PrefetchHint[PrefetchHint[\"SegmentHasLoadingBoundary\"] = 4] = \"SegmentHasLoadingBoundary\";\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n PrefetchHint[PrefetchHint[\"SubtreeHasLoadingBoundary\"] = 8] = \"SubtreeHasLoadingBoundary\";\n // This segment is at or above the application's root layout — the root layout\n // segment itself and all of its ancestors. A dynamic param in one of these\n // segments is a \"root param\".\n PrefetchHint[PrefetchHint[\"IsRootLayoutOrAbove\"] = 16] = \"IsRootLayoutOrAbove\";\n // This segment's response includes its parent's data inlined into it.\n // Set at build time by the segment size measurement pass.\n PrefetchHint[PrefetchHint[\"ParentInlinedIntoSelf\"] = 32] = \"ParentInlinedIntoSelf\";\n // This segment's data is inlined into one of its children — don't fetch\n // it separately. Set at build time by the segment size measurement pass.\n PrefetchHint[PrefetchHint[\"InlinedIntoChild\"] = 64] = \"InlinedIntoChild\";\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // in its transport data (PartialTransportData's `h`).\n PrefetchHint[PrefetchHint[\"HeadInlinedIntoSelf\"] = 128] = \"HeadInlinedIntoSelf\";\n // On the root hint node: the head was NOT inlined into any page — fetch\n // it separately. Absence of this bit means the head is bundled into a page.\n PrefetchHint[PrefetchHint[\"HeadOutlined\"] = 256] = \"HeadOutlined\";\n // The inlining hints in this tree may be stale because the tree was\n // generated before collectPrefetchHints ran (e.g. the initial RSC payload\n // for a fully static page at build time). When writing this tree into the\n // cache, the route entry should be immediately expired so it gets\n // re-fetched with correct hints. Only set during build-time prerendering,\n // never at runtime.\n PrefetchHint[PrefetchHint[\"InliningHintsStale\"] = 512] = \"InliningHintsStale\";\n // This segment has prefetch = 'force-disabled'. The opt-out is passive\n // and applies to this segment only: it never INITIATES a prefetch — no\n // static data is emitted or fetched, and it's never the reason a runtime\n // prefetch spawns — but it may ride along in a runtime response issued on\n // another segment's behalf. Descendants prefetch normally.\n //\n // TODO: Also set as an internal fallback when the prefetch hints manifest\n // is unavailable (see #91407 mitigations), which only means \"no static\n // prefetch data exists\" — not a user opt-out. Split the fallback into its\n // own bit so the two intents can diverge.\n PrefetchHint[PrefetchHint[\"PrefetchDisabled\"] = 1024] = \"PrefetchDisabled\";\n // NOTE: The 0b100000000000 bit was previously SubtreeHasRuntimePrefetch.\n // Partial Prefetching now implies runtime completeness for every segment\n // (see SubtreeHasPartialPrefetching), so the bit was removed. Do not reuse\n // it without considering caches populated by older builds.\n // NOTE: The 0b1000000000000 bit was previously SubtreeHasEagerPrefetch\n // (prefetch: 'unstable_eager', plus every segment that did not opt into\n // Partial Prefetching). After `unstable_eager` was removed, it's no longer needed.\n // This segment or one of its descendants exports `instant = false`,\n // explicitly opting out of Partial Prefetching. Propagates upward so the root\n // reflects the entire subtree. Used only to suppress the dev-time\n // `<Link prefetch={true}>` warning — unlike PrefetchDisabled, it has no effect\n // on the actual prefetch behavior.\n PrefetchHint[PrefetchHint[\"SubtreeHasInstantFalse\"] = 8192] = \"SubtreeHasInstantFalse\";\n // The client should attempt a static prefetch for this route: the\n // build-time prerender did not access any runtime data (cookies, headers,\n // searchParams, ...), so a static prefetch is expected to be as complete\n // as a runtime one. A fallback-param access only unsets the bit when the\n // route can never be upgraded from a fallback to a concrete prerender —\n // on an upgradeable route, ISR later produces the concrete prerender a\n // static attempt would hit (until then, the static responses' own\n // signal reports the insufficiency per response). Purely advisory, and\n // both error directions are safe: if set when a runtime request is\n // actually needed, that same response-level signal (the load-bearing\n // `needsRuntimeRequest` promise combined with each segment's `isPartial`)\n // directs the client to follow up — the cost is a wasted static attempt.\n // If unset when static would have sufficed, the client goes straight to a\n // runtime prefetch, which is a superset of the static response — the cost\n // is only reduced cacheability. Like the other bits, this one is computed\n // once per build and stays constant for the build's lifetime; it rides\n // the prefetch-hints manifest into every response that carries hints —\n // `/_tree` prefetch responses and the FlightRouterState of dynamic\n // navigations alike. (Routes missing from the manifest — see the #91407\n // fallbacks — simply never carry it.) Set on every node of the tree, but\n // does not propagate.\n PrefetchHint[PrefetchHint[\"ShouldAttemptStaticShell\"] = 16384] = \"ShouldAttemptStaticShell\";\n PrefetchHint[PrefetchHint[\"ShouldAttemptStaticPrefetch\"] = 32768] = \"ShouldAttemptStaticPrefetch\";\n // This dynamic segment only accepts build-time parameter values. Kept on\n // the affected node, without propagating or copying it to other segments.\n // Until the client knows the allowed values, any such node prevents route\n // prediction, even when the route's components never read the parameter.\n PrefetchHint[PrefetchHint[\"IsClosedParam\"] = 65536] = \"IsClosedParam\";\n // A descendant segment (but not this one) has a closed parameter. Propagates\n // upward so route prediction can check the root instead of walking the tree.\n PrefetchHint[PrefetchHint[\"SubtreeHasClosedParams\"] = 131072] = \"SubtreeHasClosedParams\";\n return PrefetchHint;\n}({});\n/**\n * Bitmask for checking whether a segment's static prefetch is skipped — i.e.\n * the server emits no static data for it (its node in a segment response\n * carries identity only, and it participates in a bundle only as a\n * pass-through) and the client never issues a static request for it.\n *\n * Static prefetching is disabled ONLY by `prefetch: 'force-disabled'`\n * (PrefetchDisabled). Notably, Partial Prefetching segments DO have static\n * data even though they can use runtime requests: the server emits it\n * unconditionally — it can't be gated on the ShouldAttemptStatic{Shell,Prefetch}\n * hints, because which segments carry static data must be deterministic\n * from build-time config. A runtime request may still be needed for the\n * segment, but the scheduler may attempt a static prefetch first (per the\n * ShouldAttemptStatic{Shell,Prefetch} hints) and skip the runtime request if the\n * static response proves sufficient.\n *\n * Usage: `(hints & StaticPrefetchDisabled) !== 0`\n */ export const StaticPrefetchDisabled = 1024;\nexport const StaticAttemptHints = 16384 | 32768;\n/**\n * The subset of PrefetchHint bits that propagate upward from a child segment to\n * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary\n * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them\n * from a node's children.\n */ export const SubtreePrefetchHints = 2 | 8 | 8192 | 131072;\n/**\n * Folds a child segment's prefetch hints into its parent's, propagating the\n * \"subtree\" flags. A child's segment-local flag (e.g. it has a loading\n * boundary) becomes the corresponding \"subtree\" flag on the parent, so the\n * root segment ends up reflecting the entire subtree.\n *\n * Used wherever a route tree is assembled bottom-up: on the server when building\n * a transport tree (createTransportTreeFromLoaderTree) and on the client when\n * overlaying a navigation response onto the existing tree\n * (createNavigationSeed). Keep these in sync by routing both through\n * this helper.\n */ export function propagateSubtreeBits(parentHints, childHints) {\n if (childHints & 2) {\n parentHints |= 2;\n }\n // A child with a loading boundary (directly, or anywhere in its subtree) makes\n // this a SubtreeHasLoadingBoundary on the parent.\n if (childHints & (4 | 8)) {\n parentHints |= 8;\n }\n // And for `instant = false`. The bit is set directly on each opted-out\n // segment, so there's no separate segment-local flag — propagate it as-is.\n if (childHints & 8192) {\n parentHints |= 8192;\n }\n if (childHints & (65536 | 131072)) {\n parentHints |= 131072;\n }\n return parentHints;\n}\n\n//# sourceMappingURL=app-router-types.js.map","import { PAGE_SEGMENT_KEY } from './segment';\n/**\n * Creates the data for a skipped segment: a null `r` marks the position as\n * acknowledged by the response, with no output attached (see the note on\n * TransportSegmentData). Used by producers for the segments along the path\n * from the root down to the rendered subtrees.\n */ export function createSkippedSegmentData() {\n return {\n r: null,\n p: true,\n v: null\n };\n}\n/**\n * Reads a late-resolving value from a fully-buffered Flight decode via the\n * thenable's status. Flight sets `status`/`value` on a row's promise once\n * its bytes are processed, and a buffered decode processes every byte\n * synchronously, so any row that made it into the payload is readable\n * without awaiting. Returns `unresolvedValue` for a row that is pending or\n * absent in this decode — e.g. one whose fulfillment landed past a\n * truncated shell decode's boundary; that's what scopes a response's\n * late-resolving signals to the payload being decoded. Returns\n * `rejectedValue` (defaults to `unresolvedValue`) for a rejected row — an\n * aborted render errors rows that were still pending when it happened.\n *\n * Shared by client and server: the client reads buffered prefetch\n * responses; the server (collect-segment-data) reads the buffered page\n * payload it re-serializes into per-segment responses.\n */ export function readFulfilledValue(valueFromServer, unresolvedValue, rejectedValue = unresolvedValue) {\n const thenable = valueFromServer;\n // Force Flight to unwrap a received-but-not-yet-settled row.\n thenable.then(noop, noop);\n switch(thenable.status){\n case 'fulfilled':\n return thenable.value;\n case 'rejected':\n return rejectedValue;\n // No status yet: the row is still pending, or absent from this decode.\n case undefined:\n default:\n return unresolvedValue;\n }\n}\nconst noop = ()=>{};\n/**\n * Converts a segment's client/server-internal representation to its wire\n * representation.\n */ export function segmentToTransportSegment(segment) {\n if (typeof segment === 'string') {\n return segment;\n }\n return {\n n: segment[0],\n t: segment[2],\n k: segment[1],\n s: segment[3]\n };\n}\n/**\n * Converts a segment's wire representation to the client/server-internal\n * `Segment` type.\n */ export function transportSegmentToSegment(transportSegment) {\n if (typeof transportSegment === 'string') {\n return transportSegment;\n }\n return [\n transportSegment.n,\n // `k` may be null when the client is expected to parse the param value\n // from the URL (per-segment prefetch responses). Callers that need the\n // real value resolve it from the rendered pathname instead of using this\n // function (see resolveTransportSegment in decode-server-response); the\n // remaining callers are value-insensitive (segment request keys, which\n // never include param values) or only see concrete keys.\n transportSegment.k ?? '',\n transportSegment.t,\n transportSegment.s\n ];\n}\n/**\n * Derives a FlightRouterState from a transport tree. Used where the client\n * needs a router-state representation of a full response (e.g. the initial\n * hydration payload). Render output (`d`) is not carried over.\n */ export function transportNodeToFlightRouterState(node, renderedSearch) {\n const parallelRoutes = {};\n const children = node.c;\n if (children !== undefined) {\n for (const [parallelRouteKey, childNode] of children){\n parallelRoutes[parallelRouteKey] = transportNodeToFlightRouterState(childNode, renderedSearch);\n }\n }\n const flightRouterState = [\n transportSegmentToSegment(node.s),\n parallelRoutes\n ];\n if (node.h !== undefined) {\n flightRouterState[4] = node.h;\n }\n if (flightRouterState[0] === PAGE_SEGMENT_KEY) {\n flightRouterState[5] = renderedSearch;\n }\n return flightRouterState;\n}\n\n//# sourceMappingURL=rsc-transport.js.map","import { compareParams, ParamsChange } from './vary-path';\nimport { PrefetchHint, StaticPrefetchDisabled } from '../../../shared/lib/app-router-types';\nimport { readOrCreateRouteCacheEntry, readRouteCacheEntry, readOrCreateSegmentCacheEntry, fetchRouteOnCacheMiss, fetchSegmentPrefetchesUsingStaticRequest, EntryStatus, fetchSegmentPrefetchesUsingRuntimeRequest, convertRouteTreeToFlightRouterState, doesRouteStructureMatch, readOrCreateRevalidatingSegmentEntry, upgradeToPendingSegment, overwriteRevalidatingSegmentCacheEntry, canNewFetchStrategyProvideMoreContent, attemptToFulfillDynamicSegmentFromBFCache, attemptToUpgradeSegmentFromBFCache } from './cache';\nimport { createCacheKey } from './cache-key';\nimport { FetchStrategy, PrefetchPriority } from './types';\nimport { segmentCacheMap, getCurrentRouteCacheVersion, getCurrentSegmentCacheVersion } from './cache';\nimport { cleanup } from './lru';\nconst scheduleMicrotask = typeof queueMicrotask === 'function' ? queueMicrotask : (fn)=>Promise.resolve().then(fn).catch((error)=>setTimeout(()=>{\n throw error;\n }));\nconst taskHeap = [];\nlet inProgressRequests = 0;\nlet sortIdCounter = 0;\nlet didScheduleMicrotask = false;\n// The most recently hovered (or touched, etc) link, i.e. the most recent task\n// scheduled at Intent priority. There's only ever a single task at Intent\n// priority at a time. We reserve special network bandwidth for this task only.\nlet mostRecentlyHoveredLink = null;\n// CDN cache propagation delay after revalidation (in milliseconds)\nconst REVALIDATION_COOLDOWN_MS = 300;\n// Timeout handle for the revalidation cooldown. When non-null, prefetch\n// requests are blocked to allow CDN cache propagation.\nlet revalidationCooldownTimeoutHandle = null;\n/**\n * Called by the cache when revalidation occurs. Starts a cooldown period\n * during which prefetch requests are blocked to allow CDN cache propagation.\n */ export function startRevalidationCooldown() {\n // Clear any existing timeout in case multiple revalidations happen\n // in quick succession.\n if (revalidationCooldownTimeoutHandle !== null) {\n clearTimeout(revalidationCooldownTimeoutHandle);\n }\n // Schedule the cooldown to expire after the delay.\n revalidationCooldownTimeoutHandle = setTimeout(()=>{\n revalidationCooldownTimeoutHandle = null;\n // Retry the prefetch queue now that the cooldown has expired.\n pingPrefetchScheduler();\n }, REVALIDATION_COOLDOWN_MS);\n}\n/**\n * Initiates a prefetch task for the given URL. If a prefetch for the same URL\n * is already in progress, this will bump it to the top of the queue.\n *\n * This is not a user-facing function. By the time this is called, the href is\n * expected to be validated and normalized.\n *\n * @param key The RouteCacheKey to prefetch.\n * @param renderTreeAtTimeOfPrefetch The active render tree and head, and\n * their vary paths\n * @param fetchStrategy Whether to prefetch dynamic data, in addition to\n * static data. This is used by `<Link prefetch={true}>`.\n * @param navigationLockPrefetch Testing API only. Non-null when this prefetch\n * drives a locked navigation (from `ensurePrefetchThenNavigate`); carries that\n * navigation's \"wait for prefetch to fulfill\" state. Null otherwise.\n */ export function schedulePrefetchTask(key, renderTreeAtTimeOfPrefetch, fetchStrategy, priority, onInvalidate, navigationLockPrefetch) {\n // Bind the task to the segment cache map that is active right now: the\n // shared map, unless the Instant Navigation Testing lock is held, in which\n // case the task gets the lock scope's private map. This is the single\n // place work is bound to a map based on lock state — everything downstream\n // receives the map explicitly. See `segmentCacheMap` in cache.ts.\n let taskSegmentCacheMap = segmentCacheMap;\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { getNavigationLockSegmentCacheMap } = require('./navigation-testing-lock');\n const lockMap = getNavigationLockSegmentCacheMap();\n if (lockMap !== null) {\n taskSegmentCacheMap = lockMap;\n }\n }\n // Spawn a new prefetch task\n const task = {\n key,\n renderTreeAtTimeOfPrefetch,\n routeCacheVersion: getCurrentRouteCacheVersion(),\n segmentCacheVersion: getCurrentSegmentCacheVersion(),\n segmentCacheMap: taskSegmentCacheMap,\n priority,\n phase: 2,\n hasBackgroundWork: false,\n hasPendingResponses: false,\n spawnedRuntimePrefetches: null,\n fetchStrategy,\n sortId: sortIdCounter++,\n isCanceled: false,\n fallbackRetryStatus: EntryStatus.Empty,\n onInvalidate,\n _heapIndex: -1\n };\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n task._navigationLockPrefetch = navigationLockPrefetch;\n }\n trackMostRecentlyHoveredLink(task);\n heapPush(taskHeap, task);\n // Schedule an async task to process the queue.\n //\n // The main reason we process the queue in an async task is for batching.\n // It's common for a single JS task/event to trigger multiple prefetches.\n // By deferring to a microtask, we only process the queue once per JS task.\n // If they have different priorities, it also ensures they are processed in\n // the optimal order.\n pingPrefetchScheduler();\n return task;\n}\nexport function cancelPrefetchTask(task) {\n // Remove the prefetch task from the queue. If the task already completed,\n // then this is a no-op.\n //\n // We must also explicitly mark the task as canceled so that a blocked task\n // does not get added back to the queue when it's pinged by the network.\n task.isCanceled = true;\n // A running fallback-retry loop notices `isCanceled` when it next wakes and\n // bails (settling its status to Rejected), so there's nothing to clean up here.\n heapDelete(taskHeap, task);\n}\nexport function reschedulePrefetchTask(task, renderTreeAtTimeOfPrefetch, fetchStrategy, priority) {\n // Bump the prefetch task to the top of the queue, as if it were a fresh\n // task. This is essentially the same as canceling the task and scheduling\n // a new one, except it reuses the original object.\n //\n // The primary use case is to increase the priority of a Link-initated\n // prefetch on hover.\n // Un-cancel the task, in case it was previously canceled.\n task.isCanceled = false;\n task.phase = 2;\n // Note: fallback-retry state is deliberately NOT reset here. A retry loop runs\n // at most once per task, even across reschedules, so a re-hover never starts a\n // second loop. A loop already running simply continues (it only stops on\n // cancel); `fallbackRetryStatus` never returns to `Empty` once it leaves it.\n // Assign a new sort ID to move it ahead of all other tasks at the same\n // priority level. (Higher sort IDs are processed first.)\n task.sortId = sortIdCounter++;\n task.priority = // If this task is the most recently hovered link, maintain its\n // Intent priority, even if the rescheduled priority is lower.\n task === mostRecentlyHoveredLink ? PrefetchPriority.Intent : priority;\n task.renderTreeAtTimeOfPrefetch = renderTreeAtTimeOfPrefetch;\n task.fetchStrategy = fetchStrategy;\n trackMostRecentlyHoveredLink(task);\n if (task._heapIndex !== -1) {\n // The task is already in the queue.\n heapResift(taskHeap, task);\n } else {\n heapPush(taskHeap, task);\n }\n pingPrefetchScheduler();\n}\nexport function isPrefetchTaskDirty(task, nextUrl, root) {\n // This is used to quickly bail out of a prefetch task if the result is\n // guaranteed to not have changed since the task was initiated. This is\n // strictly an optimization — theoretically, if it always returned true, no\n // behavior should change because a full prefetch task will effectively\n // perform the same checks.\n return task.routeCacheVersion !== getCurrentRouteCacheVersion() || task.segmentCacheVersion !== getCurrentSegmentCacheVersion() || task.renderTreeAtTimeOfPrefetch !== root || task.key.nextUrl !== nextUrl;\n}\nfunction trackMostRecentlyHoveredLink(task) {\n // Track the mostly recently hovered link, i.e. the most recently scheduled\n // task at Intent priority. There must only be one such task at a time.\n if (task.priority === PrefetchPriority.Intent && task !== mostRecentlyHoveredLink) {\n if (mostRecentlyHoveredLink !== null) {\n // Bump the previously hovered link's priority down to Default.\n if (mostRecentlyHoveredLink.priority !== PrefetchPriority.Background) {\n mostRecentlyHoveredLink.priority = PrefetchPriority.Default;\n heapResift(taskHeap, mostRecentlyHoveredLink);\n }\n }\n mostRecentlyHoveredLink = task;\n }\n}\nexport function pingPrefetchScheduler() {\n if (didScheduleMicrotask) {\n // Already scheduled a task to process the queue\n return;\n }\n didScheduleMicrotask = true;\n scheduleMicrotask(processQueueInMicrotask);\n}\n/**\n * Checks if we've exceeded the maximum number of concurrent prefetch requests,\n * to avoid saturating the browser's internal network queue. This is a\n * cooperative limit — prefetch tasks should check this before issuing\n * new requests.\n *\n * Also checks if we're within the revalidation cooldown window, during which\n * prefetch requests are delayed to allow CDN cache propagation.\n */ function hasNetworkBandwidth(task) {\n // When offline, don't issue any prefetch requests. The scheduler will be\n // re-pinged when connectivity is restored.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { getOffline } = require('../offline');\n if (getOffline()) {\n return false;\n }\n }\n // Check if we're within the revalidation cooldown window\n if (revalidationCooldownTimeoutHandle !== null) {\n // We're within the cooldown window. Return false to prevent prefetching.\n // When the cooldown expires, the timeout will call ensureWorkIsScheduled()\n // to retry the queue.\n return false;\n }\n // TODO: Also check if there's an in-progress navigation. We should never\n // add prefetch requests to the network queue if an actual navigation is\n // taking place, to ensure there's sufficient bandwidth for render-blocking\n // data and resources.\n // TODO: Consider reserving some amount of bandwidth for static prefetches.\n if (task.priority === PrefetchPriority.Intent) {\n // The most recently hovered link is allowed to exceed the default limit.\n //\n // The goal is to always have enough bandwidth to start a new prefetch\n // request when hovering over a link.\n //\n // However, because we don't abort in-progress requests, it's still possible\n // we'll run out of bandwidth. When links are hovered in quick succession,\n // there could be multiple hover requests running simultaneously.\n return inProgressRequests < 12;\n }\n // The default limit is lower than the limit for a hovered link.\n return inProgressRequests < 4;\n}\nfunction spawnPrefetchSubtask(prefetchSubtask) {\n // When the scheduler spawns an async task, we don't await its result.\n // Instead, the async task writes its result directly into the cache, then\n // pings the scheduler to continue.\n //\n // We process server responses streamingly, so the prefetch subtask will\n // likely resolve before we're finished receiving all the data. The subtask\n // result includes a promise that resolves once the network connection is\n // closed. The scheduler uses this to control network bandwidth by tracking\n // and limiting the number of concurrent requests.\n inProgressRequests++;\n return prefetchSubtask.then((result)=>{\n if (result === null) {\n // The prefetch task errored before it could start processing the\n // network stream. Assume the connection is closed.\n onPrefetchConnectionClosed();\n return null;\n }\n // Wait for the connection to close before freeing up more bandwidth.\n result.closed.then(onPrefetchConnectionClosed);\n return result.value;\n });\n}\nfunction onPrefetchConnectionClosed() {\n inProgressRequests--;\n // Notify the scheduler that we have more bandwidth, and can continue\n // processing tasks.\n pingPrefetchScheduler();\n}\n/**\n * Notify the scheduler that we've received new data for an in-progress\n * prefetch. The corresponding task will be added back to the queue (unless the\n * task has been canceled in the meantime).\n */ export function pingPrefetchTask(task) {\n // \"Ping\" a prefetch that's already in progress to notify it of new data.\n if (// Check if prefetch was canceled.\n task.isCanceled || // Check if prefetch is already queued.\n task._heapIndex !== -1) {\n return;\n }\n // Add the task back to the queue.\n heapPush(taskHeap, task);\n pingPrefetchScheduler();\n}\nfunction processQueueInMicrotask() {\n didScheduleMicrotask = false;\n // We aim to minimize how often we read the current time. Since nearly all\n // functions in the prefetch scheduler are synchronous, we can read the time\n // once and pass it as an argument wherever it's needed.\n const now = Date.now();\n // Process the task queue until we run out of network bandwidth.\n let task = heapPeek(taskHeap);\n while(task !== null && hasNetworkBandwidth(task)){\n task.routeCacheVersion = getCurrentRouteCacheVersion();\n task.segmentCacheVersion = getCurrentSegmentCacheVersion();\n const exitStatus = pingRoute(now, task);\n // These fields are only valid for a single \"pass\" — one pingRoute\n // invocation for a task, which is what the comments here also call an\n // attempt or an iteration. Reset them after each iteration of the\n // task queue.\n const hasBackgroundWork = task.hasBackgroundWork;\n task.hasBackgroundWork = false;\n task.hasPendingResponses = false;\n task.spawnedRuntimePrefetches = null;\n switch(exitStatus){\n case 0:\n // The task yielded because there are too many requests in progress.\n // Stop processing tasks until we have more bandwidth.\n return;\n case 1:\n // The task is blocked. It needs more data before it can proceed.\n // Keep the task out of the queue until the server responds.\n heapPop(taskHeap);\n // Continue to the next task\n task = heapPeek(taskHeap);\n continue;\n case 2:\n if (task.phase === 2) {\n // Finished prefetching the route tree. The two-phase (Shell then\n // Speculative) flow only applies to routes that have opted into\n // Partial Prefetching — either globally via the `partialPrefetching`\n // config or per segment (`prefetch: 'partial'`), both surfaced as the\n // `SubtreeHasPartialPrefetching` hint on the route tree. Every other\n // route skips the Shell phase and goes straight to Speculative.\n //\n // The route entry is fulfilled at this point (the RouteTree phase\n // just completed), so its prefetch hints are available.\n const route = readRouteCacheEntry(now, task.key);\n const routeHasPartialPrefetching = route !== null && route.status === EntryStatus.Fulfilled && (route.root.tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0;\n task.phase = routeHasPartialPrefetching ? 1 : 0;\n heapResift(taskHeap, task);\n } else if (task.phase === 1) {\n // Shell phase complete — a Done exit means the pass observed every\n // response it cares about (otherwise it would have exited Blocked;\n // see hasPendingResponses). Always advance to Speculative regardless\n // of whether Shell-phase work fired — Speculative is responsible\n // for the per-link concrete work and runs even on routes whose\n // shell phase was a no-op.\n task.phase = 0;\n heapResift(taskHeap, task);\n } else if (hasBackgroundWork) {\n // The task spawned additional background work. Reschedule the task\n // at background priority.\n task.priority = PrefetchPriority.Background;\n heapResift(taskHeap, task);\n } else {\n // The prefetch is complete. Continue to the next task.\n //\n // Completion is terminal in the normal flow: a task only completes\n // after a full pass observed every response it cares about. In rare\n // cases, though, a task can complete while still registered on an\n // entry from an earlier pass whose subtree the final pass no longer\n // reached; when that entry later settles, it re-pings the completed\n // task. The re-run is a harmless idempotent no-op, but any\n // per-completion side effect added here must be idempotent or\n // once-guarded — in particular, the navigation-lock release below\n // must not fire twice (hence the nulling).\n if (process.env.__NEXT_EXPOSE_TESTING_API && task._navigationLockPrefetch != null) {\n // This locked-navigation prefetch is complete: the final pass\n // observed every segment response it cares about, so the data the\n // navigation will read has settled. Resolve the prefetch's\n // promise (awaited by `ensurePrefetchThenNavigate`) so the\n // navigation proceeds against present data rather than a\n // still-in-flight entry.\n const { resolveNavigationLockPrefetch } = require('./navigation-testing-lock');\n resolveNavigationLockPrefetch(task._navigationLockPrefetch);\n // Release at most once per task: a stale registration from an\n // earlier pass can re-ping a completed task (see above), so it can\n // pass through here again.\n task._navigationLockPrefetch = null;\n }\n heapPop(taskHeap);\n }\n task = heapPeek(taskHeap);\n continue;\n default:\n exitStatus;\n }\n }\n // Run LRU cleanup only when the scheduler is fully idle: no queued tasks and\n // no in-progress requests. At that point, all active prefetch tasks have\n // finished reading from the cache (moving recently used entries to the front\n // of the list), so only genuinely stale data gets evicted.\n if (task === null && inProgressRequests === 0) {\n cleanup();\n }\n}\n/**\n * Check this during a prefetch task to determine if background work can be\n * performed. If so, it evaluates to `true`. Otherwise, it returns `false`,\n * while also scheduling a background task to run later. Usage:\n *\n * @example\n * if (background(task)) {\n * // Perform background-pri work\n * }\n *\n * TODO: Model \"background\" as a phase (like Shell / Speculative) rather\n * than as a priority. Conceptually it's the same pattern: defer work\n * until a later pass over the task. The current priority-based encoding\n * predates the phase model and could be unified.\n */ function background(task) {\n if (task.priority === PrefetchPriority.Background) {\n return true;\n }\n task.hasBackgroundWork = true;\n return false;\n}\nfunction pingRoute(now, task) {\n const key = task.key;\n const route = readOrCreateRouteCacheEntry(now, task, key);\n const exitStatus = pingRootRouteTree(now, task, route);\n if (exitStatus !== 0 && key.search !== '') {\n // If the URL has a non-empty search string, also prefetch the pathname\n // without the search string. We use the searchless route tree as a base for\n // optimistic routing; see requestOptimisticRouteCacheEntry for details.\n //\n // Note that we don't need to prefetch any of the segment data. Just the\n // route tree.\n //\n // TODO: This is a temporary solution; the plan is to replace this by adding\n // a wildcard lookup method to the TupleMap implementation. This is\n // non-trivial to implement because it needs to account for things like\n // fallback route entries, hence this temporary workaround.\n const url = new URL(key.pathname, location.origin);\n const keyWithoutSearch = createCacheKey(url.href, key.nextUrl);\n const routeWithoutSearch = readOrCreateRouteCacheEntry(now, task, keyWithoutSearch);\n switch(routeWithoutSearch.status){\n case EntryStatus.Empty:\n {\n if (background(task)) {\n routeWithoutSearch.status = EntryStatus.Pending;\n spawnPrefetchSubtask(fetchRouteOnCacheMiss(routeWithoutSearch, keyWithoutSearch));\n }\n break;\n }\n case EntryStatus.Pending:\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n {\n break;\n }\n default:\n routeWithoutSearch;\n }\n }\n if (exitStatus === 2 && task.hasPendingResponses) {\n // The pass traversed the whole tree, but some segment responses haven't\n // arrived yet, so the current phase isn't actually complete. Block until\n // they do (see blockTaskOnPendingResponse for the full rationale).\n return 1;\n }\n return exitStatus;\n}\nfunction pingRootRouteTree(now, task, route) {\n switch(route.status){\n case EntryStatus.Empty:\n {\n // Route is not yet cached, and there's no request already in progress.\n // Spawn a task to request the route, load it into the cache, and ping\n // the task to continue.\n // TODO: There are multiple strategies in the <Link> API for prefetching\n // a route. Currently we've only implemented the main one: per-segment,\n // static-data only.\n //\n // There's also `<Link prefetch={true}>`\n // which prefetch both static *and* dynamic data.\n // Similarly, we need to fallback to the old, per-page\n // behavior if PPR is disabled for a route (via the incremental opt-in).\n //\n // Those cases will be handled here.\n spawnPrefetchSubtask(fetchRouteOnCacheMiss(route, task.key));\n // If the request takes longer than a minute, a subsequent request should\n // retry instead of waiting for this one. When the response is received,\n // this value will be replaced by a new value based on the stale time sent\n // from the server.\n // TODO: We should probably also manually abort the fetch task, to reclaim\n // server bandwidth.\n route.staleAt = now + 60 * 1000;\n // Upgrade to Pending so we know there's already a request in progress\n route.status = EntryStatus.Pending;\n // Intentional fallthrough to the Pending branch\n }\n case EntryStatus.Pending:\n {\n // Still pending. We can't start prefetching the segments until the route\n // tree has loaded. Add the task to the set of blocked tasks so that it\n // is notified when the route tree is ready.\n const blockedTasks = route.blockedTasks;\n if (blockedTasks === null) {\n route.blockedTasks = new Set([\n task\n ]);\n } else {\n blockedTasks.add(task);\n }\n return 1;\n }\n case EntryStatus.Rejected:\n {\n // Route tree failed to load. Treat as a 404.\n return 2;\n }\n case EntryStatus.Fulfilled:\n {\n if (task.phase === 2) {\n // Do not prefetch segment data during the route tree phase.\n return 2;\n }\n // Recursively fill in the segment tree.\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return 0;\n }\n const tree = route.root.tree;\n // A task's fetch strategy gets set to `PPR` for any \"auto\" prefetch.\n // If it turned out that the route isn't PPR-enabled, we need to use `LoadingBoundary` instead.\n // We don't need to do this for runtime prefetches, because those are only available in\n // `cacheComponents`, where every route is PPR.\n let fetchStrategy;\n if (tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n // If Partial Prefetching is enabled anywhere on the target route,\n // ignore the fetch strategy and switch to unified strategy used by\n // Cache Components (called `PPR` for now, will likely be renamed).\n //\n // In practice, this just means that a \"full\" prefetch (<Link\n // prefetch={true}>) has no effect. You're meant to use Runtime\n // Prefetching instead — that's the new pattern that replaces\n // prefetch={true}.\n //\n // The reason we check for the Partial Prefetching opt-in rather than\n // the `cacheComponents` flag is to support incremental adoption.\n // `prefetch={true}` will continue to work until you opt into\n // Partial Prefetching.\n fetchStrategy = FetchStrategy.PPR;\n } else if (task.fetchStrategy === FetchStrategy.PPR) {\n fetchStrategy = route.supportsPerSegmentPrefetching ? FetchStrategy.PPR : FetchStrategy.LoadingBoundary;\n } else {\n fetchStrategy = task.fetchStrategy;\n }\n switch(fetchStrategy){\n case FetchStrategy.PPR:\n {\n // For Cache Components pages, each segment may be prefetched\n // statically or using a runtime request, based on various\n // configurations and heuristics. We'll do this in two passes: first\n // traverse the tree and perform all the static prefetches.\n //\n // Then, if there are any segments that need a runtime request,\n // do another pass to perform a runtime prefetch.\n // Derive the static walk's parameters once per pass; the walk\n // functions below receive them as arguments and are phase-agnostic.\n // During the Shell phase the walk requests each segment's\n // shell-stage variant (keyed at the shell vary paths); otherwise\n // it's the ordinary per-segment static strategy. This is the only\n // place the phase is consulted — everything below keys off\n // the strategy.\n const staticWalkStrategy = task.phase === 1 ? FetchStrategy.StaticShell : FetchStrategy.PPR;\n // In PPF, links may skip speculative prefetching if they only need a shell.\n if (staticWalkStrategy === FetchStrategy.PPR && !needsSpeculativePrefetch(task.fetchStrategy, route.root.tree.prefetchHints)) {\n return 2;\n }\n // The head is a one-node tree beside the route tree (see\n // createMetadataRouteTree in cache.ts); it takes the same walk as\n // a segment the current page doesn't have. If the head was inlined\n // into a page's bundle (HeadOutlined is NOT set on the root), skip\n // the standalone walk — the head data will arrive as part of that\n // page's response, and its runtime-completeness signal is carried\n // by that page's own entries.\n const head = route.root.head;\n if (!process.env.__NEXT_PREFETCH_INLINING || (route.root.tree.prefetchHints & PrefetchHint.HeadOutlined) !== 0 || // An inlined head that can't attempt a static fetch still deopts\n // to the runtime request (the first check of the decision point\n // in pingSegmentInCacheComponentsTree); only the static fetch\n // itself is skipped for an inlined head.\n walkCanUseRuntimeRequests(staticWalkStrategy, route) && !shouldSegmentAttemptStaticRequest(staticWalkStrategy, head)) {\n const headExitStatus = pingNewPartOfCacheComponentsTree(now, task, route, head, null, staticWalkStrategy);\n if (headExitStatus === 0) {\n return 0;\n }\n }\n const exitStatus = pingSharedPartOfCacheComponentsTree(now, task, route, task.renderTreeAtTimeOfPrefetch.tree, tree, null, staticWalkStrategy);\n if (exitStatus === 0) {\n // Child yielded without finishing.\n return 0;\n }\n // `pingSegmentInCacheComponentsTree` may have determined that\n // we need to do a runtime prefetch for one or more segments.\n // Bail out early if runtime prefetches are not permitted for this route.\n if (walkCanUseRuntimeRequests(staticWalkStrategy, route)) {\n const runtimeStrategy = staticWalkStrategy === FetchStrategy.StaticShell ? FetchStrategy.RuntimeShell : FetchStrategy.PPRRuntime;\n // spawnedRuntimePrefetches was populated during the traversal\n // above: every subtree in the new part of the tree that needs a\n // runtime prefetch, the head included — it registers under its\n // own request key, like any segment, when its own static attempt\n // was insufficient or never happened.\n //\n // If it's null, nothing in the new part of the tree is a candidate\n // for runtime prefetching, and we don't fetch the head, either —\n // the head is runtime prefetched only if something is.\n const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches;\n if (spawnedRuntimePrefetches !== null) {\n const spawnedEntries = new Map();\n // The head has no position in the request tree — a runtime\n // response carries it beside the segments (see\n // writeServerResponseIntoCache in cache.ts) — so the head's\n // own request tree is discarded.\n pingRouteTreeAndIncludeDynamicData(now, task, route, head, false, spawnedEntries, runtimeStrategy);\n const requestTree = pingRuntimePrefetches(now, task, route, tree, spawnedRuntimePrefetches, spawnedEntries, runtimeStrategy);\n if (spawnedEntries.size > 0) {\n spawnPrefetchSubtask(fetchSegmentPrefetchesUsingRuntimeRequest(task, route, runtimeStrategy, requestTree, spawnedEntries));\n }\n }\n }\n return 2;\n }\n case FetchStrategy.Full:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.LoadingBoundary:\n {\n if (task.phase === 1) {\n // Shell phase only does work on routes that use the PPR strategy\n // (Cache Components routes). Other strategies are Shell no-ops\n // and fall through to Speculative.\n return 2;\n }\n // Prefetch multiple segments using a single runtime request.\n // TODO: We can consolidate this branch with previous one by modeling\n // it as if the first segment in the new tree has runtime prefetching\n // enabled. Will do this as a follow-up refactor. Might want to remove\n // the special metatdata case below first. In the meantime, it's not\n // really that much duplication, just would be nice to remove one of\n // these codepaths.\n const spawnedEntries = new Map();\n // The head has no position in the request tree — a runtime response\n // carries it beside the segments (see writeServerResponseIntoCache\n // in cache.ts) — so the head's own request tree is discarded.\n const head = route.root.head;\n pingRouteTreeAndIncludeDynamicData(now, task, route, head, false, spawnedEntries, // When prefetching the head, there's no difference between Full\n // and LoadingBoundary: the head has no loading boundary, so a\n // LoadingBoundary request would skip it.\n fetchStrategy === FetchStrategy.LoadingBoundary ? FetchStrategy.Full : fetchStrategy);\n const dynamicRequestTree = diffRouteTreeAgainstCurrent(now, task, route, task.renderTreeAtTimeOfPrefetch.tree, tree, spawnedEntries, fetchStrategy);\n let needsDynamicRequest = spawnedEntries.size > 0;\n if (needsDynamicRequest) {\n spawnPrefetchSubtask(fetchSegmentPrefetchesUsingRuntimeRequest(task, route, fetchStrategy, dynamicRequestTree, spawnedEntries));\n }\n return 2;\n }\n default:\n fetchStrategy;\n }\n break;\n }\n default:\n {\n route;\n }\n }\n return 2;\n}\n/**\n * Whether the task can use runtime requests to prefetch the content.\n *\n * This is true for every walk of a route that opts into Partial Prefetching\n * (any segment with a partial-prefetching config, or the global `partialPrefetching`\n * flag, indicated by `SubtreeHasPartialPrefetching` on the route root),\n * in both the Shell and Speculative phases.\n *\n * Note that this does not mean that the route *will* use runtime requests --\n * it might be optimized statically, either because it does not use runtime data\n * in the shell/prefetch, or if it's forced to use static requests by\n * `export const ensureStatic = \"shell\" | \"prefetch\" | \"navigation\"`.\n *\n * Routes without Partial Prefetching never use runtime requests for prefetches\n * (excluding `Full` prefetches)\n */ function walkCanUseRuntimeRequests(staticWalkStrategy, route) {\n if (staticWalkStrategy === FetchStrategy.StaticShell) {\n // `FetchStrategy.StaticShell` is only used on PPF routes.\n return true;\n }\n // `FetchStrategy.PPR` can only use runtime requests if PPF is enabled on the route.\n return (route.root.tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0;\n}\n/**\n * Whether a static request for this segment should be attempted.\n * This may vary on the static walk's strategy, because we might e.g.\n * have a shell that's static, but a prefetch that requires runtime requests.\n *\n * NOTE: Should only be used on Partial Prefetching routes, where\n * `walkCanUseRuntimeRequests` is true.\n * */ function shouldSegmentAttemptStaticRequest(staticWalkStrategy, tree) {\n const { prefetchHints } = tree;\n switch(staticWalkStrategy){\n case FetchStrategy.StaticShell:\n return (prefetchHints & PrefetchHint.ShouldAttemptStaticShell) !== 0;\n case FetchStrategy.PPR:\n return (prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0;\n default:\n staticWalkStrategy;\n return false;\n }\n}\n/**\n * The runtime counterpart of a pass's static walk strategy: the strategy the\n * batched runtime request uses if this walk deopts. Each phase has exactly one\n * — the Shell phase escalates to a shell-scoped runtime request\n * (RuntimeShell), the Speculative phase to a per-link concrete\n * runtime prefetch.\n */ function getRuntimeStrategyForWalk(staticWalkStrategy) {\n return staticWalkStrategy === FetchStrategy.StaticShell ? FetchStrategy.RuntimeShell : FetchStrategy.PPRRuntime;\n}\n/**\n * Whether this phase's runtime request would return more content for a\n * fulfilled entry than the entry already holds.\n *\n * An entry records the tier its CONTENT achieved, not the one it was requested\n * at, and that tier spans both axes — so a static response that needed no\n * runtime data records the runtime counterpart of its own variant (see\n * `recordedFetchStrategy` in cache.ts). That makes this a pure tier\n * comparison: an entry at or above the phase's runtime tier has nothing to\n * gain from it.\n */ function wouldRuntimeRequestProvideMore(entry, staticWalkStrategy) {\n return canNewFetchStrategyProvideMoreContent(entry.fetchStrategy, getRuntimeStrategyForWalk(staticWalkStrategy));\n}\n/**\n * Whether a fulfilled shell-tier entry should take a static attempt (a\n * spawned revalidation at the walk's static tier) before its position deopts\n * to a runtime request. A shell-tier recorded entry (StaticShell or\n * RuntimeShell) is not evidence that a static attempt would be pointless —\n * unlike a concrete static (PPR) entry, where a static re-fetch would return\n * the same bytes — so when the segment's hint says a static attempt is\n * worthwhile (the build-time prerender accessed no runtime data), the\n * attempt is taken and its response's own verdict decides whether to\n * escalate afterward.\n *\n * Consults the revalidation slot so an attempt that already ran and settled\n * without healing the entry (a rejected attempt: server miss or network\n * error; a successful one upserts over the shell-tier entry, so the caller\n * reads the healed entry instead) doesn't suppress the runtime deopt\n * forever. The slot read creates an Empty placeholder on first evaluation —\n * there is no read-only variant — which is harmless: when the entry is\n * eligible, the spawn that follows claims the same slot.\n */ function isShellEntryEligibleForStaticAttempt(now, map, entry, tree, fetchStrategy) {\n if (!((entry.fetchStrategy === FetchStrategy.StaticShell || entry.fetchStrategy === FetchStrategy.RuntimeShell) && shouldSegmentAttemptStaticRequest(fetchStrategy, tree) && // if the `fetchStrategy` is `FetchStrategy.PPR`, it might provide more content\n // (e.g. static params that this shell doesn't have)\n canNewFetchStrategyProvideMoreContent(entry.fetchStrategy, fetchStrategy))) {\n return false;\n }\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(now, map, fetchStrategy, tree);\n return revalidatingEntry.status === EntryStatus.Empty || revalidatingEntry.status === EntryStatus.Pending;\n}\n/**\n * Register a subtree root (the head is one, under its own request key) for\n * the batched runtime request issued by the gate at the end of\n * pingRootRouteTree.\n */ function addSpawnedRuntimePrefetch(task, requestKey) {\n if (task.spawnedRuntimePrefetches === null) {\n task.spawnedRuntimePrefetches = new Set([\n requestKey\n ]);\n } else {\n task.spawnedRuntimePrefetches.add(requestKey);\n }\n}\n// TODO: Rename dynamic -> runtime throughout this module\n/**\n * The static walk over the part of the target route that also exists on the\n * current page: the current page's node and the target route's node at the\n * same position in the tree. It mirrors the navigation's traversal order (see\n * updateRenderTreeOnNavigation in render-tree.ts): first whether the route\n * position still matches — if not, this node begins the new part of the route\n * (pingNewPartOfCacheComponentsTree) — and then whether any of the node's\n * param values changed — if so, the node and everything below it begin the\n * new part of the route too. The walk does not consult which params a\n * segment read, so it prefetches more than the navigation replaces: the\n * navigation keeps data whose read params did not change and decides each\n * descendant on its own. A node the walk keeps is prefetched at the ordinary\n * static tier.\n * Its children continue here wherever the current page has a child in the\n * same slot; a child in a slot the current page doesn't have enters the new\n * part of the route directly.\n *\n * Bundle chains must not cross the strategy boundary: a kept node walks at\n * PPR while a Shell-phase new part walks at StaticShell, and a chain spanning\n * both would fulfill the kept node's concrete-path entry with shell-variant\n * data. Nor may the chain be finished by fetching the new-part node at PPR\n * — that would prefetch new-part segments at the concrete tier during the\n * Shell phase, which only the Speculative phase is allowed to do. So the\n * chain is dropped wherever the walk hands off to the new part during a\n * StaticShell walk, exactly like the drop sites in\n * pingSegmentInCacheComponentsTree: nothing in a dropped chain was upgraded\n * to Pending, so no entry is stranded, and the inlined kept data is fetched\n * by the Speculative pass whenever its walk of the new part permits the\n * child fetch.\n */ function pingSharedPartOfCacheComponentsTree(now, task, route, currentTree, newTree, parentBundle, // The per-pass static walk strategy; see pingRootRouteTree where\n// it's derived.\nfetchStrategy) {\n if (!doesRouteStructureMatch(currentTree, newTree)) {\n // We're entering the part of the target route that doesn't exist on the\n // current page.\n return pingNewPartOfCacheComponentsTree(now, task, route, newTree, fetchStrategy === FetchStrategy.StaticShell ? null : parentBundle, fetchStrategy);\n }\n if (compareParams(currentTree.varyPath, newTree.varyPath) !== ParamsChange.None) {\n // A param changed. The navigation replaces only the data that read it and\n // decides each descendant on its own (see updateRenderTreeOnNavigation in\n // render-tree.ts); this walk doesn't know what each segment read, so it\n // prefetches the whole subtree.\n return pingNewPartOfCacheComponentsTree(now, task, route, newTree, fetchStrategy === FetchStrategy.StaticShell ? null : parentBundle, fetchStrategy);\n }\n // The navigation keeps this segment's current data. A kept segment always\n // performs the ordinary static (PPR) prefetch, regardless of phase.\n // Phase-specific strategies — the runtime shell request and the Shell\n // phase's StaticShell walk — apply only to the new part of the tree, so the\n // per-pass walk strategy is irrelevant here. (The needs-runtime signal is\n // ignored: kept segments are already rendered on the current page, so a\n // runtime prefetch has nothing to add.)\n const bundleInProgress = accumulateSegmentBundle(now, task, route, newTree, parentBundle, FetchStrategy.PPR, true).bundle;\n // Recursively ping the children, continuing in lockstep with the current\n // page wherever it has a child in the same slot.\n const newTreeChildren = newTree.slots;\n if (newTreeChildren !== null) {\n const currentSlots = currentTree.slots;\n for (const [parallelRouteKey, newTreeChild] of newTreeChildren){\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return 0;\n }\n // Only pass the bundle to the child that accepts it. A parent is\n // only ever bundled into one child.\n const bundleForChild = process.env.__NEXT_PREFETCH_INLINING && bundleInProgress !== null && newTreeChild.prefetchHints & PrefetchHint.ParentInlinedIntoSelf ? bundleInProgress : null;\n let currentTreeChild = undefined;\n if (currentSlots !== null) {\n currentTreeChild = currentSlots.get(parallelRouteKey);\n }\n let childExitStatus;\n if (currentTreeChild !== undefined) {\n childExitStatus = pingSharedPartOfCacheComponentsTree(now, task, route, currentTreeChild, newTreeChild, bundleForChild, fetchStrategy);\n } else {\n childExitStatus = pingNewPartOfCacheComponentsTree(now, task, route, newTreeChild, fetchStrategy === FetchStrategy.StaticShell ? null : bundleForChild, fetchStrategy);\n }\n if (childExitStatus === 0) {\n // Child yielded without finishing.\n return 0;\n }\n }\n }\n // The static attempt was sufficient for this segment (each child is its\n // own decision point) — or parts of it are still in flight, in which case\n // the task is blocked and the decision re-runs against the received\n // responses.\n return 2;\n}\n/**\n * The static walk over the part of the target route that doesn't exist on\n * the current page. Nothing here is compared against the current tree: every\n * segment goes through the per-segment decision point.\n */ function pingNewPartOfCacheComponentsTree(now, task, route, tree, parentBundle, // The per-pass static walk strategy; see pingRootRouteTree where\n// it's derived.\nfetchStrategy) {\n const accumulation = pingSegmentInCacheComponentsTree(now, task, route, tree, parentBundle, fetchStrategy);\n if (accumulation === null) {\n return 2;\n }\n const bundleInProgress = accumulation.bundle;\n // Recursively ping the children.\n const treeChildren = tree.slots;\n if (treeChildren !== null) {\n for (const treeChild of treeChildren.values()){\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return 0;\n }\n // Only pass the bundle to the child that accepts it. A parent is\n // only ever bundled into one child.\n const bundleForChild = process.env.__NEXT_PREFETCH_INLINING && bundleInProgress !== null && treeChild.prefetchHints & PrefetchHint.ParentInlinedIntoSelf ? bundleInProgress : null;\n const childExitStatus = pingNewPartOfCacheComponentsTree(now, task, route, treeChild, bundleForChild, fetchStrategy);\n if (childExitStatus === 0) {\n // Child yielded without finishing.\n return 0;\n }\n }\n }\n // The static attempt was sufficient for this segment (each child is its\n // own decision point) — or parts of it are still in flight, in which case\n // the task is blocked and the decision re-runs against the received\n // responses.\n return 2;\n}\n/**\n * The per-segment decision point of the static walk: the one place that\n * decides how a segment in the new part of the route — one the navigation\n * won't keep — is prefetched (pingNewPartOfCacheComponentsTree).\n *\n * When Cache Components is enabled (or PPR, or a fully static route when PPR\n * is disabled; those cases are treated equivalently to Cache Components), we\n * prefetch each segment individually, statically, at the per-pass strategy\n * derived in pingRootRouteTree.\n *\n * This is where we decide whether we should use runtime requests, if the walk\n * is allowed to do so (see `walkCanUseRuntimeRequests`).\n *\n * If runtime requests are allowed, but the segment's node has one of the\n * `ShouldAttemptStatic{Shell,Prefetch}` hints set (either because the build-time\n * prerender accessed no runtime data, or because of `ensureStatic`), then its\n * subtree should be prefetched statically first.\n * However, the hint may be stale after a revalidation, so we'll also check the\n * `needsRuntimeRequest` promise on the static response, and will follow up with\n * a runtime request if needed.\n * Pending responses block the task, so the attempt is serial, never raced:\n * static attempt → observe → runtime (if needed).\n *\n * The static hints and `needsRuntimeRequest` have no effect if runtime requests\n * are not allowed (i.e. outside of Partial Prefetching).\n *\n * Returns the segment's bundle accumulation when the walk should continue\n * into its children, and null when the walk stops at this segment: the link\n * needs no speculative prefetch, or the segment deopted and the batched\n * runtime request covers the whole subtree.\n */ function pingSegmentInCacheComponentsTree(now, task, route, tree, parentBundle, // The per-pass static walk strategy; see pingRootRouteTree where\n// it's derived.\nfetchStrategy) {\n // In PPF, links may skip speculative prefetching if they only need a shell.\n if (fetchStrategy === FetchStrategy.PPR && !needsSpeculativePrefetch(task.fetchStrategy, route.root.tree.prefetchHints)) {\n return null;\n }\n // Constant for the whole pass; recomputed here only because the walk is\n // recursive and the check is cheap.\n const canUseRuntimeRequests = walkCanUseRuntimeRequests(fetchStrategy, route);\n // A force-disabled segment deliberately does NOT deopt here: disabling\n // prefetch is passive. It never initiates a request — its accumulation\n // below contributes nothing — and must never be the reason a runtime\n // prefetch spawns, though it may ride along in a runtime response issued\n // on another segment's behalf.\n if (canUseRuntimeRequests && !shouldSegmentAttemptStaticRequest(fetchStrategy, tree)) {\n // Deopt directly to a runtime prefetch, without a static attempt.\n addSpawnedRuntimePrefetch(task, tree.requestKey);\n // If there's a pending static bundle from a parent, we need to finish\n // prefetching it before bailing out to runtime prefetching.\n if (parentBundle !== null) {\n finishStaticBundleOnRuntimeBailout(now, task, route, tree, parentBundle, fetchStrategy);\n }\n return null;\n }\n // Prefetch this segment and its subtree statically, using the normal\n // static bundling walk.\n const accumulation = accumulateSegmentBundle(now, task, route, tree, parentBundle, fetchStrategy, true);\n if (canUseRuntimeRequests && accumulation.needsRuntimeRequest) {\n // The static attempt for this segment was insufficient. Stop the walk\n // and deopt — the runtime prefetch covers the whole subtree. (Unlike the\n // direct deopt above, any open bundle is dropped rather than finished: a\n // fulfilled InlinedIntoChild node can report a true signal while its\n // chain is still open. That's safe — nothing in an un-pinged chain was\n // upgraded to Pending, so no entry is stranded blocking the task, and\n // Empty entries in the dropped chain are re-fetched by a later pass.)\n addSpawnedRuntimePrefetch(task, tree.requestKey);\n return null;\n }\n return accumulation;\n}\nfunction diffRouteTreeAgainstCurrent(now, task, route, oldTree, newTree, spawnedEntries, fetchStrategy) {\n // This is a single recursive traversal that does multiple things:\n // - Finds the segments that differ from the current route, comparing each\n // segment the same way the navigation will (see\n // updateRenderTreeOnNavigation in render-tree.ts): its route position,\n // then whether any of its param values changed.\n // - Constructs a request tree (FlightRouterState) that describes which\n // segments need to be prefetched and which ones are already cached.\n // - Creates a set of pending cache entries for the segments that need to\n // be prefetched, so that a subsequent prefetch task does not request the\n // same segments again.\n const oldSlots = oldTree.slots;\n const newTreeChildren = newTree.slots;\n let requestTreeChildren = {};\n if (newTreeChildren !== null) {\n for (const [parallelRouteKey, newTreeChild] of newTreeChildren){\n const oldTreeChild = oldSlots?.get(parallelRouteKey);\n requestTreeChildren[parallelRouteKey] = diffSegmentAgainstCurrent(now, task, route, oldTreeChild, newTreeChild, spawnedEntries, fetchStrategy);\n }\n }\n const requestTree = [\n newTree.segment,\n requestTreeChildren,\n null,\n null\n ];\n if (newTree.prefetchHints !== 0) {\n requestTree[4] = newTree.prefetchHints;\n }\n return requestTree;\n}\n/**\n * The per-segment decision of a runtime request's tree walk\n * (diffRouteTreeAgainstCurrent): the segment at this position of the target\n * route, and the current page's segment at the same position, if it has one.\n * A segment the navigation keeps — same route position, and none of its param\n * values changed — is omitted from the request and the walk continues into\n * its children. Otherwise this segment begins a part of the tree that needs\n * to be prefetched (unless everything is already cached), requested according\n * to the strategy.\n */ function diffSegmentAgainstCurrent(now, task, route, oldTree, newTree, spawnedEntries, fetchStrategy) {\n if (oldTree !== undefined && doesRouteStructureMatch(oldTree, newTree)) {\n // This segment is already part of the current route.\n if (compareParams(oldTree.varyPath, newTree.varyPath) === ParamsChange.None) {\n // The navigation keeps its data. Keep traversing.\n return diffRouteTreeAgainstCurrent(now, task, route, oldTree, newTree, spawnedEntries, fetchStrategy);\n }\n }\n // This segment is not part of the current route, or the navigation\n // replaces its data. We're entering a part of the tree that we need to\n // prefetch (unless everything is already cached).\n switch(fetchStrategy){\n case FetchStrategy.LoadingBoundary:\n {\n // When PPR is disabled, we can't prefetch per segment. We must\n // fallback to the old prefetch behavior and send a runtime request.\n // Only routes that include a loading boundary can be prefetched in\n // this way.\n //\n // This is simlar to a \"full\" prefetch, but we're much more\n // conservative about which segments to include in the request.\n //\n // The server will only render up to the first loading boundary\n // inside new part of the tree. If there's no loading boundary\n // anywhere in the tree, the server will never return any data, so\n // we can skip the request.\n const subtreeHasLoadingBoundary = (newTree.prefetchHints & (PrefetchHint.SegmentHasLoadingBoundary | PrefetchHint.SubtreeHasLoadingBoundary)) !== 0;\n if (subtreeHasLoadingBoundary) {\n return pingPPRDisabledRouteTreeUpToLoadingBoundary(now, task, route, newTree, null, spawnedEntries);\n }\n // There's no loading boundary within this tree. Bail out.\n return convertRouteTreeToFlightRouterState(newTree);\n }\n case FetchStrategy.PPRRuntime:\n {\n // This is a runtime prefetch. Fetch all cacheable data in the tree,\n // not just the static PPR shell.\n return pingRouteTreeAndIncludeDynamicData(now, task, route, newTree, false, spawnedEntries, fetchStrategy);\n }\n case FetchStrategy.Full:\n {\n // This is a \"full\" prefetch. Fetch all the data in the tree, both\n // static and dynamic. We issue roughly the same request that we\n // would during a real navigation. The goal is that once the\n // navigation occurs, the router should not have to fetch any\n // additional data.\n //\n // Although the response will include dynamic data, opting into a\n // Full prefetch — via <Link prefetch={true}> — implicitly\n // instructs the cache to treat the response as \"static\", or non-\n // dynamic, since the whole point is to cache it for\n // future navigations.\n //\n // Construct a tree (currently a FlightRouterState) that represents\n // which segments need to be prefetched and which ones are already\n // cached. If the tree is empty, then we can exit. Otherwise, we'll\n // send the request tree to the server and use the response to\n // populate the segment cache.\n return pingRouteTreeAndIncludeDynamicData(now, task, route, newTree, false, spawnedEntries, fetchStrategy);\n }\n }\n}\nfunction pingPPRDisabledRouteTreeUpToLoadingBoundary(now, task, route, tree, refetchMarkerContext, spawnedEntries) {\n // This function is similar to pingRouteTreeAndIncludeDynamicData, except the\n // server is only going to return a minimal loading state — it will stop\n // rendering at the first loading boundary. Whereas a Full prefetch is\n // intentionally aggressive and tries to pretfetch all the data that will be\n // needed for a navigation, a LoadingBoundary prefetch is much more\n // conservative. For example, it will omit from the request tree any segment\n // that is already cached, regardles of whether it's partial or full. By\n // contrast, a Full prefetch will refetch partial segments.\n // \"inside-shared-layout\" tells the server where to start looking for a\n // loading boundary.\n let refetchMarker = refetchMarkerContext === null ? 'inside-shared-layout' : null;\n const segment = readOrCreateSegmentCacheEntry(now, task.segmentCacheMap, task.fetchStrategy, tree);\n switch(segment.status){\n case EntryStatus.Empty:\n {\n // This segment is not cached. Add a refetch marker so the server knows\n // to start rendering here.\n // TODO: Instead of a \"refetch\" marker, we could just omit this subtree's\n // FlightRouterState from the request tree. I think this would probably\n // already work even without any updates to the server. For consistency,\n // though, I'll send the full tree and we'll look into this later as part\n // of a larger redesign of the request protocol.\n // Add the pending cache entry to the result map.\n const pendingSegment = upgradeToPendingSegment(segment, // Set the fetch strategy to LoadingBoundary to indicate that the server\n // might not include it in the pending response. If another route is able\n // to issue a per-segment request, we'll do that in the background.\n FetchStrategy.LoadingBoundary);\n spawnedEntries.set(tree.requestKey, pendingSegment);\n // The pass blocks on every request it spawns, not just requests it\n // finds already in flight.\n blockTaskOnPendingResponse(task, pendingSegment);\n if (refetchMarkerContext !== 'refetch') {\n refetchMarker = refetchMarkerContext = 'refetch';\n } else {\n // There's already a parent with a refetch marker, so we don't need\n // to add another one.\n }\n break;\n }\n case EntryStatus.Fulfilled:\n {\n // The segment is already cached.\n const segmentHasLoadingBoundary = (tree.prefetchHints & PrefetchHint.SegmentHasLoadingBoundary) !== 0;\n if (segmentHasLoadingBoundary) {\n // This segment has a loading boundary, which means the server won't\n // render its children. So there's nothing left to prefetch along this\n // path. We can bail out.\n return convertRouteTreeToFlightRouterState(tree);\n }\n break;\n }\n case EntryStatus.Pending:\n {\n // There's another prefetch currently in progress. Don't add the refetch\n // marker yet, so the server knows it can skip rendering this segment.\n // The pass still depends on the in-flight response, so wait for it\n // before the phase can complete.\n blockTaskOnPendingResponse(task, segment);\n break;\n }\n case EntryStatus.Rejected:\n {\n break;\n }\n default:\n segment;\n }\n const requestTreeChildren = {};\n if (tree.slots !== null) {\n for (const [parallelRouteKey, childTree] of tree.slots){\n requestTreeChildren[parallelRouteKey] = pingPPRDisabledRouteTreeUpToLoadingBoundary(now, task, route, childTree, refetchMarkerContext, spawnedEntries);\n }\n }\n const requestTree = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker\n ];\n if (tree.prefetchHints !== 0) {\n requestTree[4] = tree.prefetchHints;\n }\n return requestTree;\n}\n/**\n * Called during a pass when a segment's response hasn't been received yet —\n * whether the request was just spawned by this pass or was already in flight.\n * Marks the task as blocked: a phase only completes once a full pass observes\n * every segment response it cares about, because later decisions (like\n * whether a segment needs a follow-up runtime request) are made against the\n * contents of those responses, and a phase may need to restart its work based\n * on what they contain. The task is re-pinged (via pingBlockedTasks in\n * cache.ts) when the entry resolves, re-running the pass against the\n * received data. Only a pass that observes every response may advance the\n * phase or complete the task.\n *\n * Never call this for an entry that's already Rejected — nothing ever pings\n * a Rejected entry, so registering on one would strand the task. A rejected\n * segment is simply skipped: the pass keeps prefetching the rest of the tree\n * without it.\n */ function blockTaskOnPendingResponse(task, segment) {\n // This state is reset after each iteration of the task queue. We use it to\n // inform the scheduler that the task is blocked.\n task.hasPendingResponses = true;\n // Add the task to this segment's blocked tasks, so it can be rescheduled\n // once the segment finishes loading.\n if (segment.blockedTasks === null) {\n segment.blockedTasks = new Set([\n task\n ]);\n } else {\n segment.blockedTasks.add(task);\n }\n}\nfunction pingRouteTreeAndIncludeDynamicData(now, task, route, tree, isInsideRefetchingParent, spawnedEntries, fetchStrategy) {\n // The tree we're constructing is the same shape as the tree we're navigating\n // to. But even though this is a \"new\" tree, some of the individual segments\n // may be cached as a result of other route prefetches.\n //\n // So we need to find the first uncached segment along each path add an\n // explicit \"refetch\" marker so the server knows where to start rendering.\n // Once the server starts rendering along a path, it keeps rendering the\n // entire subtree.\n const segment = readOrCreateSegmentCacheEntry(now, task.segmentCacheMap, // Note that `fetchStrategy` might be different from `task.fetchStrategy`,\n // and we have to use the former here.\n // We can have a task with `FetchStrategy.PPR` where some of its segments are configured to\n // always use runtime prefetching (via `export const prefetch`), and those should check for\n // entries that include search params.\n fetchStrategy, tree);\n let spawnedSegment = null;\n switch(segment.status){\n case EntryStatus.Empty:\n {\n // This segment is not cached.\n if (fetchStrategy === FetchStrategy.Full) {\n // Check if there's a matching entry in the bfcache. If so, fulfill the\n // segment using the bfcache entry instead of issuing a new request.\n const fulfilled = attemptToFulfillDynamicSegmentFromBFCache(now, segment, tree);\n if (fulfilled !== null) {\n break;\n }\n }\n // Include it in the request.\n spawnedSegment = upgradeToPendingSegment(segment, fetchStrategy);\n break;\n }\n case EntryStatus.Fulfilled:\n {\n // The segment is already cached.\n if (segment.isPartial && canNewFetchStrategyProvideMoreContent(segment.fetchStrategy, fetchStrategy)) {\n // The cached segment contains dynamic holes, and was prefetched using a\n // less specific strategy than the current one. This means we're in one\n // of these cases:\n // - we have a static prefetch, and we're doing a runtime prefetch\n // - we have a static or runtime prefetch, and we're doing a Full\n // prefetch (or a navigation).\n // In either case, we need to include it in the request to get a more\n // specific (or full) version. However, if there's a non-stale bfcache\n // entry from a previous navigation, prefer that over making a new\n // request.\n if (fetchStrategy === FetchStrategy.Full) {\n const fulfilled = attemptToUpgradeSegmentFromBFCache(now, task.segmentCacheMap, tree);\n if (fulfilled !== null) {\n break;\n }\n }\n spawnedSegment = pingFullSegmentRevalidation(now, task, tree, fetchStrategy);\n }\n break;\n }\n case EntryStatus.Pending:\n case EntryStatus.Rejected:\n {\n // There's either another prefetch currently in progress, or the previous\n // attempt failed. If the new strategy can provide more content, fetch it again.\n if (canNewFetchStrategyProvideMoreContent(segment.fetchStrategy, fetchStrategy)) {\n spawnedSegment = pingFullSegmentRevalidation(now, task, tree, fetchStrategy);\n }\n if (segment.status === EntryStatus.Pending) {\n // A response for this segment is still in flight. The pass must\n // observe it before the phase can complete.\n blockTaskOnPendingResponse(task, segment);\n } else {\n // The segment failed to load, or the server intentionally omitted it\n // from a response (both are encoded as Rejected). Skip it and keep\n // prefetching the rest of the tree; the entry's staleAt governs when\n // it may be retried. Don't register the task on the rejected entry —\n // nothing ever pings a Rejected entry.\n //\n // TODO: The cache encodes real failures and intentional server\n // omissions identically (both Rejected); with per-segment skipping\n // this has no task-lifecycle consequence, but distinguishing them\n // could still be useful someday.\n }\n break;\n }\n default:\n segment;\n }\n if (spawnedSegment !== null) {\n // A pass must observe the response for every request it spawns before\n // its phase can complete — not just requests it finds already in flight.\n // Block on the entry we just spawned; the task is re-pinged when it's\n // fulfilled or rejected.\n blockTaskOnPendingResponse(task, spawnedSegment);\n }\n const requestTreeChildren = {};\n if (tree.slots !== null) {\n for (const [parallelRouteKey, childTree] of tree.slots){\n requestTreeChildren[parallelRouteKey] = pingRouteTreeAndIncludeDynamicData(now, task, route, childTree, isInsideRefetchingParent || spawnedSegment !== null, spawnedEntries, fetchStrategy);\n }\n }\n if (spawnedSegment !== null) {\n // Add the pending entry to the result map.\n spawnedEntries.set(tree.requestKey, spawnedSegment);\n }\n // Don't bother to add a refetch marker if one is already present in a parent.\n const refetchMarker = !isInsideRefetchingParent && spawnedSegment !== null ? 'refetch' : null;\n const requestTree = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker\n ];\n if (tree.prefetchHints !== 0) {\n requestTree[4] = tree.prefetchHints;\n }\n return requestTree;\n}\nfunction pingRuntimePrefetches(now, task, route, tree, spawnedRuntimePrefetches, spawnedEntries, fetchStrategy) {\n // Construct a request tree (FlightRouterState) for a runtime prefetch. If\n // a segment is part of the runtime prefetch, the tree is constructed by\n // diffing against what's already in the prefetch cache. Otherwise, we send\n // a regular FlightRouterState with no special markers.\n //\n // See pingRouteTreeAndIncludeDynamicData for details.\n if (spawnedRuntimePrefetches.has(tree.requestKey)) {\n // This segment needs a runtime prefetch.\n return pingRouteTreeAndIncludeDynamicData(now, task, route, tree, false, spawnedEntries, fetchStrategy);\n }\n let requestTreeChildren = {};\n const slots = tree.slots;\n if (slots !== null) {\n for (const [parallelRouteKey, childTree] of slots){\n requestTreeChildren[parallelRouteKey] = pingRuntimePrefetches(now, task, route, childTree, spawnedRuntimePrefetches, spawnedEntries, fetchStrategy);\n }\n }\n // This segment is not part of the runtime prefetch. Clone the base tree.\n const requestTree = [\n tree.segment,\n requestTreeChildren,\n null,\n null\n ];\n if (tree.prefetchHints !== 0) {\n requestTree[4] = tree.prefetchHints;\n }\n return requestTree;\n}\n/**\n * Walk a SegmentBundle, apply status-based logic to each entry, and if any\n * entries need data, spawn a single fetch request for the whole bundle.\n *\n * Returns true if a fulfilled entry in the bundle reported that a runtime\n * request would return more content than the entry contains\n * (needsRuntimeRequest, derived at write time from the response that\n * produced the entry). The callers surface this signal to the per-segment\n * decision point in pingSegmentInCacheComponentsTree, which uses it during\n * a static attempt to decide whether to fall back to a runtime prefetch. One\n * exception withholds the signal: a shell-tier entry whose segment carries\n * the static-attempt hint spawns a concrete static attempt first — see the\n * Fulfilled case.\n */ function pingSegmentBundle(now, task, route, routeKey, tree, segments, // Per-pass static walk strategy; see pingRootRouteTree where it's derived.\nfetchStrategy, // False when finishing an open bundle chain on a runtime-prefetch bailout\n// (finishStaticBundleOnRuntimeBailout). The finish exists only to fetch\n// data the batched runtime request won't cover — Empty entries in the\n// chain — so it must not spawn revalidations over entries that are\n// already settled or in flight: the chain's terminal segments are inside\n// the deopted subtree, and re-fetching their static bundle would at best\n// duplicate the runtime request and at worst replace a runtime-complete\n// entry (e.g. a RuntimeShell-tier entry) with a less complete static\n// fallback response.\nspawnRevalidations) {\n let needsRuntimeRequest = false;\n // The pending entries this task owns — Empty entries upgraded here, plus\n // any revalidations spawned here — keyed by segment request key. If any\n // accumulate, a single fetch is spawned for the whole bundle, and the\n // response fulfills them.\n let spawnedEntries = null;\n let node = segments;\n while(node !== null){\n const nodeEntry = node.entry;\n const nodeTree = node.tree;\n if (nodeEntry === null || nodeTree === null) {\n node = node.parent;\n continue;\n }\n switch(nodeEntry.status){\n case EntryStatus.Empty:\n {\n const pendingEntry = upgradeToPendingSegment(nodeEntry, fetchStrategy);\n if (spawnedEntries === null) {\n spawnedEntries = new Map();\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry);\n // The pass blocks on every request it spawns, not just requests it\n // finds already in flight.\n blockTaskOnPendingResponse(task, pendingEntry);\n break;\n }\n case EntryStatus.Pending:\n if (spawnRevalidations && // During a static shell attempt, never spawn revalidations — just\n // wait for the in-flight response (blocked below); its sufficiency\n // is checked on the re-run pass.\n fetchStrategy === FetchStrategy.PPR && canNewFetchStrategyProvideMoreContent(nodeEntry.fetchStrategy, fetchStrategy)) {\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(now, task.segmentCacheMap, fetchStrategy, nodeTree);\n if (revalidatingEntry.status === EntryStatus.Empty) {\n const pendingEntry = upgradeToPendingSegment(revalidatingEntry, fetchStrategy);\n if (spawnedEntries === null) {\n spawnedEntries = new Map();\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry);\n // Block on the revalidation request we just spawned, in\n // addition to the original in-flight entry (blocked below).\n blockTaskOnPendingResponse(task, pendingEntry);\n }\n }\n blockTaskOnPendingResponse(task, nodeEntry);\n break;\n case EntryStatus.Rejected:\n if (spawnRevalidations && // During a static shell attempt, a rejected entry is skipped\n // outright: no retry revalidation, and — deliberately — no runtime\n // fallback either (per-segment rejection semantics; the entry's\n // staleAt governs when it may be retried). Note that the cache\n // path encodes \"no shell exists\" (a static response whose shell\n // byte offset is 0, i.e. the page wasn't produced by staged\n // rendering) as a rejection too, so such segments get no shell\n // prefetch at all — an edge that shouldn't occur for hint-set\n // Cache Components routes.\n fetchStrategy === FetchStrategy.PPR && canNewFetchStrategyProvideMoreContent(nodeEntry.fetchStrategy, fetchStrategy)) {\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(now, task.segmentCacheMap, fetchStrategy, nodeTree);\n if (revalidatingEntry.status === EntryStatus.Empty) {\n const pendingEntry = upgradeToPendingSegment(revalidatingEntry, fetchStrategy);\n if (spawnedEntries === null) {\n spawnedEntries = new Map();\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry);\n // Block on the retry revalidation we just spawned, like any\n // other pending response. If the retry succeeds, its upsert\n // evicts the rejected entry (see evictShadowingSegmentEntries\n // in cache.ts) and the re-run pass reads the healed data. If it\n // rejects too, the re-run observes a settled revalidation and\n // moves on.\n blockTaskOnPendingResponse(task, pendingEntry);\n }\n }\n break;\n case EntryStatus.Fulfilled:\n {\n let willBeSupersededByRuntimeRequest = false;\n if (walkCanUseRuntimeRequests(fetchStrategy, route)) {\n const runtimeWouldProvideMore = wouldRuntimeRequestProvideMore(nodeEntry, fetchStrategy);\n // An eligible shell-tier entry takes the static attempt path below\n // (the revalidation) instead of deopting straight to a runtime\n // request; see isShellEntryEligibleForStaticAttempt. The attempt\n // can't recur: its response records at least the concrete static\n // tier, which fails the shell-tier check on the re-run pass — and an\n // attempt that already settled without healing the entry reads as\n // ineligible, so the deopt proceeds after all.\n const shellEntryEligibleForStaticAttempt = isShellEntryEligibleForStaticAttempt(now, task.segmentCacheMap, nodeEntry, nodeTree, fetchStrategy);\n if (runtimeWouldProvideMore && !shellEntryEligibleForStaticAttempt) {\n // A runtime request would return more content for this segment\n // than the entry contains. Surface it via the return value, so the\n // caller can deopt this subtree to a runtime prefetch. (An\n // eligible shell-tier entry withholds the signal for this pass:\n // the static attempt spawned below blocks the task, and the re-run\n // pass reads the attempt's result instead.)\n needsRuntimeRequest = true;\n // If a runtime request would return more content skip the static path\n // entirely — unless the entry is an eligible shell-tier entry (see above),\n // whose static attempt IS this upgrade.\n // Otherwise the runtime request covers this segment and supersedes\n // anything a static fetch could add, so a static upgrade would at best\n // duplicate it — delivering the same content twice — and at worst replace\n // runtime content with static content.\n willBeSupersededByRuntimeRequest = true;\n }\n }\n // If this is the speculative phase (not the shell phase), check if we\n // should attempt to upgrade a fallback ISR response to a concrete\n // version.\n //\n // For entries below this phase's tier, upgrade during the phase\n // itself — no background deferral, since the whole point of the\n // Speculative phase is to bring the cache up to the\n // per-link-concrete tier. `isPartial` ensures a complete entry isn't\n // re-fetched.\n //\n // If we can use runtime requests and a runtime request would provide more\n // data, we also skip the upgrade (see `willBeSupersededByRuntimeRequest`)\n const isUpgradeableISRFallbackRetry = fetchStrategy === FetchStrategy.PPR && nodeEntry.isUpgradeableISRFallback && // If the status is empty, then we haven't yet attempted to upgrade\n // the fallback.\n //\n // If the status is fulfilled, then the fallback was\n // successfully upgraded to a concrete version.\n //\n // Do not attempt to upgrade if the status is Pending or Rejected.\n (task.fallbackRetryStatus === EntryStatus.Empty || task.fallbackRetryStatus === EntryStatus.Fulfilled);\n if (spawnRevalidations && !willBeSupersededByRuntimeRequest && (nodeEntry.isPartial && canNewFetchStrategyProvideMoreContent(nodeEntry.fetchStrategy, fetchStrategy) || isUpgradeableISRFallbackRetry)) {\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(now, task.segmentCacheMap, fetchStrategy, nodeTree);\n if (revalidatingEntry.status === EntryStatus.Empty) {\n const pendingEntry = upgradeToPendingSegment(revalidatingEntry, fetchStrategy);\n if (spawnedEntries === null) {\n spawnedEntries = new Map();\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry);\n // The pass blocks on every request it spawns, including\n // revalidations of an already-fulfilled entry.\n blockTaskOnPendingResponse(task, pendingEntry);\n } else {\n // A non-empty revalidating entry means a request is already in\n // flight (or recently settled), so we dedupe and don't issue a\n // competing one — including for ISR-fallback upgrades, which then\n // share the same revalidation across tasks.\n if (revalidatingEntry.status === EntryStatus.Pending) {\n // The deduped-against revalidation is still in flight, and this\n // pass depends on its response. Wait for it before the phase\n // can complete. (A settled revalidation we chose not to use\n // needs no waiting and is not a prefetch failure — the base\n // entry here is already Fulfilled. A settled revalidation\n // can't strand an eligible shell-tier entry either:\n // isShellEntryEligibleForStaticAttempt reads the slot, so a\n // settled attempt makes the entry ineligible and the runtime\n // deopt proceeds above.)\n blockTaskOnPendingResponse(task, revalidatingEntry);\n }\n }\n }\n break;\n }\n default:\n nodeEntry;\n }\n node = node.parent;\n }\n if (spawnedEntries !== null) {\n spawnPrefetchSubtask(fetchSegmentPrefetchesUsingStaticRequest(task, route, routeKey, tree, spawnedEntries, fetchStrategy));\n }\n return needsRuntimeRequest;\n}\n/**\n * During the tree walk, decide whether this segment should be added to the\n * in-progress bundle (if it has InlinedIntoChild) or finalize the bundle\n * and ping it, triggering a fetch if any of its entries need data (if it\n * doesn't). Returns the updated bundle to pass to children (null if the\n * bundle was finalized here), along with the needs-runtime signal from the\n * bundle ping, if one happened (always false otherwise).\n */ function accumulateSegmentBundle(now, task, route, tree, parentBundle, // Per-pass static walk strategy; see pingRootRouteTree where it's derived.\n// PPR for the normal static bundling walk; StaticShell during the Shell\n// phase's static shell attempt, whose entries are keyed at the shell\n// vary paths.\nfetchStrategy, // False when finishing a chain on a runtime-prefetch bailout; see\n// pingSegmentBundle.\nspawnRevalidations) {\n // Prefetching is disabled for this segment (prefetch: 'force-disabled'):\n // the server emits identity only for its response node, and it\n // participates in the bundle chain with null tree/entry — no cache entry\n // is created for it.\n // (Partial Prefetching segments are NOT in this mask — the server emits\n // static data for them unconditionally.) Intentionally not gated by the\n // prefetch inlining flag: we never statically prefetch unprefetchable\n // segments.\n if (tree.prefetchHints & StaticPrefetchDisabled) {\n return {\n bundle: {\n tree: null,\n entry: null,\n parent: parentBundle\n },\n needsRuntimeRequest: false\n };\n }\n const segment = readOrCreateSegmentCacheEntry(now, task.segmentCacheMap, fetchStrategy, tree);\n if (process.env.__NEXT_PREFETCH_INLINING && tree.prefetchHints & PrefetchHint.InlinedIntoChild) {\n if (segment.status === EntryStatus.Pending) {\n // The chain this entry joins may be dropped before it's ever pinged\n // (see the drop sites in pingSegmentInCacheComponentsTree), and only\n // the ping blocks on Pending entries. Register on the in-flight\n // response at read time instead, so the pass observes it before the\n // phase can complete even if the chain is dropped. When the chain does\n // get pinged, the ping's own registration dedupes against this one.\n blockTaskOnPendingResponse(task, segment);\n }\n return {\n bundle: {\n tree,\n entry: segment,\n parent: parentBundle\n },\n // No bundle ping happens here, but the node's own entry may already be\n // fulfilled and insufficient. Report that signal directly: the chain\n // ping only reaches the terminal descendant, and if that descendant is\n // itself a decision point it consumes the signal for its own subtree,\n // leaving this ancestor's insufficiency invisible to the decision\n // point above it. An eligible shell-tier entry withholds the signal,\n // the same exception the bundle ping applies: deopting here would\n // pre-empt the static attempt the chain ping spawns for this node when\n // it reaches the terminal descendant (its Fulfilled case runs for\n // every node in the chain).\n needsRuntimeRequest: segment.status === EntryStatus.Fulfilled && wouldRuntimeRequestProvideMore(segment, fetchStrategy) && !isShellEntryEligibleForStaticAttempt(now, task.segmentCacheMap, segment, tree, fetchStrategy)\n };\n }\n // Not bundled. Build a single-node bundle and ping it. If this page\n // accepts the head (HeadInlinedIntoSelf), prepend the head's cache entry\n // to the bundle.\n let effectiveParent = parentBundle;\n if (process.env.__NEXT_PREFETCH_INLINING && tree.prefetchHints & PrefetchHint.HeadInlinedIntoSelf) {\n effectiveParent = {\n tree: route.root.head,\n entry: readOrCreateSegmentCacheEntry(now, task.segmentCacheMap, fetchStrategy, route.root.head),\n parent: parentBundle\n };\n }\n const segments = {\n tree,\n entry: segment,\n parent: effectiveParent\n };\n const needsRuntimeRequest = pingSegmentBundle(now, task, route, task.key, tree, segments, fetchStrategy, spawnRevalidations);\n return {\n bundle: null,\n needsRuntimeRequest\n };\n}\nfunction finishStaticBundleOnRuntimeBailout(now, task, route, tree, parentBundle, // The same static walk strategy the parent bundle was accumulated with.\n// Any needs-runtime signal from finishing the bundle is dropped: the\n// caller is already deopting this subtree to a runtime prefetch.\nfetchStrategy) {\n const bundle = accumulateSegmentBundle(now, task, route, tree, parentBundle, fetchStrategy, // The batched runtime request covers the deopted subtree; only fetch\n // Empty entries the chain would otherwise strand — never spawn\n // revalidations over settled or in-flight ones. See pingSegmentBundle.\n false).bundle;\n if (bundle === null) {\n return;\n }\n if (tree.slots !== null) {\n for (const childTree of tree.slots.values()){\n if (childTree.prefetchHints & PrefetchHint.ParentInlinedIntoSelf) {\n finishStaticBundleOnRuntimeBailout(now, task, route, childTree, bundle, fetchStrategy);\n return;\n }\n }\n }\n}\nfunction pingFullSegmentRevalidation(now, task, tree, fetchStrategy) {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(now, task.segmentCacheMap, fetchStrategy, tree);\n if (revalidatingSegment.status === EntryStatus.Empty) {\n // During a Full/PPRRuntime prefetch, a single runtime request is made for\n // all the segments that we need. So we don't initiate a request here\n // directly. By returning a pending entry from this function, it signals\n // to the caller that this segment should be included in the request\n // that's sent to the server.\n const pendingSegment = upgradeToPendingSegment(revalidatingSegment, fetchStrategy);\n // The upsert is handled by writeSegmentDataIntoCache\n // when the runtime request's response is written into the cache.\n return pendingSegment;\n } else {\n // There's already a revalidation in progress.\n const nonEmptyRevalidatingSegment = revalidatingSegment;\n if (canNewFetchStrategyProvideMoreContent(nonEmptyRevalidatingSegment.fetchStrategy, fetchStrategy)) {\n // The existing revalidation was fetched using a less specific strategy.\n // Reset it and start a new revalidation.\n const emptySegment = overwriteRevalidatingSegmentCacheEntry(now, task.segmentCacheMap, fetchStrategy, tree);\n const pendingSegment = upgradeToPendingSegment(emptySegment, fetchStrategy);\n // The upsert is handled by writeSegmentDataIntoCache\n // when the runtime request's response is written into the cache.\n return pendingSegment;\n }\n switch(nonEmptyRevalidatingSegment.status){\n case EntryStatus.Pending:\n // There's already an in-progress prefetch that includes this segment.\n // The pass needs the contents of that response, too. Wait for it\n // before the phase can complete.\n blockTaskOnPendingResponse(task, nonEmptyRevalidatingSegment);\n return null;\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n // A previous revalidation attempt finished, but we chose not to replace\n // the existing entry in the cache. Don't try again until or unless the\n // revalidation entry expires.\n return null;\n default:\n nonEmptyRevalidatingSegment;\n return null;\n }\n }\n}\n/**\n * Decides whether to speculatively prefetch a subtree. Under Partial\n * Prefetching we only do this if the Link's prefetch prop is set to true —\n * otherwise the subtree relies on the shell that the Shell phase prefetches.\n */ export function needsSpeculativePrefetch(taskfetchStrategy, rootPrefetchHints) {\n if ((rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0) {\n // PPF - only needs a speculative prefetch if this is a `<Link prefetch={true}>`.\n return taskfetchStrategy === FetchStrategy.Full;\n } else {\n // non-PPF -- all prefetches are speculative.\n return true;\n }\n}\n// -----------------------------------------------------------------------------\n// The remainder of the module is a MinHeap implementation. Try not to put any\n// logic below here unless it's related to the heap algorithm. We can extract\n// this to a separate module if/when we need multiple kinds of heaps.\n// -----------------------------------------------------------------------------\nfunction compareQueuePriority(a, b) {\n // Since the queue is a MinHeap, this should return a positive number if b is\n // higher priority than a, and a negative number if a is higher priority\n // than b.\n // `priority` is an integer, where higher numbers are higher priority.\n const priorityDiff = b.priority - a.priority;\n if (priorityDiff !== 0) {\n return priorityDiff;\n }\n // If the priority is the same, check which phase the prefetch is in — is it\n // prefetching the route tree, or the segments? Route trees are prioritized.\n const phaseDiff = b.phase - a.phase;\n if (phaseDiff !== 0) {\n return phaseDiff;\n }\n // Finally, check the insertion order. `sortId` is an incrementing counter\n // assigned to prefetches. We want to process the newest prefetches first.\n return b.sortId - a.sortId;\n}\nfunction heapPush(heap, node) {\n const index = heap.length;\n heap.push(node);\n node._heapIndex = index;\n heapSiftUp(heap, node, index);\n}\nfunction heapPeek(heap) {\n return heap.length === 0 ? null : heap[0];\n}\nfunction heapPop(heap) {\n if (heap.length === 0) {\n return null;\n }\n const first = heap[0];\n first._heapIndex = -1;\n const last = heap.pop();\n if (last !== first) {\n heap[0] = last;\n last._heapIndex = 0;\n heapSiftDown(heap, last, 0);\n }\n return first;\n}\nfunction heapDelete(heap, node) {\n const index = node._heapIndex;\n if (index !== -1) {\n node._heapIndex = -1;\n if (heap.length !== 0) {\n const last = heap.pop();\n if (last !== node) {\n heap[index] = last;\n last._heapIndex = index;\n heapSiftDown(heap, last, index);\n }\n }\n }\n}\nfunction heapResift(heap, node) {\n const index = node._heapIndex;\n if (index !== -1) {\n if (index === 0) {\n heapSiftDown(heap, node, 0);\n } else {\n const parentIndex = index - 1 >>> 1;\n const parent = heap[parentIndex];\n if (compareQueuePriority(parent, node) > 0) {\n // The parent is larger. Sift up.\n heapSiftUp(heap, node, index);\n } else {\n // The parent is smaller (or equal). Sift down.\n heapSiftDown(heap, node, index);\n }\n }\n }\n}\nfunction heapSiftUp(heap, node, i) {\n let index = i;\n while(index > 0){\n const parentIndex = index - 1 >>> 1;\n const parent = heap[parentIndex];\n if (compareQueuePriority(parent, node) > 0) {\n // The parent is larger. Swap positions.\n heap[parentIndex] = node;\n node._heapIndex = parentIndex;\n heap[index] = parent;\n parent._heapIndex = index;\n index = parentIndex;\n } else {\n // The parent is smaller. Exit.\n return;\n }\n }\n}\nfunction heapSiftDown(heap, node, i) {\n let index = i;\n const length = heap.length;\n const halfLength = length >>> 1;\n while(index < halfLength){\n const leftIndex = (index + 1) * 2 - 1;\n const left = heap[leftIndex];\n const rightIndex = leftIndex + 1;\n const right = heap[rightIndex];\n // If the left or right node is smaller, swap with the smaller of those.\n if (compareQueuePriority(left, node) < 0) {\n if (rightIndex < length && compareQueuePriority(right, left) < 0) {\n heap[index] = right;\n right._heapIndex = index;\n heap[rightIndex] = node;\n node._heapIndex = rightIndex;\n index = rightIndex;\n } else {\n heap[index] = left;\n left._heapIndex = index;\n heap[leftIndex] = node;\n node._heapIndex = leftIndex;\n index = leftIndex;\n }\n } else if (rightIndex < length && compareQueuePriority(right, node) < 0) {\n heap[index] = right;\n right._heapIndex = index;\n heap[rightIndex] = node;\n node._heapIndex = rightIndex;\n index = rightIndex;\n } else {\n // Neither child is smaller. Exit.\n return;\n }\n }\n}\n\n//# sourceMappingURL=scheduler.js.map","// http://www.cse.yorku.ca/~oz/hash.html\n// More specifically, 32-bit hash via djbxor\n// (ref: https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765)\n// This is due to number type differences between rust for turbopack to js number types,\n// where rust does not have easy way to repreesnt js's 53-bit float number type for the matching\n// overflow behavior. This is more `correct` in terms of having canonical hash across different runtime / implementation\n// as can gaurantee determinstic output from 32bit hash.\nexport function djb2Hash(str) {\n let hash = 5381;\n for(let i = 0; i < str.length; i++){\n const char = str.charCodeAt(i);\n hash = (hash << 5) + hash + char & 0xffffffff;\n }\n return hash >>> 0;\n}\nexport function hexHash(str) {\n return djb2Hash(str).toString(36).slice(0, 5);\n}\n\n//# sourceMappingURL=hash.js.map","/**\n * Decoding of RSC server responses (the transport format defined in\n * shared/lib/rsc-transport) into the client's own representations. This is\n * the only place on the client that consumes transport types; everything\n * downstream operates on RouteTree / NavigationSeed / CacheNode.\n */ import { PrefetchHint, SubtreePrefetchHints, propagateSubtreeBits } from '../../../shared/lib/app-router-types';\nimport { readFulfilledValue } from '../../../shared/lib/rsc-transport';\nimport { decodeVaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding';\nimport { ROOT_SEGMENT_REQUEST_KEY, appendSegmentRequestKeyPart, createSegmentRequestKeyPart } from '../../../shared/lib/segment-cache/segment-value-encoding';\nimport { DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../../../shared/lib/segment';\nimport { InvariantError } from '../../../shared/lib/invariant-error';\nimport { doesStaticSegmentAppearInURL, getCacheKeyForDynamicParam, parseDynamicParamFromURLPart } from '../../route-params';\nimport { splitPathnameIntoParts } from './cache-key';\nimport { appendLayoutVaryPath, finalizeVaryPath, getPartialVaryPath, getShellSegmentVaryPath } from './vary-path';\nimport { convertFlightRouterStateToRouteTree, convertRootFlightRouterStateToRouteTree, createMetadataRouteTree, createRootRouteTree, getHeadRequestKey } from './cache';\nimport { computeDynamicStaleAt } from './bfcache';\n/**\n * During a client navigation or prefetch, the server responds with a\n * transport tree that covers only the parts of the route that have changed.\n * This overlays it onto the base tree to produce a full RouteTree — slots the\n * response carries no information about are reused from the client's current\n * state — with the response's render output (RSCSegmentData) attached to\n * each node.\n *\n * \"Create\", not \"decode\": callers may pass no transport data at all\n * (refreshes and history restores do), in which case this converts the base\n * tree alone rather than decoding a response.\n */ export function createNavigationSeed(now, // Null when the response is not an overlay over existing client state —\n// per-segment prefetch responses, whose root-anchored tree covers its own\n// spine. Must be non-null when transportData is null (there'd be nothing\n// to convert otherwise).\ncurrentTree, transportData, // The response's root vary params (its `r` field): the root params\n// accessed anywhere in the response, emitted once at the response level\n// and unioned into the head's and every segment's own drained set here at\n// the decode boundary. Pass null when the response streams in\n// incrementally (navigation and reducer flows): the wire iterables can\n// only be drained completely from a fully-buffered response, so their sets\n// decode as null (\"unknown; key on all params\") without touching the wire\n// iterables.\nrootVaryParams, // Whether anything in the response is not fully resolved: dynamic holes, runtime holes, anything suspended.\n// Boolean-form nodes resolve their partiality to this value (their wire\n// boolean is a render-wide constant that carries no per-node information —\n// see decodeTransportNode), and under Cache Components so does a\n// boolean-form head (see the head read below); staged (promise-form)\n// nodes encode it per-node and ignore it. Only segment-cache writes\n// consume the decoded partiality, so callers whose seeds are never\n// written to the cache may pass the conservative value (true).\nisResponsePartial, // The pathname the response was rendered for. Required to resolve dynamic\n// segments the server sent without a param value (`k: null`); see\n// decodeTransportTreeIntoRouteTree. Callers whose responses always carry\n// concrete values (navigation responses) may pass null.\nrenderedPathname, // Already normalized by the response reader (see getRenderedSearch); the\n// router state stores it as a plain string, so it is re-branded here.\nrenderedSearch, // Where to key the head. Null derives it from the route's own first page\n// node (see createRouteTreeNode). Per-segment prefetch payloads pass the\n// route's own metadata vary path instead: a standalone head response's tree\n// is a bare root identity with no page node.\nmetadataVaryPath, dynamicStaleTimeSeconds) {\n const normalizedRenderedSearch = renderedSearch;\n const acc = {\n metadataVaryPath: null,\n treeDivergedFromBase: false\n };\n let routeTree;\n let headData = null;\n if (transportData !== null) {\n routeTree = decodeTransportTreeIntoRouteTree(transportData.t, currentTree, rootVaryParams, isResponsePartial, renderedPathname, normalizedRenderedSearch, acc);\n const transportHead = transportData.h;\n if (transportHead !== undefined) {\n // The wire form of `p` determines which signal is authoritative for\n // the head's partiality, mirroring the per-node rule in\n // decodeTransportNode:\n //\n // - Promise form (per-segment prefetch responses, fully buffered\n // before they're decoded): partiality is encoded exactly, per node,\n // via the staged encoding, so the thenable-status read is\n // authoritative.\n // - Boolean form (navigation and live-render responses): when Cache\n // Components is enabled, the server's flag (isPossiblyPartialHead in\n // app-render.tsx) is unreliable: it's computed before the head is\n // serialized, so it's conservatively `true` for every\n // statically-generated PPR page — even pages whose head is actually\n // complete — and it's `false` for live-render responses whose head\n // is actually partial (e.g. a route with an async\n // `generateMetadata`). So we ignore it and derive the head's\n // partiality from whether the response itself was partial, exactly\n // as the per-node rule does for segments. A non-partial response\n // carries a complete head; a partial (postponed) one does not.\n // Without Cache Components, the server sends the correct\n // isHeadPartial, so the wire boolean is used as-is.\n headData = {\n rsc: transportHead.r,\n isPartial: typeof transportHead.p === 'boolean' ? process.env.__NEXT_CACHE_COMPONENTS ? isResponsePartial : transportHead.p : readFulfilledIsPartial(transportHead.p),\n varyParams: decodeVaryParams(transportHead.v, rootVaryParams),\n staleTimeSeconds: transportHead.s !== undefined ? readFulfilledStaleTimeSeconds(transportHead.s) : null\n };\n }\n } else {\n if (currentTree === null) {\n throw new InvariantError('Cannot convert a server response with no transport data and no ' + 'base tree.');\n }\n routeTree = convertRootFlightRouterStateToRouteTree(currentTree, normalizedRenderedSearch, acc);\n }\n if (metadataVaryPath === null) {\n metadataVaryPath = acc.metadataVaryPath;\n if (metadataVaryPath === null) {\n // Every route renders a page, so a rendered tree always has a node to\n // key the head under.\n throw new InvariantError('Cannot key the head of a server response: its tree has no page ' + 'segment.');\n }\n }\n return {\n root: createRootRouteTree(routeTree, createMetadataRouteTree(metadataVaryPath, routeTree.prefetchHints, headData)),\n renderedSearch: normalizedRenderedSearch,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n treeDivergedFromBase: acc.treeDivergedFromBase\n };\n}\n/**\n * Creates a RouteTree node for a segment, with its identity and cache-key\n * information (vary paths, the normalized segment value, the refresh state)\n * initialized, and the remaining fields set to their defaults. The caller\n * finishes initializing those in place after recursing into the children.\n * Shared by FlightRouterState conversion, transport decoding, and subtree\n * rebasing so their routing identity stays consistent.\n */ export function createRouteTreeNode(originalSegment, isRootParam, requestKey, parentPartialVaryPath, renderedSearch, refreshState, acc) {\n let segment;\n let partialVaryPath;\n let varyPath;\n if (Array.isArray(originalSegment)) {\n const paramCacheKey = originalSegment[1];\n const paramName = originalSegment[0];\n partialVaryPath = appendLayoutVaryPath(parentPartialVaryPath, paramCacheKey, paramName, isRootParam);\n varyPath = finalizeVaryPath(requestKey, null, partialVaryPath);\n segment = originalSegment;\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath;\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n segment = PAGE_SEGMENT_KEY;\n varyPath = finalizeVaryPath(requestKey, renderedSearch, partialVaryPath);\n // The head is keyed under the route's own first page and varies on the\n // same params as that page (see getHeadRequestKey). A page reused from\n // another URL carries a refresh state and never keys it.\n if (refreshState === null && acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeVaryPath(getHeadRequestKey(requestKey), renderedSearch, partialVaryPath);\n }\n } else {\n // This is a layout segment.\n segment = originalSegment;\n varyPath = finalizeVaryPath(requestKey, null, partialVaryPath);\n }\n }\n return {\n requestKey,\n segment,\n shellVaryPath: getShellSegmentVaryPath(varyPath),\n refreshState,\n data: null,\n varyPath,\n slots: null,\n prefetchHints: 0\n };\n}\n/**\n * Decodes a response's transport tree into a RouteTree, using the client's\n * current router state as the base for the parts of the route the response\n * carries no information about.\n *\n * The response is an overlay over the base:\n *\n * - Nodes with rendered output — and nodes with no data at all, which are\n * server-sent structure whose output the client fetches lazily — are\n * authoritative: their identity, hints, and subtree come entirely from\n * the response.\n * - Skipped nodes (data with a null rsc) sit on the path from the root down\n * to the rendered subtrees. The client is expected to already have them,\n * so their refresh state and hints are inherited from the base tree, and\n * any slot the response doesn't mention is reused from the base as-is.\n *\n * TODO: The base is a FlightRouterState only because that's the\n * representation the client router currently renders from (the router\n * reducer's `state.tree`, which the render tree and layout-router are\n * keyed against). Once the rendering path is updated to use RouteTree as its\n * source of truth, the base tree here can be a RouteTree, and the base-only\n * conversion path (convertFlightRouterStateToRouteTree) goes away with it.\n */ export function decodeTransportTreeIntoRouteTree(transportNode, baseRouterState, // The response's root vary params, unioned into every segment's drained\n// set. Pass null when vary params are unavailable or unwanted; see\n// createNavigationSeed.\nrootVaryParams, // The response-level partiality, which boolean-form nodes resolve their\n// own partiality to; see createNavigationSeed.\nisResponsePartial, // The pathname the response was rendered for (from the response headers).\n// Required to resolve dynamic segments the server sent without a param\n// value (`k: null` — per-segment prefetch responses omit the value to stay\n// cacheable across param values); the client parses the value from the\n// pathname instead. Callers whose responses always carry concrete values\n// (navigation responses) may pass null.\nrenderedPathname, renderedSearch, acc) {\n const pathnameParts = renderedPathname !== null ? splitPathnameIntoParts(renderedPathname) : null;\n return decodeTransportNode(transportNode, resolveTransportSegment(transportNode.s, pathnameParts, 0), baseRouterState ?? undefined, baseRouterState ?? undefined, rootVaryParams, isResponsePartial, ROOT_SEGMENT_REQUEST_KEY, null, renderedSearch, pathnameParts, 0, acc);\n}\n/**\n * Converts a segment's wire identity to the client `Segment` type, resolving\n * dynamic segments whose param value the server omitted (`k: null`) by\n * parsing the value from the rendered pathname. `pathnamePartsIndex` is the\n * URL position this segment occupies (tracked by the tree walk: incremented\n * only for segments that appear in the URL, so route groups and other\n * virtual segments don't consume a part).\n */ function resolveTransportSegment(transportSegment, pathnameParts, pathnamePartsIndex) {\n if (typeof transportSegment === 'string') {\n return transportSegment;\n }\n const paramKey = transportSegment.k;\n if (paramKey !== null) {\n return [\n transportSegment.n,\n paramKey,\n transportSegment.t,\n transportSegment.s\n ];\n }\n if (pathnameParts === null) {\n throw new InvariantError('Cannot resolve a dynamic segment that has no param value: the ' + 'response provides no rendered pathname to parse it from.');\n }\n const paramValue = parseDynamicParamFromURLPart(transportSegment.t, pathnameParts, pathnamePartsIndex);\n return [\n transportSegment.n,\n getCacheKeyForDynamicParam(paramValue),\n transportSegment.t,\n transportSegment.s\n ];\n}\nfunction doSegmentsMatch(baseSegment, segment) {\n if (typeof baseSegment === 'string' || typeof segment === 'string') {\n // Static segments have to match exactly.\n return baseSegment === segment;\n }\n // Both segments are dynamic. The static sibling hints aren't part of the\n // segment's identity, so only compare the param name, type, and value.\n const [baseParamName, baseParamValue, baseParamType] = baseSegment;\n const [paramName, paramValue, paramType] = segment;\n return baseParamName === paramName && baseParamType === paramType && baseParamValue === paramValue;\n}\nfunction decodeTransportNode(node, // The node's identity, already resolved by the caller (the parent's child\n// loop, which has the URL position needed to parse omitted param values).\noriginalSegment, base, // The base node to compare segment identities against (see\n// NavigationSeed.treeDivergedFromBase). Tracked separately from `base`:\n// inheritance drops the base inside authoritative subtrees, where the\n// comparison must continue, and keeps it through inactive parallel routes,\n// where the comparison must stop.\ncompareBase, rootVaryParams, isResponsePartial, requestKey, parentPartialVaryPath, parentRenderedSearch, pathnameParts, // The URL position this node's children read from.\npathnamePartsIndex, acc) {\n const nodeData = node.d;\n const inheritsFromBase = nodeData !== undefined && nodeData.r === null;\n // The base node this position inherits from, when it does.\n const inheritedBase = inheritsFromBase ? base : undefined;\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n // Every transport node echoes the segment's identity, even \"skipped\"\n // ones, so each position can be compared against the base.\n const transportSegment = node.s;\n if (typeof transportSegment !== 'string' && transportSegment.k == null) {\n // The server omitted the param value for the client to parse from the\n // URL (see resolveTransportSegment). Nothing to compare; the children\n // are still checked.\n } else {\n const baseSegment = compareBase[0];\n if (originalSegment === DEFAULT_SEGMENT_KEY) {\n // A default filled in by the server is not a claim about the\n // position's identity.\n } else if (!doSegmentsMatch(baseSegment, originalSegment)) {\n acc.treeDivergedFromBase = true;\n }\n }\n }\n const baseHints = inheritedBase !== undefined ? inheritedBase[4] ?? 0 : 0;\n let prefetchHints = node.h ?? baseHints;\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = (prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0;\n // Inherited positions keep the base tree's refresh state. Its rendered\n // search is updated to this response's, since all pages within the same\n // response share the same search value. (The refresh state acts like a\n // \"context provider\" for inactive parallel routes.)\n const baseCompressedRefreshState = inheritedBase !== undefined ? inheritedBase[2] ?? null : null;\n const refreshState = baseCompressedRefreshState !== null ? {\n canonicalUrl: baseCompressedRefreshState[0],\n renderedSearch: parentRenderedSearch\n } : null;\n const renderedSearch = refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch;\n const tree = createRouteTreeNode(originalSegment, isRootParam, requestKey, parentPartialVaryPath, renderedSearch, refreshState, acc);\n const partialVaryPath = getPartialVaryPath(tree.varyPath);\n let slots = null;\n const transportChildren = node.c;\n const baseChildren = inheritedBase !== undefined ? inheritedBase[1] : undefined;\n if (transportChildren !== undefined) {\n for (const [parallelRouteKey, childNode] of transportChildren){\n const childBase = baseChildren !== undefined ? baseChildren[parallelRouteKey] : undefined;\n const childSegment = resolveTransportSegment(childNode.s, pathnameParts, pathnamePartsIndex);\n let childCompareBase;\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n const childCompareCandidate = compareBase[1][parallelRouteKey];\n if (childCompareCandidate === undefined) {\n // A slot the base tree doesn't have. Unless the server merely\n // filled it with a default, the trees have different structures.\n if (childSegment !== DEFAULT_SEGMENT_KEY) {\n acc.treeDivergedFromBase = true;\n }\n } else if ((childCompareCandidate[2] ?? null) !== null) {\n // The base branch carries a refresh state: an inactive parallel\n // route reused from a different route (e.g. a \"default\" slot). The\n // server's answer is expected to differ, so skip the branch.\n } else {\n childCompareBase = childCompareCandidate;\n }\n }\n // Only advance the URL position for segments that appear in the URL.\n // Virtual segments, like route groups, don't consume a part.\n const childDoesAppearInURL = typeof childSegment === 'string' ? doesStaticSegmentAppearInURL(childSegment) : true;\n const childPathnamePartsIndex = childDoesAppearInURL ? pathnamePartsIndex + 1 : pathnamePartsIndex;\n const childRequestKey = appendSegmentRequestKeyPart(requestKey, parallelRouteKey, createSegmentRequestKeyPart(childSegment));\n const childTree = decodeTransportNode(childNode, childSegment, childBase, childCompareBase, rootVaryParams, isResponsePartial, childRequestKey, partialVaryPath, renderedSearch, pathnameParts, childPathnamePartsIndex, acc);\n if (slots === null) {\n slots = new Map();\n }\n slots.set(parallelRouteKey, childTree);\n }\n }\n if (baseChildren !== undefined) {\n // Slots the response carries no information about are reused from the\n // base tree, structure-only.\n for(const parallelRouteKey in baseChildren){\n if (transportChildren !== undefined && transportChildren.has(parallelRouteKey)) {\n continue;\n }\n const childBase = baseChildren[parallelRouteKey];\n const childRequestKey = appendSegmentRequestKeyPart(requestKey, parallelRouteKey, createSegmentRequestKeyPart(childBase[0]));\n const childTree = convertFlightRouterStateToRouteTree(childBase, childRequestKey, partialVaryPath, renderedSearch, acc);\n if (slots === null) {\n slots = new Map();\n }\n slots.set(parallelRouteKey, childTree);\n }\n }\n if (inheritsFromBase) {\n // Recompute the propagated \"subtree\" prefetch hints for this segment,\n // since its children may combine response and base subtrees. Mirrors the\n // propagation done on the server in createTransportTreeFromLoaderTree.\n let propagated = prefetchHints & ~SubtreePrefetchHints;\n if (slots !== null) {\n for (const childTree of slots.values()){\n propagated = propagateSubtreeBits(propagated, childTree.prefetchHints);\n }\n }\n prefetchHints = propagated;\n }\n if (nodeData !== undefined) {\n tree.data = {\n rsc: nodeData.r,\n // The wire form of `p` determines which signal is authoritative for\n // this segment's partiality:\n //\n // - Boolean form (navigation and live-render responses): the wire\n // value is a render-wide constant (`isPossiblyPartialResponse` in\n // create-component-tree.tsx), identical on every node, so it carries\n // no per-node information — and it's inaccurate in both directions:\n // `true` for every node of a statically-generated PPR page even when\n // the page is actually complete, and `false` for every node of a\n // dynamic render even when this decode is a truncated stage prefix\n // whose dynamic rows landed past the boundary. The caller's\n // response-level value captures both (the `~`/`#` marker for whole\n // responses; truncation-implied partiality for stage decodes), so it\n // replaces the wire boolean here.\n // - Promise form (per-segment prefetch responses, fully buffered\n // before they're decoded): partiality is encoded per node, exactly,\n // and survives the truncated shell double-decode — a fulfillment row\n // past the boundary reads as partial. The fulfillment (or its\n // absence) is already visible on the thenable's status, so it's\n // authoritative and the response-level value is ignored.\n isPartial: typeof nodeData.p === 'boolean' ? isResponsePartial : readFulfilledIsPartial(nodeData.p),\n // The source of the params this segment's output depends on: the\n // segment's wire iterable, drained here, unioning in the response-level\n // root params (same buffered-read reasoning as `p` above), or decoded\n // as null (\"unknown\") when the caller passed no root params — see\n // createNavigationSeed.\n varyParams: decodeVaryParams(nodeData.v, rootVaryParams),\n // Per-node staleTime, only present in per-segment prefetch responses\n // (same buffered-read reasoning as `p` above).\n staleTimeSeconds: nodeData.s !== undefined ? readFulfilledStaleTimeSeconds(nodeData.s) : null\n };\n }\n tree.slots = slots;\n tree.prefetchHints = prefetchHints;\n return tree;\n}\n// A sentinel `readFulfilledValue` fallback that no fulfillment can produce,\n// for reads that only care whether the row settled at all.\nconst notFulfilled = Symbol();\n/**\n * Reads a segment's partialness from its `isPartial` promise. (The\n * fulfillment value is void — partialness is encoded as the ABSENCE of a\n * fulfillment.) The server fulfills it only for a fully-static segment and\n * leaves it pending for a partial one (see the promise form of\n * `TransportSegmentData['p']`), so partial == not fulfilled. A pending row,\n * or a truncated shell decode whose fulfillment landed past the boundary,\n * reads as partial, which is correct either way.\n */ export function readFulfilledIsPartial(isPartial) {\n return readFulfilledValue(isPartial, notFulfilled) === notFulfilled;\n}\n/**\n * Reads a staleTime (in seconds) from the staleTime async iterable of a\n * fully-buffered response. Because the bytes are all present, each yielded\n * value is already visible on its chunk's thenable status, so this drains\n * synchronously and takes the last value (the final staleTime, matching the\n * async `resolveStaleAt` in cache.ts). Returns null when no usable value was\n * yielded — e.g. a truncated shell decode whose value landed past the\n * boundary — so the caller can fall back to its response-level staleness.\n */ export function readFulfilledStaleTimeSeconds(staleTime) {\n const iterator = staleTime[Symbol.asyncIterator]();\n let staleTimeSeconds;\n while(true){\n const chunk = readFulfilledValue(iterator.next(), undefined);\n if (chunk === undefined || chunk.done) {\n break;\n }\n staleTimeSeconds = chunk.value;\n }\n if (staleTimeSeconds === undefined || isNaN(staleTimeSeconds)) {\n return null;\n }\n return staleTimeSeconds;\n}\n\n//# sourceMappingURL=decode-server-response.js.map","import { PrefetchHint, StaticAttemptHints } from '../../../shared/lib/app-router-types';\nimport { createVaryParams, readVaryParams, SEARCH_PARAMS_VARY_ID } from '../../../shared/lib/segment-cache/vary-params-decoding';\nimport { readFulfilledValue } from '../../../shared/lib/rsc-transport';\nimport { NEXT_DID_POSTPONE_HEADER, NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_STALE_TIME_HEADER, NEXT_ROUTER_STATE_TREE_HEADER, NEXT_URL, RSC_CONTENT_TYPE_HEADER, RSC_HEADER } from '../app-router-headers';\nimport { createFetch, createFromNextReadableStream, decodeBufferedStage, resolveShellStageResponse } from '../router-reducer/fetch-server-response';\nimport { fetch } from './fetch';\nimport { pingPrefetchTask, isPrefetchTaskDirty } from './scheduler';\nimport { getRouteVaryPath, getFulfilledRouteVaryPath, getFulfilledSegmentVaryPath, getSegmentVaryPathForRequest, getShellSegmentVaryPath, cloneVaryPathWithNewSearchParams, getPartialVaryPath } from './vary-path';\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url';\nimport { createCacheKey as createPrefetchRequestKey } from './cache-key';\nimport { getPathnameFromRequestURL, getRenderedPathname, getRenderedSearch, normalizeRenderedSearch } from '../../route-params';\nimport { createCacheMap, getFromCacheMap, setInCacheMap, setSizeInCacheMap, deleteFromCacheMap, isValueExpired, EntryStatus } from './cache-map';\nexport { EntryStatus } from './cache-map';\nimport { appendSegmentRequestKeyPart, convertSegmentPathToStaticExportFilename, createSegmentRequestKeyPart, HEAD_REQUEST_KEY, ROOT_SEGMENT_REQUEST_KEY } from '../../../shared/lib/segment-cache/segment-value-encoding';\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers';\nimport { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer';\nimport { pingVisibleLinks } from '../links';\nimport { FetchStrategy } from './types';\nimport { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers';\nimport { readFromBFCache, UnknownDynamicStaleTime } from './bfcache';\nimport { discoverKnownRoute, matchKnownRoute } from './optimistic-routes';\nimport { createNavigationSeed, decodeTransportTreeIntoRouteTree, createRouteTreeNode, readFulfilledStaleTimeSeconds } from './decode-server-response';\nimport { getNavigationBuildId } from '../../navigation-build-id';\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants';\n/**\n * Ensures a minimum stale time of 30s to avoid issues where the server sends a too\n * short-lived stale time, which would prevent anything from being prefetched.\n */ export function getStaleTimeMs(staleTimeSeconds) {\n return Math.max(staleTimeSeconds, 30) * 1000;\n}\n// How long a rejected cache entry blocks re-fetching before it may be\n// retried (its staleAt is set this far in the future).\nconst REJECTION_BACKOFF_MS = 10 * 1000;\n/**\n * The staleAt to reject entries with when a prefetch fails: if we're\n * offline, expire immediately (-1) so the entry is re-fetched once the\n * scheduler is re-pinged after connectivity is restored; otherwise apply a\n * short backoff. (Unlike navigations and server actions, prefetches don't\n * await `waitForConnection`.)\n */ function getPrefetchErrorStaleAt(error) {\n if (process.env.__NEXT_USE_OFFLINE) {\n const { checkOfflineError } = require('../offline');\n if (checkOfflineError(error)) {\n return -1;\n }\n }\n return Date.now() + REJECTION_BACKOFF_MS;\n}\nexport function createRootRouteTree(tree, head) {\n return {\n tree,\n head\n };\n}\nexport function doesRouteStructureMatch(currentTree, nextTree) {\n // The request key includes the param names and types, but not the values.\n if (currentTree.requestKey !== nextTree.requestKey) {\n return false;\n }\n // The root request key is always empty (even for global Not Found), so we\n // have to compare the root segment directly.\n return nextTree.requestKey !== ROOT_SEGMENT_REQUEST_KEY || currentTree.segment === nextTree.segment;\n}\nconst isOutputExportMode = process.env.NODE_ENV === 'production' && process.env.__NEXT_CONFIG_OUTPUT === 'export';\nexport const MetadataOnlyRequestTree = [\n '',\n {},\n null,\n 'metadata-only'\n];\nconst routeCacheMap = createCacheMap();\n/**\n * The shared segment cache map. Segment cache functions do not access this\n * ambiently — every unit of work is bound to a map when it is created, and\n * reads and writes receive that map explicitly:\n *\n * - A prefetch task captures its map when it is scheduled\n * (`PrefetchTask.segmentCacheMap` in scheduler.ts). Almost always this one;\n * a task scheduled while the Instant Navigation Testing lock is held gets\n * the lock scope's private map instead (which starts empty and is discarded\n * at release), so a locked navigation observes only data fetched under the\n * lock — never a stale entry left in the shared cache by an earlier\n * navigation, prefetch, or scope.\n * - A locked navigation inherits the map of the prefetch task that drives it\n * (see `ensurePrefetchThenNavigate` in navigation.ts).\n * - Everything else — unlocked navigations, hydration, and router work that\n * is not a captured navigation (refreshes, history-traversal restores,\n * server-action redirects, server patches) — uses this shared map\n * directly, even while a lock is held.\n *\n * Binding at creation means a task queued before a lock scope begins never\n * leaks entries into the scope's map (or reads out of it), and a scope task's\n * late responses never leak into the shared map.\n */ export const segmentCacheMap = createCacheMap();\n// All invalidation listeners for the whole cache are tracked in single set.\n// Since we don't yet support tag or path-based invalidation, there's no point\n// tracking them any more granularly than this. Once we add granular\n// invalidation, that may change, though generally the model is to just notify\n// the listeners and allow the caller to poll the prefetch cache with a new\n// prefetch task if desired.\nlet invalidationListeners = null;\n// Incrementing counters used to track cache invalidations. Route and segment\n// caches have separate versions so they can be invalidated independently.\n// Invalidation does not eagerly evict anything from the cache; entries are\n// lazily evicted when read.\nlet currentRouteCacheVersion = 0;\nlet currentSegmentCacheVersion = 0;\nexport function getCurrentRouteCacheVersion() {\n return currentRouteCacheVersion;\n}\nexport function getCurrentSegmentCacheVersion() {\n return currentSegmentCacheVersion;\n}\n/**\n * Invalidates all prefetch cache entries (both route and segment caches).\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */ export function invalidateEntirePrefetchCache(nextUrl, root) {\n currentRouteCacheVersion++;\n currentSegmentCacheVersion++;\n pingVisibleLinks(nextUrl, root);\n pingInvalidationListeners(nextUrl, root);\n}\n/**\n * Invalidates all route cache entries. Route entries contain the tree structure\n * (which segments exist at a given URL) but not the segment data itself.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */ export function invalidateRouteCacheEntries(nextUrl, root) {\n currentRouteCacheVersion++;\n pingVisibleLinks(nextUrl, root);\n pingInvalidationListeners(nextUrl, root);\n}\n/**\n * Invalidates all segment cache entries. Segment entries contain the actual\n * RSC data for each segment.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */ export function invalidateSegmentCacheEntries(nextUrl, root) {\n currentSegmentCacheVersion++;\n pingVisibleLinks(nextUrl, root);\n pingInvalidationListeners(nextUrl, root);\n}\nfunction attachInvalidationListener(task) {\n // This function is called whenever a prefetch task reads a cache entry. If\n // the task has an onInvalidate function associated with it — i.e. the one\n // optionally passed to router.prefetch(onInvalidate) — then we attach that\n // listener to the every cache entry that the task reads. Then, if an entry\n // is invalidated, we call the function.\n if (task.onInvalidate !== null) {\n if (invalidationListeners === null) {\n invalidationListeners = new Set([\n task\n ]);\n } else {\n invalidationListeners.add(task);\n }\n }\n}\nfunction notifyInvalidationListener(task) {\n const onInvalidate = task.onInvalidate;\n if (onInvalidate !== null) {\n // Clear the callback from the task object to guarantee it's not called more\n // than once.\n task.onInvalidate = null;\n // This is a user-space function, so we must wrap in try/catch.\n try {\n onInvalidate();\n } catch (error) {\n if (typeof reportError === 'function') {\n reportError(error);\n } else {\n console.error(error);\n }\n }\n }\n}\nexport function pingInvalidationListeners(nextUrl, root) {\n // The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.\n // This is called when the Next-Url or the base tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n if (invalidationListeners !== null) {\n const tasks = invalidationListeners;\n invalidationListeners = null;\n for (const task of tasks){\n if (isPrefetchTaskDirty(task, nextUrl, root)) {\n notifyInvalidationListener(task);\n }\n }\n }\n}\nexport function readRouteCacheEntry(now, key) {\n const varyPath = getRouteVaryPath(key.pathname, key.search, key.nextUrl);\n const isRevalidation = false;\n const existingEntry = getFromCacheMap(now, getCurrentRouteCacheVersion(), routeCacheMap, varyPath, isRevalidation, false);\n if (existingEntry !== null) {\n return existingEntry;\n }\n // No cache hit. Attempt to construct from template using the new\n // optimistic routing mechanism (pattern-based matching).\n if (process.env.__NEXT_OPTIMISTIC_ROUTING) {\n return matchKnownRoute(now, key.pathname, key.search);\n }\n return null;\n}\n/**\n * Reads the cache entry for a segment during a navigation. Unlike a plain\n * lookup, prefers a Fulfilled entry over a more-specific Pending or Rejected\n * entry: during a navigation, a less-specific shell entry (e.g. params ->\n * Fallback) should be rendered immediately rather than blocking on a\n * more-specific Pending entry that may still be in-flight.\n *\n * Performs up to two lookups:\n * 1. An `onlyMatchFulfilled` lookup that walks past Pending/Rejected entries\n * at more-specific keypaths to find a Fulfilled fallback (e.g. a cached\n * shell).\n * 2. If no Fulfilled entry is found, a regular lookup that returns the most\n * specific match regardless of status.\n */ export function readSegmentCacheEntryForNavigation(now, // The map the navigation is bound to: a locked navigation's driving-task\n// map, or the shared map otherwise.\nmap, varyPath, restrictToShell = false) {\n const isRevalidation = false;\n let lookupVaryPath = varyPath;\n if (process.env.__NEXT_EXPOSE_TESTING_API && restrictToShell) {\n // Instant Navigation Testing API: we're navigating to a link that 1) has\n // Partial Prefetching enabled, and 2) does not have a prefetch prop set.\n // Only the shell may render, not anything that varies on concrete route\n // params.\n lookupVaryPath = getShellSegmentVaryPath(varyPath);\n }\n // Prefer a Fulfilled entry (e.g. a cached shell) over a more-specific\n // Pending/Rejected one so it renders immediately instead of blocking on an\n // in-flight entry.\n const fulfilled = getFromCacheMap(now, getCurrentSegmentCacheVersion(), map, lookupVaryPath, isRevalidation, true);\n if (fulfilled !== null) {\n return fulfilled;\n }\n return getFromCacheMap(now, getCurrentSegmentCacheVersion(), map, lookupVaryPath, isRevalidation, false);\n}\nfunction readRevalidatingSegmentCacheEntry(now, map, varyPath) {\n const isRevalidation = true;\n return getFromCacheMap(now, getCurrentSegmentCacheVersion(), map, varyPath, isRevalidation, false);\n}\nexport function waitForSegmentCacheEntry(pendingEntry) {\n // Because the entry is pending, there's already a in-progress request.\n // Attach a promise to the entry that will resolve when the server responds.\n let promiseWithResolvers = pendingEntry.promise;\n if (promiseWithResolvers === null) {\n promiseWithResolvers = pendingEntry.promise = createPromiseWithResolvers();\n } else {\n // There's already a promise we can use\n }\n return promiseWithResolvers.promise;\n}\nfunction createDetachedRouteCacheEntry() {\n return {\n canonicalUrl: null,\n status: EntryStatus.Empty,\n blockedTasks: null,\n root: null,\n // This is initialized to true because we don't know yet whether the route\n // could be intercepted. It's only set to false once we receive a response\n // from the server.\n couldBeIntercepted: true,\n // Similarly, we don't yet know if the route supports PPR.\n supportsPerSegmentPrefetching: false,\n predictedFrom: null,\n renderedSearch: null,\n // Map-related fields\n ref: null,\n size: 0,\n // Since this is an empty entry, there's no reason to ever evict it. It will\n // be updated when the data is populated.\n staleAt: Infinity,\n version: getCurrentRouteCacheVersion()\n };\n}\n/**\n * Checks if an entry for a route exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */ export function readOrCreateRouteCacheEntry(now, task, key) {\n attachInvalidationListener(task);\n const existingEntry = readRouteCacheEntry(now, key);\n if (existingEntry !== null) {\n return existingEntry;\n }\n // Create a pending entry and add it to the cache.\n const pendingEntry = createDetachedRouteCacheEntry();\n const varyPath = getRouteVaryPath(key.pathname, key.search, key.nextUrl);\n const isRevalidation = false;\n setInCacheMap(routeCacheMap, varyPath, pendingEntry, isRevalidation);\n return pendingEntry;\n}\n// TODO: This function predates the new optimisticRouting feature and will be\n// removed once optimisticRouting is stable. The new mechanism (matchKnownRoute)\n// handles search param variations more robustly as part of the general route\n// prediction system. This fallback remains for when optimisticRouting is\n// disabled (staticChildren is null).\nexport function deprecated_requestOptimisticRouteCacheEntry(now, requestedUrl, nextUrl) {\n // This function is called during a navigation when there was no matching\n // route tree in the prefetch cache. Before de-opting to a blocking,\n // unprefetched navigation, we will first attempt to construct an \"optimistic\"\n // route tree by checking the cache for similar routes.\n //\n // Check if there's a route with the same pathname, but with different\n // search params. We can then base our optimistic route tree on this entry.\n //\n // Conceptually, we are simulating what would happen if we did perform a\n // prefetch the requested URL, under the assumption that the server will\n // not redirect or rewrite the request in a different manner than the\n // base route tree. This assumption might not hold, in which case we'll have\n // to recover when we perform the dynamic navigation request. However, this\n // is what would happen if a route were dynamically rewritten/redirected\n // in between the prefetch and the navigation. So the logic needs to exist\n // to handle this case regardless.\n // Look for a route with the same pathname, but with an empty search string.\n // TODO: There's nothing inherently special about the empty search string;\n // it's chosen somewhat arbitrarily, with the rationale that it's the most\n // likely one to exist. But we should update this to match _any_ search\n // string. The plan is to generalize this logic alongside other improvements\n // related to \"fallback\" cache entries.\n const requestedSearch = requestedUrl.search;\n if (requestedSearch === '') {\n // The caller would have already checked if a route with an empty search\n // string is in the cache. So we can bail out here.\n return null;\n }\n const urlWithoutSearchParams = new URL(requestedUrl);\n urlWithoutSearchParams.search = '';\n const routeWithNoSearchParams = readRouteCacheEntry(now, createPrefetchRequestKey(urlWithoutSearchParams.href, nextUrl));\n if (routeWithNoSearchParams === null || routeWithNoSearchParams.status !== EntryStatus.Fulfilled) {\n // Bail out of constructing an optimistic route tree. This will result in\n // a blocking, unprefetched navigation.\n return null;\n }\n // Now we have a base route tree we can \"patch\" with our optimistic values.\n // Optimistically assume that redirects for the requested pathname do\n // not vary on the search string. Therefore, if the base route was\n // redirected to a different search string, then the optimistic route\n // should be redirected to the same search string. Otherwise, we use\n // the requested search string.\n const canonicalUrlForRouteWithNoSearchParams = new URL(routeWithNoSearchParams.canonicalUrl, requestedUrl.origin);\n const optimisticCanonicalSearch = canonicalUrlForRouteWithNoSearchParams.search !== '' ? canonicalUrlForRouteWithNoSearchParams.search : requestedSearch;\n // Similarly, optimistically assume that rewrites for the requested\n // pathname do not vary on the search string. Therefore, if the base\n // route was rewritten to a different search string, then the optimistic\n // route should be rewritten to the same search string. Otherwise, we use\n // the requested search string.\n const optimisticRenderedSearch = routeWithNoSearchParams.renderedSearch !== '' ? routeWithNoSearchParams.renderedSearch : normalizeRenderedSearch(requestedSearch);\n const optimisticUrl = new URL(routeWithNoSearchParams.canonicalUrl, location.origin);\n optimisticUrl.search = optimisticCanonicalSearch;\n const optimisticCanonicalUrl = createHrefFromUrl(optimisticUrl);\n const optimisticRouteTree = deprecated_createOptimisticRouteTree(routeWithNoSearchParams.root.tree, optimisticRenderedSearch);\n const baseMetadataTree = routeWithNoSearchParams.root.head;\n const optimisticMetadataTree = createMetadataRouteTree(cloneVaryPathWithNewSearchParams(baseMetadataTree.varyPath, optimisticRenderedSearch), baseMetadataTree.prefetchHints, null);\n // Clone the base route tree, and override the relevant fields with our\n // optimistic values.\n const optimisticEntry = {\n canonicalUrl: optimisticCanonicalUrl,\n status: EntryStatus.Fulfilled,\n // This isn't cloned because it's instance-specific\n blockedTasks: null,\n root: createRootRouteTree(optimisticRouteTree, optimisticMetadataTree),\n couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,\n supportsPerSegmentPrefetching: routeWithNoSearchParams.supportsPerSegmentPrefetching,\n predictedFrom: null,\n // Override the rendered search with the optimistic value.\n renderedSearch: optimisticRenderedSearch,\n // Map-related fields\n ref: null,\n size: 0,\n staleAt: routeWithNoSearchParams.staleAt,\n version: routeWithNoSearchParams.version\n };\n // Do not insert this entry into the cache. It only exists so we can\n // perform the current navigation. Just return it to the caller.\n return optimisticEntry;\n}\nfunction deprecated_createOptimisticRouteTree(tree, newRenderedSearch) {\n // Create a new route tree that identical to the original one except for\n // the rendered search string, which is contained in the vary path.\n let clonedSlots = null;\n const originalSlots = tree.slots;\n if (originalSlots !== null) {\n clonedSlots = new Map();\n for (const [parallelRouteKey, childTree] of originalSlots){\n clonedSlots.set(parallelRouteKey, deprecated_createOptimisticRouteTree(childTree, newRenderedSearch));\n }\n }\n // The shell vary path Fallbacks search params, so it's unaffected by the\n // new rendered search and can be reused as-is.\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n shellVaryPath: tree.shellVaryPath,\n refreshState: tree.refreshState,\n // Optimistic trees are structure-only. (The input tree comes from the\n // route cache, which never carries render output.)\n data: null,\n varyPath: cloneVaryPathWithNewSearchParams(tree.varyPath, newRenderedSearch),\n slots: clonedSlots,\n prefetchHints: tree.prefetchHints\n };\n}\n/**\n * Checks if an entry for a segment exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */ export function readOrCreateSegmentCacheEntry(now, // The map the calling task operates in (`PrefetchTask.segmentCacheMap`,\n// captured when the task was scheduled).\nmap, fetchStrategy, tree) {\n const existingEntry = getFromCacheMap(now, getCurrentSegmentCacheVersion(), map, tree.varyPath, false, false);\n if (existingEntry !== null) {\n return existingEntry;\n }\n return insertEmptySegmentCacheEntry(now, map, fetchStrategy, tree);\n}\n/**\n * Creates an empty segment cache entry and inserts it into the cache, keyed\n * at the vary path a request made with the given fetch strategy is stored\n * under. The stale time is set to a default value; the actual stale time will\n * be set when the entry is fulfilled with data from the server response.\n */ function insertEmptySegmentCacheEntry(now, map, fetchStrategy, tree) {\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree);\n const emptyEntry = createDetachedSegmentCacheEntry(now);\n const isRevalidation = false;\n setInCacheMap(map, varyPathForRequest, emptyEntry, isRevalidation);\n return emptyEntry;\n}\nexport function readOrCreateRevalidatingSegmentEntry(now, // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\nmap, fetchStrategy, tree) {\n // This function is called when we've already confirmed that a particular\n // segment is cached, but we want to perform another request anyway in case it\n // returns more complete and/or fresher data than we already have. The logic\n // for deciding whether to replace the existing entry is handled elsewhere;\n // this function just handles retrieving a cache entry that we can use to\n // track the revalidation.\n //\n // The reason revalidations are stored in the cache is because we need to be\n // able to dedupe multiple revalidation requests. The reason they have to be\n // handled specially is because we shouldn't overwrite a \"normal\" entry if\n // one exists at the same keypath. So, for each internal cache location, there\n // is a special \"revalidation\" slot that is used solely for this purpose.\n //\n // You can think of it as if all the revalidation entries were stored in a\n // separate cache map from the canonical entries, and then transfered to the\n // canonical cache map once the request is complete — this isn't how it's\n // actually implemented, since it's more efficient to store them in the same\n // data structure as the normal entries, but that's how it's modeled\n // conceptually.\n // TODO: Once we implement Fallback behavior for params, where an entry is\n // re-keyed based on response information, we'll need to account for the\n // possibility that the keypath of the previous entry is more generic than\n // the keypath of the revalidating entry. In other words, the server could\n // return a less generic entry upon revalidation. For now, though, this isn't\n // a concern because the keypath is based solely on the prefetch strategy,\n // not on data contained in the response.\n const existingEntry = readRevalidatingSegmentCacheEntry(now, map, tree.varyPath);\n if (existingEntry !== null) {\n return existingEntry;\n }\n // Create a pending entry and add it to the cache. The stale time is set to a\n // default value; the actual stale time will be set when the entry is\n // fulfilled with data from the server response.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree);\n const pendingEntry = createDetachedSegmentCacheEntry(now);\n const isRevalidation = true;\n setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation);\n return pendingEntry;\n}\nexport function overwriteRevalidatingSegmentCacheEntry(now, // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\nmap, fetchStrategy, tree) {\n // This function is called when we've already decided to replace an existing\n // revalidation entry. Create a new entry and write it into the cache,\n // overwriting the previous value. The stale time is set to a default value;\n // the actual stale time will be set when the entry is fulfilled with data\n // from the server response.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree);\n const pendingEntry = createDetachedSegmentCacheEntry(now);\n const isRevalidation = true;\n setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation);\n return pendingEntry;\n}\n/**\n * Whether an existing cache entry is preferred over an incoming candidate —\n * i.e. the candidate does NOT supersede it. (On an exact tie — same fetch\n * strategy, same partialness — this returns false, so the candidate replaces\n * the existing entry.) This is the precedence rule used both when deciding\n * whether an upsert may replace the entry at its own keypath, and when\n * deciding whether an entry at a more specific keypath may be evicted because\n * it shadows a just-inserted candidate (see `evictShadowingSegmentEntries`).\n *\n * Note that \"less/more specific\" in the comments below refers to fetch\n * strategy content tiers (how much content a strategy can produce), not the\n * vary-path specificity the eviction docs are concerned with.\n */ function isExistingSegmentEntryPreferred(existingEntry, candidateEntry) {\n if (existingEntry.status === EntryStatus.Empty) {\n // An Empty entry is a placeholder that carries no data, and its\n // fetchStrategy is a spawn-time default, not a fact about any content —\n // it must never win a precedence comparison. (Without this, a candidate\n // fetched at a tier below the placeholder's default would be discarded\n // in favor of an entry with nothing in it.)\n return false;\n }\n return(// We fetched the new segment using a different, less specific fetch\n // strategy than the segment we already have in the cache, so it can't\n // have more content.\n candidateEntry.fetchStrategy !== existingEntry.fetchStrategy && !canNewFetchStrategyProvideMoreContent(existingEntry.fetchStrategy, candidateEntry.fetchStrategy) || // The existing entry isn't partial, but the new one is.\n // (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)\n !existingEntry.isPartial && candidateEntry.isPartial);\n}\nexport function upsertSegmentEntry(now, // The map the whole upsert (existing-entry read, insert, shadow eviction)\n// operates in. Prefetch response-write paths pass the spawning task's map\n// (`PrefetchTask.segmentCacheMap`), so a response that lands after a\n// testing-lock scope boundary still writes into the map its entries\n// live in.\nmap, varyPath, candidateEntry, // The fully concrete vary path a read for this segment position resolves\n// against (all concrete param values, i.e. `tree.varyPath`) — the most\n// specific path a read would use. Note this is the opposite of the\n// generalized keying path that `getSegmentVaryPathForRequest` computes.\n// Used to detect and evict stale entries at more specific keypaths that\n// would otherwise shadow the candidate. Pass null when there's no request\n// context; the shadow check is skipped.\nlookupVaryPath) {\n // We have a new entry that has not yet been inserted into the cache. Before\n // we do so, we need to confirm whether it takes precedence over the existing\n // entry (if one exists).\n // TODO: We should not upsert an entry if its key was invalidated in the time\n // since the request was made. We can do that by passing the \"owner\" entry to\n // this function and confirming it's the same as `existingEntry`.\n if (isValueExpired(now, getCurrentSegmentCacheVersion(), candidateEntry)) {\n // The entry is expired. We cannot upsert it.\n return null;\n }\n const existingEntry = getFromCacheMap(now, getCurrentSegmentCacheVersion(), map, varyPath, false, false);\n if (existingEntry !== null) {\n // Don't replace a more specific segment with a less-specific one. A case where this\n // might happen is if the existing segment was fetched via\n // `<Link prefetch={true}>`.\n if (isExistingSegmentEntryPreferred(existingEntry, candidateEntry)) {\n // The candidate does not supersede the existing entry. Leave the\n // existing entry in place and discard the candidate by not inserting it.\n //\n // We must not mutate the candidate here (e.g. downgrade it to Rejected or\n // null out its `rsc`). The caller does not transfer exclusive ownership\n // of it: it may already have been fulfilled, resolving its promise to a\n // waiter that holds the entry and reads `rsc` off it later. A navigation\n // seed is such a waiter, via `waitForSegmentCacheEntry`. Nulling `rsc`\n // after the fact resolves that read to `null`, so the waiter loses the\n // data it was about to render. Declining to insert it is enough: the\n // existing entry stays canonical, and the candidate keeps its valid (if\n // less complete) data for any waiter that already took it.\n return null;\n }\n // Ping any tasks blocked on the existing entry before replacing it so they\n // re-run and pick up the new entry. Without this, tasks waiting on the\n // existing Empty/Pending entry would be stranded — the new fulfilled\n // candidate has no blockedTasks of its own.\n if (existingEntry.status === EntryStatus.Empty || existingEntry.status === EntryStatus.Pending) {\n pingBlockedTasks(existingEntry);\n }\n // Replace the existing entry by writing the candidate over its keypath\n // below (the same mechanism `overwriteRevalidatingSegmentCacheEntry`\n // uses). We intentionally do NOT call `deleteFromCacheMap` first: deleting\n // vacates the canonical slot, and `deleteMapEntry` promotes a pending\n // Revalidation-slot entry into the vacated slot — which the immediate\n // insert below would then silently overwrite. The in-flight revalidation\n // would vanish from the map, so the next scheduler pass would find an\n // empty revalidation slot and spawn a duplicate request instead of\n // deduping against it. Replacing in place never vacates the slot, so\n // promotion never runs and the pending revalidating entry stays in its\n // Revalidation slot where `readOrCreateRevalidatingSegmentEntry`'s dedupe\n // finds it.\n //\n // The displaced entry's map/LRU accounting is handled by the replacement\n // itself: `setMapEntryValue` drops the displaced value's `ref` and\n // `updateLruSize` swaps its size for the candidate's, which is exactly\n // what delete-then-insert did.\n }\n const isRevalidation = false;\n setInCacheMap(map, varyPath, candidateEntry, isRevalidation);\n if (lookupVaryPath !== null) {\n evictShadowingSegmentEntries(now, map, lookupVaryPath, candidateEntry);\n }\n return candidateEntry;\n}\n/**\n * Evicts stale entries at more specific keypaths that shadow a just-inserted\n * candidate entry.\n *\n * A response can be written to the cache at a MORE GENERIC vary path than the\n * path the request was issued against — for example, the server may report\n * that a segment doesn't vary on a param, so the entry is re-keyed with that\n * param as Fallback. Meanwhile, an older, less useful entry can exist at a\n * more specific path within the same fallback chain — for example, a partial\n * shell entry keyed with root params concrete (see\n * `getShellSegmentVaryPath`). Because segment lookup is\n * most-specific-match-wins, every subsequent read at the concrete request\n * path keeps returning the stale specific entry, and the more complete\n * generic entry is unreachable from that URL. That both wastes the completed\n * request and can loop: a prefetch task that revalidated the segment reads\n * back the same stale entry, decides it needs to revalidate again, and\n * repeats forever.\n *\n * The upsert is the one moment we know the ordering between the two entries:\n * the candidate was produced by a request for this segment position, and\n * `lookupVaryPath` is the fully concrete path a read for that position\n * resolves against, so any entry that a read at that path would return in the\n * candidate's stead is directly comparable to it. If such an entry is settled\n * and the candidate supersedes it — under the same precedence rules the\n * upsert applies at its own keypath — we know we never want to match against\n * it again, so delete it, making the candidate reachable.\n *\n * Pending entries are never evicted here: they're owned by an in-flight\n * request that will settle them. Empty entries ARE evictable — they're\n * unclaimed placeholders with nothing in them, so they must not shadow real\n * data; their blocked tasks are pinged so they re-run against the candidate.\n */ function evictShadowingSegmentEntries(now, map, lookupVaryPath, candidateEntry) {\n // There can in principle be multiple shadowing entries at successively less\n // specific keypaths, so loop until the read returns the candidate (or an\n // entry we don't supersede). Each iteration re-reads and re-checks from\n // scratch (in part because `deleteFromCacheMap` can promote a settled\n // Revalidation-slot value into the just-vacated slot, surfacing a new entry\n // at the same keypath). Each iteration deletes an entry from the map, so\n // the loop terminates naturally; the bound is defensive, and 32 is far\n // beyond any real fallback chain, which is bounded by the vary\n // path's length.\n for(let i = 0; i < 32; i++){\n const shadowEntry = getFromCacheMap(now, getCurrentSegmentCacheVersion(), map, lookupVaryPath, false, false);\n if (shadowEntry === null || shadowEntry === candidateEntry) {\n // The candidate is reachable from the lookup path (or the read missed\n // entirely, e.g. because the candidate expired). Done.\n return;\n }\n if (shadowEntry.status === EntryStatus.Pending) {\n // A Pending entry may not be evicted: it's held by an in-flight\n // request and will settle on its own. (An Empty shadow entry, by\n // contrast, is an unclaimed placeholder with nothing in it — never\n // preferred over the candidate, per isExistingSegmentEntryPreferred —\n // so it falls through to the eviction below, waking any tasks blocked\n // on it so they re-run and find the candidate.)\n return;\n }\n if (isExistingSegmentEntryPreferred(shadowEntry, candidateEntry)) {\n // The shadowing entry is preferred over the candidate (e.g. it's a\n // complete entry fetched with a more specific strategy). Leave it —\n // reads at this path should keep matching it.\n return;\n }\n // The candidate supersedes the shadowing entry. Evict it. Settled entries\n // shouldn't have blocked tasks (Fulfilled always has `blockedTasks:\n // null`, and Rejected entries were pinged at rejection), but an Empty\n // entry may have them — ping before deleting, matching the upsert-evict\n // pattern above.\n pingBlockedTasks(shadowEntry);\n deleteFromCacheMap(shadowEntry);\n }\n}\nexport function createDetachedSegmentCacheEntry(now) {\n // Default stale time for pending segment cache entries. The actual stale time\n // is set when the entry is fulfilled with data from the server response.\n const staleAt = now + 30 * 1000;\n const emptyEntry = {\n status: EntryStatus.Empty,\n blockedTasks: null,\n // Default to assuming the fetch strategy will be PPR. This will be updated\n // when a fetch is actually initiated.\n fetchStrategy: FetchStrategy.PPR,\n rsc: null,\n isPartial: true,\n isUpgradeableISRFallback: false,\n promise: null,\n // Map-related fields\n ref: null,\n size: 0,\n staleAt,\n version: 0\n };\n return emptyEntry;\n}\nexport function upgradeToPendingSegment(emptyEntry, fetchStrategy) {\n const pendingEntry = emptyEntry;\n pendingEntry.status = EntryStatus.Pending;\n pendingEntry.fetchStrategy = fetchStrategy;\n if (fetchStrategy === FetchStrategy.Full) {\n // The Pending-Full convention: pre-set isPartial to false before any\n // data exists. Normally partiality is absolute — anything unresolved in\n // the entry's output makes it true, and a pending entry has no output at\n // all — but a Full response is a complete navigation payload, so this\n // segment may already be omitted from navigation requests that happen\n // while the data is still in flight. That \"may be omitted\" signal is\n // exactly what isPartial: false means to a navigation, so this\n // deliberately breaks the absolute definition for the pending window.\n pendingEntry.isPartial = false;\n }\n // Set the version here, since this is right before the request is initiated.\n // The next time the segment cache version is incremented, the entry will\n // effectively be evicted. This happens before initiating the request, rather\n // than when receiving the response, because it's guaranteed to happen\n // before the data is read on the server.\n pendingEntry.version = getCurrentSegmentCacheVersion();\n return pendingEntry;\n}\nexport function attemptToFulfillDynamicSegmentFromBFCache(now, segment, tree) {\n // Attempts to fulfill an empty segment cache entry using data from the\n // bfcache. This is only valid during a Full prefetch (i.e. one that includes\n // dynamic data), because the bfcache stores data from navigations which\n // always include dynamic data.\n // We always use the canonical vary path when checking the bfcache. This is\n // the same operation we'd use to access the cache during a\n // regular navigation.\n const varyPath = tree.varyPath;\n // Read from the BFCache without expiring it (pass -1). We check freshness\n // ourselves using navigatedAt, because the BFCache's staleAt may have been\n // overridden by a per-page unstable_dynamicStaleTime and can't be used to\n // derive the original request time.\n const bfcacheEntry = readFromBFCache(varyPath);\n if (bfcacheEntry !== null) {\n // The stale time for dynamic prefetches (default: 5 mins) is different\n // from the stale time for regular navigations (default: 0 secs). Use\n // navigatedAt to compute the correct expiry for prefetch purposes.\n const dynamicPrefetchStaleAt = bfcacheEntry.navigatedAt + STATIC_STALETIME_MS;\n if (now > dynamicPrefetchStaleAt) {\n return null;\n }\n const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full);\n const isPartial = false;\n return fulfillSegmentCacheEntry(pendingSegment, bfcacheEntry.rsc, dynamicPrefetchStaleAt, isPartial, bfcacheEntry.varyParams, // bfcache data is concrete, never an ISR fallback.\n false, FetchStrategy.Full);\n }\n return null;\n}\n/**\n * Attempts to replace an existing segment cache entry with data from the\n * bfcache. Unlike `attemptToFulfillDynamicSegmentFromBFCache` (which fills an\n * empty entry), this creates a new entry and upserts it, so it works even when\n * the segment is already fulfilled.\n */ export function attemptToUpgradeSegmentFromBFCache(now, // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\nmap, tree) {\n const varyPath = tree.varyPath;\n const bfcacheEntry = readFromBFCache(varyPath);\n if (bfcacheEntry !== null) {\n const dynamicPrefetchStaleAt = bfcacheEntry.navigatedAt + STATIC_STALETIME_MS;\n if (now > dynamicPrefetchStaleAt) {\n return null;\n }\n const pendingSegment = upgradeToPendingSegment(createDetachedSegmentCacheEntry(now), FetchStrategy.Full);\n const isPartial = false;\n const newEntry = fulfillSegmentCacheEntry(pendingSegment, bfcacheEntry.rsc, dynamicPrefetchStaleAt, isPartial, bfcacheEntry.varyParams, // bfcache data is concrete, never an ISR fallback.\n false, FetchStrategy.Full);\n const segmentVaryPath = getSegmentVaryPathForRequest(FetchStrategy.Full, tree);\n const upserted = upsertSegmentEntry(now, map, segmentVaryPath, newEntry, // The concrete lookup path this BFCache upgrade applies to. (In\n // practice a Full request path is already fully concrete, so nothing\n // can shadow the new entry and the shadow check is a no-op.)\n tree.varyPath);\n if (upserted !== null && upserted.status === EntryStatus.Fulfilled) {\n return upserted;\n }\n }\n return null;\n}\nfunction pingBlockedTasks(entry) {\n const blockedTasks = entry.blockedTasks;\n if (blockedTasks !== null) {\n for (const task of blockedTasks){\n pingPrefetchTask(task);\n }\n entry.blockedTasks = null;\n }\n}\n/**\n * The head's request key on the client. The server's own key for the head,\n * HEAD_REQUEST_KEY, carries no path information: there is only one head per\n * URL, so the server has no need to distinguish parallel pages. On the client\n * the request key is the head's cache identity and what doesRouteStructureMatch\n * compares, so the head takes its page's request key with HEAD_REQUEST_KEY\n * appended — the key the server would have assigned had the head been a\n * segment below the page — and two pages' heads never match. The head varies\n * on the same params as its page, so the rest of its vary path is the page's.\n * The page must be the route's own: a page in a slot retained from another\n * URL (one with a refresh state) belongs to that URL's head. When a route has\n * multiple parallel pages of its own, the first one is used; the keys only\n * differ in route groups and slot names, so any of them works as long as it\n * is always the same one.\n */ export function getHeadRequestKey(pageRequestKey) {\n return pageRequestKey + HEAD_REQUEST_KEY;\n}\nexport function createMetadataRouteTree(metadataVaryPath, // The route root's prefetch hints. The head has no node of its own on the\n// wire, so the route-level hint that applies to it is copied from the root.\nrootPrefetchHints, // The head's payload, with the same lifetimes as a segment node's `data`\n// (see RouteTree): null in the route cache, the response's decoded\n// head on a navigation seed, a CacheNode on the router state.\ndata) {\n // The head is a one-node tree beside the route tree (see RootRouteTree). It\n // has no position in the route tree, but it's fetched, cached, compared, and\n // rendered like a segment, so it is a RouteTree node like any other.\n const metadata = {\n // The first entry of the head's vary path (see getHeadRequestKey). The\n // server knows nothing of this key; it is always asked for\n // HEAD_REQUEST_KEY, which is why the segment stays the bare marker.\n requestKey: metadataVaryPath.value,\n segment: HEAD_REQUEST_KEY,\n shellVaryPath: getShellSegmentVaryPath(metadataVaryPath),\n refreshState: null,\n data,\n varyPath: metadataVaryPath,\n slots: null,\n // Only the static-attempt bits apply to the head: it's a route-level\n // fact (\"static per-segment responses may exist for this route\"), and\n // it's what lets a shell-tier cached head attempt a static head fetch\n // before deopting to a runtime request (see the shell-tier eligibility\n // check in pingSegmentBundle). The other bits describe tree structure\n // the head doesn't participate in.\n prefetchHints: rootPrefetchHints & StaticAttemptHints\n };\n return metadata;\n}\n/**\n * Returns an equivalent tree with `data: null` at every node, cloning only\n * the subtrees that carry data. Called when a tree is stored in the route\n * cache: route cache entries live indefinitely, so retaining render output\n * there would pin RSC payloads in memory outside the segment cache's eviction\n * control. See the lifecycle note on RouteTree.\n */ function stripDataFromRouteTree(tree) {\n let clonedSlots = null;\n const slots = tree.slots;\n if (slots !== null) {\n for (const [parallelRouteKey, childTree] of slots){\n const strippedChild = stripDataFromRouteTree(childTree);\n if (strippedChild !== childTree && clonedSlots === null) {\n // Sound cast: any copied value that isn't overwritten below is one\n // where stripDataFromRouteTree returned the child unchanged, which\n // means that subtree carries no data.\n clonedSlots = new Map(slots);\n }\n if (clonedSlots !== null) {\n clonedSlots.set(parallelRouteKey, strippedChild);\n }\n }\n }\n if (tree.data === null && clonedSlots === null) {\n // Neither this node nor any descendant carries data. Reuse it as-is.\n // This is the common case for trees that never carried render output\n // (e.g. route tree prefetch responses). Sound cast for the same reason.\n return tree;\n }\n // Sound cast: clonedSlots is null here only if every child subtree was\n // verified data-free by the loop above.\n const strippedSlots = clonedSlots ?? slots;\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n shellVaryPath: tree.shellVaryPath,\n refreshState: tree.refreshState,\n data: null,\n varyPath: tree.varyPath,\n slots: strippedSlots,\n prefetchHints: tree.prefetchHints\n };\n}\nexport function fulfillRouteCacheEntry(now, entry, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching) {\n const tree = root.tree;\n const fulfilledEntry = entry;\n fulfilledEntry.status = EntryStatus.Fulfilled;\n fulfilledEntry.root = createRootRouteTree(stripDataFromRouteTree(tree), stripDataFromRouteTree(root.head));\n // Route structure is essentially static — it only changes on deploy.\n // Always use the static stale time.\n // NOTE: An exception is rewrites/redirects in middleware or proxy, which can\n // change routes dynamically. We have other strategies for handling those.\n //\n // If the route tree has stale inlining hints (e.g. the initial RSC payload\n // for a build-time static page, generated before collectPrefetchHints ran),\n // immediately expire the entry so it gets re-fetched with correct hints.\n // The segment data itself is still valid — only the route tree (which\n // contains the hint bits) needs to be re-fetched.\n if (tree.prefetchHints & PrefetchHint.InliningHintsStale) {\n fulfilledEntry.staleAt = -1;\n } else {\n fulfilledEntry.staleAt = now + STATIC_STALETIME_MS;\n }\n fulfilledEntry.couldBeIntercepted = couldBeIntercepted;\n fulfilledEntry.canonicalUrl = canonicalUrl;\n fulfilledEntry.renderedSearch = renderedSearch;\n fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching;\n pingBlockedTasks(entry);\n return fulfilledEntry;\n}\nexport function writeRouteIntoCache(now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching) {\n const pendingEntry = createDetachedRouteCacheEntry();\n const fulfilledEntry = fulfillRouteCacheEntry(now, pendingEntry, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n const varyPath = getFulfilledRouteVaryPath(pathname, search, nextUrl, couldBeIntercepted);\n const isRevalidation = false;\n setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation);\n return fulfilledEntry;\n}\nfunction fulfillSegmentCacheEntry(segmentCacheEntry, rsc, staleAt, isPartial, varyParams, // Only static (per-segment PPR) responses can be ISR fallbacks; all other\n// callers pass false. Always assigned (even when false) so that re-fulfilling\n// a previously-fallback entry with a concrete response clears the flag and\n// ends the retry loop.\nisUpgradeableISRFallback, // The strategy tier describing the CONTENT this entry is fulfilled with —\n// which comes from the response, not the tier the entry was requested at.\n// Usually the two agree, but when a response's shell payload IS the full\n// response (no shell/full split), shell-spawned entries are fulfilled with\n// full-tier content and recorded as such (see the promotion in\n// writeSegmentDataIntoCache). Always assigned, replacing\n// the spawn-time strategy set by upgradeToPendingSegment; the write walks'\n// matching and keying decisions all happen against the spawn-time\n// strategy, before fulfillment, so they are unaffected. See\n// SegmentCacheEntryShared['fetchStrategy'].\nfetchStrategy) {\n const fulfilledEntry = segmentCacheEntry;\n fulfilledEntry.status = EntryStatus.Fulfilled;\n fulfilledEntry.rsc = rsc;\n fulfilledEntry.staleAt = staleAt;\n fulfilledEntry.isPartial = isPartial;\n fulfilledEntry.varyParams = varyParams;\n fulfilledEntry.isUpgradeableISRFallback = isUpgradeableISRFallback;\n fulfilledEntry.fetchStrategy = fetchStrategy;\n // Resolve any listeners that were waiting for this data.\n if (segmentCacheEntry.promise !== null) {\n segmentCacheEntry.promise.resolve(fulfilledEntry);\n // Free the promise for garbage collection.\n fulfilledEntry.promise = null;\n }\n pingBlockedTasks(segmentCacheEntry);\n return fulfilledEntry;\n}\nfunction rejectRouteCacheEntry(entry, staleAt) {\n const rejectedEntry = entry;\n rejectedEntry.status = EntryStatus.Rejected;\n rejectedEntry.staleAt = staleAt;\n pingBlockedTasks(entry);\n}\nfunction rejectSegmentCacheEntry(entry, staleAt) {\n const rejectedEntry = entry;\n rejectedEntry.status = EntryStatus.Rejected;\n rejectedEntry.staleAt = staleAt;\n if (entry.promise !== null) {\n // NOTE: We don't currently propagate the reason the prefetch was canceled\n // but we could by accepting a `reason` argument.\n entry.promise.resolve(null);\n entry.promise = null;\n }\n pingBlockedTasks(entry);\n}\nexport function convertRootFlightRouterStateToRouteTree(flightRouterState, renderedSearch, acc) {\n return convertFlightRouterStateToRouteTree(flightRouterState, ROOT_SEGMENT_REQUEST_KEY, null, renderedSearch, acc);\n}\nexport function rebaseInactiveRouteTree(treeToRebase) {\n // A parallel route slot that the target route doesn't provide keeps the\n // slot already active on the current route, under the new parent. The slot\n // sits at the same route position, so its request keys and vary paths are\n // unchanged: copy the structure and drop the payloads, which belong to the\n // previous render and are reused separately by render-tree.\n let slots = null;\n if (treeToRebase.slots !== null) {\n slots = new Map();\n for (const [parallelRouteKey, child] of treeToRebase.slots){\n slots.set(parallelRouteKey, rebaseInactiveRouteTree(child));\n }\n }\n return {\n requestKey: treeToRebase.requestKey,\n segment: treeToRebase.segment,\n varyPath: treeToRebase.varyPath,\n shellVaryPath: treeToRebase.shellVaryPath,\n refreshState: treeToRebase.refreshState,\n data: null,\n slots,\n prefetchHints: treeToRebase.prefetchHints\n };\n}\nexport function convertFlightRouterStateToRouteTree(flightRouterState, requestKey, parentPartialVaryPath, parentRenderedSearch, acc) {\n const originalSegment = flightRouterState[0];\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = ((flightRouterState[4] ?? 0) & PrefetchHint.IsRootLayoutOrAbove) !== 0;\n // If the FlightRouterState has a refresh state, then this segment is part of\n // an inactive parallel route. It has a different rendered search query than\n // the outer parent route. In order to construct the inactive route correctly,\n // we must restore the query that was originally used to render it.\n const compressedRefreshState = flightRouterState[2] ?? null;\n const refreshState = compressedRefreshState !== null ? {\n canonicalUrl: compressedRefreshState[0],\n renderedSearch: compressedRefreshState[1]\n } : null;\n // Use the incoming search params, even if the response has no new data for\n // this segment. The base tree may still have the previous URL's. History\n // restores pass in their saved search params instead.\n const renderedSearch = refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch;\n const tree = createRouteTreeNode(originalSegment, isRootParam, requestKey, parentPartialVaryPath, renderedSearch, refreshState, acc);\n const partialVaryPath = getPartialVaryPath(tree.varyPath);\n let slots = null;\n const parallelRoutes = flightRouterState[1];\n for(let parallelRouteKey in parallelRoutes){\n const childRouterState = parallelRoutes[parallelRouteKey];\n const childSegment = childRouterState[0];\n // TODO: Eventually, the param values will not be included in the response\n // from the server. We'll instead fill them in on the client by parsing\n // the URL. This is where we'll do that.\n const childRequestKeyPart = createSegmentRequestKeyPart(childSegment);\n const childRequestKey = appendSegmentRequestKeyPart(requestKey, parallelRouteKey, childRequestKeyPart);\n const childTree = convertFlightRouterStateToRouteTree(childRouterState, childRequestKey, partialVaryPath, renderedSearch, acc);\n if (slots === null) {\n slots = new Map();\n }\n slots.set(parallelRouteKey, childTree);\n }\n tree.slots = slots;\n tree.prefetchHints = flightRouterState[4] ?? 0;\n return tree;\n}\nexport function convertRouteTreeToFlightRouterState(routeTree) {\n const parallelRoutes = {};\n const slots = routeTree.slots;\n if (slots !== null) {\n for (const [parallelRouteKey, childTree] of slots){\n parallelRoutes[parallelRouteKey] = convertRouteTreeToFlightRouterState(childTree);\n }\n }\n const flightRouterState = [\n routeTree.segment,\n parallelRoutes,\n null,\n null\n ];\n if (routeTree.prefetchHints !== 0) {\n flightRouterState[4] = routeTree.prefetchHints;\n }\n return flightRouterState;\n}\nexport async function fetchRouteOnCacheMiss(entry, key) {\n // This function is allowed to use async/await because it contains the actual\n // fetch that gets issued on a cache miss. Notice it writes the result to the\n // cache entry directly, rather than return data that is then written by\n // the caller.\n const pathname = key.pathname;\n const search = key.search;\n const nextUrl = key.nextUrl;\n const segmentPath = '/_tree';\n const headers = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: segmentPath\n };\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl;\n }\n try {\n const url = new URL(pathname + search, location.origin);\n let response;\n let urlAfterRedirects;\n if (isOutputExportMode) {\n // In output: \"export\" mode, we can't use headers to request a particular\n // segment. Instead, we encode the extra request information into the URL.\n // This is not part of the \"public\" interface of the app; it's an internal\n // Next.js implementation detail that the app developer should not need to\n // concern themselves with.\n //\n // For example, to request a segment:\n //\n // Path passed to <Link>: /path/to/page\n // Path passed to fetch: /path/to/page/__next-segments/_tree\n //\n // (This is not the exact protocol, just an illustration.)\n //\n // Before we do that, though, we need to account for redirects. Even in\n // output: \"export\" mode, a proxy might redirect the page to a different\n // location, but we shouldn't assume or expect that they also redirect all\n // the segment files, too.\n //\n // To check whether the page is redirected, previously we perform a range\n // request of 64 bytes of the HTML document to check if the target page\n // is part of this app (by checking if build id matches). Only if the target\n // page is part of this app do we determine the final canonical URL.\n //\n // However, as mentioned in https://github.com/vercel/next.js/pull/85903,\n // some popular static hosting providers (like Cloudflare Pages or Render.com)\n // do not support range requests, in the worst case, the entire HTML instead\n // of 64 bytes could be returned, which is wasteful.\n //\n // So instead, we drops the check for build id here, and simply perform\n // a HEAD request to rejects 1xx/4xx/5xx responses, and then determine the\n // final URL after redirects.\n //\n // NOTE: We could embed the route tree into the HTML document, to avoid\n // a second request. We're not doing that currently because it would make\n // the HTML document larger and affect normal page loads.\n const headResponse = await fetch(url, {\n method: 'HEAD'\n });\n if (headResponse.status < 200 || headResponse.status >= 400) {\n // The target page responded w/o a successful status code\n // Could be a WAF serving a 403, or a 5xx from a backend\n //\n // Note that we can't use headResponse.ok here, because\n // Response#ok returns `false` with 3xx responses.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n urlAfterRedirects = headResponse.redirected ? new URL(headResponse.url) : url;\n response = await fetchPrefetchResponse(addSegmentPathToUrlInOutputExportMode(urlAfterRedirects, segmentPath), headers);\n } else {\n // \"Server\" mode. We can use request headers instead of the pathname.\n // TODO: The eventual plan is to get rid of our custom request headers and\n // encode everything into the URL, using a similar strategy to the\n // \"output: export\" block above.\n response = await fetchPrefetchResponse(url, headers);\n urlAfterRedirects = response !== null && response.redirected ? new URL(response.url) : url;\n }\n if (!response || !response.ok || !response.body) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n // TODO: The canonical URL is the href without the origin. I think\n // historically the reason for this is because the initial canonical URL\n // gets passed as a prop to the top-level React component, which means it\n // needs to be computed during SSR. If it were to include the origin, it\n // would need to always be same as location.origin on the client, to prevent\n // a hydration mismatch. To sidestep this complexity, we omit the origin.\n //\n // However, since this is neither a native URL object nor a fully qualified\n // URL string, we need to be careful about how we use it. To prevent subtle\n // mistakes, we should create a special type for it, instead of just string.\n // Or, we should just use a (readonly) URL object instead. The type of the\n // prop that we pass to seed the initial state does not need to be the same\n // type as the state itself.\n const canonicalUrl = createHrefFromUrl(urlAfterRedirects);\n // Check whether the response varies based on the Next-Url header.\n const varyHeader = response.headers.get('vary');\n const couldBeIntercepted = varyHeader !== null && varyHeader.includes(NEXT_URL);\n // TODO: The `closed` promise was originally used to track when a streaming\n // network connection closes, so the scheduler could limit concurrent\n // connections. Now that prefetch responses are buffered, `closed` is\n // resolved immediately after buffering — before the outer function even\n // returns. This mechanism is only still meaningful for dynamic (Full)\n // prefetches, which use incremental streaming. Consider removing the\n // `closed` plumbing for buffered prefetch paths.\n const closed = createPromiseWithResolvers();\n // Note this doesn't imply PPR is enabled for the route: fully static\n // routes serve from the per-segment cache too. What it does tell us is\n // that per-segment prefetching is supported, which is what the route\n // entry records below.\n const supportsPerSegmentPrefetching = wasServedFromPerSegmentCache(response);\n // Decode the response. Routes that support per-segment prefetching\n // respond from static storage; other routes respond with a live render\n // (see the isRouteTreePrefetchRequest branch in\n // walk-tree-with-flight-router-state). Both are\n // NavigationFlightResponses carrying a buildId and a structure-only\n // transport tree — which is all this flow reads — so one decode path\n // serves both.\n const buffer = await bufferPrefetchResponseBody(response.body);\n closed.resolve();\n setSizeInCacheMap(entry, buffer.byteLength);\n const serverData = await decodeBufferedStage(buffer, headers);\n if ((response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b) !== getNavigationBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: We should cache the fact that this is an MPA navigation.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n const transportData = serverData.t;\n if (transportData === undefined || serverData.n !== undefined) {\n // The response carries no route tree (e.g. it's an MPA navigation), so\n // there's nothing to cache.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n // Get the params that were used to render the target page. These may\n // be different from the params in the request URL, if the page\n // was rewritten. The rendered pathname is also used to fill in the param\n // values the server omitted from the response (omitting them keeps the\n // response cacheable across param values).\n const renderedPathname = getRenderedPathname(response);\n const renderedSearch = getRenderedSearch(response);\n // Decode the server-sent tree into the RouteTree format used by the\n // client cache.\n //\n // During this traversal, we accumulate additional data into this\n // \"accumulator\" object.\n const acc = {\n metadataVaryPath: null,\n treeDivergedFromBase: false\n };\n const routeTree = decodeTransportTreeIntoRouteTree(transportData.t, null, // The tree is structure-only (no data nodes), so there are no vary\n // params to decode...\n null, // ...and no partiality either; the conservative value is never read.\n true, renderedPathname, renderedSearch, acc);\n const metadataVaryPath = acc.metadataVaryPath;\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n discoverKnownRoute(Date.now(), pathname, search, nextUrl, entry, {\n tree: routeTree,\n head: createMetadataRouteTree(metadataVaryPath, routeTree.prefetchHints, null)\n }, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching, false // hasDynamicRewrite\n );\n if (!couldBeIntercepted) {\n // This route will never be intercepted. So we can use this entry for all\n // requests to this route, regardless of the Next-Url header. This works\n // because when reading the cache we always check for a valid\n // non-intercepted entry first.\n // Re-key the entry. The `set` implementation handles removing it from\n // its previous position in the cache. We don't need to do anything to\n // update the LRU, because the entry is already in it.\n // TODO: Treat this as an upsert — should check if an entry already\n // exists at the new keypath, and if so, whether we should keep that\n // one instead.\n const fulfilledVaryPath = getFulfilledRouteVaryPath(pathname, search, nextUrl, couldBeIntercepted);\n const isRevalidation = false;\n setInCacheMap(routeCacheMap, fulfilledVaryPath, entry, isRevalidation);\n }\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n return {\n value: null,\n closed: closed.promise\n };\n } catch (error) {\n // Either the connection itself failed, or something bad happened while\n // decoding the response.\n rejectRouteCacheEntry(entry, getPrefetchErrorStaleAt(error));\n return null;\n }\n}\n// When a static (per-segment PPR) prefetch receives an upgradeable fallback\n// shell, the localized retry loop re-issues the same fetch after this delay to\n// pick up the concrete version once the server's background regeneration\n// finishes.\nconst FALLBACK_RETRY_DELAY_MS = 2000;\n// Maximum number of fallback retries per task, to avoid looping indefinitely\n// if the server keeps returning a fallback (e.g. misconfiguration).\nconst MAX_FALLBACK_RETRIES = 3;\nexport async function fetchSegmentPrefetchesUsingStaticRequest(task, route, routeKey, tree, // The pending cache entries this task spawned for the bundle, keyed by\n// segment request key. The response fulfills them when it arrives.\nspawnedEntries, // Which walk spawned the bundle's entries. The request on the wire is\n// identical either way; this only decides which payload of the response\n// fulfills the entries.\nfetchStrategy) {\n // This function is allowed to use async/await because it contains the actual\n // fetch that gets issued on a cache miss. Notice it writes the result to the\n // cache entry directly, rather than return data that is then written by\n // the caller.\n //\n // Segment fetches are non-blocking so we don't need to ping the scheduler\n // on completion.\n let isUpgradeableISRFallback;\n try {\n isUpgradeableISRFallback = await fetchAndWritePerSegmentPrefetchResponse(task, route, routeKey, tree, spawnedEntries, fetchStrategy, // Write the response even if it's an upgradeable fallback shell — the\n // fallback content is better than nothing while the retry loop waits\n // for the concrete version.\n false);\n } catch (error) {\n // The connection failed, or the response couldn't be decoded. Reject the\n // pending entries so they don't stay Pending forever, and get retried\n // once the entry expires.\n rejectSegmentEntriesIfStillPending(spawnedEntries, getPrefetchErrorStaleAt(error));\n return null;\n }\n if (isUpgradeableISRFallback === null) {\n // The response was fetched but isn't usable yet (server error/miss, empty\n // data, or a build-id mismatch — the server may be transiently unready).\n // Reject with a short backoff so the entries are retried soon.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n return {\n value: null,\n // The response is fully buffered before it's decoded, so the network\n // connection is already closed by the time the fetch returns. See TODO\n // in fetchRouteOnCacheMiss about removing `closed` for buffered\n // prefetch paths.\n closed: Promise.resolve()\n };\n}\n/**\n * Issues a single segment-bundle prefetch request, validates and decodes the\n * response, and writes every payload of it into the cache — the full\n * payload, and, when the response carries a shell byte boundary, a second\n * decode of the same bytes truncated at that boundary, the segments'\n * shell-stage variant — through the shared payload-write orchestration\n * (writeResponsePayloadsIntoCache), which owns which payload fulfills the\n * spawned entries and the tier each payload is written at.\n *\n * Returns whether the response was an upgradeable ISR fallback shell (the\n * page hadn't been prerendered with concrete params yet), or `null` if the\n * response was fetched but isn't usable yet (server error/miss, empty data,\n * or a build-id mismatch — the server may be transiently unready, so it's\n * worth retrying; nothing is written and no entries are rejected). THROWS if\n * the connection failed or the response couldn't be decoded; re-issuing the\n * identical request won't fix that, so callers should give up rather\n * than retry.\n *\n * When the response is an upgradeable fallback shell, this also starts the\n * task's localized fallback-retry loop (at most one per task, ever), BEFORE\n * writing the fallback content — see the comment on the transition below.\n *\n * Calling this again with the same arguments reproduces the exact same\n * request. The retry loop uses that to re-issue the request until the server\n * has the concrete version, passing `discardFallbackResponse` so a response\n * that is STILL a fallback isn't pointlessly re-written over the identical\n * fallback content the initial fetch already cached. (The retry's entries\n * are already settled, so its writes are all detached upserts.)\n */ async function fetchAndWritePerSegmentPrefetchResponse(task, route, routeKey, tree, spawnedEntries, fetchStrategy, // When true, a response that is still an upgradeable fallback shell is\n// discarded instead of written (the fallback-retry loop's re-issued\n// requests).\ndiscardFallbackResponse) {\n // Use the canonical URL to request the segment, not the original URL. These\n // are usually the same, but the canonical URL will be different if the route\n // tree response was redirected. To avoid an extra waterfall on every segment\n // request, we pass the redirected URL instead of the original one.\n const url = new URL(route.canonicalUrl, location.origin);\n const nextUrl = routeKey.nextUrl;\n let normalizedRequestKey;\n if (tree.segment === HEAD_REQUEST_KEY) {\n // The head's request key is its client cache identity; the server only\n // knows the head by its bare marker, which is also the head node's\n // segment (see createMetadataRouteTree).\n normalizedRequestKey = HEAD_REQUEST_KEY;\n } else if (tree.requestKey === ROOT_SEGMENT_REQUEST_KEY) {\n // The root segment is a special case. To simplify the server-side\n // handling of these requests, we encode the root segment path as\n // `_index` instead of as an empty string. This should be treated as\n // an implementation detail and not as a stable part of the protocol.\n // It just needs to match the equivalent logic that happens when\n // prerendering the responses. It should not leak outside of Next.js.\n normalizedRequestKey = '/_index';\n } else {\n normalizedRequestKey = tree.requestKey;\n }\n const headers = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: normalizedRequestKey\n };\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl;\n }\n const requestUrl = isOutputExportMode ? addSegmentPathToUrlInOutputExportMode(url, normalizedRequestKey) : url;\n const response = await fetchPrefetchResponse(requestUrl, headers);\n if (!response || !response.ok || // Theoretically this check should never fail, because we only issue\n // requests for segments once we've verified that the route supports PPR.\n !wasServedFromPerSegmentCache(response) || !response.body) {\n // Server responded with an error or a miss — fetched but not usable.\n return null;\n }\n const buffer = await bufferPrefetchResponseBody(response.body);\n // Parse the response. Always a PrefetchFlightResponse. A connection drop\n // or malformed stream throws here, which propagates to the caller as a\n // non-retryable failure.\n const serverResponse = await decodeBufferedStage(buffer, headers);\n if (serverResponse.t === undefined) {\n // The response carries no segment data at all — not usable.\n // writeServerResponseIntoCache checks this again, but this fetch-layer\n // copy is deliberate: it must run before the fallback-retry loop is\n // started and before the payload writes below, neither of which should\n // happen for an empty response.\n return null;\n }\n if ((response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverResponse.b) !== getNavigationBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n return null;\n }\n // True if the server served an upgradeable fallback shell (the page hadn't\n // been prerendered with concrete params yet, but the route can be\n // upgraded once the server's background regeneration finishes).\n const isUpgradeableISRFallback = serverResponse.f === true;\n if (isUpgradeableISRFallback) {\n if (discardFallbackResponse) {\n // Still a fallback — the server hasn't finished regenerating. Don't\n // write it; the retry loop will re-issue the request.\n return true;\n }\n // Drive a localized retry loop to pick up the concrete version once the\n // server's background regeneration finishes. Only the first fallback\n // response per task starts a loop (`fallbackRetryStatus === Empty`);\n // once it leaves Empty, no second loop is started — sibling bundle\n // responses that also got a fallback don't, and neither does a re-hover.\n //\n // The transition to Pending must happen BEFORE the fallback content is\n // written below: fulfilling an entry pings the tasks blocked on it, and\n // a scheduler pass that ran before the transition would observe a\n // fulfilled fallback entry with the retry gate still Empty and spawn a\n // duplicate revalidation request (see isUpgradeableISRFallbackRetry in\n // pingSegmentBundle in scheduler.ts).\n if (task.fallbackRetryStatus === EntryStatus.Empty && !task.isCanceled) {\n task.fallbackRetryStatus = EntryStatus.Pending;\n // Fire-and-forget: the loop drives itself via timers and pings the\n // task on success.\n void retryUpgradeableFallbackPrefetch(task, route, routeKey, tree, spawnedEntries, fetchStrategy);\n }\n }\n // Extract the shell payload, if the response carries a distinct one\n // (positive shell byte offset): decode the buffered bytes a SECOND time,\n // truncated at the boundary. The truncation is what produces the shell\n // variant: each segment's param-dependent rows land past the boundary and\n // decode as still-pending, which renders as the param fallback. It also\n // rewinds the response's signals — `needsRuntimeRequest` and `isPartial`\n // fulfillments past the boundary read as pending in this decode, so a\n // post-shell runtime-data access doesn't mark the shell variant itself as\n // needing a runtime request.\n // (A 0 offset means the response carries no shell: the server emits a\n // fulfilled 0 when the page wasn't staged at all — see the `a` resolution\n // in collect-segment-data — and 0 is also the default read of an\n // unfulfilled `a`, which would be a Next.js bug since the full buffer is\n // present. Both read the same here: no shell, and the scheduler skips the\n // affected segments rather than falling back to a runtime request — see\n // the no-shell handling in writeResponsePayloadsIntoCache. Failing in that\n // direction costs a shell prefetch but never leaks post-shell content into\n // shell positions. 0 can double as \"none\" on the wire precisely because\n // it's never a valid offset — see the `a` field doc on\n // NavigationFlightResponse.)\n const shellOffset = serverResponse.a !== undefined ? readFulfilledValue(serverResponse.a, 0) : 0;\n let shellResponse;\n if (shellOffset === null) {\n shellResponse = serverResponse;\n } else if (shellOffset === 0) {\n shellResponse = null;\n } else {\n try {\n shellResponse = await decodeBufferedStage(buffer.subarray(0, shellOffset), headers);\n } catch {\n // The truncated prefix couldn't be decoded. Treat it as if no shell\n // exists; the full payload is still usable. (For a StaticShell-spawned\n // bundle this means the spawned entries are rejected — the scheduler\n // then skips them rather than issuing a runtime substitute; see the\n // no-shell handling in writeResponsePayloadsIntoCache.)\n shellResponse = null;\n }\n }\n // The pathname the page was rendered for, derived the same way the route\n // tree fetch derives it (the rewritten-path header when the request was\n // rewritten, the request URL otherwise) so the vary paths computed from\n // this response's decoded tree agree with the ones on the route entry's\n // tree. In output: \"export\" mode the response URL has the segment filename\n // appended to the pathname, so derive it from the page URL instead\n // (rewrites don't exist on a static host).\n const renderedPathname = isOutputExportMode ? getPathnameFromRequestURL(url) : getRenderedPathname(response);\n // Write the payloads into the cache. Each payload is decoded like any\n // other server response — a root-anchored tree plus an optional head, with\n // no base overlay (the response covers its own spine) — and written\n // through the same path as a live-render response. Notes on the\n // arguments:\n // - Dynamic segments the server sent without a param value (`k: null`) are\n // parsed from the rendered pathname, and the rendered search is the one\n // the route tree was built with, so the decoded tree's vary paths agree\n // with the ones on the route entry's tree.\n // - The build id was already verified above, so none is passed.\n // - The response-level staleness is only a fallback, for segments that\n // don't carry their own staleTime (per-segment responses normally\n // always do).\n // - Response-level partiality is unused for per-segment writes — each\n // segment (and the head) carries its own partiality via the staged\n // promise encoding, which the decode reads in preference to the\n // response-level value — so the conservative value (true) is passed.\n // - The head is keyed at the route's own metadata vary path: the head has\n // no tree position, so the decode could only derive a vary path for it\n // from a page node in the payload's own tree. A per-segment response\n // carries only the spine from the root to the requested segment, so any\n // response whose terminal isn't a page has no page node to key the head\n // from; the standalone head response is one such case.\n const now = Date.now();\n const metadataVaryPath = route.root.head.varyPath;\n writeResponsePayloadsIntoCache(now, fetchStrategy, serverResponse, shellResponse, null, // The payloads are root-anchored (no base tree), so there's no\n // prediction to diverge from.\n null, renderedPathname, route.renderedSearch, undefined, now + STATIC_STALETIME_MS, true, metadataVaryPath, spawnedEntries, buffer.byteLength, task.segmentCacheMap);\n return isUpgradeableISRFallback;\n}\n/**\n * Reads a stale-at time from the staleTime async iterable of a fully-buffered\n * response — stage decodes, which go through\n * `bufferPrefetchResponseBody`. Drains synchronously via\n * `readFulfilledStaleTimeSeconds` (see decode-server-response). A missing\n * iterable, or a truncated shell decode whose value landed past the\n * boundary, reads as absent and falls back to the static stale time.\n *\n * For the one response kind that isn't buffered when read — a dynamic `Full`\n * response (fetchStrategy.Full with Partial Prefetching disabled) — use\n * `resolveStaleAt` instead, since its values aren't materialized synchronously.\n */ function readFulfilledStaleAt(now, staleTime) {\n if (staleTime === undefined) {\n return now + STATIC_STALETIME_MS;\n }\n const staleTimeSeconds = readFulfilledStaleTimeSeconds(staleTime);\n if (staleTimeSeconds === null) {\n return now + STATIC_STALETIME_MS;\n }\n return now + getStaleTimeMs(staleTimeSeconds);\n}\n/**\n * The localized retry loop for an upgradeable fallback shell. Re-issues the\n * exact same segment-bundle request up to MAX_FALLBACK_RETRIES times,\n * FALLBACK_RETRY_DELAY_MS apart, until the server returns the concrete\n * (upgraded) version. The fetch writes the upgraded response through the\n * same payload writes as the initial fetch, so every slot the initial fetch\n * wrote — including the shell paths, even when the upgraded response is\n * fully static (shell === full) — is upgraded; the spawned entries were\n * already settled by the initial fetch, so every write is a detached upsert\n * that replaces the fallback. On success the loop pings the task, so the\n * task's *other* fallback segments get re-attempted. If every attempt is\n * still a fallback (or fails), it gives up.\n *\n * A loop runs at most once per task, ever (fetchAndWritePerSegmentPrefetchResponse\n * gates on `fallbackRetryStatus === Empty`, set to `Pending` before this runs\n * and never reset to `Empty`). The sleep timer is never `clearTimeout`-ed, so\n * the awaited sleep always settles; the loop simply checks `isCanceled` after\n * waking and bails if the task was canceled in the meantime. On success the\n * status becomes `Fulfilled`; on any non-success exit (exhausted retries,\n * fetch error, or cancel) it becomes `Rejected`.\n */ async function retryUpgradeableFallbackPrefetch(task, route, routeKey, tree, spawnedEntries, // The strategy the initial fetch wrote its payloads with.\nfetchStrategy) {\n for(let attempt = 0; attempt < MAX_FALLBACK_RETRIES; attempt++){\n await new Promise((resolve)=>setTimeout(resolve, FALLBACK_RETRY_DELAY_MS));\n if (task.isCanceled) {\n break;\n }\n let isUpgradeableISRFallback;\n try {\n isUpgradeableISRFallback = await fetchAndWritePerSegmentPrefetchResponse(task, route, routeKey, tree, spawnedEntries, fetchStrategy, // A response that is still a fallback shell is discarded rather than\n // pointlessly re-written over the identical fallback content the\n // initial fetch already cached.\n true);\n } catch {\n break;\n }\n if (task.isCanceled) {\n break;\n }\n if (isUpgradeableISRFallback === null) {\n continue;\n }\n if (isUpgradeableISRFallback) {\n continue;\n }\n // Success: the server returned the concrete (upgraded) version, and the\n // fetch wrote it into the cache. The task's other fallback segments are\n // now allowed to revalidate.\n task.fallbackRetryStatus = EntryStatus.Fulfilled;\n pingPrefetchTask(task);\n return;\n }\n // The loop finished without success (exhausted its retries, broke out on a\n // fetch error, or the task was canceled). It won't run again for this task.\n task.fallbackRetryStatus = EntryStatus.Rejected;\n}\n// The runtime counterpart of the per-segment static prefetch flow\n// (fetchSegmentPrefetchesUsingStaticRequest). The two flows differ in how\n// they obtain their payloads — one runtime request here (streamed for Full\n// prefetches), versus a buffered per-segment response with a shell\n// double-decode there — but share the payload write orchestration\n// (writeResponsePayloadsIntoCache).\nexport async function fetchSegmentPrefetchesUsingRuntimeRequest(task, route, fetchStrategy, requestTree, spawnedEntries) {\n const key = task.key;\n const url = new URL(route.canonicalUrl, location.origin);\n const nextUrl = key.nextUrl;\n // When the request tree was derived from a predicted route entry, pass the\n // node it was predicted from to the write path so the prediction can be\n // disabled if the server's rendered tree diverges from it. For an entry\n // the server resolved this is null: a divergence from it says nothing\n // about route prediction, and its unfulfilled entries take the usual\n // backoff.\n let dynamicRequestTree;\n let predictedFrom;\n if (spawnedEntries.size === 1 && spawnedEntries.has(route.root.head.requestKey)) {\n // Only the head is pending, so ask the server for metadata only: it skips\n // the segments and renders just the head. The stub is not derived from\n // the route entry, so divergence from it carries no signal.\n dynamicRequestTree = MetadataOnlyRequestTree;\n predictedFrom = null;\n } else {\n dynamicRequestTree = requestTree;\n predictedFrom = route.predictedFrom;\n }\n const headers = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(dynamicRequestTree)\n };\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl;\n }\n switch(fetchStrategy){\n case FetchStrategy.Full:\n {\n break;\n }\n case FetchStrategy.PPRRuntime:\n {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '2';\n break;\n }\n case FetchStrategy.RuntimeShell:\n {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '3';\n break;\n }\n case FetchStrategy.LoadingBoundary:\n {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '1';\n break;\n }\n default:\n {\n fetchStrategy;\n }\n }\n try {\n const response = await fetchPrefetchResponse(url, headers);\n if (!response || !response.ok || !response.body) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n const renderedSearch = getRenderedSearch(response);\n if (renderedSearch !== route.renderedSearch) {\n // The search params that were used to render the target page are\n // different from the search params in the request URL. This only happens\n // when there's a dynamic rewrite in between the tree prefetch and the\n // data prefetch.\n // TODO: For now, since this is an edge case, we reject the prefetch, but\n // the proper way to handle this is to evict the stale route tree entry\n // then fill the cache with the new response.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + REJECTION_BACKOFF_MS);\n return null;\n }\n // Track when the network connection closes. Only meaningful for Full\n // (dynamic) prefetches which use incremental streaming. For buffered\n // paths, this is resolved immediately — see TODO in fetchRouteOnCacheMiss.\n const closed = createPromiseWithResolvers();\n let fulfilledEntries = null;\n let bufferedResponseSize = null;\n let serverDataPromise;\n if (fetchStrategy === FetchStrategy.Full) {\n // Full prefetches are dynamic responses stored in the prefetch cache.\n // They don't carry vary params or other cache metadata, so there's no\n // need to buffer them. Use the incremental version to allow data to be\n // processed as it arrives.\n const prefetchStream = createIncrementalPrefetchResponseStream(response.body, closed.resolve, function onResponseSizeUpdate(totalBytesReceivedSoFar) {\n // When processing a dynamic response, we don't know how large each\n // individual segment is, so approximate by assigning each segment\n // the average of the total response size.\n if (fulfilledEntries === null) {\n // Haven't received enough data yet to know which segments\n // were included.\n return;\n }\n const averageSize = totalBytesReceivedSoFar / fulfilledEntries.length;\n for (const entry of fulfilledEntries){\n setSizeInCacheMap(entry, averageSize);\n }\n });\n serverDataPromise = createFromNextReadableStream(prefetchStream, headers, {\n allowPartialStream: true\n });\n } else {\n const buffer = await bufferPrefetchResponseBody(response.body);\n closed.resolve();\n bufferedResponseSize = buffer.byteLength;\n serverDataPromise = decodeBufferedStage(buffer, headers);\n }\n const [serverData, cacheData] = await Promise.all([\n serverDataPromise,\n response.cacheData\n ]);\n const now = Date.now();\n const staleAt = await resolveStaleAt(now, serverData.s, response);\n const buildId = response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b;\n // Extract the response's shell-stage payload, when it carries one. No\n // shell can be extracted without cache metadata (only present when\n // Cached Navigations is enabled); for responses without a distinct\n // shell stage the extraction is a no-op anyway\n // (`resolveShellStageResponse` returns null), so the null check just\n // short-circuits that case.\n const shellResponse = cacheData !== null ? await resolveShellStageResponse(cacheData, serverData, headers) : null;\n // Runtime prefetch responses (PPRRuntime and RuntimeShell requests) are\n // partial when the server marks the response as '~' (Partial).\n // Full/LoadingBoundary prefetch responses are always complete.\n const isFullResponsePartial = (fetchStrategy === FetchStrategy.PPRRuntime || fetchStrategy === FetchStrategy.RuntimeShell) && (cacheData?.isResponsePartial ?? false);\n // Aside from writing the data into the cache, this also returns the\n // entries that were fulfilled, so we can streamingly update their sizes\n // in the LRU as more data comes in (Full responses, which stream).\n fulfilledEntries = writeResponsePayloadsIntoCache(now, fetchStrategy, serverData, shellResponse, dynamicRequestTree, predictedFrom, // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null, renderedSearch, buildId, staleAt, isFullResponsePartial, null, spawnedEntries, bufferedResponseSize, task.segmentCacheMap);\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n return {\n value: null,\n closed: closed.promise\n };\n } catch (error) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, getPrefetchErrorStaleAt(error));\n return null;\n }\n}\nfunction rejectSegmentEntriesIfStillPending(entries, staleAt) {\n for (const entry of entries.values()){\n if (entry.status === EntryStatus.Pending) {\n rejectSegmentCacheEntry(entry, staleAt);\n }\n }\n}\n/**\n * Writes a prefetch response's payloads into the cache: the full payload,\n * plus its shell payload when the response carries one. This is the write\n * orchestration shared by the prefetch response kinds — per-segment\n * static responses (fetchAndWritePerSegmentPrefetchResponse) and\n * live-render responses (fetchSegmentPrefetchesUsingRuntimeRequest, and the\n * embedded runtime prefetch stream via writeRuntimePrefetchStreamIntoCache)\n * — which differ in how they obtain their payloads but not in what must\n * happen to them.\n *\n * Returns the entries the fulfilling payload's write produced content into\n * (so the streaming caller can keep updating their LRU sizes as bytes\n * arrive), or null if nothing entered the cache.\n */ function writeResponsePayloadsIntoCache(now, // The strategy of the request that produced the response. Decides which\n// payload fulfills the spawned entries and their keying, and identifies\n// the response family: PPR/StaticShell are per-segment static responses,\n// everything else a live-render response.\nfetchStrategy, fullPayload, // The response's shell payload: null (the response carries no shell),\n// `fullPayload` itself (the shell IS the full response), or a distinct\n// stage decode truncated at the shell byte boundary.\nshellPayload, // The next five are threaded through to every write; see\n// writeServerResponseIntoCache for their meaning.\nbaseTree, predictedFrom, renderedPathname, renderedSearch, buildId, // Response-level staleness of the full payload. The shell payload's own\n// staleness is read off the shell decode below (a shell payload is always\n// fully buffered).\nstaleAt, // Whether anything in the full payload is not fully resolved (dynamic or runtime holes, anything suspended). Shell-tier\n// writes don't consume it: a shell payload is partial by construction.\n// (Per-segment payloads encode partiality per node and ignore the\n// response-level value entirely.)\nisFullResponsePartial, metadataVaryPath, // The pending entries this response fulfills. Null when the caller owns\n// none (the embedded runtime prefetch stream), in which case every write\n// is a detached upsert.\nspawnedEntries, // The response's size in bytes, distributed across the entries the\n// fulfilling payload's write produced; null when unknown (streamed Full\n// responses — the caller sizes those incrementally as bytes\n// arrive instead).\nresponseByteLength, // The map the work that spawned this response's request is bound to. See\n// writeServerResponseIntoCache.\nmap) {\n let fulfilledEntries;\n if (shellPayload === null || // `FetchStrategy.LoadingBoundary` is not used in Cache Components,\n // and we only recover shells in Cache Components.\n fetchStrategy === FetchStrategy.LoadingBoundary) {\n if (fetchStrategy === FetchStrategy.StaticShell) {\n // A static shell was requested but the response carries no shell (its\n // shell byte offset read as 0 — a bug in Next.js itself — or the\n // shell prefix couldn't be decoded). The full payload is still\n // usable, so it's written detached at the concrete tier; the spawned\n // entries are rejected so the task isn't stranded blocking on them.\n // Note the scheduler does NOT fall back to a runtime request for\n // rejected segments — it skips them outright (see the Rejected case\n // in pingSegmentBundle in scheduler.ts), so these segments get no\n // shell prefetch and no runtime substitute until the rejection's\n // backoff expires.\n writeServerResponseIntoCache(now, FetchStrategy.PPR, fullPayload, baseTree, predictedFrom, renderedPathname, renderedSearch, buildId, staleAt, isFullResponsePartial, metadataVaryPath, null, null, map);\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + REJECTION_BACKOFF_MS);\n }\n return null;\n }\n // This request either:\n // - didn't allow recovering a shell (no staged rendering),\n // - or was a (runtime) shell request (that was NOT served by a fully static prerender)\n // so we already have a shell without recovering anything.\n // In either case, we don't have anything to consider other than the request itself,\n // so the payload simply fulfills the spawned entries at the request's own keying.\n fulfilledEntries = writeServerResponseIntoCache(now, fetchStrategy, fullPayload, baseTree, predictedFrom, renderedPathname, renderedSearch, buildId, staleAt, isFullResponsePartial, metadataVaryPath, spawnedEntries, null, map);\n } else if (shellPayload === fullPayload) {\n // The shell IS the full response (reference-equal — a page with nothing\n // below its shell). One payload fulfills the spawned entries, recording\n // the strategy that describes the CONTENT — the full payload's tier.\n // The content tier also drives the entries' keying: content that isn't\n // shell-grade is param-independent only on the server's vary-params\n // evidence, so it must not be parked in the shell slot on the strength\n // of the missing split alone (see the keying derivation in\n // writeSegmentDataIntoCache).\n let contentFetchStrategy;\n switch(fetchStrategy){\n case FetchStrategy.StaticShell:\n {\n // a StaticShell always uses a PPR-tier request, so we need to fulfill\n // the spawned shell entries at the PPR tier.\n contentFetchStrategy = FetchStrategy.PPR;\n break;\n }\n case FetchStrategy.RuntimeShell:\n {\n // a runtime shell request is not normally rewindable, but fully static pages\n // the server will return a static prerender result, which *is* rewindable.\n contentFetchStrategy = FetchStrategy.PPRRuntime;\n break;\n }\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full:\n {\n // No shell was requested, so we don't need to override the fetch strategy.\n contentFetchStrategy = null;\n }\n }\n fulfilledEntries = writeServerResponseIntoCache(now, fetchStrategy, fullPayload, baseTree, predictedFrom, renderedPathname, renderedSearch, buildId, staleAt, isFullResponsePartial, metadataVaryPath, spawnedEntries, contentFetchStrategy, map);\n } else {\n // The shell is a strict prefix of the response. Write both payloads.\n // The payload matching the tier the spawned entries were requested at\n // fulfills them; the other is written detached (no owned entries —\n // every write is an upsert). Fulfilling a spawned shell entry with the\n // concrete payload would store content that doesn't match the entry's\n // shell vary path — wrong for every later read at that key, and\n // immediately observable during a navigation, where a pending entry can\n // be rendered as a promise that resolves to its eventual value.\n //\n // The full payload is written first. The order is not observable: the\n // two writes key at different tiers, upsert precedence between a full\n // payload and its own shell payload is order-independent (the full\n // payload always wins the comparison — a shell segment is never\n // complete where its full counterpart is partial, see\n // readFulfilledIsPartial), and fulfillment pings only enqueue scheduler\n // work that runs after this synchronous block. Full-first is preferred\n // so the shell write's precedence checks and shadow eviction compare\n // against the fresh concrete entry rather than whatever stale entry\n // preceded it.\n let responseFetchStrategy;\n let shellFetchStrategy;\n switch(fetchStrategy){\n case FetchStrategy.StaticShell:\n case FetchStrategy.PPR:\n {\n // Static request.\n // a StaticShell fetch strategy performs a request that returns\n // a PPR-tier response that can be rewound to a StaticShell response,\n // So we upgrade the full response's strategy to `PPR`.\n // (A static response's tier may be raised if we know that a static request\n // would satisfy a runtime request -- see `recordedFetchStrategy` in\n // `writeSegmentDataIntoCache`)\n responseFetchStrategy = FetchStrategy.PPR;\n shellFetchStrategy = FetchStrategy.StaticShell;\n break;\n }\n case FetchStrategy.RuntimeShell:\n {\n // A runtime shell request is normally not rewindable -- it only produces\n // the shell itself. However, if a page is fully static, a runtime shell\n // will return a static prerender, i.e. the static content with an embedded shell.\n // The page is static, so we can treat the content as runtime-complete.\n responseFetchStrategy = FetchStrategy.PPRRuntime;\n shellFetchStrategy = FetchStrategy.RuntimeShell;\n break;\n }\n case FetchStrategy.PPRRuntime:\n {\n // A runtime prefetch response can be rewound into a runtime shell.\n // (This may also be a fully static response, same as RuntimeShell above,\n // in which case we also know that the shell is equivalent to a runtime shell)\n responseFetchStrategy = FetchStrategy.PPRRuntime;\n shellFetchStrategy = FetchStrategy.RuntimeShell;\n break;\n }\n case FetchStrategy.Full:\n {\n // Navigation responses can be rewound into a *static* app shell.\n // On PPF routes they also contain a runtime prefetch stream which will give us\n // a runtime shell/prefetch, but that's handled separately from the main response.\n // (see `writeRuntimePrefetchStreamIntoCache`)\n responseFetchStrategy = FetchStrategy.Full;\n shellFetchStrategy = FetchStrategy.StaticShell;\n break;\n }\n }\n // We have to fulfill the correct pending entries depending on what was requested:\n // - If we originally needed a shell but and got more content, the spawned entries\n // should be fulfilled using the shell.\n // - If we needed a speculative or full request but rewound it into a shell,\n // the spawned entries should be fulfilled using the full response.\n const wasShellRequested = fetchStrategy === FetchStrategy.StaticShell || fetchStrategy === FetchStrategy.RuntimeShell;\n const fullFulfilledEntries = writeServerResponseIntoCache(now, responseFetchStrategy, fullPayload, baseTree, predictedFrom, renderedPathname, renderedSearch, buildId, staleAt, isFullResponsePartial, metadataVaryPath, wasShellRequested ? null : spawnedEntries, null, map);\n const shellFulfilledEntries = writeServerResponseIntoCache(now, shellFetchStrategy, shellPayload, baseTree, predictedFrom, renderedPathname, renderedSearch, buildId, // The shell payload carries its own staleness, independent of the\n // full payload's. Shell decodes are fully buffered, so it's read\n // synchronously; when absent (per-segment responses carry staleTime\n // per node instead) this falls back to the same static stale time the\n // per-segment writes use as their response-level fallback.\n readFulfilledStaleAt(now, shellPayload.s), // A shell payload is a strict subset of the full response, so it does\n // not represent the entire UI of the target page — it's partial\n // by construction.\n true, metadataVaryPath, wasShellRequested ? spawnedEntries : null, null, map);\n fulfilledEntries = wasShellRequested ? shellFulfilledEntries : fullFulfilledEntries;\n }\n // Entries created by a detached write aren't sized: one wire response is\n // only charged to the LRU once, to the entries it fulfilled.\n if (responseByteLength !== null && fulfilledEntries !== null && fulfilledEntries.length > 0) {\n const averageSize = responseByteLength / fulfilledEntries.length;\n for (const entry of fulfilledEntries){\n setSizeInCacheMap(entry, averageSize);\n }\n }\n return fulfilledEntries;\n}\n/**\n * Writes a decoded server response into the segment cache: decodes the\n * response's transport tree into a RouteTree — overlaid on `baseTree` when\n * the response is an overlay over existing client state, root-anchored when\n * it covers its own spine (per-segment prefetch payloads) — then writes\n * every rendered segment, plus the head, into the cache. Fulfills the\n * entries in `spawnedEntries` that the response covers; rejects the rest, so\n * a task blocked on them isn't stranded. Returns the entries the write\n * produced content into — fulfilled spawned entries plus installed detached\n * upserts — for LRU size accounting, or null if nothing entered the cache.\n *\n * Serves every response kind: live-render prefetch responses (runtime\n * prefetches, and Full/LoadingBoundary prefetches in the\n * non-Partial-Prefetching regime), prerender stage decodes (shell-stage\n * extraction, cached navigations, the initial payload), embedded runtime\n * prefetch streams, and the payloads of per-segment prefetch responses.\n */ function writeServerResponseIntoCache(now, fetchStrategy, // The decoded response payload to write. For a per-segment prefetch\n// response this is one of its payloads: the full response, or the\n// truncated shell decode.\nresponse, // The base router state the response overlays. Null when the response's\n// tree is root-anchored (per-segment prefetch payloads).\nbaseTree, // Non-null when `baseTree` was predicted: the node in the known route tree\n// whose pattern it was predicted from (see matchKnownRoute). The\n// prediction assumes the URL's rewrite (if any) behaves statically; if the\n// server's rendered tree diverges from the base, that prediction failed —\n// the rewrite behaves dynamically, so the params baked into the request\n// are wrong. The node is marked so the shape is never predicted again, and\n// the entries that could not be fulfilled are rejected with immediate\n// expiration so the task retries right away — against the server-resolved\n// route this time. The response data is still written into the cache: it's\n// real data keyed by what the server actually rendered, useful regardless\n// of whether the prediction matched.\npredictedFrom, // The pathname the response was rendered for, used to resolve dynamic\n// segments the server sent without a param value (`k: null`). Null for\n// responses that always carry concrete values (navigation responses).\nrenderedPathname, renderedSearch, buildId, // Response-level staleness; a segment (or the head) with its own\n// staleTime overrides it.\nstaleAt, // Whether anything in the response is not fully resolved: dynamic holes, runtime holes, anything suspended.\n// Threaded into the decode, where each segment's (and the head's)\n// partiality is resolved from it and the wire form (see\n// createNavigationSeed). Per-segment prefetch responses encode\n// partiality per node, so their writes pass the conservative value\n// (true), which is never read.\nisResponsePartial, // Where to key the head; see createNavigationSeed.\nmetadataVaryPath, spawnedEntries, // The strategy tier describing the CONTENT of the payload being written,\n// when it differs from `fetchStrategy` (which drives matching and\n// keying); null when they agree. See the param docs on\n// writeSegmentDataIntoCache.\ncontentFetchStrategy, // The map the work that spawned this response's request is bound to: the\n// spawning task's `PrefetchTask.segmentCacheMap` for prefetches, the\n// navigation's map for navigation-side writes. Binding the write to the\n// requesting work means a response that lands after a testing-lock scope\n// boundary still writes into the map its entries live in.\nmap) {\n // Which layer owns the buildId check differs by flow. The route and\n // segment fetch layers check it themselves (see fetchRouteOnCacheMiss and\n // fetchAndWritePerSegmentPrefetchResponse) because they need the early-out\n // before side effects this layer can't undo — starting the fallback-retry\n // loop, writing the second (shell) payload — and then pass no buildId\n // here. This check owns it for the flows that don't: live-render prefetch\n // responses and navigation static-stage writes, which pass their\n // buildId through.\n if (buildId && buildId !== getNavigationBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + REJECTION_BACKOFF_MS);\n }\n return null;\n }\n const transportData = response.t;\n if (transportData === undefined) {\n // The response carries no tree. Settle anything we own so a task blocked\n // on it isn't stranded.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + REJECTION_BACKOFF_MS);\n }\n return null;\n }\n const navigationSeed = createNavigationSeed(now, baseTree, transportData, // Root params are emitted once at the top level of the response; the\n // decode unions them into the head's and each segment's own set. For\n // per-segment prefetch responses this must be read from the payload\n // being written: a truncated shell decode rewinds the response's\n // late-resolving values to the shell stage.\n response.r ?? null, // The decode resolves each segment's partiality from this and the wire:\n // boolean-form nodes resolve to this response-level value; staged\n // (promise-form) nodes encode partiality per node and ignore it.\n isResponsePartial, renderedPathname, renderedSearch, metadataVaryPath, // Only navigations consume the seed's dynamicStaleAt; cache writes pass\n // unknown to use the default.\n UnknownDynamicStaleTime);\n const requiresRuntimeCompleteness = (navigationSeed.root.tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0;\n const treeDivergedFromPrediction = predictedFrom !== null && navigationSeed.treeDivergedFromBase;\n if (treeDivergedFromPrediction) {\n predictedFrom.hasDynamicRewrite = true;\n }\n // Only static (per-segment) responses can be ISR fallbacks (`f`). A\n // present `u` means the response carries a stage-scoped runtime-data\n // verdict — per-segment prefetch responses always emit one, and so does\n // any prerendered page payload, which embeds the prerender's runtime-data\n // probe; live renders emit none. A response without one decodes to a null\n // verdict, and its entries record their request's own strategy unrefined\n // (see writeSegmentDataIntoCache).\n // `u` is deliberately read here, off THIS decode's thenable status, rather\n // than normalized where the response is fetched: the read scopes it to the\n // payload being written — a truncated shell decode reads a post-shell\n // runtime access as pending, i.e. `false`, because the shell variant\n // itself doesn't need that data. The read is load-bearing in one direction\n // only: a false `true` costs a wasted runtime request; a false `false`\n // would record too high a tier and skip a runtime request that had more\n // content. A rejected row (an aborted prerender errors rows that were\n // still pending at the abort) must therefore read as `true`, matching the\n // server's own read of the page payload's flag (see the `u` read in\n // collect-segment-data.tsx).\n const isUpgradeableISRFallback = response.f === true;\n const responseNeedsRuntimeRequest = response.u !== undefined ? readFulfilledValue(response.u, false, /* rejectedValue */ true) : null;\n const routeTree = navigationSeed.root.tree;\n // The route tree carries the render output of every segment the response\n // included, so a single traversal from the root writes all of it into\n // the cache.\n const writtenEntries = [];\n writeTreeDataIntoCache(now, map, fetchStrategy, routeTree, staleAt, spawnedEntries, contentFetchStrategy, isUpgradeableISRFallback, requiresRuntimeCompleteness, responseNeedsRuntimeRequest, writtenEntries);\n const metadataTree = navigationSeed.root.head;\n const headData = metadataTree.data;\n if (headData !== null && headData.rsc !== null) {\n // The head follows the same stale-time rules as a segment.\n const headStaleAt = headData.staleTimeSeconds !== null ? now + getStaleTimeMs(headData.staleTimeSeconds) : staleAt;\n // A head has no loading boundary. Match the scheduler, which spawns\n // LoadingBoundary head entries using the concrete Full strategy (see the\n // head's runtime fetch in pingRootRouteTree).\n const headFetchStrategy = fetchStrategy === FetchStrategy.LoadingBoundary ? FetchStrategy.Full : fetchStrategy;\n const writtenHeadEntry = writeSegmentDataIntoCache(now, map, headFetchStrategy, headData.rsc, // The decode already resolved the head's partiality from the wire\n // form and the response-level value — see the head read in\n // createNavigationSeed.\n headData.isPartial, headStaleAt, headData.varyParams, metadataTree, spawnedEntries, contentFetchStrategy, isUpgradeableISRFallback, requiresRuntimeCompleteness, responseNeedsRuntimeRequest);\n if (writtenHeadEntry !== null) {\n writtenEntries.push(writtenHeadEntry);\n }\n }\n // Any entry that's still pending was intentionally not rendered by the\n // server, because it was inside the loading boundary. Mark them as rejected\n // so we know not to fetch them again.\n // TODO: If PPR is enabled on some routes but not others, then it's possible\n // that a different page is able to do a per-segment prefetch of one of the\n // segments we're marking as rejected here. We should mark on the segment\n // somehow that the reason for the rejection is because of a non-PPR prefetch.\n // That way a per-segment prefetch knows to disregard the rejection.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, // When the response diverged from the prediction, the leftover entries\n // can never be fulfilled — their keys were derived from the wrong\n // tree. Reject with an immediate expiration instead of the usual\n // backoff so the task retries right away. The prediction was disabled\n // above, so the retry resolves the route on the server instead of\n // predicting it again.\n treeDivergedFromPrediction ? -1 : now + REJECTION_BACKOFF_MS);\n }\n return writtenEntries.length > 0 ? writtenEntries : null;\n}\nfunction writeTreeDataIntoCache(now, map, fetchStrategy, tree, staleAt, spawnedEntries, contentFetchStrategy, isUpgradeableISRFallback, requiresRuntimeCompleteness, responseNeedsRuntimeRequest, // Accumulates the entries the walk wrote content into (fulfilled spawned\n// entries and installed detached upserts), for LRU size accounting.\nwrittenEntries) {\n // Writes the render output embedded in the route tree into the\n // prefetch cache.\n const data = tree.data;\n if (data !== null && data.rsc !== null) {\n // A segment carries its own staleTime only in per-segment prefetch\n // responses; everywhere else the response-level staleness governs.\n const entryStaleAt = data.staleTimeSeconds !== null ? now + getStaleTimeMs(data.staleTimeSeconds) : staleAt;\n const writtenEntry = writeSegmentDataIntoCache(now, map, fetchStrategy, data.rsc, data.isPartial, entryStaleAt, data.varyParams, tree, spawnedEntries, contentFetchStrategy, isUpgradeableISRFallback, requiresRuntimeCompleteness, responseNeedsRuntimeRequest);\n if (writtenEntry !== null) {\n writtenEntries.push(writtenEntry);\n }\n } else {\n // Either the response carried no information for this segment (no data\n // object — e.g. the identity spine of a per-segment prefetch response,\n // or a slot reused from the base tree), or it acknowledged the position\n // without rendering it (a data object with a null rsc — an intermediate\n // position on the path to a rendered subtree). Nothing to write either\n // way, but the children may have output, so keep descending.\n }\n // Recursively write the child data into the cache.\n const slots = tree.slots;\n if (slots !== null) {\n for (const childTree of slots.values()){\n writeTreeDataIntoCache(now, map, fetchStrategy, childTree, staleAt, spawnedEntries, contentFetchStrategy, isUpgradeableISRFallback, requiresRuntimeCompleteness, responseNeedsRuntimeRequest, writtenEntries);\n }\n }\n}\n/**\n * Writes one segment's render output into the cache: fulfills the entry at\n * the same tree position if this task owns one, otherwise creates one (or\n * upserts a detached one). Shared by every response kind; responses that\n * carry a runtime-data verdict (per-segment prefetch responses and\n * prerendered page payloads) additionally refine the tier the entry\n * records — see `recordedFetchStrategy` below.\n *\n * Returns the entry this write produced content into — the fulfilled spawned\n * entry, or the detached entry the upsert installed — so the caller can\n * charge the response's size to it. Null when nothing entered the cache (the\n * upsert declined a detached candidate).\n */ function writeSegmentDataIntoCache(now, map, fetchStrategy, rsc, isPartial, staleAt, segmentVaryParams, tree, spawnedEntries, // The strategy tier describing the CONTENT of the payload this write came\n// from, when it differs from the write's own `fetchStrategy` (which\n// drives matching and keying); null when they agree. It differs only for\n// the coincident-shell case: a write that fulfills shell-keyed entries\n// with a payload that IS the full response passes the full payload's tier\n// — see writeResponsePayloadsIntoCache.\ncontentFetchStrategy, // Whether the response is an upgradeable fallback shell. Always false for\n// live-render responses — they are never ISR fallbacks.\nisUpgradeableISRFallback, // The response's runtime-data verdict: whether the render that produced\n// this payload accessed runtime data (page-global; combined with the\n// segment's own `isPartial` to decide the tier the entry records below).\n// Null when the response carries no verdict (`u`) — live renders emit\n// none; per-segment prefetch responses and prerendered page payloads\n// (including the truncated initial payload) do — in which case the entry\n// records the payload's tier unrefined.\nrequiresRuntimeCompleteness, responseNeedsRuntimeRequest) {\n // The strategy tier recorded on the entry — the tier of the content that\n // actually satisfied it, which spans both axes: shell-vs-concrete AND\n // static-vs-runtime. The payload's content tier (`fetchStrategy`, unless\n // the caller passed a distinct `contentFetchStrategy`), refined by the\n // response's runtime-data verdict when it carries one:\n //\n // A runtime prefetch can only provide more content than this entry if the\n // render accessed runtime data AND this particular segment has holes — a\n // fully static segment gains nothing from a runtime request no matter\n // what the page accessed. When this payload fully satisfied the segment —\n // no runtime request needed — the content is as complete as a RUNTIME\n // response of the same variant would have been, so it records that\n // runtime tier. That's what lets the scheduler decide \"would a runtime\n // request return more?\" by comparing tiers alone, with no separate signal\n // to consult. Otherwise the content is only as complete as the static\n // tier it was requested at, so a follow-up runtime request can still\n // supersede it.\n let recordedFetchStrategy;\n if (responseNeedsRuntimeRequest === null) {\n // The response carries no verdict — a live render's, or the synthesized\n // initial-payload subset's (see create-initial-router-state): record\n // the payload's tier as-is. A verdict is honored wherever it appears:\n // prerendered page payloads carry one too (the prerender's runtime-data\n // probe), and refining on it is correct — a prerendered response whose\n // verdict is `false` is genuinely runtime-complete content.\n recordedFetchStrategy = contentFetchStrategy ?? fetchStrategy;\n } else if (responseNeedsRuntimeRequest && isPartial) {\n // A runtime request would provide more than this payload, so no runtime\n // tier is recorded — but the entry must still honor the payload's\n // CONTENT grade. In the coincident-shell case the payload that satisfied\n // a shell-keyed entry IS the full response, whose content grades at the\n // concrete static tier (`contentFetchStrategy`, PPR — the verdict only\n // rides static-family responses, so no higher grade can appear here).\n // The verdict is consistent with that grade: it says the runtime tiers\n // would provide more, which they would over PPR just as over the shell\n // tier.\n recordedFetchStrategy = contentFetchStrategy ?? fetchStrategy;\n } else {\n const payloadFetchStrategy = contentFetchStrategy ?? fetchStrategy;\n if (requiresRuntimeCompleteness) {\n // The verdict says this payload does not need a runtime request.\n // If we requested it at a static tier, raise the recorded tier up to the\n // runtime tier of the same variant.\n // This also makes the verdict a noop for Full payloads, which matters because\n // the Full flow decodes incrementally, and synchronously reading `response.u`\n // is only sound for a buffered payload.\n recordedFetchStrategy = payloadFetchStrategy === FetchStrategy.StaticShell ? FetchStrategy.RuntimeShell : payloadFetchStrategy === FetchStrategy.PPR ? FetchStrategy.PPRRuntime : payloadFetchStrategy;\n } else {\n // Only upgrade static segments to their runtime equivalents if the route\n // can use runtime requests. Otherwise, when re-using a shell segment across\n // params, `pingSegmentBundle` for a PPR strategy would see a `ShellRuntime`\n // shell entry and incorrectly decide that a new PPR request would not\n // provide more content.\n recordedFetchStrategy = payloadFetchStrategy;\n }\n }\n // Decide whether to re-key the entry under a more generic vary path based on\n // which params the segment actually depends on.\n //\n // Skip re-keying for Full prefetches: as of today, `varyParams` tracking only\n // works within the static stage portion of a response. A Full prefetch\n // response covers all stages, and we can't track params during the dynamic\n // stage without dead-locking the Flight stream, so the server-reported set is\n // incomplete and can't be trusted for the full response. Re-keying with an\n // untrustworthy set could replace concrete params with Fallback and let\n // unrelated URLs read each other's content from the cache.\n //\n // Key the entry by which params the server said this segment depends on\n // (judged by the payload's CONTENT: contentFetchStrategy differs from\n // fetchStrategy exactly when a shell request's response turned out to\n // carry more — the coincident case). Reusing one copy across param values\n // is the point of the shell, but it requires knowing the content doesn't\n // depend on those params, and the server's report is the direct evidence\n // of that.\n //\n // Without that report, assume every param varies — a response without a\n // shell/full split is also what a page fully prerendered at concrete\n // params looks like, and keying that at the shell path would serve one\n // slug's content to every sibling. The exception is a shell variant,\n // which reduces param-dependent content to param fallbacks, so it really\n // is good for any value of them (its request path below IS the shell\n // vary path).\n const payloadStrategy = contentFetchStrategy ?? fetchStrategy;\n let fulfilledVaryPath = null;\n // The dependency source the entry records, so a navigation that renders\n // its content can tell which params that content read. It is the same\n // evidence the key derivation below trusts, under the same condition, with\n // the same correction; otherwise null, and consumers assume every param.\n let recordedVaryParams = null;\n if (process.env.__NEXT_VARY_PARAMS && payloadStrategy !== FetchStrategy.Full && segmentVaryParams !== null) {\n // Read the reported set now, when the key is chosen. The payload is fully\n // buffered by the time it's written, so the source has settled; a read of\n // null means the report is unavailable and every param varies.\n let varyParams = readVaryParams(segmentVaryParams);\n if (varyParams !== null) {\n if (payloadStrategy === FetchStrategy.RuntimeShell && varyParams.has(SEARCH_PARAMS_VARY_ID)) {\n // SPECIAL CASE: for a RuntimeShell payload, the search params entry\n // is dropped from the server's vary evidence before deriving the\n // key, so the search component of the resulting path is marked as\n // the fallback. This exists ONLY because of a known compromise in\n // how the server reports search params: accessing `searchParams`\n // records a dependency on them at access time, even when the render\n // suspends on that access and cuts the content at the param\n // fallback. A shell render's page and head segments therefore report\n // the search params while the emitted bytes contain no\n // search-dependent content.\n // Trusting that report would key shell-grade content at a concrete\n // search value, where shell-restricted reads (which generalize every\n // non-root param — see getShellSegmentVaryPath) can never find it. A\n // RuntimeShell payload's search-dependent content is reduced to\n // fallbacks by construction, so its key must not vary on search\n // regardless of the over-reported evidence. Every other component of\n // the evidence is still honored as-is.\n //\n // Nothing else should rely on this branch; for every other payload\n // grade — and every other param — the server's evidence\n // is authoritative.\n //\n // TODO: Reconsider special-casing this on the server instead: don't\n // report a param access that never resolved past the fallback cut in\n // the emitted stage. A shell payload's evidence would then be\n // accurate, and this branch could be deleted.\n varyParams = new Set(varyParams);\n varyParams.delete(SEARCH_PARAMS_VARY_ID);\n recordedVaryParams = createVaryParams(varyParams);\n } else {\n recordedVaryParams = segmentVaryParams;\n }\n fulfilledVaryPath = getFulfilledSegmentVaryPath(tree.varyPath, varyParams);\n }\n }\n // The canonical path to (re-)key the entry at. When the derivation above\n // produced a path, use that; otherwise fall back to the payload's own\n // keying (this is load-bearing for entries spawned as revalidations:\n // without the re-key they'd stay in their Revalidation slot forever,\n // invisible to canonical reads, and the partial entry that prompted the\n // revalidation would keep serving navigations). Full responses are\n // excluded, matching the varyParams re-key: they're spawned as canonical\n // entries at their final path, and their vary tracking can't be trusted\n // for re-keying (see the fulfilledVaryPath derivation above).\n const canonicalVaryPath = fulfilledVaryPath !== null ? fulfilledVaryPath : payloadStrategy !== FetchStrategy.Full ? getSegmentVaryPathForRequest(payloadStrategy, tree) : null;\n // We should only write into cache entries that are owned by us. Or create\n // a new one and write into that. We must never write over an entry that was\n // created by a different task, because that causes data races.\n //\n // The status check matters for the fallback-retry loop, which re-writes a\n // response over entries the initial fetch already settled: those writes\n // must fall through to the detached path below.\n const ownedEntry = spawnedEntries !== null ? spawnedEntries.get(tree.requestKey) : undefined;\n const isOwned = ownedEntry !== undefined && ownedEntry.status === EntryStatus.Pending;\n let fulfilledEntry;\n let insertVaryPath;\n if (isOwned) {\n // We own this entry — fulfill it directly.\n fulfilledEntry = fulfillSegmentCacheEntry(ownedEntry, rsc, staleAt, isPartial, recordedVaryParams, isUpgradeableISRFallback, recordedFetchStrategy);\n // Re-key the fulfilled entry at its canonical path. Owned Full entries\n // are the exception (canonicalVaryPath is null): they were spawned as\n // canonical entries at their final path, so no re-key happens.\n insertVaryPath = canonicalVaryPath;\n } else {\n // We don't own an entry for this segment. Create a detached one and\n // attempt to insert it at the canonical path — or, for a Full response\n // (which has no canonical re-key), at the request's own path.\n fulfilledEntry = fulfillSegmentCacheEntry(upgradeToPendingSegment(createDetachedSegmentCacheEntry(now), fetchStrategy), rsc, staleAt, isPartial, recordedVaryParams, isUpgradeableISRFallback, recordedFetchStrategy);\n insertVaryPath = canonicalVaryPath !== null ? canonicalVaryPath : getSegmentVaryPathForRequest(fetchStrategy, tree);\n }\n if (insertVaryPath !== null) {\n // Insert through the upsert so the usual precedence rules apply — an\n // existing entry with more complete content is never downgraded, and a\n // shadowed Empty/Pending entry's blocked tasks are pinged. (In the\n // common case the slot already holds the entry we just fulfilled, which\n // the upsert replaces in place; but the re-key is load-bearing for\n // entries whose spawn path differs from the canonical path — e.g.\n // spawned revalidations, which would otherwise stay in their\n // Revalidation slot forever, invisible to canonical reads, while the\n // partial entry that prompted the revalidation kept serving\n // navigations.)\n //\n // The concrete lookup path (tree.varyPath) is passed so that when the\n // canonical path is more generic, any stale settled entry — or unclaimed\n // Empty placeholder — at a more specific path that would shadow the\n // fulfilled entry is evicted. Without this, a shadowed re-keyed entry is\n // unreachable at the concrete read path: the scheduler would keep\n // re-reading the stale entry and, for a revalidation, respawn it\n // forever. See evictShadowingSegmentEntries.\n const installedEntry = upsertSegmentEntry(now, map, insertVaryPath, fulfilledEntry, tree.varyPath);\n if (installedEntry === null && !isOwned) {\n // The upsert declined the detached candidate (an existing entry took\n // precedence, or the candidate was already expired), so no cache slot\n // holds this write's content — nothing for the caller to charge to\n // the LRU. (An owned entry is returned regardless: it was fulfilled\n // above and stays live for waiters that hold it, whether or not the\n // re-key installed it.)\n return null;\n }\n }\n return fulfilledEntry;\n}\nasync function fetchPrefetchResponse(url, headers) {\n const fetchPriority = 'low';\n // When issuing a prefetch request, don't immediately decode the response; we\n // use the lower level `createFromResponse` API instead because we need to do\n // some extra processing of the response stream. See\n // `bufferPrefetchResponseBody` for more details.\n const shouldImmediatelyDecode = false;\n const response = await createFetch(url, headers, fetchPriority, shouldImmediatelyDecode);\n if (!response.ok) {\n return null;\n }\n // Check the content type\n if (isOutputExportMode) {\n // In output: \"export\" mode, we relaxed about the content type, since it's\n // not Next.js that's serving the response. If the status is OK, assume the\n // response is valid. If it's not a valid response, the Flight client won't\n // be able to decode it, and we'll treat it as a miss.\n } else {\n const contentType = response.headers.get('content-type');\n const isFlightResponse = contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER);\n if (!isFlightResponse) {\n return null;\n }\n }\n return response;\n}\n/**\n * Whether the response was served from the per-segment-capable static\n * prerender, rather than the old prefetching flow. If this fails, it implies\n * that PPR is disabled on the route.\n */ function wasServedFromPerSegmentCache(response) {\n return response.headers.get(NEXT_DID_POSTPONE_HEADER) === '2' || // In output: \"export\" mode, we can't rely on response headers. But if we\n // receive a well-formed response, we can assume it's a static response,\n // because all data is static in this mode.\n isOutputExportMode;\n}\n/**\n * Reads a prefetch response body to completion — optionally truncating at\n * `byteLimit` — and returns the bytes as a single contiguous buffer.\n *\n * Buffering the entire response before passing it to the Flight client\n * ensures that when Flight processes the stream, all model data is available\n * synchronously. This is what makes the decode boundary's thenable-status\n * reads (vary params, isPartial, staleTime — see decode-server-response)\n * sound: if data arrived in multiple network chunks, the thenables might not\n * yet be fulfilled. (`decodeBufferedStage` performs the matching\n * single-chunk decode.)\n *\n * TODO: There are too many intermediate stream transformations in the\n * prefetch response pipeline (e.g. stripIsPartialByte, this function).\n * These could all be consolidated into a single transformation. Refactor\n * once the cached navigations experiment lands.\n */ export async function bufferPrefetchResponseBody(body, byteLimit) {\n // Read the response from the network, optionally truncating at byteLimit.\n const reader = body.getReader();\n const chunks = [];\n let size = 0;\n while(true){\n const { done, value } = await reader.read();\n if (done) break;\n if (byteLimit !== undefined && size + value.byteLength >= byteLimit) {\n const remaining = byteLimit - size;\n if (remaining > 0) {\n chunks.push(value.byteLength > remaining ? value.subarray(0, remaining) : value);\n size += remaining;\n }\n reader.cancel();\n break;\n }\n chunks.push(value);\n size += value.byteLength;\n }\n // Concatenate into a single chunk so that Flight's processBinaryChunk\n // processes all rows synchronously in one call. Multiple chunks would not\n // be sufficient: even though reader.read() resolves as a microtask for\n // already-enqueued data, the `await` continuation from\n // createFromReadableStream can interleave between chunks. If the root\n // model row isn't the first row (e.g. outlined values come first), the\n // PromiseResolveThenableJob from `await` can cause the root to initialize\n // eagerly, scheduling the continuation before remaining chunks (including\n // promise value rows) are processed. A single chunk avoids this.\n if (chunks.length === 1) {\n return chunks[0];\n } else if (chunks.length > 1) {\n const buffer = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks){\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return buffer;\n } else {\n return new Uint8Array(0);\n }\n}\n/**\n * Creates a streaming (non-buffered) prefetch response stream for dynamic/Full\n * prefetches. These are essentially dynamic responses that get stored in the\n * prefetch cache — they don't carry vary params or other cache metadata that\n * requires synchronous thenable resolution, so there's no need to buffer them.\n * They should continue to stream so consumers can process data as it arrives.\n */ function createIncrementalPrefetchResponseStream(originalFlightStream, onStreamClose, onResponseSizeUpdate) {\n // While processing the original stream, we incrementally update the size\n // of the cache entry in the LRU.\n let totalByteLength = 0;\n const reader = originalFlightStream.getReader();\n return new ReadableStream({\n async pull (controller) {\n while(true){\n const { done, value } = await reader.read();\n if (!done) {\n // Pass to the target stream and keep consuming the Flight response\n // from the server.\n controller.enqueue(value);\n // Incrementally update the size of the cache entry in the LRU.\n totalByteLength += value.byteLength;\n onResponseSizeUpdate(totalByteLength);\n continue;\n }\n controller.close();\n onStreamClose();\n return;\n }\n }\n });\n}\nfunction addSegmentPathToUrlInOutputExportMode(url, segmentPath) {\n if (isOutputExportMode) {\n // In output: \"export\" mode, we cannot use a header to encode the segment\n // path. Instead, we append it to the end of the pathname.\n const staticUrl = new URL(url);\n const routeDir = staticUrl.pathname.endsWith('/') ? staticUrl.pathname.slice(0, -1) : staticUrl.pathname;\n const staticExportFilename = convertSegmentPathToStaticExportFilename(segmentPath);\n staticUrl.pathname = `${routeDir}/${staticExportFilename}`;\n return staticUrl;\n }\n return url;\n}\n/**\n * Checks whether the new fetch strategy is likely to provide more content than the old one.\n *\n * Generally, when an app uses dynamic data, a \"more specific\" fetch strategy is expected to provide more content:\n * - `LoadingBoundary` only provides static layouts\n * - `StaticShell` provides the shell-stage variant extracted from a static response —\n * param-dependent content reduced to pending fallbacks, and never any content that\n * depends on session data (cookies, headers)\n * - `RuntimeShell` provides the shell stage rendered by a runtime request, which can\n * additionally include shell-stage content that depends on session data\n * - `PPR` can provide static shells for each segment, including prerendered param-dependent\n * content at concrete paths (excluding dynamic data)\n * - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies\n * - `Full` includes all the content, even if it uses dynamic data\n *\n * However, it's possible that a more specific fetch strategy *won't* give us more content if:\n * - a segment is fully static\n * (then, `PPR`/`PPRRuntime`/`Full` will all yield equivalent results)\n * - providing searchParams/params/cookies doesn't reveal any more content, e.g. because of an `await connection()`\n * (then, `PPR` and `PPRRuntime` will yield equivalent results, only `Full` will give us more)\n * Because of this, when comparing two segments, we should also check if the existing segment is partial.\n * If it's not partial, then there's no need to prefetch it again, even using a \"more specific\" strategy.\n * There's currently no way to know if `PPRRuntime` will yield more data that `PPR`, so we have to assume it will.\n *\n * Also note that, in practice, we don't expect to be comparing `LoadingBoundary` to `PPR`/`PPRRuntime`,\n * because a non-PPR-enabled route wouldn't ever use the latter strategies. It might however use `Full`.\n */ export function canNewFetchStrategyProvideMoreContent(currentStrategy, newStrategy) {\n return currentStrategy < newStrategy;\n}\nfunction getStaleAtFromHeader(now, response) {\n const staleTimeSeconds = parseInt(response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER) ?? '', 10);\n const staleTimeMs = !isNaN(staleTimeSeconds) ? getStaleTimeMs(staleTimeSeconds) : STATIC_STALETIME_MS;\n return now + staleTimeMs;\n}\n/**\n * Reads a stale-at time by `await`ing the staleTime async iterable (last\n * yielded value wins) and, if a `response` is given and the iterable yields\n * nothing, falling back to the `Next-Router-Stale-Time` header.\n *\n * The async form is required for the two things `readFulfilledStaleAt` can't\n * do: the header fallback, and reading a dynamic `Full` response\n * (fetchStrategy.Full with Partial Prefetching disabled) — the one response\n * kind that isn't buffered before it's read, so its iterable values must be\n * awaited rather than drained synchronously off their thenable status.\n *\n * Buffered responses (static PPR, runtime prefetch, stage decodes) don't need\n * the async form: segment bundles and the shell-stage decode already read\n * staleTime synchronously via `readFulfilledStaleAt`, and the remaining\n * buffered callers here could be moved to it too.\n */ export async function resolveStaleAt(now, staleTimeIterable, response) {\n if (staleTimeIterable !== undefined) {\n // Iterate the async iterable and take the last yielded value. The server\n // yields updated staleTime values during the render; the last one is the\n // final staleTime.\n let staleTimeSeconds;\n for await (const value of staleTimeIterable){\n staleTimeSeconds = value;\n }\n if (staleTimeSeconds !== undefined) {\n const staleTimeMs = isNaN(staleTimeSeconds) ? STATIC_STALETIME_MS : getStaleTimeMs(staleTimeSeconds);\n return now + staleTimeMs;\n }\n }\n if (response !== undefined) {\n return getStaleAtFromHeader(now, response);\n }\n return now + STATIC_STALETIME_MS;\n}\n/**\n * Fire-and-forget (\"spawn\"), unlike the synchronous cache-write family it\n * wraps (writeServerResponseIntoCache and below): the stage's staleTime must\n * be resolved asynchronously from the response's own `s` field before the\n * write can happen, and failures are swallowed — a failed cache write is not\n * fatal to the render that produced the response.\n *\n * Writes the static stage of a navigation response — or of the initial RSC\n * payload — into the segment cache, so subsequent navigations can serve\n * cached static segments instantly.\n */ export function spawnStaticStageCacheWrite(now, response, isResponsePartial, // The navigation response's headers, used to derive the buildId for the\n// write-layer build check (the deployment header, falling back to the\n// response's `b` field). Null for the initial payload, which arrived in\n// the HTML document and has no build-id check.\nresponseHeaders, baseTree, renderedSearch, // The map the work that spawned this response's request is bound to. See\n// writeServerResponseIntoCache.\nmap) {\n const buildId = responseHeaders !== null ? responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? response.b : undefined;\n resolveStaleAt(now, response.s).then((staleAt)=>{\n // TODO: This entire write is legacy and will be deleted in a future\n // PR: caching is organized around the conceptual shell vs not-shell\n // distinction, not around the static vs runtime render stages, so a\n // static-stage write has no place in the model. It's kept only until\n // its removal PR lands — do not extend it (e.g. with shell\n // extraction).\n writeServerResponseIntoCache(now, FetchStrategy.PPR, response, baseTree, // The base tree is the navigation's current tree, not a prediction;\n // divergence from it carries no signal.\n null, // Navigation responses always include the param values in the tree,\n // so there's no pathname to parse them from (nor a need to).\n null, renderedSearch, buildId, staleAt, isResponsePartial, null, // No owned entries; every write is a detached upsert.\n null, null, map);\n }).catch(()=>{\n // The static stage processing failed. Not fatal — the render\n // completed normally, we just won't write into the cache.\n });\n}\n/**\n * Decodes an embedded runtime prefetch Flight stream and writes it into the\n * segment cache, so subsequent navigations can serve runtime-prefetchable\n * content from cache without a separate prefetch request.\n *\n * The stream is buffered before it's decoded, like every prefetch response\n * that carries cache metadata: the shell byte offset (`a`) and staleTime are\n * read synchronously off their thenable status, and extracting a distinct\n * shell stage requires re-decoding a truncated copy of the same bytes. The\n * writes go through the shared payload-pair orchestration\n * (writeResponsePayloadsIntoCache): the full payload is written at\n * PPRRuntime and a distinct shell stage at the shell tier (RuntimeShell),\n * like any other runtime prefetch response. This flow owns no pending\n * entries, so every write is a detached upsert.\n */ export async function writeRuntimePrefetchStreamIntoCache(now, runtimePrefetchStream, baseTree, renderedSearch, // The map the work that spawned this response's request is bound to. See\n// writeServerResponseIntoCache.\nmap) {\n const { stream, isPartial } = await stripIsPartialByte(runtimePrefetchStream);\n const buffer = await bufferPrefetchResponseBody(stream);\n const serverData = await decodeBufferedStage(buffer, undefined);\n // Extract the shell payload, when the response carries one. Same wire\n // convention as the other live-render responses (see\n // resolveShellStageResponse): `a` absent means the render wasn't staged —\n // no shell exists; `null` means the shell IS the full response; a number\n // is the byte boundary of a distinct shell prefix, which is re-decoded\n // from a truncated copy of the buffer. An unreadable `a` — pending or\n // rejected, which only an aborted render produces — conservatively reads\n // as no shell: the full payload is still written, there's just no shell\n // stage to extract from it.\n let shellResponse = null;\n if (serverData.a !== undefined) {\n const shellByteLength = readFulfilledValue(serverData.a, undefined);\n if (shellByteLength === null) {\n shellResponse = serverData;\n } else if (shellByteLength !== undefined) {\n try {\n shellResponse = await decodeBufferedStage(buffer.subarray(0, shellByteLength), undefined);\n } catch {\n // The truncated prefix couldn't be decoded. Treat it as if no shell\n // exists; the full payload is still usable.\n shellResponse = null;\n }\n }\n }\n writeResponsePayloadsIntoCache(now, // A runtime prefetch stream is by definition a runtime prefetch.\n FetchStrategy.PPRRuntime, serverData, shellResponse, baseTree, // The base tree is the navigation's current tree, not a prediction;\n // divergence from it carries no signal.\n null, // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null, renderedSearch, serverData.b, // The response is fully buffered, so staleTime is read synchronously.\n readFulfilledStaleAt(now, serverData.s), isPartial, null, // This flow owns no pending entries; every write is a detached upsert.\n null, // Detached writes aren't sized; see writeResponsePayloadsIntoCache.\n null, map);\n}\n/**\n * Strips the leading isPartial byte from an RSC response stream.\n *\n * The server prepends a single byte: '~' (0x7e) for partial, '#' (0x23) for\n * complete. These bytes cannot appear as the first byte of a valid RSC Flight\n * response (Flight rows start with a hex digit or ':').\n *\n * If the first byte is not a recognized marker, the stream is returned intact\n * and `isPartial` is determined by the cachedNavigations experimental flag.\n */ export async function stripIsPartialByte(stream) {\n // When there is no recognized marker byte, the fallback depends on whether\n // Cached Navigations is enabled. When enabled, dynamic navigation responses\n // don't have a marker but may contain dynamic holes, so they are treated as\n // partial. When disabled, unmarked responses are treated as non-partial.\n const defaultIsPartial = !!process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS;\n const reader = stream.getReader();\n const { done, value } = await reader.read();\n if (done || !value || value.byteLength === 0) {\n return {\n stream: new ReadableStream({\n start: (c)=>c.close()\n }),\n isPartial: defaultIsPartial\n };\n }\n const firstByte = value[0];\n const hasMarker = firstByte === 0x23 || firstByte === 0x7e;\n const isPartial = hasMarker ? firstByte === 0x7e : defaultIsPartial;\n const remainder = hasMarker ? value.byteLength > 1 ? value.subarray(1) : null : value;\n return {\n isPartial,\n stream: new ReadableStream({\n start (controller) {\n if (remainder) {\n controller.enqueue(remainder);\n }\n },\n async pull (controller) {\n const result = await reader.read();\n if (result.done) {\n controller.close();\n } else {\n controller.enqueue(result.value);\n }\n }\n })\n };\n}\n\n//# sourceMappingURL=cache.js.map","/**\n * Vary Params Decoding\n *\n * This module is shared between server and client.\n */ import { readFulfilledValue } from '../rsc-transport';\n/**\n * The vary path id for search params. Path params are identified by their\n * name. Search params don't have a fixed set of names, so any access to them\n * is reported under this one id, and the segment is keyed by the whole search\n * string (see createVaryingSearchParams in app-render/vary-params.ts).\n *\n * It's a number so it can't collide with a param name. `app/[?]/page.tsx` is a\n * valid route.\n */ export const SEARCH_PARAMS_VARY_ID = 0;\n/**\n * Synchronously drains a vary params `AsyncIterable`, adding each yielded name\n * to `target`.\n *\n * By the time this runs (on the client, or in collectSegmentData), the Flight\n * stream has been fully buffered, so every yielded value is already\n * materialized and can be read without awaiting: each iterator result is a\n * Flight chunk whose settled state `readFulfilledValue` reads off the\n * thenable's status.\n *\n * We add \"every param yielded up to the point the stream suspends\": a\n * normally-closed iterable drains fully, while one left hanging (a sync-I/O\n * abort, or a `close()` whose row hasn't flushed yet) drains to the prefix\n * already in the stream. Both are correct — a segment's param accesses are all\n * flushed as they happen during its render, so the prefix is exactly the set\n * the response depends on. We therefore never need the terminating `done` row\n * to be present; it's only stream hygiene.\n */ function drainVaryParams(iterable, target) {\n const iterator = iterable[Symbol.asyncIterator]();\n while(true){\n const step = readFulfilledValue(iterator.next(), undefined);\n if (step === undefined || step.done) {\n // Either the stream suspended here — everything yielded before this\n // point has already been added — or the iterable finished cleanly.\n return;\n }\n target.add(step.value);\n }\n}\n/**\n * Converts a segment's (or the head's) vary params off the wire, at the\n * decode boundary, unioning in the response-level root params.\n *\n * Root params are emitted once at the top level rather than folded into every\n * segment by the server, so every decode recombines them here — building the\n * merge into the decode means a caller can't forget it, and it's done in a\n * single pass with no intermediate set.\n *\n * Returns null (\"unknown\", key on all params) unless BOTH iterables are\n * present. A null/absent `iterable` means the segment's own tracking wasn't\n * enabled (e.g. not a prerender). A null/absent `rootIterable` means root\n * params weren't tracked — and since a segment's own iterable never includes\n * root params (those are accessed in layouts above it), narrowing on the\n * segment set alone would wrongly assume no root params were accessed. In\n * either case we stay conservative.\n *\n * When both are present each is authoritative even when it drains to the empty\n * set — a tracked segment that read no params, with no root params accessed,\n * can be shared across all param values.\n */ export function decodeVaryParams(iterable, rootIterable) {\n if (iterable === null || iterable === undefined || rootIterable === null || rootIterable === undefined) {\n return null;\n }\n const total = new Set();\n drainVaryParams(iterable, total);\n drainVaryParams(rootIterable, total);\n return createVaryParams(total);\n}\n/**\n * Wraps an already-known set as a vary params source. Shaped like a settled\n * Flight promise so readVaryParams can read it off the thenable's status.\n */ export function createVaryParams(total) {\n // TODO: Don't need to use a native promise. Just inline a thenable that\n // immediately calls its listener.\n const settled = Promise.resolve(total);\n settled.status = 'fulfilled';\n settled.value = total;\n return settled;\n}\n/**\n * Reads the set from a vary params source. Null when it is not available;\n * the reader assumes every param varies.\n */ export function readVaryParams(varyParams) {\n return readFulfilledValue(varyParams, null);\n}\n\n//# sourceMappingURL=vary-params-decoding.js.map","// The sequential implementation of callServer (app-call-server.ts): Server\n// Actions are dispatched into the sequential router action queue. Callers\n// must never import this module directly; they import './app-call-server',\n// which resolves here unless `experimental.concurrentRouterQueue` swaps in\n// './concurrent-call-server' at the bundler level (see\n// create-compiler-aliases.ts and next_import_map.rs).\n//\n// This module must remain free of side effects at module scope: in addition\n// to the browser bundle, a statically-resolved copy may be compiled into the\n// pre-compiled app-page runtime bundles, where the bundler alias cannot\n// reach. Only the browser copy ever runs.\nimport { startTransition } from 'react';\nimport { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types';\nimport { dispatchAppRouterAction } from './components/use-action-queue';\nexport async function callServer(actionId, actionArgs) {\n return new Promise((resolve, reject)=>{\n startTransition(()=>{\n dispatchAppRouterAction({\n type: ACTION_SERVER_ACTION,\n actionId,\n actionArgs,\n resolve,\n reject\n });\n });\n });\n}\n\n//# sourceMappingURL=sequential-call-server.js.map","import { PrefetchHint } from '../../shared/lib/app-router-types';\nimport { DEFAULT_SEGMENT_KEY, NOT_FOUND_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../../shared/lib/segment';\nimport { HEAD_REQUEST_KEY } from '../../shared/lib/segment-cache/segment-value-encoding';\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url';\nimport { fetchServerResponse } from './router-reducer/fetch-server-response';\nimport { dispatchAppRouterAction } from './use-action-queue';\nimport { ACTION_SERVER_PATCH } from './router-reducer/router-reducer-types';\nimport { isNavigatingToNewRootLayout } from './router-reducer/is-navigating-to-new-root-layout';\nimport { getLastCommittedTree } from './router-reducer/reducers/committed-state';\nimport { createNavigationSeed } from './segment-cache/decode-server-response';\nimport { segmentCacheMap, rebaseInactiveRouteTree, doesRouteStructureMatch, readSegmentCacheEntryForNavigation, waitForSegmentCacheEntry, invalidateRouteCacheEntries, spawnStaticStageCacheWrite, writeRuntimePrefetchStreamIntoCache, EntryStatus, MetadataOnlyRequestTree } from './segment-cache/cache';\nimport { discoverKnownRoute } from './segment-cache/optimistic-routes';\nimport { getRenderedSearchFromVaryPath, compareParams, ParamsChange, didReadChangedParam } from './segment-cache/vary-path';\nimport { readFromBFCache, readFromBFCacheDuringRegularNavigation, writeToBFCache, updateBFCacheEntryFromDynamicResponse, computeDynamicStaleAt } from './segment-cache/bfcache';\nexport function createRootNavigationTask(tree, head) {\n return {\n tree,\n head\n };\n}\nexport var FreshnessPolicy = /*#__PURE__*/ function(FreshnessPolicy) {\n FreshnessPolicy[FreshnessPolicy[\"Default\"] = 0] = \"Default\";\n FreshnessPolicy[FreshnessPolicy[\"Hydration\"] = 1] = \"Hydration\";\n FreshnessPolicy[FreshnessPolicy[\"HistoryTraversal\"] = 2] = \"HistoryTraversal\";\n FreshnessPolicy[FreshnessPolicy[\"RefreshAll\"] = 3] = \"RefreshAll\";\n FreshnessPolicy[FreshnessPolicy[\"HMRRefresh\"] = 4] = \"HMRRefresh\";\n FreshnessPolicy[FreshnessPolicy[\"Gesture\"] = 5] = \"Gesture\";\n return FreshnessPolicy;\n}({});\nconst noop = ()=>{};\nexport function createInitialRenderTreeForHydration(navigatedAt, initialRoot, seedDynamicStaleAt) {\n // Create the initial cache node tree, using the data embedded into the\n // HTML document.\n const accumulation = {\n separateRefreshUrls: null,\n scrollRef: null\n };\n const parentNeedsDynamicRequest = false;\n const restrictToShell = false;\n // Hydration is bound to the shared map.\n const map = segmentCacheMap;\n const tree = createRenderTreeOnNavigation(navigatedAt, initialRoot.tree, 1, seedDynamicStaleAt, parentNeedsDynamicRequest, accumulation, map, restrictToShell);\n const head = createRenderTreeOnNavigation(navigatedAt, initialRoot.head, 1, seedDynamicStaleAt, parentNeedsDynamicRequest, accumulation, map, restrictToShell);\n return createRootNavigationTask(tree, head);\n}\n// Creates a new Cache Node tree (i.e. copy-on-write) that represents the\n// optimistic result of a navigation, using both the current Cache Node tree and\n// data that was prefetched prior to navigation.\n//\n// At the moment we call this function, we haven't yet received the navigation\n// response from the server. It could send back something completely different\n// from the tree that was prefetched — due to rewrites, default routes, parallel\n// routes, etc.\n//\n// But in most cases, it will return the same tree that we prefetched, just with\n// the dynamic holes filled in. So we optimistically assume this will happen,\n// and accept that the real result could be arbitrarily different.\n//\n// We'll reuse anything that was already in the previous tree, since that's what\n// the server does.\n//\n// New segments (ones that don't appear in the old tree) are assigned an\n// unresolved promise. The data for these promises will be fulfilled later, when\n// the navigation response is received.\n//\n// The tree can be rendered immediately after it is created (that's why this is\n// a synchronous function). Any new trees that do not have prefetch data will\n// suspend during rendering, until the dynamic data streams in.\n//\n// Returns the tasks for the route tree and the head, each containing both the\n// updated Cache Node and a path to the pending subtrees that need to be\n// resolved by the navigation response.\n//\n// A return value of `null` means a full-page (MPA) navigation is required.\nexport function startPPRNavigation(navigatedAt, oldUrl, oldRenderedSearch, oldRoot, newRoot, freshness, seedDynamicStaleAt, isSamePageNavigation, accumulation, // The segment cache map this navigation is bound to: a locked navigation's\n// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\nmap, // Instant Navigation Testing API only — restricts segment reads to shell\n// entries. Always false outside the testing API. See navigation-testing-lock.\nrestrictToShell) {\n const parentNeedsDynamicRequest = false;\n const parentRefreshState = null;\n const oldRootRefreshState = {\n canonicalUrl: createHrefFromUrl(oldUrl),\n renderedSearch: oldRenderedSearch\n };\n const tree = updateRenderTreeOnNavigation(navigatedAt, oldRoot.tree, newRoot.tree, freshness, seedDynamicStaleAt, isSamePageNavigation, parentNeedsDynamicRequest, oldRootRefreshState, parentRefreshState, accumulation, map, restrictToShell);\n if (tree === null) {\n // The route tree changed at or above the root layout. Perform a full-page\n // navigation.\n return null;\n }\n const head = updateRenderTreeOnNavigation(navigatedAt, oldRoot.head, newRoot.head, freshness, seedDynamicStaleAt, isSamePageNavigation, parentNeedsDynamicRequest, oldRootRefreshState, parentRefreshState, accumulation, map, restrictToShell);\n if (head === null) {\n // Unreachable: a one-node tree has no root layout to change and no slots.\n return null;\n }\n return createRootNavigationTask(tree, head);\n}\n// TODO: Unify NavigationTask with CacheNode.\nfunction createNavigationTask(status, route, node, dynamicRequestTree, children) {\n return {\n status,\n route,\n node,\n dynamicRequestTree,\n children\n };\n}\nfunction updateRenderTreeOnNavigation(navigatedAt, oldRenderTree, newRouteTree, freshness, seedDynamicStaleAt, isSamePageNavigation, parentNeedsDynamicRequest, oldRootRefreshState, parentRefreshState, accumulation, map, // Instant Navigation Testing API only — restricts segment reads to shell\n// entries. Always false outside the testing API. See navigation-testing-lock.\nrestrictToShell) {\n // Check if the route structure changed. If only the params changed, that's\n // handled further down.\n const newSegment = newRouteTree.segment;\n if (!doesRouteStructureMatch(oldRenderTree, newRouteTree)) {\n // This segment does not match the previous route. We're now entering the\n // new part of the target route. Switch to the \"create\" path.\n if ((newRouteTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0 && isNavigatingToNewRootLayout(oldRenderTree, newRouteTree) || // The global Not Found route (app/global-not-found.tsx) is a special\n // case, because it acts like a root layout, but in the router tree, it\n // is rendered in the same position as app/layout.tsx.\n //\n // Any navigation to the global Not Found route should trigger a\n // full-page navigation.\n //\n // TODO: We should probably model this by changing the key of the root\n // segment when this happens. Then the root layout check would work\n // as expected, without a special case.\n newSegment === NOT_FOUND_SEGMENT_KEY) {\n return null;\n }\n return createRenderTreeOnNavigation(navigatedAt, newRouteTree, freshness, seedDynamicStaleAt, parentNeedsDynamicRequest, accumulation, map, restrictToShell);\n }\n const newSlots = newRouteTree.slots;\n let shouldRefreshDynamicData = false;\n switch(freshness){\n case 0:\n case 2:\n case 1:\n case 5:\n shouldRefreshDynamicData = false;\n break;\n case 3:\n case 4:\n shouldRefreshDynamicData = true;\n break;\n default:\n freshness;\n break;\n }\n const isLeafSegment = newSlots === null;\n // Get the data for this segment. Since it was part of the previous route,\n // usually we just reuse the data from the old render tree. If the params\n // changed, or during a refresh or revalidation, consult the prefetch cache\n // or response seed instead.\n let newRenderTree;\n let needsDynamicRequest;\n const paramsChange = compareParams(oldRenderTree.varyPath, newRouteTree.varyPath);\n if (paramsChange !== ParamsChange.None) {\n // Path params are part of LayoutRouter's React key, so changing one\n // remounts this segment and everything below it. Generate a new bfcacheId\n // to match. Search params aren't part of the key, so a page whose search\n // params changed keeps its existing id.\n let bfcacheId;\n if (paramsChange === ParamsChange.PathParam) {\n bfcacheId = generateBFCacheId(freshness);\n } else {\n bfcacheId = oldRenderTree.data.bfcacheId;\n }\n switch(freshness){\n case 0:\n case 5:\n {\n // If the existing data didn't read any of the params that changed, we\n // can keep using it. Refreshes always fetch new data, and back/forward\n // navigations restore the entry from the BFCache instead.\n const oldCacheNode = oldRenderTree.data;\n if (!didReadChangedParam(oldRenderTree.varyPath, newRouteTree.varyPath, oldCacheNode.varyParams)) {\n const cacheNode = createCacheNode(oldCacheNode.rsc, oldCacheNode.prefetchRsc, oldCacheNode.varyParams, bfcacheId);\n if (freshness !== 5) {\n writeToBFCache(navigatedAt, newRouteTree.varyPath, cacheNode, seedDynamicStaleAt);\n }\n newRenderTree = createRenderTree(newRouteTree, cacheNode);\n needsDynamicRequest = false;\n break;\n }\n // Intentional fallthrough\n }\n case 1:\n case 2:\n case 3:\n case 4:\n {\n const result = createRenderTreeForSegment(navigatedAt, newRouteTree, freshness, seedDynamicStaleAt, bfcacheId, map, restrictToShell);\n newRenderTree = result.node;\n needsDynamicRequest = result.needsDynamicRequest;\n break;\n }\n }\n // A param change mostly acts the same as a refresh, except it does\n // trigger a scroll.\n if (isLeafSegment) {\n accumulateScrollRef(freshness, newRenderTree.data, accumulation);\n }\n } else if (shouldRefreshDynamicData || // During a same-page navigation, we always refetch the page segments\n isLeafSegment && isSamePageNavigation) {\n // This is a refresh of an existing segment. Ignore the existing render\n // tree and create a new one.\n const result = createRenderTreeForSegment(navigatedAt, newRouteTree, freshness, seedDynamicStaleAt, // Refreshing data preserves the identity of the active segment.\n oldRenderTree.data.bfcacheId, map, restrictToShell);\n newRenderTree = result.node;\n needsDynamicRequest = result.needsDynamicRequest;\n // Carry forward the old node's scrollRef. This preserves scroll intent\n // when a prior navigation's render tree is replaced by a refresh before\n // the scroll handler has had a chance to fire — e.g. when router.push()\n // and router.refresh() are called in the same startTransition batch.\n newRenderTree.data.scrollRef = oldRenderTree.data.scrollRef;\n } else {\n // This segment appears in both the old and new routes. Reuse the existing\n // data without triggering a request.\n // TODO: Consider adding a fast path where if this segment is unchanged and\n // all of its children are unchanged, we return the exact same RenderTree\n // object. Reusing the exact previous object gives React more of a chance to\n // bail out of rendering.\n newRenderTree = createRenderTree(newRouteTree, oldRenderTree.data);\n needsDynamicRequest = false;\n }\n // During a refresh navigation, there's a special case that happens when\n // entering a \"default\" slot. The default slot may not be part of the\n // current route; it may have been reused from an older route. If so,\n // we need to fetch its data from the old route's URL rather than current\n // route's URL. Keep track of this as we traverse the tree.\n const maybeRefreshState = newRouteTree.refreshState;\n const refreshState = maybeRefreshState !== undefined && maybeRefreshState !== null ? // refresh URL as we continue traversing the tree.\n maybeRefreshState : parentRefreshState;\n newRenderTree.refreshState = refreshState;\n // If this segment itself needs to fetch new data from the server, then by\n // definition it is being refreshed. Track its refresh URL so we know which\n // URL to request the data from.\n if (needsDynamicRequest && refreshState !== null) {\n accumulateRefreshUrl(accumulation, refreshState);\n }\n // As we diff the trees, we may sometimes modify (copy-on-write, not mutate)\n // the Route Tree that was returned by the server — for example, in the case\n // of default parallel routes, we preserve the currently active segment. To\n // avoid mutating the original tree, we clone the router state children along\n // the return path.\n let patchedRouterStateChildren = {};\n let taskChildren = null;\n // Most navigations require a request to fetch additional data from the\n // server, either because the data was not already prefetched, or because the\n // target route contains dynamic data that cannot be prefetched.\n //\n // However, if the target route is fully static, and it's already completely\n // loaded into the segment cache, then we can skip the server request.\n //\n // This starts off as `false`, and is set to `true` if any of the child\n // routes requires a dynamic request.\n let childNeedsDynamicRequest = false;\n // As we traverse the children, we'll construct a FlightRouterState that can\n // be sent to the server to request the dynamic data. If it turns out that\n // nothing in the subtree is dynamic (i.e. childNeedsDynamicRequest is false\n // at the end), then this will be discarded.\n // TODO: We can probably optimize the format of this data structure to only\n // include paths that are dynamic. Instead of reusing the\n // FlightRouterState type.\n let dynamicRequestTreeChildren = {};\n if (newSlots !== null) {\n const oldRenderTreeSlots = oldRenderTree.slots;\n const newRenderTreeSlots = new Map();\n newRenderTree.slots = newRenderTreeSlots;\n taskChildren = new Map();\n for (let [parallelRouteKey, newRouteTreeChild] of newSlots){\n const oldRenderTreeChild = oldRenderTreeSlots?.get(parallelRouteKey);\n if (oldRenderTreeChild === undefined) {\n // This should never happen, but if it does, it suggests a malformed\n // server response. Trigger a full-page navigation.\n return null;\n }\n const oldSegmentChild = oldRenderTreeChild.segment;\n const newSegmentChild = newRouteTreeChild.segment;\n if (// Skip this branch during a history traversal. We restore the tree that\n // was stashed in the history entry as-is.\n freshness !== 2 && newSegmentChild === DEFAULT_SEGMENT_KEY && oldSegmentChild !== DEFAULT_SEGMENT_KEY && // The active segment was rendered with this layout's params. If a\n // path param changed, we can't keep it. Use the default segment from\n // the server instead.\n paramsChange !== ParamsChange.PathParam) {\n // This is a \"default\" segment. These are never sent by the server during\n // a soft navigation; instead, the client reuses whatever segment was\n // already active in that slot on the previous route.\n newRouteTreeChild = reuseActiveSegmentInDefaultSlot(oldRootRefreshState, oldRenderTreeChild);\n }\n const taskChild = updateRenderTreeOnNavigation(navigatedAt, oldRenderTreeChild, newRouteTreeChild, freshness, seedDynamicStaleAt, isSamePageNavigation, parentNeedsDynamicRequest || needsDynamicRequest, oldRootRefreshState, refreshState, accumulation, map, restrictToShell);\n if (taskChild === null) {\n // One of the child tasks discovered a change to the root layout.\n // Immediately unwind from this recursive traversal. This will trigger a\n // full-page navigation.\n return null;\n }\n // Recursively propagate up the child tasks.\n taskChildren.set(parallelRouteKey, taskChild);\n newRenderTreeSlots.set(parallelRouteKey, taskChild.node);\n // The child tree's route state may be different from the prefetched\n // route sent by the server. We need to clone it as we traverse back up\n // the tree.\n const taskChildRoute = taskChild.route;\n patchedRouterStateChildren[parallelRouteKey] = taskChildRoute;\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree;\n if (dynamicRequestTreeChild !== null) {\n // Something in the child tree is dynamic.\n childNeedsDynamicRequest = true;\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild;\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute;\n }\n }\n }\n const newFlightRouterState = createRouterStateForSegment(newRouteTree, patchedRouterStateChildren, refreshState);\n return createNavigationTask(needsDynamicRequest ? 0 : 1, newFlightRouterState, newRenderTree, createDynamicRequestTree(newFlightRouterState, dynamicRequestTreeChildren, needsDynamicRequest, childNeedsDynamicRequest, parentNeedsDynamicRequest), taskChildren);\n}\n/**\n * Assigns a ScrollRef to a new leaf CacheNode so the scroll handler\n * knows to scroll to it after navigation. All leaves in the same\n * navigation share the same ScrollRef — the first segment to scroll\n * consumes it, preventing others from also scrolling.\n *\n * Called for newly entered segments, and for segments whose params changed\n * (even if their data was reused). Refreshes keep the existing scroll ref.\n *\n * Skipped during hydration (initial render should not scroll) and\n * history traversal (scroll restoration is handled separately).\n *\n * The head passes through here as a leaf too; its `scrollRef` is never read\n * (only LayoutRouter reads one), and the page leaf sets the same shared ref.\n */ function accumulateScrollRef(freshness, cacheNode, accumulation) {\n switch(freshness){\n case 0:\n case 5:\n case 3:\n case 4:\n if (accumulation.scrollRef === null) {\n accumulation.scrollRef = {\n current: true\n };\n }\n cacheNode.scrollRef = accumulation.scrollRef;\n break;\n case 1:\n break;\n case 2:\n break;\n default:\n freshness;\n break;\n }\n}\nfunction createRenderTreeOnNavigation(navigatedAt, newRouteTree, freshness, seedDynamicStaleAt, parentNeedsDynamicRequest, accumulation, map, // Instant Navigation Testing API only — restricts segment reads to shell\n// entries. Always false outside the testing API. See navigation-testing-lock.\nrestrictToShell) {\n // Same traversal as updateRenderTreeOnNavigation, but simpler. We switch to this\n // path once we reach the part of the tree that was not in the previous route.\n // We don't need to diff against the old tree, we just need to create a new\n // one. We also don't need to worry about any refresh-related logic.\n //\n // For the most part, this is a subset of updateRenderTreeOnNavigation, so any\n // change that happens in this function likely needs to be applied to that\n // one, too. However there are some places where the behavior intentionally\n // diverges, which is why we keep them separate.\n const newSlots = newRouteTree.slots;\n const result = createRenderTreeForSegment(navigatedAt, newRouteTree, freshness, seedDynamicStaleAt, // This segment was not part of the previous route, so mint a fresh\n // bfcacheId.\n generateBFCacheId(freshness), map, restrictToShell);\n const newRenderTree = result.node;\n const needsDynamicRequest = result.needsDynamicRequest;\n const isLeafSegment = newSlots === null;\n if (isLeafSegment) {\n accumulateScrollRef(freshness, newRenderTree.data, accumulation);\n }\n let patchedRouterStateChildren = {};\n let taskChildren = null;\n let childNeedsDynamicRequest = false;\n let dynamicRequestTreeChildren = {};\n if (newSlots !== null) {\n const newRenderTreeSlots = new Map();\n newRenderTree.slots = newRenderTreeSlots;\n taskChildren = new Map();\n for (const [parallelRouteKey, newRouteTreeChild] of newSlots){\n const taskChild = createRenderTreeOnNavigation(navigatedAt, newRouteTreeChild, freshness, seedDynamicStaleAt, parentNeedsDynamicRequest || needsDynamicRequest, accumulation, map, restrictToShell);\n taskChildren.set(parallelRouteKey, taskChild);\n newRenderTreeSlots.set(parallelRouteKey, taskChild.node);\n const taskChildRoute = taskChild.route;\n patchedRouterStateChildren[parallelRouteKey] = taskChildRoute;\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree;\n if (dynamicRequestTreeChild !== null) {\n childNeedsDynamicRequest = true;\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild;\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute;\n }\n }\n }\n // This route is not part of the current tree, so there's no reason to\n // track the refresh URL.\n const refreshState = null;\n const newFlightRouterState = createRouterStateForSegment(newRouteTree, patchedRouterStateChildren, refreshState);\n return createNavigationTask(needsDynamicRequest ? 0 : 1, newFlightRouterState, newRenderTree, createDynamicRequestTree(newFlightRouterState, dynamicRequestTreeChildren, needsDynamicRequest, childNeedsDynamicRequest, parentNeedsDynamicRequest), taskChildren);\n}\n// Converts a route tree node into the router state the client sends back to\n// the server. Page nodes carry their rendered search in its own slot.\nfunction createRouterStateForSegment(routeTree, children, refreshState) {\n const routerState = [\n routeTree.segment,\n children,\n refreshState !== null ? [\n refreshState.canonicalUrl,\n refreshState.renderedSearch\n ] : null,\n null,\n routeTree.prefetchHints\n ];\n if (routeTree.segment === PAGE_SEGMENT_KEY) {\n const renderedSearch = getRenderedSearchFromVaryPath(routeTree.varyPath);\n if (renderedSearch !== null) {\n routerState[5] = renderedSearch;\n }\n }\n return routerState;\n}\nfunction patchRouterStateWithNewChildren(baseRouterState, newChildren) {\n const clone = [\n baseRouterState[0],\n newChildren\n ];\n // Based on equivalent logic in apply-router-state-patch-to-tree, but should\n // confirm whether we need to copy all of these fields. Not sure the server\n // ever sends, e.g. the refetch marker.\n if (2 in baseRouterState) {\n clone[2] = baseRouterState[2];\n }\n if (3 in baseRouterState) {\n clone[3] = baseRouterState[3];\n }\n if (4 in baseRouterState) {\n clone[4] = baseRouterState[4];\n }\n if (5 in baseRouterState) {\n clone[5] = baseRouterState[5];\n }\n return clone;\n}\nfunction createDynamicRequestTree(newRouterState, dynamicRequestTreeChildren, needsDynamicRequest, childNeedsDynamicRequest, parentNeedsDynamicRequest) {\n // Create a FlightRouterState that instructs the server how to render the\n // requested segment.\n //\n // Or, if neither this segment nor any of the children require a new data,\n // then we return `null` to skip the request.\n let dynamicRequestTree = null;\n if (needsDynamicRequest) {\n dynamicRequestTree = patchRouterStateWithNewChildren(newRouterState, dynamicRequestTreeChildren);\n // The \"refetch\" marker is set on the top-most segment that requires new\n // data. We can omit it if a parent was already marked.\n if (!parentNeedsDynamicRequest) {\n dynamicRequestTree[3] = 'refetch';\n }\n } else if (childNeedsDynamicRequest) {\n // This segment does not request new data, but at least one of its\n // children does.\n dynamicRequestTree = patchRouterStateWithNewChildren(newRouterState, dynamicRequestTreeChildren);\n } else {\n dynamicRequestTree = null;\n }\n return dynamicRequestTree;\n}\nfunction accumulateRefreshUrl(accumulation, refreshState) {\n // This is a refresh navigation, and we're inside a \"default\" slot that's\n // not part of the current route; it was reused from an older route. In\n // order to get fresh data for this reused route, we need to issue a\n // separate request using the old route's URL.\n //\n // Track these extra URLs in the accumulated result. Later, we'll construct\n // an appropriate request for each unique URL in the final set. The reason\n // we don't do it immediately here is so we can deduplicate multiple\n // instances of the same URL into a single request. See\n // listenForDynamicRequest for more details.\n const refreshUrl = refreshState.canonicalUrl;\n const separateRefreshUrls = accumulation.separateRefreshUrls;\n if (separateRefreshUrls === null) {\n accumulation.separateRefreshUrls = new Set([\n refreshUrl\n ]);\n } else {\n separateRefreshUrls.add(refreshUrl);\n }\n}\nfunction reuseActiveSegmentInDefaultSlot(oldRootRefreshState, oldRenderTree) {\n // This is a \"default\" segment. These are never sent by the server during a\n // soft navigation; instead, the client reuses whatever segment was already\n // active in that slot on the previous route. This means if we later need to\n // refresh the segment, it will have to be refetched from the previous route's\n // URL. We store the refresh context on the active render tree.\n let reusedUrl;\n let reusedRenderedSearch;\n const oldRefreshState = oldRenderTree.refreshState;\n if (oldRefreshState !== null) {\n // This segment was already reused from an even older route. Keep its\n // existing URL and refresh state.\n reusedUrl = oldRefreshState.canonicalUrl;\n reusedRenderedSearch = oldRefreshState.renderedSearch;\n } else {\n // Since this route didn't already have a refresh state, it must have been\n // reachable from the root of the old route. So we use the refresh state\n // that represents the old route.\n reusedUrl = oldRootRefreshState.canonicalUrl;\n reusedRenderedSearch = oldRootRefreshState.renderedSearch;\n }\n const reusedRouteTree = rebaseInactiveRouteTree(oldRenderTree);\n reusedRouteTree.refreshState = {\n canonicalUrl: reusedUrl,\n renderedSearch: reusedRenderedSearch\n };\n return reusedRouteTree;\n}\nfunction createRenderTree(routeTree, cacheNode) {\n return {\n requestKey: routeTree.requestKey,\n segment: routeTree.segment,\n shellVaryPath: routeTree.shellVaryPath,\n refreshState: null,\n data: cacheNode,\n varyPath: routeTree.varyPath,\n slots: null,\n prefetchHints: routeTree.prefetchHints\n };\n}\nfunction createRenderTreeForSegment(now, // A route tree node, or the one-node metadata tree that stands in for the\n// head (see createMetadataRouteTree).\ntree, freshness, dynamicStaleAt, bfcacheId, map, // Instant Navigation Testing API only — restricts segment reads to shell\n// entries. Always false outside the testing API. See navigation-testing-lock.\nrestrictToShell) {\n // Construct an owned render tree using data from the BFCache, the client's\n // Segment Cache, or seeded from a server response.\n //\n // If there's a cache miss, or if we only have a partial hit, we'll render\n // the partial state immediately, and spawn a request to the server to fill\n // in the missing data.\n //\n // If the segment is fully cached on the client already, we can omit this\n // segment from the server request.\n //\n // If we already have a dynamic data response associated with this navigation,\n // as in the case of a Server Action-initiated redirect or refresh, we may\n // also be able to use that data without spawning a new request. (This is\n // referred to as the \"seed\" data.)\n const seedData = tree.data;\n const seedRsc = seedData !== null ? seedData.rsc : null;\n const seedVaryParams = seedData !== null ? seedData.varyParams : null;\n // During certain kinds of navigations, we may be able to render from\n // the BFCache.\n switch(freshness){\n case 0:\n {\n // Check BFCache during regular navigations. The entry's staleAt\n // determines whether it's still fresh. This is used when\n // staleTimes.dynamic is configured globally or when a page exports\n // unstable_dynamicStaleTime for per-page control.\n const bfcacheEntry = readFromBFCacheDuringRegularNavigation(now, tree.varyPath);\n if (bfcacheEntry !== null) {\n // A regular navigation that happens to read cached data is still a\n // fresh navigation, so we use the caller-supplied bfcacheId — the\n // BFCacheEntry's id is only restored on history-traversal\n // navigations.\n return {\n node: createRenderTree(tree, createCacheNode(bfcacheEntry.rsc, bfcacheEntry.prefetchRsc, bfcacheEntry.varyParams, bfcacheId)),\n needsDynamicRequest: false\n };\n }\n break;\n }\n case 1:\n {\n // This is not related to the BFCache but it is a special case.\n //\n // We should never spawn network requests during hydration. We must treat\n // the initial payload as authoritative, because the initial page load is\n // used as a last-ditch mechanism for recovering the app.\n //\n // This is also an important safety check because if this leaks into the\n // server rendering path (which theoretically it never should because the\n // server payload should be consistent), the server would hang because these\n // promises would never resolve.\n //\n // TODO: There is an existing case where the global \"not found\" boundary\n // triggers this path. But it does render correctly despite that. That's an\n // unusual render path so it's not surprising, but we should look into\n // modeling it in a more consistent way. See also the /_notFound special\n // case in updateRenderTreeOnNavigation.\n const cacheNode = createCacheNode(seedRsc, null, seedVaryParams, bfcacheId);\n writeToBFCache(now, tree.varyPath, cacheNode, dynamicStaleAt);\n return {\n node: createRenderTree(tree, cacheNode),\n needsDynamicRequest: false\n };\n }\n case 2:\n const bfcacheEntry = readFromBFCache(tree.varyPath);\n if (bfcacheEntry !== null) {\n // Only show prefetched data if the dynamic data is still pending. This\n // avoids a flash back to the prefetch state in a case where it's highly\n // likely to have already streamed in.\n //\n // Tehnically, what we're actually checking is whether the dynamic\n // network response was received. But since it's a streaming response,\n // this does not mean that all the dynamic data has fully streamed in.\n // It just means that _some_ of the dynamic data was received. But as a\n // heuristic, we assume that the rest dynamic data will stream in\n // quickly, so it's still better to skip the prefetch state.\n const oldRsc = bfcacheEntry.rsc;\n const oldRscDidResolve = !isDeferredRsc(oldRsc) || oldRsc.status !== 'pending';\n const dropPrefetchRsc = oldRscDidResolve;\n // Restore the bfcacheId from the cached entry so that back/forward\n // navigations preserve the original id, regardless of whether\n // `cacheComponents` Activity preservation is enabled.\n return {\n node: createRenderTree(tree, createCacheNode(bfcacheEntry.rsc, dropPrefetchRsc ? null : bfcacheEntry.prefetchRsc, bfcacheEntry.varyParams, bfcacheEntry.bfcacheId)),\n needsDynamicRequest: false\n };\n }\n break;\n case 3:\n case 4:\n case 5:\n break;\n default:\n freshness;\n break;\n }\n let cachedRsc = null;\n let isCachedRscPartial = true;\n let cachedVaryParams = null;\n const segmentEntry = readSegmentCacheEntryForNavigation(now, map, tree.varyPath, restrictToShell);\n if (segmentEntry !== null) {\n switch(segmentEntry.status){\n case EntryStatus.Fulfilled:\n {\n // Happy path: a cache hit\n cachedRsc = segmentEntry.rsc;\n isCachedRscPartial = segmentEntry.isPartial;\n cachedVaryParams = segmentEntry.varyParams;\n break;\n }\n case EntryStatus.Pending:\n {\n // We haven't received data for this segment yet, but there's already\n // an in-progress request. Since it's extremely likely to arrive\n // before the dynamic data response, we might as well use it.\n const promiseForFulfilledEntry = waitForSegmentCacheEntry(segmentEntry);\n cachedRsc = promiseForFulfilledEntry.then((entry)=>entry !== null ? entry.rsc : null);\n // The entry's data hasn't arrived, and neither has the source of the\n // params it depends on; `cachedVaryParams` stays null.\n // Because the request is still pending, we typically don't know yet\n // whether the response will be partial. We shouldn't skip this segment\n // during the dynamic navigation request. Otherwise, we might need to\n // do yet another request to fill in the remaining data, creating\n // a waterfall.\n //\n // The one exception is if this segment is being fetched with via\n // prefetch={true} (i.e. the \"force stale\" or \"full\" strategy). If so,\n // we can assume the response will be full. This field is set to `false`\n // for such segments.\n isCachedRscPartial = segmentEntry.isPartial;\n break;\n }\n case EntryStatus.Empty:\n case EntryStatus.Rejected:\n {\n break;\n }\n default:\n {\n segmentEntry;\n break;\n }\n }\n }\n if (process.env.__NEXT_OPTIMISTIC_ROUTING && tree.segment === HEAD_REQUEST_KEY && isCachedRscPartial) {\n // TODO: When optimistic routing is enabled, don't block on waiting for\n // the viewport to resolve. This is a temporary workaround until Vary\n // Params are tracked when rendering the metadata. We'll fix it before\n // this feature is stable. However, it's not a critical issue because 1)\n // it will stream in eventually anyway 2) metadata is wrapped in an\n // internal Suspense boundary, so is always non-blocking; this only\n // affects the viewport node, which is meant to blocking, however... 3)\n // before Segment Cache landed this wasn't always the case, anyway, so\n // it's unlikely that many people are relying on this behavior. Still,\n // will be fixed before stable. It's the very next step in the sequence of\n // work on this project.\n //\n // This line of code works because the App Router treats `null` as\n // \"no renderable head available\", rather than an empty head. React treats\n // an empty string as empty.\n cachedRsc = '';\n }\n // Now combine the cached data with the seed data to determine what we can\n // render immediately, versus what needs to stream in later.\n // A partial state to show immediately while we wait for the final data to\n // arrive. If `rsc` is already a complete value (not partial), or if we\n // don't have any useful partial state, this will be `null`.\n let prefetchRsc;\n // The final, resolved segment data. If the data is missing, this will be a\n // promise that resolves to the eventual data. A resolved value of `null`\n // means the data failed to load; the LayoutRouter will suspend indefinitely\n // until the router updates again (refer to finishNavigationTask).\n let rsc;\n // The source of the params `rsc` depends on. A server response or a\n // fulfilled segment cache entry carries one; a deferred `rsc` gets its\n // source when the response arrives (finishPendingCacheNode).\n let varyParams;\n let doesSegmentNeedDynamicRequest;\n if (seedRsc !== null) {\n // We already have a dynamic server response for this segment.\n if (isCachedRscPartial) {\n // The seed data may still be streaming in, so it's worth showing the\n // partial cached state in the meantime.\n prefetchRsc = cachedRsc;\n rsc = seedRsc;\n varyParams = seedVaryParams;\n } else {\n // We already have a completely cached segment. Ignore the seed data,\n // which may still be streaming in. This shouldn't happen in the normal\n // case because the client will inform the server which segments are\n // already fully cached, and the server will skip rendering them.\n prefetchRsc = null;\n rsc = cachedRsc;\n varyParams = cachedVaryParams;\n }\n doesSegmentNeedDynamicRequest = false;\n } else {\n if (isCachedRscPartial) {\n // The cached data contains dynamic holes, or it's missing entirely. We'll\n // show the partial state immediately (if available), and stream in the\n // final data.\n //\n // Create a pending promise that we can later write to when the\n // data arrives from the server.\n prefetchRsc = cachedRsc;\n rsc = createDeferredRsc();\n varyParams = null;\n } else {\n // The data is fully cached.\n prefetchRsc = null;\n rsc = cachedRsc;\n varyParams = cachedVaryParams;\n }\n doesSegmentNeedDynamicRequest = isCachedRscPartial;\n }\n // Now that we're creating a new segment, write its data to the BFCache. A\n // subsequent back/forward navigation will reuse this same data, until or\n // unless it's cleared by a refresh/revalidation.\n //\n // Skip BFCache writes for optimistic navigations since they are transient\n // and will be replaced by the canonical navigation.\n const cacheNode = createCacheNode(rsc, prefetchRsc, varyParams, bfcacheId);\n if (freshness !== 5) {\n writeToBFCache(now, tree.varyPath, cacheNode, dynamicStaleAt);\n }\n return {\n node: createRenderTree(tree, cacheNode),\n // TODO: We should store this field on the CacheNode itself. I think we can\n // probably unify NavigationTask, CacheNode, and DeferredRsc into a\n // single type. Or at least CacheNode and DeferredRsc.\n needsDynamicRequest: doesSegmentNeedDynamicRequest\n };\n}\nfunction createCacheNode(rsc, prefetchRsc, varyParams, bfcacheId, scrollRef = null) {\n return {\n rsc,\n prefetchRsc,\n varyParams,\n scrollRef,\n bfcacheId\n };\n}\n// Globally-unique counter for fresh bfcacheIds. Incremented every time a new\n// CacheNode is created on the client. The id surfaces to user code as a\n// string via `useRouter().bfcacheId`.\nlet nextBFCacheId = 0;\nfunction generateBFCacheId(freshness) {\n // Server-side rendering and the initial client-side hydration tree both\n // use a fixed sentinel so they reconcile cleanly across hydration. The\n // counter only advances on real client-side navigations after hydration.\n if (typeof window === 'undefined') return 0;\n if (freshness === 1) return 0;\n return ++nextBFCacheId;\n}\n// Represents whether the previuos navigation resulted in a route tree mismatch.\n// A mismatch results in a refresh of the page. If there are two successive\n// mismatches, we will fall back to an MPA navigation, to prevent a retry loop.\nlet previousNavigationDidMismatch = false;\n// Writes a dynamic server response into the tree created by\n// updateRenderTreeOnNavigation. All pending promises that were spawned by the\n// navigation will be resolved, either with dynamic data from the server, or\n// `null` to indicate that the data is missing.\n//\n// A `null` value will trigger a lazy fetch during render, which will then patch\n// up the tree using the same mechanism as the non-PPR implementation\n// (serverPatchReducer).\n//\n// Usually, the server will respond with exactly the subset of data that we're\n// waiting for — everything below the nearest shared layout. But technically,\n// the server can return anything it wants.\n//\n// This does _not_ create a new tree; it modifies the existing one in place.\n// Which means it must follow the Suspense rules of cache safety.\nexport function spawnDynamicRequests(navigation, primaryUrl, nextUrl, freshnessPolicy, accumulation, // The route cache entry used for this navigation, if it came from route\n// prediction. Passed through so it can be marked as having a dynamic rewrite\n// if the server returns a different pathname than expected (indicating\n// dynamic rewrite behavior that varies by param value).\nrouteCacheEntry, // The original navigation's push/replace intent. Threaded through to the\n// server-patch retry logic so it can inherit the intent if the original\n// transition hasn't committed yet.\nnavigateType, navigationLock, // The segment cache map this navigation is bound to. See `segmentCacheMap`\n// in cache.ts.\nmap, signal) {\n let dynamicRequestTree = navigation.tree.dynamicRequestTree;\n if (dynamicRequestTree === null) {\n if (navigation.head.status === 0) {\n // Every segment is cached, but the head is not. Ask the server for the\n // head alone.\n dynamicRequestTree = MetadataOnlyRequestTree;\n } else {\n // This navigation was fully cached. There are no dynamic requests to spawn.\n previousNavigationDidMismatch = false;\n return;\n }\n }\n // This is intentionally not an async function to discourage the caller from\n // awaiting the result. Any subsequent async operations spawned by this\n // function should result in a separate navigation task, rather than\n // block the original one.\n //\n // In this function we spawn (but do not await) all the network requests that\n // block the navigation, and collect the promises. The next function,\n // `finishNavigationTask`, can await the promises in any order without\n // accidentally introducing a network waterfall.\n const primaryRequestPromise = fetchMissingDynamicData(navigation.tree, navigation.head, dynamicRequestTree, primaryUrl, nextUrl, freshnessPolicy, routeCacheEntry, navigationLock, map, signal);\n const separateRefreshUrls = accumulation.separateRefreshUrls;\n let refreshRequestPromises = null;\n if (separateRefreshUrls !== null) {\n // There are multiple URLs that we need to request the data from. This\n // happens when a \"default\" parallel route slot is present in the tree, and\n // its data cannot be fetched from the current route. We need to split the\n // combined dynamic request tree into separate requests per URL.\n // TODO: Create a scoped dynamic request tree that omits anything that\n // is not relevant to the given URL. Without doing this, the server may\n // sometimes render more data than necessary; this is not a regression\n // compared to the pre-Segment Cache implementation, though, just an\n // optimization we can make in the future.\n // Construct a request tree for each additional refresh URL. This will\n // prune away everything except the parts of the tree that match the\n // given refresh URL.\n refreshRequestPromises = [];\n const canonicalUrl = createHrefFromUrl(primaryUrl);\n for (const refreshUrl of separateRefreshUrls){\n if (refreshUrl === canonicalUrl) {\n continue;\n }\n // TODO: Create a scoped dynamic request tree that omits anything that\n // is not relevant to the given URL. Without doing this, the server may\n // sometimes render more data than necessary; this is not a regression\n // compared to the pre-Segment Cache implementation, though, just an\n // optimization we can make in the future.\n // const scopedDynamicRequestTree = splitTaskByURL(task, refreshUrl)\n const scopedDynamicRequestTree = dynamicRequestTree;\n if (scopedDynamicRequestTree !== null) {\n refreshRequestPromises.push(fetchMissingDynamicData(navigation.tree, // The head belongs to the primary URL.\n null, scopedDynamicRequestTree, new URL(refreshUrl, location.origin), // TODO: Just noticed that this should actually the Next-Url at the\n // time the refresh URL was set, not the current Next-Url. Need to\n // start tracking this alongside the refresh URL. In the meantime,\n // if a refresh fails due to a mismatch, it will trigger a\n // hard refresh.\n nextUrl, freshnessPolicy, routeCacheEntry, navigationLock, map, signal));\n }\n }\n }\n // Further async operations are moved into this separate function to\n // discourage sequential network requests.\n const voidPromise = finishNavigationTask(navigation, nextUrl, primaryRequestPromise, refreshRequestPromises, routeCacheEntry, navigateType);\n // `finishNavigationTask` is responsible for error handling, so we can attach\n // noop callbacks to this promise.\n voidPromise.then(noop, noop);\n}\nasync function finishNavigationTask(navigation, nextUrl, primaryRequestPromise, refreshRequestPromises, routeCacheEntry, navigateType) {\n // Wait for all the requests to finish, or for the first one to fail.\n let exitStatus = await waitForRequestsToFinish(primaryRequestPromise, refreshRequestPromises);\n // Once the all the requests have finished, check the tree for any remaining\n // pending tasks. If anything is still pending, it means the server response\n // does not match the client, and we must refresh to get back to a consistent\n // state. We can skip this step if we already detected a mismatch during the\n // first phase; it doesn't matter in that case because we're going to refresh\n // the whole tree regardless.\n if (exitStatus === 0) {\n exitStatus = abortRemainingPendingTasks(navigation.tree, null, null);\n // A response without a head is a mismatch, like any missing segment. The\n // head's deferred rsc must be resolved to `null` here, never rejected: it\n // renders at the app root, so a rejection would hit the root error\n // boundary while the retry is in flight.\n const headExitStatus = abortRemainingPendingTasks(navigation.head, null, null);\n if (headExitStatus > exitStatus) {\n exitStatus = headExitStatus;\n }\n }\n switch(exitStatus){\n case -1:\n {\n // This navigation was superseded and its request aborted. Its cache nodes\n // may already be reused by the newer navigation, so leave them untouched\n // for the newer request to fulfill. If the tree was abandoned entirely,\n // it can be garbage collected along with its unresolved promises. We do\n // not retry or hard-navigate.\n return;\n }\n case 0:\n {\n // The task has completely finished. There's no missing data. Exit.\n previousNavigationDidMismatch = false;\n return;\n }\n case 1:\n {\n // Some data failed to finish loading. Trigger a soft retry that re-fetches\n // the tree's dynamic data.\n // TODO: As an extra precaution against soft retry loops, consider\n // tracking whether a navigation was itself triggered by a retry. If two\n // happen in a row, fall back to a hard retry.\n const isHardRetry = false;\n const primaryRequestResult = await primaryRequestPromise;\n dispatchRetryDueToTreeMismatch(isHardRetry, primaryRequestResult.url, nextUrl, primaryRequestResult.seed, navigation, routeCacheEntry, navigateType, 3);\n return;\n }\n case 3:\n {\n // The route matched, but the request was redirected, so we committed the\n // wrong canonical URL. Re-resolve the route to invalidate the now-stale\n // route cache and correct the URL — but reuse the data we already received\n // (HistoryTraversal) instead of re-fetching it. See issue #95195.\n const isHardRetry = false;\n const primaryRequestResult = await primaryRequestPromise;\n dispatchRetryDueToTreeMismatch(isHardRetry, primaryRequestResult.url, nextUrl, primaryRequestResult.seed, navigation, routeCacheEntry, navigateType, 2);\n return;\n }\n case 2:\n {\n // Some data failed to finish loading in a non-recoverable way, such as a\n // network error. Trigger an MPA navigation.\n //\n // Hard navigating/refreshing is how we prevent an infinite retry loop\n // caused by a network error — when the network fails, we fall back to the\n // browser behavior for offline navigations. In the future, Next.js may\n // introduce its own custom handling of offline navigations, but that\n // doesn't exist yet.\n const isHardRetry = true;\n const primaryRequestResult = await primaryRequestPromise;\n dispatchRetryDueToTreeMismatch(isHardRetry, primaryRequestResult.url, nextUrl, primaryRequestResult.seed, navigation, routeCacheEntry, navigateType, 3);\n return;\n }\n default:\n {\n return exitStatus;\n }\n }\n}\nfunction waitForRequestsToFinish(primaryRequestPromise, refreshRequestPromises) {\n // Custom async combinator logic. This could be replaced by Promise.any but\n // we don't assume that's available.\n //\n // Each promise resolves once the server responsds and the data is written\n // into the render tree. Resolve the combined promise once all the\n // requests finish.\n //\n // Or, resolve as soon as one of the requests fails, without waiting for the\n // others to finish.\n return new Promise((resolve)=>{\n const onFulfill = (result)=>{\n if (result.exitStatus === 0) {\n remainingCount--;\n if (remainingCount === 0) {\n // All the requests finished successfully.\n resolve(0);\n }\n } else {\n // One of the requests failed. Exit with a failing status.\n // NOTE: It's possible for one of the requests to fail with SoftRetry\n // and a later one to fail with HardRetry. In this case, we choose to\n // retry immediately, rather than delay the retry until all the requests\n // finish. If it fails again, we will hard retry on the next\n // attempt, anyway.\n resolve(result.exitStatus);\n }\n };\n // onReject shouldn't ever be called because fetchMissingDynamicData's\n // entire body is wrapped in a try/catch. This is just defensive.\n const onReject = ()=>resolve(2);\n // Attach the listeners to the promises.\n let remainingCount = 1;\n primaryRequestPromise.then(onFulfill, onReject);\n if (refreshRequestPromises !== null) {\n remainingCount += refreshRequestPromises.length;\n refreshRequestPromises.forEach((refreshRequestPromise)=>refreshRequestPromise.then(onFulfill, onReject));\n }\n });\n}\nfunction dispatchRetryDueToTreeMismatch(isHardRetry, retryUrl, retryNextUrl, seed, navigation, // The route cache entry used for this navigation, if it came from route\n// prediction. If the navigation results in a mismatch, we mark it as having\n// a dynamic rewrite so future predictions bail out.\nrouteCacheEntry, // The original navigation's push/replace intent.\noriginalNavigateType, // Freshness policy for the retry navigation. `RefreshAll` re-fetches the\n// tree's dynamic data (used for genuine tree mismatches). `HistoryTraversal`\n// reuses the data already in the tree (used when only the URL needs\n// correcting after a redirect).\nretryFreshnessPolicy) {\n // If the navigation used a route prediction, mark the node it was predicted\n // from as having a dynamic rewrite since it resulted in a mismatch. A route\n // entry the server resolved has nothing to mark: nothing was predicted\n // from it.\n if (routeCacheEntry !== null) {\n const predictedFrom = routeCacheEntry.predictedFrom;\n if (predictedFrom !== null) {\n predictedFrom.hasDynamicRewrite = true;\n }\n } else if (seed !== null) {\n // Even without a direct reference to the route cache entry, we can still\n // mark the route as having a dynamic rewrite by traversing the known route\n // tree. This handles cases where the navigation didn't originate from a\n // route prediction, but still needs to mark the pattern.\n const now = Date.now();\n discoverKnownRoute(now, retryUrl.pathname, retryUrl.search, retryNextUrl, null, seed.root, false, createHrefFromUrl(retryUrl), seed.renderedSearch, false, true // hasDynamicRewrite\n );\n }\n // Invalidate all route cache entries. If the navigation used a route entry\n // the server resolved, its tree is what the server just contradicted, so\n // the retry must re-fetch it rather than navigate with it again. This also\n // triggers re-prefetching of visible links.\n invalidateRouteCacheEntries(retryNextUrl, {\n tree: navigation.tree.node,\n head: navigation.head.node\n });\n // If this is the second time in a row that a navigation resulted in a\n // mismatch, fall back to a hard (MPA) refresh.\n isHardRetry = isHardRetry || previousNavigationDidMismatch;\n previousNavigationDidMismatch = true;\n // If the original navigation hasn't committed to the browser history yet\n // (the transition suspended before React committed), inherit its push/replace\n // intent. Otherwise, the pushState already ran, so use 'replace' to avoid\n // creating a duplicate history entry.\n //\n // This works because React entangles the retry's state update with the\n // original pending transition — they commit together as a single batch,\n // so the navigate type from the retry is what HistoryUpdater ultimately sees.\n //\n // TODO: Ideally this check would happen right before we schedule the React\n // update (i.e., closer to where the action is dispatched into the queue),\n // not here where the action is constructed. But the current action queue\n // doesn't provide a natural place for that. Revisit when we refactor the\n // action queue into a more reactive navigation model.\n const baseTree = navigation.tree.route;\n const lastCommitted = getLastCommittedTree();\n const retryNavigateType = lastCommitted !== null && baseTree !== lastCommitted ? originalNavigateType : 'replace';\n const retryAction = {\n type: ACTION_SERVER_PATCH,\n previousTree: baseTree,\n url: retryUrl,\n nextUrl: retryNextUrl,\n seed,\n mpa: isHardRetry,\n navigateType: retryNavigateType,\n freshnessPolicy: retryFreshnessPolicy\n };\n dispatchAppRouterAction(retryAction);\n}\nasync function fetchMissingDynamicData(tree, head, dynamicRequestTree, url, nextUrl, freshnessPolicy, routeCacheEntry, navigationLock, map, signal) {\n try {\n const result = await fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n isHmrRefresh: freshnessPolicy === 4,\n signal\n });\n if (typeof result === 'string') {\n // fetchServerResponse will return an href to indicate that the SPA\n // navigation failed. For example, if the server triggered a hard\n // redirect, or the fetch request errored. Initiate an MPA navigation\n // to the given href.\n return {\n exitStatus: 2,\n url: new URL(result, location.origin),\n seed: null\n };\n }\n const now = Date.now();\n const seed = createNavigationSeed(now, tree.route, result.transportData, // Navigation responses stream in incrementally, so their vary params\n // can't be drained here; they decode as null.\n null, result.isResponsePartial, // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null, result.renderedSearch, null, result.dynamicStaleTime);\n // If the navigation lock is active, wait for it to be released before\n // writing the dynamic data. This allows tests to assert on the prefetched\n // UI state.\n if (process.env.__NEXT_EXPOSE_TESTING_API && navigationLock !== null) {\n await navigationLock;\n }\n if (routeCacheEntry !== null && result.staticStageResponse !== null) {\n spawnStaticStageCacheWrite(now, result.staticStageResponse, result.isResponsePartial, result.responseHeaders, dynamicRequestTree, result.renderedSearch, map);\n }\n if (routeCacheEntry !== null && result.runtimePrefetchStream !== null) {\n writeRuntimePrefetchStreamIntoCache(now, result.runtimePrefetchStream, dynamicRequestTree, result.renderedSearch, map).catch(()=>{\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n });\n }\n // result.dynamicStaleTime is in seconds (from the server's `d` field).\n // Convert to an absolute timestamp using the centralized helper.\n const dynamicStaleAt = computeDynamicStaleAt(now, result.dynamicStaleTime);\n const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(tree, seed.root.tree, dynamicStaleAt, result.debugInfo, result.revealAfter);\n if (head !== null) {\n writeDynamicDataIntoNavigationTask(head, seed.root.head, dynamicStaleAt, result.debugInfo, result.revealAfter);\n }\n const resolvedUrl = new URL(result.canonicalUrl, location.origin);\n // Decide whether the navigation needs to be retried.\n //\n // - A tree mismatch (unknown parallel route) means the data is incomplete,\n // so we soft-retry and re-fetch the whole tree.\n // - Otherwise, the navigation committed the canonical URL from the route\n // cache entry it used (a prediction or prefetch). If the request resolved\n // to a *different* canonical URL — e.g. a middleware/proxy redirect the\n // prediction didn't account for — then the committed URL is wrong and the\n // route cache it came from is no longer reliable (the redirect implies a\n // server change the prediction couldn't know about, like logging in or\n // out). We re-resolve the route to invalidate the stale cache and correct\n // the browser URL, reusing the data we just received rather than\n // re-fetching it. When the entry already reflects the redirect (e.g. a\n // prefetch that followed it), the committed URL matches and no retry is\n // needed. See issue #95195.\n let didCommitWrongUrl = false;\n if (routeCacheEntry !== null) {\n const committedUrl = new URL(routeCacheEntry.canonicalUrl, location.origin);\n didCommitWrongUrl = committedUrl.pathname !== resolvedUrl.pathname || committedUrl.search !== resolvedUrl.search;\n }\n const exitStatus = didReceiveUnknownParallelRoute ? 1 : didCommitWrongUrl ? 3 : 0;\n return {\n exitStatus,\n url: resolvedUrl,\n seed\n };\n } catch {\n if (signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request. Treat\n // it as canceled rather than a failure, so we don't retry or\n // hard-navigate.\n return {\n exitStatus: -1,\n url,\n seed: null\n };\n }\n // This shouldn't happen because fetchServerResponse's entire body is\n // wrapped in a try/catch. If it does, though, it implies the server failed\n // to respond with any tree at all. So we must fall back to a hard retry.\n return {\n exitStatus: 2,\n url: url,\n seed: null\n };\n }\n}\nfunction writeDynamicDataIntoNavigationTask(task, serverRouteTree, dynamicStaleAt, debugInfo, revealAfter) {\n // A non-null data object means the response accounted for this segment,\n // even if it didn't render it (data.rsc may still be null, e.g. for the\n // intermediate segments on the path to a rendered subtree).\n const dynamicData = serverRouteTree.data;\n if (task.status === 0 && dynamicData !== null) {\n task.status = 1;\n const cacheNode = task.node.data;\n finishPendingCacheNode(cacheNode, dynamicData, debugInfo, revealAfter);\n // The BFCache entry for this segment was written before the response\n // arrived. Bring it up to date with what the response filled in: its\n // staleAt (the per-page unstable_dynamicStaleTime if set, or the default\n // DYNAMIC_STALETIME_MS) and the source of the params its data depends\n // on. We only update segments that received dynamic data — static\n // segments are unaffected.\n updateBFCacheEntryFromDynamicResponse(serverRouteTree.varyPath, cacheNode, dynamicStaleAt);\n }\n const taskChildren = task.children;\n const serverChildren = serverRouteTree.slots;\n // Detect whether the server sends a parallel route slot that the client\n // doesn't know about.\n let didReceiveUnknownParallelRoute = false;\n if (taskChildren !== null) {\n if (serverChildren !== null) {\n for (const [parallelRouteKey, serverRouteTreeChild] of serverChildren){\n const taskChild = taskChildren.get(parallelRouteKey);\n if (taskChild === undefined) {\n // The server sent a child segment that the client doesn't know about.\n //\n // When we receive an unknown parallel route, we must consider it a\n // mismatch. This is unlike the case where the segment itself\n // mismatches, because multiple routes can be active simultaneously.\n // But a given layout should never have a mismatching set of\n // child slots.\n //\n // Theoretically, this should only happen in development during an HMR\n // refresh, because the set of parallel routes for a layout does not\n // change over the lifetime of a build/deployment. In production, we\n // should have already mismatched on either the build id or the segment\n // path. But as an extra precaution, we validate in prod, too.\n didReceiveUnknownParallelRoute = true;\n } else {\n // Check that the response is for the route we expected: same route\n // structure and same params, including the page's search params.\n if (doesRouteStructureMatch(taskChild.node, serverRouteTreeChild) && serverRouteTreeChild.data !== null && compareParams(taskChild.node.varyPath, serverRouteTreeChild.varyPath) === ParamsChange.None) {\n // Found a match for this task. Keep traversing down the task tree.\n const childDidReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(taskChild, serverRouteTreeChild, dynamicStaleAt, debugInfo, revealAfter);\n if (childDidReceiveUnknownParallelRoute) {\n didReceiveUnknownParallelRoute = true;\n }\n }\n }\n }\n } else {\n if (serverChildren !== null) {\n // The server sent a child segment that the client doesn't know about.\n didReceiveUnknownParallelRoute = true;\n }\n }\n }\n return didReceiveUnknownParallelRoute;\n}\nfunction finishPendingCacheNode(cacheNode, dynamicData, debugInfo, revealAfter) {\n // Writes a dynamic response into an existing render tree. This does _not_\n // create a new tree, it updates the existing tree in-place. So it must follow\n // the Suspense rules of cache safety — it can resolve pending promises, but\n // it cannot overwrite existing data. It can add segments to the tree (because\n // a missing segment will cause the layout router to suspend) but it cannot\n // delete them.\n //\n // We must resolve every promise in the tree, or else it will suspend\n // indefinitely. If we did not receive data for a segment, we will resolve its\n // data promise to `null` to trigger a lazy fetch during render.\n // Use the dynamic data from the server to fulfill the deferred RSC promise.\n const rsc = cacheNode.rsc;\n const dynamicSegmentData = dynamicData.rsc;\n if (dynamicSegmentData === null) {\n // This particular server request did not\n // render this segment. There may be a separate pending request that will,\n // though, so we won't abort the task until all pending requests finish.\n return;\n }\n // TODO: `varyParams` must always describe the render that produced `rsc`,\n // but nothing in the CacheNode type ties the two fields together; this\n // function keeps them in lockstep by writing both at once. Eventually the\n // whole CacheNode should be a thenable whose fields are populated through\n // dedicated helpers that own the state transition.\n if (rsc === null) {\n // This is a lazy cache node. We can overwrite it. This is only safe\n // because we know that the LayoutRouter suspends if `rsc` is `null`.\n cacheNode.rsc = dynamicSegmentData;\n cacheNode.varyParams = dynamicData.varyParams;\n } else if (isDeferredRsc(rsc) && rsc.status === 'pending') {\n // This is a deferred RSC promise. We can fulfill it with the data we just\n // received from the server. The source of the params that data depends\n // on travels with it.\n //\n // In the streaming dev render, defer the fill until `revealAfter` settles,\n // so React doesn't render the boundary's children before their row has been\n // decoded (otherwise it suspends on the still-pending children and commits\n // a premature fallback). Outside that render `revealAfter` is null and we\n // resolve immediately.\n cacheNode.varyParams = dynamicData.varyParams;\n if (revealAfter !== null) {\n const resolveRsc = ()=>rsc.resolve(dynamicSegmentData, debugInfo);\n // Use the same callback for both outcomes: we don't expect `revealAfter`\n // to reject, but if it ever did (e.g. a connection drop mid-stream) we'd\n // still want to resolve the RSC.\n revealAfter.then(resolveRsc, resolveRsc);\n } else {\n rsc.resolve(dynamicSegmentData, debugInfo);\n }\n } else {\n // This is not a deferred RSC promise that's still pending, nor is it\n // empty, so it must have been populated by a different navigation. We\n // must not overwrite it (nor its dependency source).\n }\n}\nfunction abortRemainingPendingTasks(task, error, debugInfo) {\n let exitStatus;\n if (task.status === 0) {\n // The data for this segment is still missing.\n task.status = 2;\n abortPendingCacheNode(task.node.data, error, debugInfo);\n // If the server failed to fulfill the data for this segment, it implies\n // that the route tree received from the server mismatched the tree that\n // was previously prefetched.\n //\n // In an app with fully static routes and no proxy-driven redirects or\n // rewrites, this should never happen, because the route for a URL would\n // always be the same across multiple requests. So, this implies that some\n // runtime routing condition changed, likely in a proxy, without being\n // pushed to the client.\n //\n // When this happens, we treat this the same as a refresh(). The entire\n // tree will be re-rendered from the root.\n if (task.node.refreshState === null) {\n // Trigger a \"soft\" refresh. Essentially the same as calling `refresh()`\n // in a Server Action.\n exitStatus = 1;\n } else {\n // The mismatch was discovered inside an inactive parallel route. This\n // implies the inactive parallel route is no longer reachable at the URL\n // that originally rendered it. Fall back to an MPA refresh.\n // TODO: An alternative could be to trigger a soft refresh but to _not_\n // re-use the inactive parallel routes this time. Similar to what would\n // happen if were to do a hard refrehs, but without the HTML page.\n exitStatus = 2;\n }\n } else {\n // This segment finished. (An error here is treated as Done because they are\n // surfaced to the application during render.)\n exitStatus = 0;\n }\n const taskChildren = task.children;\n if (taskChildren !== null) {\n for (const [, taskChild] of taskChildren){\n const childExitStatus = abortRemainingPendingTasks(taskChild, error, debugInfo);\n // Propagate the exit status up the tree. The statuses are ordered by\n // their precedence.\n if (childExitStatus > exitStatus) {\n exitStatus = childExitStatus;\n }\n }\n }\n return exitStatus;\n}\nfunction abortPendingCacheNode(cacheNode, error, debugInfo) {\n const rsc = cacheNode.rsc;\n if (isDeferredRsc(rsc)) {\n if (error === null) {\n // This will trigger a lazy fetch during render.\n rsc.resolve(null, debugInfo);\n } else {\n // This will trigger an error during rendering.\n rsc.reject(error, debugInfo);\n }\n }\n}\nconst DEFERRED = Symbol();\n// This type exists to distinguish a DeferredRsc from a Flight promise. It's a\n// compromise to avoid adding an extra field on every Cache Node, which would be\n// awkward because the pre-PPR parts of codebase would need to account for it,\n// too. We can remove it once type Cache Node type is more settled.\nexport function isDeferredRsc(value) {\n return value && typeof value === 'object' && value.tag === DEFERRED;\n}\nfunction createDeferredRsc() {\n // Create an unresolved promise that represents data derived from a Flight\n // response. The promise will be resolved later as soon as we start receiving\n // data from the server, i.e. as soon as the Flight client decodes and returns\n // the top-level response object.\n // The `_debugInfo` field contains profiling information. Promises that are\n // created by Flight already have this info added by React; for any derived\n // promise created by the router, we need to transfer the Flight debug info\n // onto the derived promise.\n //\n // The debug info represents the latency between the start of the navigation\n // and the start of rendering. (It does not represent the time it takes for\n // whole stream to finish.)\n const debugInfo = [];\n let resolve;\n let reject;\n const pendingRsc = new Promise((res, rej)=>{\n resolve = res;\n reject = rej;\n });\n pendingRsc.status = 'pending';\n pendingRsc.resolve = (value, responseDebugInfo)=>{\n if (pendingRsc.status === 'pending') {\n const fulfilledRsc = pendingRsc;\n fulfilledRsc.status = 'fulfilled';\n fulfilledRsc.value = value;\n if (responseDebugInfo !== null) {\n // Transfer the debug info to the derived promise.\n debugInfo.push.apply(debugInfo, responseDebugInfo);\n }\n resolve(value);\n }\n };\n pendingRsc.reject = (error, responseDebugInfo)=>{\n if (pendingRsc.status === 'pending') {\n const rejectedRsc = pendingRsc;\n rejectedRsc.status = 'rejected';\n rejectedRsc.reason = error;\n if (responseDebugInfo !== null) {\n // Transfer the debug info to the derived promise.\n debugInfo.push.apply(debugInfo, responseDebugInfo);\n }\n reject(error);\n }\n };\n pendingRsc.tag = DEFERRED;\n pendingRsc._debugInfo = debugInfo;\n return pendingRsc;\n}\n/**\n * Helper for the Instant Navigation Testing API. Captures the withheld-data\n * gate of the locked navigation that is current when router work spawns a\n * dynamic write, so the write awaits that same gate even if a newer locked\n * navigation rolls the lock over before its response is applied.\n *\n * Not exposed in production builds by default.\n */ export function getCurrentNavigationLock() {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { getCurrentNavigationGate } = require('./segment-cache/navigation-testing-lock');\n return getCurrentNavigationGate();\n }\n return null;\n}\n/**\n * Helper for the Instant Navigation Testing API. Signals that a new locked\n * navigation is beginning: force-resolves the previous locked navigation's\n * withheld-data gate (without ending the scope) and returns a fresh gate for\n * this navigation, which the caller threads to its dynamic-data write. See\n * `beginLockedNavigation` in `navigation-testing-lock`.\n *\n * Not exposed in production builds by default.\n */ export function beginLockedNavigation() {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { beginLockedNavigation: begin } = require('./segment-cache/navigation-testing-lock');\n return begin();\n }\n return null;\n}\n/**\n * Helper for the Instant Navigation Testing API. Called during a history\n * traversal: resets the testing lock to a fresh pending scope, releasing any\n * withheld data from prior navigations. See `resetNavigationLockToPending` in\n * `navigation-testing-lock`.\n */ export function resetNavigationLockToPending() {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { resetNavigationLockToPending: reset } = require('./segment-cache/navigation-testing-lock');\n reset();\n }\n}\n\n//# sourceMappingURL=render-tree.js.map","/**\n * Navigation lock for the Instant Navigation Testing API.\n *\n * Manages the in-memory lock (a promise) that gates dynamic data writes\n * during instant navigation captures, and owns all cookie state\n * transitions (pending → captured-MPA, pending → captured-SPA).\n *\n * External actors (Playwright, devtools) set [0] to start a lock scope\n * and delete the cookie to end one. Next.js writes captured values.\n * The CookieStore handler distinguishes them by value: pending = external,\n * captured = self-write (ignored).\n *\n * This module assumes the Instant Navigation Testing API is enabled. When it\n * is disabled, the bundler resolves this module to\n * `./navigation-testing-lock.disabled` instead (see\n * `create-compiler-aliases.ts` for webpack and\n * `crates/next-core/src/next_import_map.rs` for Turbopack), so none of this\n * code ships in the browser bundle.\n */ import { PrefetchHint } from '../../../shared/lib/app-router-types';\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers';\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue';\nimport { needsSpeculativePrefetch } from './scheduler';\nimport { createCacheMap } from './cache-map';\nfunction parseCookieValue(raw) {\n if (raw === '') {\n return 'empty';\n }\n try {\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) {\n if (parsed.length >= 3) {\n const rawState = parsed[2];\n return rawState === null ? 'mpa' : 'spa';\n }\n }\n } catch {}\n return 'pending';\n}\nfunction writeDocumentCookie(value, options) {\n if (typeof document === 'undefined') {\n return;\n }\n let cookie = `${NEXT_INSTANT_TEST_COOKIE}=${JSON.stringify(value)}; Path=${options.path ?? '/'}`;\n if (options.domain) {\n cookie += `; Domain=${options.domain}`;\n }\n document.cookie = cookie;\n}\nfunction writeCookieValue(value) {\n if (typeof cookieStore === 'undefined') {\n return;\n }\n // Read the existing cookie to preserve its attributes (domain, path), then\n // write back with the new value. This updates the same cookie entry that the\n // external actor created, regardless of how it was scoped. The read goes\n // through `cookieStore.get` because `document.cookie` exposes only names and\n // values, not the domain/path we need to preserve. The write goes through\n // document.cookie because WebKit exposes Cookie Store on localhost but does\n // not commit cookies written through cookieStore.set() there.\n //\n // Capture the current lockState and compare it in the callback so we only\n // write if the lock we observed at call time is still held. This guards\n // against two races: (a) the scope ended between get and set (lockState is\n // now null), and (b) the scope ended and a new one was acquired in the same\n // gap (lockState is a different object). In either case we must not write —\n // doing so would leak stale state into the next scope or outlive the current\n // one. It cannot close one window, though: the callback can run after an\n // external delete but before the deleted-event handler nulls lockState, so\n // the guard still passes and we resurrect the cookie. The deleted handler\n // clears any such entry once the lock is released (see the `event.deleted`\n // loop below).\n const lockAtCall = lockState;\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing)=>{\n if (existing && lockState === lockAtCall && lockAtCall !== null) {\n writeDocumentCookie(value, existing);\n }\n });\n}\nlet lockState = null;\nexport function getPreLockFetch() {\n return lockState !== null ? lockState.fetch : null;\n}\n/**\n * Creates the \"wait for prefetch to fulfill\" state for one locked navigation,\n * registers it on the current lock, and returns it (the caller stores it on the\n * prefetch task and awaits `.promise`). Returns null if no lock is held.\n * Resolved by the scheduler via `resolveNavigationLockPrefetch` when the\n * driving prefetch task completes.\n */ export function beginNavigationLockPrefetch() {\n if (lockState !== null) {\n let resolve;\n const promise = new Promise((r)=>{\n resolve = r;\n });\n const prefetch = {\n promise,\n resolve: resolve\n };\n lockState.activePrefetches.add(prefetch);\n return prefetch;\n }\n return null;\n}\n/**\n * Returns the current lock scope's private segment cache map, or null when no\n * lock is held. See `NavigationLockState.segmentCacheMap`.\n */ export function getNavigationLockSegmentCacheMap() {\n return lockState !== null ? lockState.segmentCacheMap : null;\n}\n/**\n * Called by the scheduler when the locked-navigation prefetch task completes.\n * A task only completes after a full pass observed every segment response it\n * cares about, so the data the navigation will read has settled by this\n * point. Unregisters from the lock (if still held) and resolves. Resolving is\n * idempotent, so it's safe even if the lock already force-resolved this on\n * release.\n */ export function resolveNavigationLockPrefetch(prefetch) {\n if (lockState !== null) {\n lockState.activePrefetches.delete(prefetch);\n }\n prefetch.resolve();\n}\nfunction acquireLock() {\n if (lockState !== null) {\n return;\n }\n let resolveReleased;\n const released = new Promise((r)=>{\n resolveReleased = r;\n });\n let resolveCurrentNavigation;\n const currentNavigation = new Promise((r)=>{\n resolveCurrentNavigation = r;\n });\n lockState = {\n released,\n resolveReleased: resolveReleased,\n fetch: window.fetch,\n activePrefetches: new Set(),\n segmentCacheMap: createCacheMap(),\n currentNavigation,\n resolveCurrentNavigation: resolveCurrentNavigation\n };\n // Install the fetch blocker. We only intercept `window.fetch` for the\n // duration of the lock so that — outside of a testing scope — user-\n // installed overrides of `window.fetch` are untouched.\n window.fetch = globalFetchOverride;\n}\nfunction releaseLock() {\n if (lockState === null) {\n return;\n }\n // Restore the pre-lock `window.fetch` before resolving the lock promise\n // so any fetches queued on the promise see the restored fetch.\n window.fetch = lockState.fetch;\n const { resolveReleased, activePrefetches, resolveCurrentNavigation } = lockState;\n lockState = null;\n // Force-resolve every prefetch that hasn't finished, so a navigation still\n // waiting on one doesn't hang now that the scope is ending.\n for (const prefetch of activePrefetches){\n prefetch.resolve();\n }\n // Resolve the current locked navigation's withheld-data gate, so its gated\n // dynamic write unblocks now that the scope is ending.\n resolveCurrentNavigation();\n // Resolve the release promise so blocked out-of-band fetches dispatch too.\n resolveReleased();\n}\n/**\n * Called when a new locked navigation begins (from `navigate` while the lock is\n * held). Rolls over the lock's withheld-data gate: it resolves the current\n * `currentNavigation` promise — so the *previous* locked navigation's withheld\n * dynamic write proceeds and the cache nodes it produced stop holding pending\n * deferred `rsc` promises that a reused shared segment in this navigation would\n * otherwise suspend on — then installs a fresh promise for this navigation.\n * Only the most recent navigation's data stays withheld; a new navigation\n * always releases the previous one. Returns this navigation's gate — the\n * immutable promise its dynamic write awaits — or null when no lock is held.\n *\n * This is the testing-lock behavior for repeated navigations while paused. It\n * is not a principled fix for the underlying `useDeferredValue`/reuse-suspend\n * behavior; it just ensures that, under the lock, a reused segment never\n * carries a still-pending deferred `rsc` from an earlier navigation.\n */ export function beginLockedNavigation() {\n if (lockState === null) {\n return null;\n }\n // Release the previous locked navigation's withheld data, then roll over to a\n // fresh gate for this navigation — all without ending the scope.\n lockState.resolveCurrentNavigation();\n let resolveCurrentNavigation;\n const currentNavigation = new Promise((r)=>{\n resolveCurrentNavigation = r;\n });\n lockState.currentNavigation = currentNavigation;\n lockState.resolveCurrentNavigation = resolveCurrentNavigation;\n return currentNavigation;\n}\n/**\n * Called when the router applies a history traversal (Back/Forward restore) while\n * the testing lock is active. A traversal is not a capture — the mental model is\n * that history entries are already cached — so it must not participate in the\n * current capture. Instead it resets the lock to a fresh pending scope:\n *\n * - `releaseLock` flushes every still-withheld write from prior forward\n * navigations, so the pages you navigated away from finish streaming.\n * - `acquireLock` immediately re-arms a fresh pending scope (no gap where the\n * lock or fetch blocker is down).\n * - the cookie flips from the captured state back to pending.\n *\n * The traversal's own dynamic requests are spawned ungated by the caller (see\n * `restore-reducer`), so they render from cache or fetch normally rather than\n * being withheld.\n */ export function resetNavigationLockToPending() {\n if (lockState === null || typeof document === 'undefined') {\n return;\n }\n releaseLock();\n acquireLock();\n writeCookieValue([\n 0,\n `c${Math.random()}`\n ]);\n}\n/**\n * Returns true if the request targets a dev-server endpoint — one of the\n * hot-reloader middleware routes (error overlay, source maps, launch-editor,\n * devtools). They all share the `/__nextjs_` path prefix and are always\n * requested root-relative on the same origin.\n */ function isDevServerRequest(input) {\n let url;\n try {\n url = new URL(typeof input === 'string' ? input : input instanceof URL ? input : input.url, window.location.href);\n } catch {\n return false;\n }\n return url.origin === window.location.origin && url.pathname.startsWith('/__nextjs_');\n}\n/**\n * Global fetch override\n *\n * While the navigation lock is active, we install this as `window.fetch` so\n * out-of-band client-side fetches (e.g. `fetch('/api/data')` inside a\n * useEffect) are blocked until the lock is released. Next.js internals\n * bypass the override by importing `fetch` from `./fetch`, which reads the\n * captured pre-lock fetch via `getPreLockFetch`.\n *\n * NOTE: This override only affects environments where the Instant Navigation\n * Testing API is enabled. It has no impact on live production behavior.\n */ function globalFetchOverride(input, init) {\n if (lockState === null) {\n // Lock is not active. Fall through to the global fetch — we reach this\n // only if a caller captured a reference to this function during a lock\n // scope and invoked it after release.\n return fetch(input, init);\n }\n if (process.env.__NEXT_DEV_SERVER && isDevServerRequest(input)) {\n // Dev-server requests must not be gated on the testing lock — blocking\n // them would break the error overlay, source maps, and devtools for the\n // whole scope. Dispatch immediately through the pre-lock fetch. Copy to a\n // local so the call doesn't bind `this` to the lock state object (native\n // fetch throws \"Illegal invocation\" for a foreign receiver).\n const preLockFetch = lockState.fetch;\n return preLockFetch(input, init);\n }\n // Block user-initiated fetches until the lock is released, then dispatch\n // through the fetch captured at acquire time. Reading from `lockState`\n // (rather than `window.fetch`) pins to the capture even if `window.fetch`\n // is reassigned after release.\n const currentLock = lockState;\n return currentLock.released.then(()=>{\n const preLockFetch = currentLock.fetch;\n return preLockFetch(input, init);\n });\n}\n/**\n * Sets up the cookie-based lock. Handles the initial page load state and\n * registers a CookieStore listener for runtime changes.\n *\n * Called once during page initialization from app-globals.ts.\n */ export function startListeningForInstantNavigationCookie() {\n // If the server served a shell, this is an MPA page load\n // while the lock is held. Transition to captured-MPA and acquire.\n if (self.__next_instant_test) {\n if (typeof cookieStore !== 'undefined') {\n // If the cookie was already cleared during the MPA page\n // transition, reload to get the full dynamic page.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie)=>{\n if (!cookie) {\n window.location.reload();\n }\n });\n }\n // Acquire the lock before writing the cookie. writeCookieValue's\n // guard requires lockState to be non-null at call time (so a stale\n // write can't outlive its scope). On a fresh page load that scope\n // is the one we're about to establish, so we have to establish it\n // first.\n acquireLock();\n writeCookieValue([\n 1,\n `c${Math.random()}`,\n null\n ]);\n }\n if (typeof cookieStore === 'undefined') {\n return;\n }\n cookieStore.addEventListener('change', (event)=>{\n for (const cookie of event.changed){\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n const state = parseCookieValue(cookie.value ?? '');\n if (state === 'pending') {\n // External actor starting a new lock scope.\n if (lockState !== null) {\n // This can be the delayed CookieStore event for the pending\n // cookie that was already observed synchronously from\n // document.cookie. Keep the existing lock identity so work that\n // captured it keeps waiting on the same promise.\n return;\n }\n acquireLock();\n }\n // Captured value (our own transition) or empty. Ignore.\n return;\n }\n }\n for (const cookie of event.deleted){\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n if (lockState === null) {\n // Either no lock is active, or this is the re-entrant change event\n // from the defensive clear below (which runs after releaseLock).\n // Nothing to release either way.\n return;\n }\n releaseLock();\n // A captured write from this page's bootstrap can resurrect the\n // cookie in the narrow gap between the external delete and this\n // handler: writeCookieValue's guard only rejects the write once the\n // lock is torn down, which happens here. Now that the lock is\n // released, no further captured write can re-add the cookie, so clear\n // any entry that was resurrected in that gap. Otherwise an unlock\n // that falls back to a hard reload (when the shell has not yet\n // hydrated) would carry the stale cookie, be served the shell again,\n // and re-enter instant mode with no scope left to release it.\n if (typeof document !== 'undefined') {\n document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0`;\n }\n refreshOnInstantNavigationUnlock();\n return;\n }\n }\n });\n}\n/**\n * Transitions the cookie from pending to captured-SPA once the prefetch resolves\n * and the navigation is known to be an SPA.\n */ export function updateCapturedSPAToTree(fromTree, toTree) {\n writeCookieValue([\n 1,\n `c${Math.random()}`,\n {\n from: fromTree,\n to: toTree\n }\n ]);\n}\n/**\n * Returns true if the navigation lock is currently active.\n */ export function isNavigationLocked() {\n if (lockState !== null) {\n return true;\n }\n // If `lockState` is null, fall back to reading the test cookie\n // synchronously from `document.cookie`. This accounts for a small race\n // between `cookieStore.set(...)` and its corresponding `change` event.\n // During that gap `lockState` is still null even though the cookie\n // indicates a new lock scope is starting.\n if (typeof document === 'undefined') {\n return false;\n }\n const allCookies = document.cookie;\n if (!allCookies.includes(NEXT_INSTANT_TEST_COOKIE)) {\n // Fast bail-out: in almost every navigation the test cookie is not\n // set at all.\n return false;\n }\n const target = NEXT_INSTANT_TEST_COOKIE + '=';\n for (const segment of allCookies.split(';')){\n const trimmed = segment.trim();\n if (trimmed.startsWith(target) && parseCookieValue(trimmed.slice(target.length)) === 'pending') {\n // The cookie was set by an external actor but the change event was not\n // yet dispatched. Acquire the lock synchronously.\n acquireLock();\n return true;\n }\n }\n return false;\n}\n/**\n * Returns the current locked navigation's withheld-data gate — the same\n * immutable promise `beginLockedNavigation` handed that navigation — or null\n * when no lock is held. For router work that spawns a dynamic write without\n * beginning a navigation of its own (refreshes, server actions, server\n * patches): it gates behind the navigation that is current when it spawns, so\n * the next locked navigation (or unlock) releases it.\n */ export function getCurrentNavigationGate() {\n return lockState !== null ? lockState.currentNavigation : null;\n}\n/**\n * Decides whether segment reads during a navigation should be restricted to\n * shell entries (every param substituted with Fallback) rather than matching\n * entries that vary on concrete route params.\n *\n * The testing tools (Navigation Inspector, instant()) simulate what a user\n * would see with a warm cache. When the lock is held, partial prefetching is\n * enabled for the target route, and no whole-route (\"speculative\") prefetch\n * would have been made, only the shell is prefetched — so that's all a\n * navigation should be allowed to match. A speculative prefetch happens for a\n * `<Link prefetch={true}>`, in which case the concrete-param entry is genuinely\n * warm and may be matched.\n *\n * Always returns false outside the testing API, via the aliased\n * `navigation-testing-lock.disabled` module.\n */ export function shouldRestrictNavigationToShell(rootPrefetchHints, linkFetchStrategy) {\n return isNavigationLocked() && (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 && !needsSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints);\n}\n\n//# sourceMappingURL=navigation-testing-lock.js.map","import { PrefetchHint } from '../../shared/lib/app-router-types';\nimport { fetchServerResponse } from './router-reducer/fetch-server-response';\nimport { startPPRNavigation, spawnDynamicRequests, FreshnessPolicy, beginLockedNavigation } from './render-tree';\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url';\nimport { EntryStatus, segmentCacheMap, readRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry, spawnStaticStageCacheWrite, writeRuntimePrefetchStreamIntoCache, createRootRouteTree } from './segment-cache/cache';\nimport { discoverKnownRoute } from './segment-cache/optimistic-routes';\nimport { createCacheKey } from './segment-cache/cache-key';\nimport { schedulePrefetchTask } from './segment-cache/scheduler';\nimport { PrefetchPriority, FetchStrategy } from './segment-cache/types';\nimport { getLinkForCurrentNavigation } from './links';\nimport { ScrollBehavior } from './router-reducer/router-reducer-types';\nimport { computeChangedPath } from './router-reducer/compute-changed-path';\nimport { isJavaScriptURLString } from '../lib/javascript-url';\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './segment-cache/bfcache';\nimport { createLinkPrefetchPartialError } from '../../shared/lib/instant-messages';\nimport { createNavigationSeed } from './segment-cache/decode-server-response';\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */ export function navigate(state, url, currentUrl, currentRenderedSearch, currentRoot, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType) {\n let navigationLock = null;\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } = require('./segment-cache/navigation-testing-lock');\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation();\n return ensurePrefetchThenNavigate(state, url, currentUrl, currentRenderedSearch, currentRoot, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock);\n }\n }\n return navigateImpl(state, url, currentUrl, currentRenderedSearch, currentRoot, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, // An unlocked navigation is bound to the shared map.\n segmentCacheMap);\n}\nfunction navigateImpl(state, url, currentUrl, currentRenderedSearch, currentRoot, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, // The segment cache map this navigation is bound to: a locked navigation's\n// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\nmap) {\n const now = Date.now();\n const href = url.href;\n const cacheKey = createCacheKey(href, nextUrl);\n const route = readRouteCacheEntry(now, cacheKey);\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentRoot, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock, map);\n }\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(now, url, nextUrl);\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentRoot, freshnessPolicy, scrollBehavior, navigateType, optimisticRoute, navigationLock, map);\n }\n }\n }\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentRoot, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock, map).catch(()=>{\n // If the navigation fails, return the current state\n return state;\n });\n}\nexport function navigateToKnownRoute(now, state, url, canonicalUrl, navigationSeed, currentUrl, currentRenderedSearch, currentRoot, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, // The segment cache map this navigation is bound to: a locked navigation's\n// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\nmap, debugInfo, // The route cache entry used for this navigation, if it came from route\n// prediction. Passed through so it can be marked as having a dynamic rewrite\n// if the server returns a different pathname (indicating dynamic rewrite\n// behavior).\n//\n// When null, the navigation did not use route prediction - either because\n// the route was already fully cached, or it's a navigation that doesn't\n// involve prediction (refresh, history traversal, server action, etc.).\n// In these cases, if a mismatch occurs, we still mark the route as having a\n// dynamic rewrite by traversing the known route tree (see\n// dispatchRetryDueToTreeMismatch).\nrouteCacheEntry, signal) {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (process.env.NODE_ENV !== 'production' && process.env.__NEXT_CACHE_COMPONENTS) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation();\n if (link !== null && link.fetchStrategy === FetchStrategy.Full && (navigationSeed.root.tree.prefetchHints & (PrefetchHint.SubtreeHasPartialPrefetching | PrefetchHint.SubtreeHasInstantFalse)) === 0) {\n const error = createLinkPrefetchPartialError(url.pathname);\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined;\n if (ownerStack === undefined) {\n console.error('' + 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' + 'This is a bug in Next.js.');\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`;\n }\n console.error(error);\n }\n }\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false;\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } = require('./segment-cache/navigation-testing-lock');\n const link = getLinkForCurrentNavigation();\n restrictToShell = shouldRestrictNavigationToShell(navigationSeed.root.tree.prefetchHints, link !== null ? link.fetchStrategy : FetchStrategy.PPR);\n }\n const accumulation = {\n separateRefreshUrls: null,\n scrollRef: null\n };\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href;\n const navigation = startPPRNavigation(now, currentUrl, currentRenderedSearch, currentRoot, navigationSeed.root, freshnessPolicy, navigationSeed.dynamicStaleAt, isSamePageNavigation, accumulation, map, restrictToShell);\n if (navigation !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(navigation, url, nextUrl, freshnessPolicy, accumulation, routeCacheEntry, navigateType, navigationLock, map, signal);\n }\n return completeSoftNavigation(state, url, nextUrl, navigation, navigationSeed.renderedSearch, canonicalUrl, navigateType, scrollBehavior, accumulation.scrollRef, debugInfo);\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType);\n}\nfunction navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentRoot, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock, map) {\n const canonicalUrl = route.canonicalUrl + url.hash;\n const renderedSearch = route.renderedSearch;\n const prefetchSeed = {\n renderedSearch,\n root: route.root,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n // Not derived from a server response; no base to diverge from.\n treeDivergedFromBase: false\n };\n return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentRoot, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, null, route, // Not an HMR refresh, so there's no request generation to cancel.\n undefined);\n}\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute = [\n '',\n {},\n null,\n 'refetch'\n];\nasync function navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentRoot, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock, map) {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the render\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n let dynamicRequestTree;\n switch(freshnessPolicy){\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState;\n break;\n case FreshnessPolicy.Hydration:\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute;\n break;\n default:\n freshnessPolicy;\n dynamicRequestTree = currentFlightRouterState;\n break;\n }\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl\n });\n const result = await promiseForDynamicServerResponse;\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin);\n return completeHardNavigation(state, redirectUrl, navigateType);\n }\n const { transportData, canonicalUrl, renderedSearch, couldBeIntercepted, supportsPerSegmentPrefetching, dynamicStaleTime, isResponsePartial, staticStageResponse, runtimePrefetchStream, responseHeaders, debugInfo } = result;\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = createNavigationSeed(now, currentFlightRouterState, transportData, // Navigation responses stream in incrementally, so their vary params\n // can't be drained here — and nothing consumes them from a navigation\n // seed (only segment-cache writes read vary params, and those decode\n // their own, buffered, payloads).\n null, isResponsePartial, // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null, renderedSearch, null, dynamicStaleTime);\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n discoverKnownRoute(now, url.pathname, url.search, nextUrl, null, navigationSeed.root, couldBeIntercepted, // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false), navigationSeed.renderedSearch, supportsPerSegmentPrefetching, false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n );\n if (staticStageResponse !== null) {\n spawnStaticStageCacheWrite(now, staticStageResponse, isResponsePartial, responseHeaders, currentFlightRouterState, renderedSearch, map);\n }\n if (runtimePrefetchStream !== null) {\n writeRuntimePrefetchStreamIntoCache(now, runtimePrefetchStream, currentFlightRouterState, renderedSearch, map).catch(()=>{\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n });\n }\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter;\n }\n return navigateToKnownRoute(now, state, url, createHrefFromUrl(canonicalUrl), navigationSeed, currentUrl, currentRenderedSearch, currentRoot, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, debugInfo, // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null, // Not an HMR refresh, so there's no request generation to cancel.\n undefined);\n}\nexport function completeHardNavigation(state, url, navigateType) {\n if (isJavaScriptURLString(url.href)) {\n console.error('Next.js has blocked a javascript: URL as a security precaution.');\n return state;\n }\n const newState = {\n canonicalUrl: url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n root: state.root,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null\n };\n return newState;\n}\nexport function completeSoftNavigation(oldState, url, referringNextUrl, navigation, renderedSearch, canonicalUrl, navigateType, scrollBehavior, scrollRef, collectedDebugInfo) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const tree = navigation.tree.route;\n const changedPath = computeChangedPath(oldState.tree, tree);\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl;\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl;\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url);\n const onlyHashChange = // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname && url.search === oldUrl.search && url.hash !== oldUrl.hash;\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef;\n let forceScroll;\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on reused cache nodes remain active.\n if (scrollRef !== null) {\n scrollRef.current = false;\n }\n activeScrollRef = oldState.scrollRef.scrollRef;\n forceScroll = false;\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef;\n if (oldScrollRef !== null) {\n oldScrollRef.current = false;\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false;\n }\n activeScrollRef = {\n current: true\n };\n forceScroll = true;\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef;\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef;\n if (oldScrollRef !== null) {\n oldScrollRef.current = false;\n }\n }\n forceScroll = false;\n }\n const newState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment: // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== '' ? decodeURIComponent(url.hash.slice(1)) : oldState.scrollRef.hashFragment\n },\n root: createRootRouteTree(navigation.tree.node, navigation.head.node),\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo\n };\n return newState;\n}\nexport function completeTraverseNavigation(state, url, renderedSearch, navigation, nextUrl) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true\n },\n scrollRef: state.scrollRef,\n root: createRootRouteTree(navigation.tree.node, navigation.head.node),\n // Restore provided tree\n tree: navigation.tree.route,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null\n };\n}\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */ async function ensurePrefetchThenNavigate(state, url, currentUrl, currentRenderedSearch, currentRoot, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock) {\n const link = getLinkForCurrentNavigation();\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR;\n const cacheKey = createCacheKey(url.href, nextUrl);\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } = require('./segment-cache/navigation-testing-lock');\n const navigationLockPrefetch = beginNavigationLockPrefetch();\n const prefetchTask = schedulePrefetchTask(cacheKey, currentRoot, fetchStrategy, PrefetchPriority.Default, null, navigationLockPrefetch);\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise;\n }\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(state, url, currentUrl, currentRenderedSearch, currentRoot, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, prefetchTask.segmentCacheMap);\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } = require('./segment-cache/navigation-testing-lock');\n updateCapturedSPAToTree(currentFlightRouterState, result.tree);\n }\n return result;\n}\n\n//# sourceMappingURL=app-router-state.js.map","/**\n * Optimistic Routing (Known Routes)\n *\n * This module enables the client to predict route structure for URLs that\n * haven't been prefetched yet, based on previously learned route patterns.\n * When successful, this allows skipping the route tree prefetch request\n * entirely.\n *\n * The core idea is that many URLs map to the same route structure. For example,\n * /blog/post-1 and /blog/post-2 both resolve to /blog/[slug]. Once we've\n * prefetched one, we can predict the structure of the other.\n *\n * However, we can't always make this prediction. Static siblings (like\n * /blog/featured alongside /blog/[slug]) have different route structures.\n * When we learn a dynamic route, we also learn its static siblings so we\n * know when NOT to apply the prediction.\n *\n * Main entry points:\n *\n * 1. discoverKnownRoute: Called after receiving a route tree from the server.\n * Traverses the route tree, compares URL parts to segments, and populates\n * the known route tree if they match. Routes are always inserted into the\n * cache.\n *\n * 2. matchKnownRoute: Called when looking up a route with no cache entry.\n * Matches the candidate URL against learned patterns. Returns a synthetic\n * cache entry if successful, or null to fall back to server resolution.\n *\n * Rewrite detection happens during traversal: if a URL path part doesn't match\n * the corresponding route segment, we stop populating the known route tree\n * (since the mapping is incorrect) but still insert the route into the cache.\n *\n * The known route tree is append-only with no eviction. Route patterns are\n * derived from the filesystem, so they don't become stale within a session.\n * Cache invalidation on deploy clears everything anyway.\n *\n * Current limitations (deopt to server resolution):\n * - Rewrites: Detected during traversal (tree not populated, but route cached)\n * - Intercepted routes: The route tree varies by referrer (Next-Url header),\n * so we can't predict the correct structure from the URL alone. Patterns are\n * still stored during discovery (so the trie stays populated for non-\n * intercepted siblings), but matching bails out when the pattern is marked\n * as interceptable.\n */ import { PrefetchHint } from '../../../shared/lib/app-router-types';\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment';\nimport { EntryStatus, writeRouteIntoCache, fulfillRouteCacheEntry, getCurrentRouteCacheVersion, createMetadataRouteTree, createRootRouteTree, getHeadRequestKey } from './cache';\nimport { isValueExpired } from './cache-map';\nimport { canonicalizeURLPart, normalizeRenderedSearch, doesStaticSegmentAppearInURL } from '../../route-params';\nimport { splitPathnameIntoParts } from './cache-key';\nimport { appendLayoutVaryPath, finalizeVaryPath, getShellSegmentVaryPath } from './vary-path';\n/**\n * Read the pattern from a KnownRoutePart, evicting it if expired.\n *\n * This prevents stale patterns (e.g. from InliningHintsStale route entries\n * with staleAt = -1) from being cloned into synthetic entries indefinitely.\n * Once evicted, the pattern slot can be repopulated by the next\n * discoverKnownRoute call with a fresh entry from a /_tree response.\n */ function readPattern(now, part) {\n const pattern = part.pattern;\n if (pattern === null) {\n return null;\n }\n if (isValueExpired(now, getCurrentRouteCacheVersion(), pattern)) {\n // The pattern is expired. Null it out so the slot can be repopulated.\n part.pattern = null;\n return null;\n }\n return pattern;\n}\nfunction createEmptyPart() {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null,\n hasConflictingDynamicChildren: false,\n hasDynamicRewrite: false\n };\n}\n// The root of the known route tree.\nlet knownRouteTreeRoot = createEmptyPart();\n/**\n * Learns a route pattern from a server response and inserts it into the cache.\n *\n * Called after receiving a route tree from the server (initial load, navigation,\n * or prefetch). Traverses the route tree, compares URL parts to segments, and\n * populates the known route tree if they match. Routes are always inserted into\n * the cache regardless of whether the URL matches the route structure.\n *\n * When pendingEntry is provided, it's fulfilled and used. When null, an entry\n * is created and inserted into the route cache map.\n *\n * When hasDynamicRewrite is true, the node the route terminates at is marked\n * as having a dynamic rewrite, which prevents URLs of its shape from being\n * predicted. This is set when we detect a mismatch between what we predicted\n * and what the server returned.\n *\n * Returns the fulfilled route cache entry.\n */ export function discoverKnownRoute(now, pathname, search, nextUrl, pendingEntry, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching, hasDynamicRewrite) {\n const tree = root.tree;\n const pathnameParts = splitPathnameIntoParts(pathname);\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(now, pendingEntry, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n // Populate the known route tree (handles rewrite detection internally).\n // The entry is already in the cache; this just stores it as a pattern\n // if the URL matches the route structure.\n discoverKnownRoutePart(knownRouteTreeRoot, tree, pathnameParts, 0, fulfilledEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching, hasDynamicRewrite);\n return fulfilledEntry;\n }\n // No pending entry - discoverKnownRoutePart will create one and insert it\n // into the cache, or return an existing pattern if one exists.\n return discoverKnownRoutePart(knownRouteTreeRoot, tree, pathnameParts, 0, null, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching, hasDynamicRewrite);\n}\n/**\n * Bail out of populating the known route tree when discovery detects that the\n * URL doesn't match the route structure (a rewrite). The route entry is still\n * inserted into the cache for direct lookup — we just don't store it as a\n * pattern, since the URL and the tree describe different shapes.\n */ function handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching) {\n if (existingEntry !== null) {\n return existingEntry;\n }\n return writeRouteIntoCache(now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n}\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart. A node can\n * have at most one dynamic child. Sibling filesystem routes can't declare two\n * different params at the same level, but parallel route branches can (e.g.\n * @modal/[...catchAll] alongside [username]) — the caller detects that case\n * and marks the level as conflicted instead of calling this.\n */ function discoverDynamicChild(part, paramName, paramType) {\n if (part.dynamicChild !== null) {\n return part.dynamicChild;\n }\n const newChild = createEmptyPart();\n // Type assertion needed because we're converting from \"without\" to \"with\"\n // dynamic child variant.\n const mutablePart = part;\n mutablePart.dynamicChild = newChild;\n mutablePart.dynamicChildParamName = paramName;\n mutablePart.dynamicChildParamType = paramType;\n return newChild;\n}\n/**\n * Recursive workhorse for discoverKnownRoute.\n *\n * Walks the route tree and URL parts in parallel, building out the known\n * route tree as it goes. At each step:\n * 1. Determines if the current segment appears in the URL (dynamic/static)\n * 2. Validates URL matches route structure (detects rewrites)\n * 3. Creates/updates the corresponding KnownRoutePart node\n * 4. Records static siblings for future matching\n * 5. Recurses into child slots (parallel routes)\n *\n * If a URL/route mismatch is detected (rewrite), we stop building the known\n * route tree but still cache the route entry for direct lookup.\n */ function discoverKnownRoutePart(parentKnownRoutePart, routeTree, pathnameParts, partIndex, existingEntry, // These are passed through unchanged for entry creation at the leaf\nnow, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching, hasDynamicRewrite) {\n const segment = routeTree.segment;\n const urlPart = partIndex < pathnameParts.length ? pathnameParts[partIndex] : null;\n let knownRoutePart = parentKnownRoutePart;\n let nextPartIndex = partIndex;\n if (typeof segment === 'string') {\n if (doesStaticSegmentAppearInURL(segment)) {\n // A visible static segment must consume exactly one URL part that\n // equals the segment. If the URL is exhausted or the URL part doesn't\n // match, the URL doesn't fit the route shape — the response was\n // rewrite-affected. Bail out.\n if (urlPart === null || urlPart !== segment) {\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map();\n }\n let existingChild = parentKnownRoutePart.staticChildren.get(urlPart);\n if (existingChild === undefined) {\n existingChild = createEmptyPart();\n parentKnownRoutePart.staticChildren.set(urlPart, existingChild);\n }\n knownRoutePart = existingChild;\n // Advance to next URL part.\n nextPartIndex = partIndex + 1;\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n const paramName = segment[0];\n const paramCacheKey = segment[1];\n const paramType = segment[2];\n const staticSiblings = segment[3];\n if (paramType !== 'oc' && urlPart === null) {\n // Every dynamic segment except the optional catch-all (`[[...param]]`)\n // must consume at least one URL part at runtime. If discovery reached\n // this segment with no URL parts left to consume, the URL doesn't fit\n // the route shape — the response was rewrite-affected. Bail out.\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n if (staticSiblings !== null && urlPart !== null && staticSiblings.includes(urlPart)) {\n // The route tree says this is a dynamic sibling, but the canonical URL\n // is a known static sibling. This is a mismatch.\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n // The param's cache key holds the value parsed from the *rendered*\n // pathname. If the URL part(s) this segment would consume don't equal\n // that value, the response was rewrite-affected in a way that shifts\n // which URL part maps to which segment (e.g. a proxy injected a leading\n // locale segment). A static segment catches this above by failing to\n // match its URL part; a dynamic segment consumes whatever part is in\n // front of it, so compare against the rendered value instead. Bail out.\n switch(paramType){\n case 'd':\n {\n // Canonicalize the URL part to the same encoded form the server used\n // for the cache key.\n if (urlPart !== null && canonicalizeURLPart(urlPart) !== paramCacheKey) {\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n break;\n }\n case 'c':\n case 'oc':\n {\n // Catch-alls consume every remaining URL part; their cache keys are\n // the rendered parts joined with '/' (empty string for an empty\n // optional catch-all). Comparing the joined remainder also catches a\n // rewrite that appended segments the URL doesn't have.\n const joinedRemainingParts = pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/');\n if (joinedRemainingParts !== paramCacheKey) {\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n break;\n }\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n break;\n default:\n paramType;\n }\n if (parentKnownRoutePart.hasConflictingDynamicChildren || parentKnownRoutePart.dynamicChild !== null && (parentKnownRoutePart.dynamicChildParamName !== paramName || parentKnownRoutePart.dynamicChildParamType !== paramType)) {\n // A different parallel route branch already claimed the dynamic child\n // at this level with a different param. Mark the level as conflicted\n // so matching bails out, and don't store a pattern via this branch.\n parentKnownRoutePart.hasConflictingDynamicChildren = true;\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n // URL matches route structure. Build the known route tree.\n knownRoutePart = discoverDynamicChild(parentKnownRoutePart, paramName, paramType);\n // Record static siblings as placeholder parts.\n // IMPORTANT: We use the null vs Map distinction to track whether\n // siblings are known at this level:\n // - staticChildren: null = siblings unknown (can't safely match dynamic)\n // - staticChildren: Map = siblings known (even if empty)\n // This matters in dev mode where webpack may not know all siblings yet.\n if (staticSiblings !== null) {\n // Siblings are known - ensure we have a Map (even if empty)\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map();\n }\n for (const sibling of staticSiblings){\n if (!parentKnownRoutePart.staticChildren.has(sibling)) {\n parentKnownRoutePart.staticChildren.set(sibling, createEmptyPart());\n }\n }\n }\n // Advance to next URL part. Catch-all segments (`[...param]` and\n // `[[...param]]`) absorb every remaining URL part at runtime (see\n // `matchKnownRoutePart`, which slices the rest of `pathnameParts`).\n if (paramType === 'c' || paramType === 'oc') {\n nextPartIndex = pathnameParts.length;\n } else {\n nextPartIndex = partIndex + 1;\n }\n }\n // Recurse into child routes. A route tree can have multiple parallel routes\n // (e.g., @modal alongside children). Each parallel route is a separate\n // branch, but they all share the same URL - we just need to traverse all\n // branches to build out the known route tree.\n const slots = routeTree.slots;\n let resultFromChildren = null;\n if (slots !== null) {\n for (const childRouteTree of slots.values()){\n // Skip branches with refreshState set - these were reused from a\n // different route (e.g., a \"default\" parallel slot) and don't represent\n // the actual route structure for this URL.\n if (childRouteTree.refreshState !== null) {\n continue;\n }\n const result = discoverKnownRoutePart(knownRoutePart, childRouteTree, pathnameParts, nextPartIndex, existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching, hasDynamicRewrite);\n // All parallel route branches share the same URL, so they should all\n // reach compatible leaf nodes. We capture any result.\n resultFromChildren = result;\n }\n if (resultFromChildren !== null) {\n return resultFromChildren;\n }\n // Defensive fallback: no children returned a result. This shouldn't happen\n // for valid route trees, but handle it gracefully.\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n // Reached a page node (`__PAGE__` leaf). If there are still URL parts\n // left to consume, the route tree is shorter than the URL, which means\n // the URL doesn't match the route structure (likely a rewrite).\n if (nextPartIndex < pathnameParts.length) {\n return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n // Reached a page node: the URL terminates here.\n if (hasDynamicRewrite) {\n knownRoutePart.hasDynamicRewrite = true;\n }\n // Create/get the route cache entry and store as a pattern. First, check if\n // there's already a pattern for this route.\n const existingPattern = readPattern(now, knownRoutePart);\n if (existingPattern !== null) {\n return existingPattern;\n }\n // Get or create the entry\n let entry;\n if (existingEntry !== null) {\n // Already have a fulfilled entry, use it directly. It's already in the\n // route cache map.\n entry = existingEntry;\n } else {\n // Create the entry and insert it into the route cache map.\n entry = writeRouteIntoCache(now, pathname, search, nextUrl, root, couldBeIntercepted, canonicalUrl, renderedSearch, supportsPerSegmentPrefetching);\n }\n // Store as pattern\n knownRoutePart.pattern = entry;\n return entry;\n}\n/**\n * Attempts to match a URL against learned route patterns.\n *\n * Returns a synthetic FulfilledRouteCacheEntry if the URL matches a known\n * pattern, or null if no match is found (fall back to server resolution).\n */ export function matchKnownRoute(now, pathname, search) {\n const pathnameParts = splitPathnameIntoParts(pathname);\n const resolvedParams = new Map();\n const match = matchKnownRoutePart(now, knownRouteTreeRoot, pathnameParts, 0, resolvedParams);\n if (match === null) {\n return null;\n }\n const matchedPart = match.part;\n const pattern = match.pattern;\n // If the pattern could be intercepted, we can't safely use it for prediction.\n // Interception routes resolve to different route trees depending on the\n // referrer (the Next-Url header), which means the same URL can map to\n // different page components depending on where the navigation originated.\n // Since the known route tree only stores a single pattern per URL shape, we\n // can't distinguish between the intercepted and non-intercepted cases, so we\n // bail out to server resolution.\n //\n // TODO: We could store interception behavior in the known route tree itself\n // (e.g., which segments use interception markers and what they resolve to).\n // With enough information embedded in the trie, we could match interception\n // routes entirely on the client without a server round-trip.\n if (pattern.couldBeIntercepted) {\n return null;\n }\n // Closed parameters affect whether the route exists, even when none of its\n // components read them. Resolve the target URL on the server instead of\n // combining a predicted tree with UI cached for an allowed parameter value.\n if (pattern.root.tree.prefetchHints & (PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)) {\n return null;\n }\n // \"Reify\" the pattern: clone the template tree with concrete param values.\n // This substitutes resolved params (e.g., slug: \"hello\") into dynamic\n // segments and recomputes vary paths for correct segment cache keying.\n const renderedSearch = normalizeRenderedSearch(search);\n const acc = {\n metadataVaryPath: null\n };\n const reifiedTree = reifyRouteTree(pattern.root.tree, resolvedParams, renderedSearch, null, acc);\n // The metadata tree is a flat page node without the intermediate layout\n // structure. Clone it with the updated metadata vary path collected during\n // the main tree traversal.\n const metadataVaryPath = acc.metadataVaryPath;\n if (metadataVaryPath === null) {\n // This shouldn't be reachable for a valid route tree.\n return null;\n }\n const reifiedMetadata = createMetadataRouteTree(metadataVaryPath, reifiedTree.prefetchHints, null);\n // Create a synthetic (predicted) entry. It's not inserted into the route\n // cache; it lives only as long as the task or navigation that read it. It\n // records the node it was predicted from so that if the prediction turns\n // out to be wrong (the server renders a different tree due to a dynamic\n // rewrite), the node can be marked and the shape is never predicted again\n // (see KnownRoutePart.hasDynamicRewrite).\n const syntheticEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n root: createRootRouteTree(reifiedTree, reifiedMetadata),\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n predictedFrom: matchedPart,\n renderedSearch,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version\n };\n return syntheticEntry;\n}\n/**\n * Recursively matches a URL against the known route tree.\n *\n * Matching priority (most specific first):\n * 1. Static children - exact path segment match\n * 2. Dynamic child - [param], [...param], [[...param]]\n * 3. Direct pattern - when no more URL parts remain\n *\n * Collects resolved param values in resolvedParams as it traverses.\n * Returns null if no match found (caller should fall back to server).\n */ function matchKnownRoutePart(now, part, pathnameParts, partIndex, resolvedParams) {\n const urlPart = partIndex < pathnameParts.length ? pathnameParts[partIndex] : null;\n // If staticChildren is null, we don't know what static routes exist at this\n // level. This happens in webpack dev mode where routes are compiled\n // on-demand. We can't safely match a dynamicChild because the URL part might\n // be a static sibling we haven't discovered yet. Example: We know\n // /blog/[slug] exists, but haven't compiled /blog/featured. A request for\n // /blog/featured would incorrectly match /blog/[slug].\n if (part.staticChildren === null) {\n // The only safe match is a direct pattern when no URL parts remain.\n if (urlPart === null && !part.hasDynamicRewrite) {\n const pattern = readPattern(now, part);\n if (pattern !== null) {\n return {\n part,\n pattern\n };\n }\n }\n return null;\n }\n // Static children take priority over dynamic. This ensures /blog/featured\n // matches its own route rather than /blog/[slug].\n if (urlPart !== null) {\n const staticChild = part.staticChildren.get(urlPart);\n if (staticChild !== undefined) {\n // Check if this is an \"unknown\" placeholder part. These are created when\n // we learn about static siblings (from the route tree's staticSiblings\n // field) but haven't prefetched them yet. We know the path exists but\n // don't know its structure, so we can't predict it.\n if (staticChild.pattern === null && staticChild.dynamicChild === null && staticChild.staticChildren === null) {\n // Bail out - server must resolve this route.\n return null;\n }\n const match = matchKnownRoutePart(now, staticChild, pathnameParts, partIndex + 1, resolvedParams);\n if (match !== null) {\n return match;\n }\n // Static child is a real node (not a placeholder) but its subtree\n // didn't match the remaining URL parts. This means the route exists\n // in the static subtree but hasn't been fully discovered yet. Do not\n // fall through to try the dynamic child — the static match is\n // authoritative. Bail out to server resolution.\n return null;\n }\n }\n // Try dynamic child. Skip it entirely if parallel route branches disagree\n // about the dynamic segment at this level — any pattern stored beneath it\n // was learned under a conflicting model.\n if (part.dynamicChild !== null && !part.hasConflictingDynamicChildren) {\n const dynamicPart = part.dynamicChild;\n const paramName = part.dynamicChildParamName;\n const paramType = part.dynamicChildParamType;\n // Catch-alls terminate at the dynamic child, so a dynamic rewrite marked\n // there rules out predicting any URL that would end in it.\n const dynamicPattern = dynamicPart.hasDynamicRewrite ? null : readPattern(now, dynamicPart);\n switch(paramType){\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (dynamicPattern !== null && urlPart !== null) {\n resolvedParams.set(paramName, pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/'));\n return {\n part: dynamicPart,\n pattern: dynamicPattern\n };\n }\n break;\n case 'oc':\n {\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null) {\n if (urlPart !== null) {\n resolvedParams.set(paramName, pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/'));\n return {\n part: dynamicPart,\n pattern: dynamicPattern\n };\n }\n // urlPart is null - can match with zero parts, but a direct pattern\n // (e.g., page.tsx alongside [[...param]]) takes precedence.\n const directPattern = part.hasDynamicRewrite ? null : readPattern(now, part);\n if (directPattern === null) {\n resolvedParams.set(paramName, '');\n return {\n part: dynamicPart,\n pattern: dynamicPattern\n };\n }\n }\n break;\n }\n case 'd':\n // Regular dynamic [param]: consumes exactly 1 URL part.\n // Unlike catch-all which terminates here, regular dynamic must\n // continue recursing to find the leaf pattern.\n if (urlPart !== null) {\n resolvedParams.set(paramName, canonicalizeURLPart(urlPart));\n return matchKnownRoutePart(now, dynamicPart, pathnameParts, partIndex + 1, resolvedParams);\n }\n break;\n // Intercepted routes use relative path markers like (.), (..), (...)\n // Their behavior depends on navigation context (soft vs hard nav),\n // so we can't predict them client-side. Defer to server.\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n return null;\n default:\n paramType;\n }\n }\n // No children matched. If we've consumed all URL parts, check for a direct\n // pattern at this node (the route terminates here).\n if (urlPart === null && !part.hasDynamicRewrite) {\n const pattern = readPattern(now, part);\n if (pattern !== null) {\n return {\n part,\n pattern\n };\n }\n }\n return null;\n}\n/**\n * \"Reify\" means to make concrete - we take an abstract pattern (the template\n * route tree) and produce a concrete instance with actual param values.\n *\n * This function clones a RouteTree, substituting dynamic segment values from\n * resolvedParams and computing new vary paths. The vary path encodes param\n * values so segment cache entries can be correctly keyed.\n *\n * Example: Pattern for /blog/[slug] with resolvedParams { slug: \"hello\" }\n * produces a tree where segment [slug] has cacheKey \"hello\".\n */ function reifyRouteTree(pattern, resolvedParams, search, parentPartialVaryPath, acc) {\n const originalSegment = pattern.segment;\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = (pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0;\n let newSegment = originalSegment;\n let partialVaryPath;\n if (typeof originalSegment !== 'string') {\n // Dynamic segment: compute new cache key and append to partial vary path\n const paramName = originalSegment[0];\n const paramType = originalSegment[2];\n const staticSiblings = originalSegment[3];\n const newValue = resolvedParams.get(paramName);\n if (newValue !== undefined) {\n // Catch-all values are already joined into a single string when they're\n // resolved in matchKnownRoutePart, so the value can be used directly.\n const newCacheKey = newValue;\n newSegment = [\n paramName,\n newCacheKey,\n paramType,\n staticSiblings\n ];\n partialVaryPath = appendLayoutVaryPath(parentPartialVaryPath, newCacheKey, paramName, isRootParam);\n } else {\n // Param not found in resolvedParams - keep original and inherit partial\n // TODO: This should never happen. Bail out with null.\n partialVaryPath = parentPartialVaryPath;\n }\n } else {\n // Static segment: inherit partial vary path from parent\n partialVaryPath = parentPartialVaryPath;\n }\n // Recurse into children with the (possibly updated) partial vary path\n let newSlots = null;\n const patternSlots = pattern.slots;\n if (patternSlots !== null) {\n newSlots = new Map();\n for (const [key, childPattern] of patternSlots){\n newSlots.set(key, reifyRouteTree(childPattern, resolvedParams, search, partialVaryPath, acc));\n }\n }\n let newVaryPath;\n if (originalSegment === PAGE_SEGMENT_KEY) {\n // Page segment: finalize with search params\n newVaryPath = finalizeVaryPath(pattern.requestKey, search, partialVaryPath);\n // Collect metadata vary path (first page wins; see getHeadRequestKey)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeVaryPath(getHeadRequestKey(pattern.requestKey), search, partialVaryPath);\n }\n } else {\n // Layout segment: finalize without search params\n newVaryPath = finalizeVaryPath(pattern.requestKey, null, partialVaryPath);\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n // Route cache patterns never carry seed data (see\n // stripDataFromRouteTree), so neither do trees reified from them.\n data: null,\n varyPath: newVaryPath,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints\n };\n}\n/**\n * Resets the known route tree. Called during development when routes may\n * change due to hot reloading.\n */ export function resetKnownRoutes() {\n knownRouteTreeRoot = createEmptyPart();\n}\n\n//# sourceMappingURL=optimistic-routes.js.map","import { lruPut, updateLruSize, deleteFromLru } from './lru';\n/**\n * A specialized data type for storing multi-key cache entries.\n *\n * The basic structure is a map whose keys are tuples, called the keypath.\n * When querying the cache, keypaths are compared per-element.\n *\n * Example:\n * set(map, ['https://localhost', 'foo/bar/baz'], 'yay');\n * get(map, ['https://localhost', 'foo/bar/baz']) -> 'yay'\n *\n * NOTE: Array syntax is used in these examples for illustration purposes, but\n * in reality the paths are lists.\n * \n * The parts of the keypath represent the different inputs that contribute\n * to the entry value. To illustrate, if you were to use this data type to store\n * HTTP responses, the keypath would include the URL and everything listed by\n * the Vary header.\n * \n * See vary-path.ts for more details.\n *\n * The order of elements in a keypath must be consistent between lookups to\n * be considered the same, but besides that, the order of the keys is not\n * semantically meaningful.\n *\n * Keypaths may include a special kind of key called Fallback. When an entry is\n * stored with Fallback as part of its keypath, it means that the entry does not\n * vary by that key. When querying the cache, if an exact match is not found for\n * a keypath, the cache will check for a Fallback match instead. Each element of\n * the keypath may have a Fallback, so retrieval is an O(n ^ 2) operation, but\n * it's expected that keypaths are relatively short.\n *\n * Example:\n * set(cacheMap, ['store', 'product', 1], PRODUCT_PAGE_1);\n * set(cacheMap, ['store', 'product', Fallback], GENERIC_PRODUCT_PAGE);\n *\n * // Exact match\n * get(cacheMap, ['store', 'product', 1]) -> PRODUCT_PAGE_1\n *\n * // Fallback match\n * get(cacheMap, ['store', 'product', 2]) -> GENERIC_PRODUCT_PAGE\n *\n * Because we have the Fallback mechanism, we can impose a constraint that\n * regular JS maps do not have: a value cannot be stored at multiple keypaths\n * simultaneously. These cases should be expressed with Fallback keys instead.\n *\n * Additionally, because values only exist at a single keypath at a time, we\n * can optimize successive lookups by caching the internal map entry on the\n * value itself, using the `ref` field. This is especially useful because it\n * lets us skip the O(n ^ 2) lookup that occurs when Fallback entries\n * are present.\n *\n\n * How to decide if stuff belongs in here, or in cache.ts?\n * -------------------------------------------------------\n * \n * Anything to do with retrival, lifetimes, or eviction needs to go in this\n * module because it affects the fallback algorithm. For example, when\n * performing a lookup, if an entry is stale, it needs to be treated as\n * semantically equivalent to if the entry was not present at all.\n * \n * If there's logic that's not related to the fallback algorithm, though, we\n * should prefer to put it in cache.ts.\n */ /**\n * Tracks the status of a cache entry as it progresses from no data (Empty),\n * waiting for server data (Pending), and finished (either Fulfilled or\n * Rejected depending on the response from the server.\n *\n * This is defined here, rather than in cache.ts, because cache-map.ts needs to\n * inspect the status when performing a `onlyMatchFulfilled` lookup.\n */ export var EntryStatus = /*#__PURE__*/ function(EntryStatus) {\n EntryStatus[EntryStatus[\"Empty\"] = 0] = \"Empty\";\n EntryStatus[EntryStatus[\"Pending\"] = 1] = \"Pending\";\n EntryStatus[EntryStatus[\"Fulfilled\"] = 2] = \"Fulfilled\";\n EntryStatus[EntryStatus[\"Rejected\"] = 3] = \"Rejected\";\n return EntryStatus;\n}({});\nexport const Fallback = {};\n// This is a special internal key that is used for \"revalidation\" entries. It's\n// an implementation detail that shouldn't leak outside of this module.\nconst Revalidation = {};\nexport function createCacheMap() {\n const cacheMap = {\n parent: null,\n key: null,\n value: null,\n map: null,\n // LRU-related fields\n prev: null,\n next: null,\n size: 0\n };\n return cacheMap;\n}\nfunction getOrInitialize(cacheMap, keys, isRevalidation) {\n // Go through each level of keys until we find the entry that matches, or\n // create a new entry if one doesn't exist.\n //\n // This function will only return entries that match the keypath _exactly_.\n // Unlike getWithFallback, it will not access fallback entries unless it's\n // explicitly part of the keypath.\n let entry = cacheMap;\n let remainingKeys = keys;\n let key = null;\n while(true){\n const previousKey = key;\n if (remainingKeys !== null) {\n key = remainingKeys.value;\n remainingKeys = remainingKeys.parent;\n } else if (isRevalidation && previousKey !== Revalidation) {\n // During a revalidation, we append an internal \"Revalidation\" key to\n // the end of the keypath. The \"normal\" entry is its parent.\n // However, if the parent entry is currently empty, we don't need to store\n // this as a revalidation entry. Just insert the revalidation into the\n // normal slot.\n if (entry.value === null) {\n return entry;\n }\n // Otheriwse, create a child entry.\n key = Revalidation;\n } else {\n break;\n }\n let map = entry.map;\n if (map !== null) {\n const existingEntry = map.get(key);\n if (existingEntry !== undefined) {\n // Found a match. Keep going.\n entry = existingEntry;\n continue;\n }\n } else {\n map = new Map();\n entry.map = map;\n }\n // No entry exists yet at this level. Create a new one.\n const newEntry = {\n parent: entry,\n key,\n value: null,\n map: null,\n // LRU-related fields\n prev: null,\n next: null,\n size: 0\n };\n map.set(key, newEntry);\n entry = newEntry;\n }\n return entry;\n}\nexport function getFromCacheMap(now, currentCacheVersion, rootEntry, keys, isRevalidation, // When true, terminal entries whose status is not Fulfilled are skipped, so\n// the lookup falls through to a less-specific Fallback entry. Use this\n// during a navigation to prefer a Fulfilled shell entry over a more-specific\n// Pending entry that may still be in-flight. Callers that want to also\n// accept non-Fulfilled entries should perform a second lookup with this set\n// to false.\nonlyMatchFulfilled) {\n const entry = getEntryWithFallbackImpl(now, currentCacheVersion, rootEntry, keys, isRevalidation, 0, onlyMatchFulfilled);\n if (entry === null || entry.value === null) {\n return null;\n }\n // This is an LRU access. Move the entry to the front of the list.\n lruPut(entry);\n return entry.value;\n}\nexport function isValueExpired(now, currentCacheVersion, value) {\n return value.staleAt <= now || value.version < currentCacheVersion;\n}\nfunction lazilyEvictIfNeeded(now, currentCacheVersion, entry, onlyMatchFulfilled) {\n // We have a matching entry, but before we can return it, we need to check if\n // it's still fresh. Otherwise it should be treated the same as a cache miss.\n if (entry.value === null) {\n // This entry has no value, so there's nothing to evict.\n return entry;\n }\n const value = entry.value;\n if (isValueExpired(now, currentCacheVersion, value)) {\n // The value expired. Lazily evict it from the cache, and return null. This\n // is conceptually the same as a cache miss.\n deleteMapEntry(entry);\n return null;\n }\n if (onlyMatchFulfilled && value.status !== 2) {\n // The entry is fresh but is not Fulfilled. Treat as a non-match so the\n // recursion can continue and try a Fallback entry.\n return null;\n }\n // The matched entry has not expired. Return it.\n return entry;\n}\nfunction getEntryWithFallbackImpl(now, currentCacheVersion, entry, keys, isRevalidation, previousKey, onlyMatchFulfilled) {\n // This is similar to getExactEntry, but if an exact match is not found for\n // a key, it will return the fallback entry instead. This is recursive at\n // every level, e.g. an entry with keypath [a, Fallback, c, Fallback] is\n // valid match for [a, b, c, d].\n //\n // It will return the most specific match available.\n //\n // When `onlyMatchFulfilled` is true, terminal entries that aren't Fulfilled\n // are treated as non-matches, so the recursion will continue searching for\n // a Fallback match. See getFromCacheMap for the rationale.\n let key;\n let remainingKeys;\n if (keys !== null) {\n key = keys.value;\n remainingKeys = keys.parent;\n } else if (isRevalidation && previousKey !== Revalidation) {\n // During a revalidation, we append an internal \"Revalidation\" key to\n // the end of the keypath.\n key = Revalidation;\n remainingKeys = null;\n } else {\n // There are no more keys. This is the terminal entry.\n return lazilyEvictIfNeeded(now, currentCacheVersion, entry, onlyMatchFulfilled);\n }\n const map = entry.map;\n if (map !== null) {\n const existingEntry = map.get(key);\n if (existingEntry !== undefined) {\n // Found an exact match for this key. Keep searching.\n const result = getEntryWithFallbackImpl(now, currentCacheVersion, existingEntry, remainingKeys, isRevalidation, key, onlyMatchFulfilled);\n if (result !== null) {\n return result;\n }\n }\n // No match found for this key. Check if there's a fallback.\n const fallbackEntry = map.get(Fallback);\n if (fallbackEntry !== undefined) {\n // Found a fallback for this key. Keep searching.\n return getEntryWithFallbackImpl(now, currentCacheVersion, fallbackEntry, remainingKeys, isRevalidation, key, onlyMatchFulfilled);\n }\n }\n return null;\n}\nexport function setInCacheMap(cacheMap, keys, value, isRevalidation) {\n // Add a value to the map at the given keypath. If the value is already\n // part of the map, it's removed from its previous keypath. (NOTE: This is\n // unlike a regular JS map, but the behavior is intentional.)\n const entry = getOrInitialize(cacheMap, keys, isRevalidation);\n setMapEntryValue(entry, value);\n // This is an LRU access. Move the entry to the front of the list.\n lruPut(entry);\n updateLruSize(entry, value.size);\n}\nfunction setMapEntryValue(entry, value) {\n if (entry.value !== null) {\n // There's already a value at the given keypath. Disconnect the old value\n // from the map. We're not calling `deleteMapEntry` here because the\n // entry itself is still in the map. We just want to overwrite its value.\n dropRef(entry.value);\n entry.value = null;\n }\n // This value may already be in the map at a different keypath.\n // Grab a reference before we overwrite it.\n const oldEntry = value.ref;\n entry.value = value;\n value.ref = entry;\n updateLruSize(entry, value.size);\n if (oldEntry !== null && oldEntry !== entry && oldEntry.value === value) {\n // This value is already in the map at a different keypath in the map.\n // Values only exist at a single keypath at a time. Remove it from the\n // previous keypath.\n //\n // Note that only the internal map entry is garbage collected; we don't\n // call `dropRef` here because it's still in the map, just\n // at a new keypath (the one we just set, above).\n deleteMapEntry(oldEntry);\n }\n}\nexport function deleteFromCacheMap(value) {\n const entry = value.ref;\n if (entry === null) {\n // This value is not a member of any map.\n return;\n }\n dropRef(value);\n deleteMapEntry(entry);\n}\nfunction dropRef(value) {\n // Drop the value from the map by setting its `ref` backpointer to\n // null. This is a separate operation from `deleteMapEntry` because when\n // re-keying a value we need to be able to delete the old, internal map\n // entry without garbage collecting the value itself.\n value.ref = null;\n}\nexport function deleteMapEntry(entry) {\n // Delete the entry from the cache.\n entry.value = null;\n deleteFromLru(entry);\n // Check if we can garbage collect the entry.\n const map = entry.map;\n if (map === null) {\n // Since this entry has no value, and also no child entries, we can\n // garbage collect it. Remove it from its parent, and keep garbage\n // collecting the parents until we reach a non-empty entry.\n let parent = entry.parent;\n let key = entry.key;\n while(parent !== null){\n const parentMap = parent.map;\n if (parentMap !== null) {\n parentMap.delete(key);\n if (parentMap.size === 0) {\n // We just removed the last entry in the parent map.\n parent.map = null;\n if (parent.value === null) {\n // The parent node has no child entries, nor does it have a value\n // on itself. It can be garbage collected. Keep going.\n key = parent.key;\n parent = parent.parent;\n continue;\n }\n }\n }\n break;\n }\n } else {\n // Check if there's a revalidating entry. If so, promote it to a\n // \"normal\" entry, since the normal one was just deleted.\n const revalidatingEntry = map.get(Revalidation);\n if (revalidatingEntry !== undefined && revalidatingEntry.value !== null) {\n setMapEntryValue(entry, revalidatingEntry.value);\n }\n }\n}\nexport function setSizeInCacheMap(value, size) {\n const entry = value.ref;\n if (entry === null) {\n // This value is not a member of any map.\n return;\n }\n // Except during initialization (when the size is set to 0), this is the only\n // place the `size` field should be updated, to ensure it's in sync with the\n // the LRU.\n value.size = size;\n updateLruSize(entry, size);\n}\n\n//# sourceMappingURL=cache-map.js.map","export function getSegmentValue(segment) {\n return Array.isArray(segment) ? segment[1] : segment;\n}\nexport function isGroupSegment(segment) {\n // Use array[0] for performant purpose\n return segment[0] === '(' && segment.endsWith(')');\n}\nexport function isParallelRouteSegment(segment) {\n return segment.startsWith('@') && segment !== '@children';\n}\nexport function computeSelectedLayoutSegment(segments, parallelRouteKey) {\n if (!segments || segments.length === 0) {\n return null;\n }\n // For 'children', use first segment; for other parallel routes, use last segment\n const rawSegment = parallelRouteKey === 'children' ? segments[0] : segments[segments.length - 1];\n // If the default slot is showing, return null since it's not technically \"selected\" (it's a fallback)\n // Returning an internal value like `__DEFAULT__` would be confusing\n return rawSegment === DEFAULT_SEGMENT_KEY ? null : rawSegment;\n}\n/** Get the canonical parameters from the current level to the leaf node. */ export function getSelectedLayoutSegmentPath(tree, parallelRouteKey, first = true, segmentPath = []) {\n let node;\n if (first) {\n // Use the provided parallel route key on the first parallel route\n node = tree[1][parallelRouteKey];\n } else {\n // After first parallel route prefer children, if there's no children pick the first parallel route.\n const parallelRoutes = tree[1];\n node = parallelRoutes.children ?? Object.values(parallelRoutes)[0];\n }\n if (!node) return segmentPath;\n const segment = node[0];\n let segmentValue = getSegmentValue(segment);\n if (!segmentValue || segmentValue === PAGE_SEGMENT_KEY) {\n return segmentPath;\n }\n segmentPath.push(segmentValue);\n return getSelectedLayoutSegmentPath(node, parallelRouteKey, false, segmentPath);\n}\nexport const PAGE_SEGMENT_KEY = '__PAGE__';\nexport const DEFAULT_SEGMENT_KEY = '__DEFAULT__';\nexport const NOT_FOUND_SEGMENT_KEY = '/_not-found';\n\n//# sourceMappingURL=segment.js.map","export const ROOT_SEGMENT_REQUEST_KEY = '';\nexport const HEAD_REQUEST_KEY = '/_head';\nexport function createSegmentRequestKeyPart(segment) {\n if (typeof segment === 'string') {\n const safeName = // TODO: FlightRouterState encodes Not Found routes as \"/_not-found\".\n // But params typically don't include the leading slash. We should use\n // a different encoding to avoid this special case.\n segment === '/_not-found' ? '_not-found' : encodeToFilesystemAndURLSafeString(segment);\n // Since this is not a dynamic segment, it's fully encoded. It does not\n // need to be \"hydrated\" with a param value.\n return safeName;\n }\n const name = segment[0];\n const paramType = segment[2];\n const safeName = encodeToFilesystemAndURLSafeString(name);\n const encodedName = '$' + paramType + '$' + safeName;\n return encodedName;\n}\nexport function appendSegmentRequestKeyPart(parentRequestKey, parallelRouteKey, childRequestKeyPart) {\n // Aside from being filesystem safe, segment keys are also designed so that\n // each segment and parallel route creates its own subdirectory. Roughly in\n // the same shape as the source app directory. This is mostly just for easier\n // debugging (you can open up the build folder and navigate the output); if\n // we wanted to do we could just use a flat structure.\n // Omit the parallel route key for children, since this is the most\n // common case. Saves some bytes (and it's what the app directory does).\n const slotKey = parallelRouteKey === 'children' ? childRequestKeyPart : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childRequestKeyPart}`;\n return parentRequestKey + '/' + slotKey;\n}\n// Define a regex pattern to match the most common characters found in a route\n// param. It excludes anything that might not be cross-platform filesystem\n// compatible, like |. It does not need to be precise because the fallback is to\n// just base64url-encode the whole parameter, which is fine; we just don't do it\n// by default for compactness, and for easier debugging.\nconst simpleParamValueRegex = /^[a-zA-Z0-9\\-_@]+$/;\nfunction encodeToFilesystemAndURLSafeString(value) {\n if (simpleParamValueRegex.test(value)) {\n return value;\n }\n // If there are any unsafe characters, base64url-encode the entire value.\n // We also add a ! prefix so it doesn't collide with the simple case.\n const base64url = btoa(value).replace(/\\+/g, '-') // Replace '+' with '-'\n .replace(/\\//g, '_') // Replace '/' with '_'\n .replace(/=+$/, '') // Remove trailing '='\n ;\n return '!' + base64url;\n}\nexport function convertSegmentPathToStaticExportFilename(segmentPath) {\n return `__next${segmentPath.replace(/\\//g, '.')}.txt`;\n}\n\n//# sourceMappingURL=segment-value-encoding.js.map","export const RSC_HEADER = 'rsc';\nexport const ACTION_HEADER = 'next-action';\n// TODO: Instead of sending the full router state, we only need to send the\n// segment path. Saves bytes. Then we could also use this field for segment\n// prefetches, which also need to specify a particular segment.\nexport const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree';\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch';\n// This contains the path to the segment being prefetched.\n// TODO: If we change next-router-state-tree to be a segment path, we can use\n// that instead. Then next-router-prefetch and next-router-segment-prefetch can\n// be merged into a single enum.\nexport const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER = 'next-router-segment-prefetch';\nexport const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh';\nexport const NEXT_URL = 'next-url';\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component';\n// Cookie for the Instant Navigation Testing API. Sent automatically with all\n// requests while a navigation lock is held; the server uses its presence to\n// render only the shell. Not exposed in production builds by default.\nexport const NEXT_INSTANT_TEST_COOKIE = 'next-instant-navigation-testing';\nexport const FLIGHT_HEADERS = [\n RSC_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER\n];\nexport const NEXT_RSC_UNION_QUERY = '_rsc';\nexport const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time';\nexport const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed';\nexport const NEXT_REWRITTEN_PATH_HEADER = 'x-nextjs-rewritten-path';\nexport const NEXT_REWRITTEN_QUERY_HEADER = 'x-nextjs-rewritten-query';\nexport const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender';\nexport const NEXT_ACTION_NOT_FOUND_HEADER = 'x-nextjs-action-not-found';\nexport const NEXT_REQUEST_ID_HEADER = 'x-nextjs-request-id';\nexport const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id';\n// TODO: Should this include nextjs in the name, like the others?\nexport const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated';\n\n//# sourceMappingURL=app-router-headers.js.map","import { hasBasePath } from './has-base-path';\nconst basePath = process.env.__NEXT_ROUTER_BASEPATH || '';\nexport function removeBasePath(path) {\n if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {\n if (!hasBasePath(path)) {\n return path;\n }\n }\n // Can't trim the basePath if it has zero length!\n if (basePath.length === 0) return path;\n path = path.slice(basePath.length);\n if (!path.startsWith('/')) path = `/${path}`;\n return path;\n}\n\n//# sourceMappingURL=remove-base-path.js.map","import { pathHasPrefix } from '../shared/lib/router/utils/path-has-prefix';\nconst basePath = process.env.__NEXT_ROUTER_BASEPATH || '';\nexport function hasBasePath(path) {\n return pathHasPrefix(path, basePath);\n}\n\n//# sourceMappingURL=has-base-path.js.map","/**\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */ export function parsePath(path) {\n const hashIndex = path.indexOf('#');\n const queryIndex = path.indexOf('?');\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex);\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : ''\n };\n }\n return {\n pathname: path,\n query: '',\n hash: ''\n };\n}\n\n//# sourceMappingURL=parse-path.js.map","import { DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../shared/lib/segment';\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding';\nimport { NEXT_REWRITTEN_PATH_HEADER, NEXT_REWRITTEN_QUERY_HEADER, NEXT_RSC_UNION_QUERY } from './components/app-router-headers';\nimport { hasBasePath } from './has-base-path';\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash';\nimport { removeBasePath } from './remove-base-path';\nimport { getRenderedSearch as getRenderedSearchFromQuery } from '../shared/lib/router/utils/querystring';\nexport function normalizeRenderedSearch(search) {\n // The same search params should produce the same string whether they came\n // from the URL, a rewrite header, or the response (e.g. '+' vs '%20'). Only\n // used for the rendered search. Request URLs keep their original form,\n // since middleware and rewrites may depend on it.\n const query = urlSearchParamsToParsedUrlQuery(new URLSearchParams(search));\n return getRenderedSearchFromQuery(query);\n}\nexport function getRenderedSearch(response) {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER);\n if (rewrittenQuery !== null) {\n return normalizeRenderedSearch(rewrittenQuery);\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return normalizeRenderedSearch(urlToUrlWithoutFlightMarker(new URL(response.url)).search);\n}\nexport function getRenderedPathname(response) {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER);\n if (rewrittenPath !== null) {\n return rewrittenPath;\n }\n const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname;\n return hasBasePath(pathname) ? removeBasePath(pathname) : pathname;\n}\n/**\n * Like getRenderedPathname, but derived from the request URL rather than the\n * response. Used in output: \"export\" mode, where the response URL has the\n * segment filename appended to the pathname — and where rewrites don't\n * exist, so the request pathname is always the rendered pathname.\n */ export function getPathnameFromRequestURL(url) {\n const pathname = url.pathname;\n return hasBasePath(pathname) ? removeBasePath(pathname) : pathname;\n}\n// Pathname parts come from `URL.pathname.split('/')`, so they are already\n// in the encoded form the URL parser produces. The server-side equivalent\n// (`get-dynamic-param.ts`) starts from a decoded param value and applies\n// `encodeURIComponent` once. The two encodings are not the same — for\n// example, the URL parser leaves `,` and `:` untouched while\n// `encodeURIComponent` percent-encodes them. To produce the same canonical\n// form on the client (and avoid double-encoding `%xx` sequences such as\n// `%2F` → `%252F`), we decode the URL part first and re-encode it.\nexport function canonicalizeURLPart(part) {\n try {\n return encodeURIComponent(decodeURIComponent(part));\n } catch {\n // `decodeURIComponent` throws on malformed sequences. Fall back to the\n // already-encoded form rather than failing the navigation.\n return part;\n }\n}\nexport function parseDynamicParamFromURLPart(paramType, pathnameParts, partIndex) {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch(paramType){\n // Catchalls\n case 'c':\n {\n // Catchalls receive all the remaining URL parts. If there are no\n // remaining pathname parts, return an empty array.\n return partIndex < pathnameParts.length ? pathnameParts.slice(partIndex).map((s)=>canonicalizeURLPart(s)) : [];\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n {\n const prefix = paramType.length - 2;\n return partIndex < pathnameParts.length ? pathnameParts.slice(partIndex).map((s, i)=>{\n if (i === 0) {\n return canonicalizeURLPart(s.slice(prefix));\n }\n return canonicalizeURLPart(s);\n }) : [];\n }\n // Optional catchalls\n case 'oc':\n {\n // Optional catchalls receive all the remaining URL parts, unless this is\n // the end of the pathname, in which case they return null.\n return partIndex < pathnameParts.length ? pathnameParts.slice(partIndex).map((s)=>canonicalizeURLPart(s)) : null;\n }\n // Dynamic\n case 'd':\n {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return '';\n }\n return canonicalizeURLPart(pathnameParts[partIndex]);\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n {\n const prefix = paramType.length - 2;\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return '';\n }\n return canonicalizeURLPart(pathnameParts[partIndex].slice(prefix));\n }\n default:\n paramType;\n return '';\n }\n}\nexport function doesStaticSegmentAppearInURL(segment) {\n // This is not a parameterized segment; however, we need to determine\n // whether or not this segment appears in the URL. For example, this route\n // groups do not appear in the URL, so they should be skipped. Any other\n // special cases must be handled here.\n // TODO: Consider encoding this directly into the router tree instead of\n // inferring it on the client based on the segment type. Something like\n // a `doesAppearInURL` flag in FlightRouterState.\n if (segment === ROOT_SEGMENT_REQUEST_KEY || // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment === PAGE_SEGMENT_KEY || // Route groups.\n segment[0] === '(' && segment.endsWith(')') || segment === DEFAULT_SEGMENT_KEY || segment === '/_not-found') {\n return false;\n } else {\n // All other segment types appear in the URL\n return true;\n }\n}\nexport function getCacheKeyForDynamicParam(paramValue) {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n return paramValue;\n } else if (paramValue === null) {\n return '';\n } else {\n return paramValue.join('/');\n }\n}\nexport function urlToUrlWithoutFlightMarker(url) {\n const urlWithoutFlightParameters = new URL(url);\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY);\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export' && urlWithoutFlightParameters.pathname.endsWith('.txt')) {\n const { pathname } = urlWithoutFlightParameters;\n // Undo the marker appended in `fetchServerResponse`, which is keyed on\n // whether the requested pathname ended with a slash: `index.txt` for\n // `/foo/`, `.txt` for `/foo`. Slicing off only `index.txt` keeps that\n // slash, then `normalizePathTrailingSlash` applies the configured\n // policy so we don't hand-roll a second one here.\n const length = pathname.endsWith('/index.txt') ? 9 : 4;\n urlWithoutFlightParameters.pathname = normalizePathTrailingSlash(pathname.slice(0, -length));\n }\n }\n return urlWithoutFlightParameters;\n}\nexport function getParamValueFromCacheKey(paramCacheKey, paramType) {\n // Turn the cache key string sent by the server (as part of FlightRouterState)\n // into a value that can be passed to `useParams` and client components.\n const isCatchAll = paramType === 'c' || paramType === 'oc';\n if (isCatchAll) {\n // Catch-all param keys are a concatenation of the path segments.\n // See equivalent logic in `getSelectedParams`.\n // TODO: We should just pass the array directly, rather than concatenate\n // it to a string and then split it back to an array. It needs to be an\n // array in some places, like when passing a key React, but we can convert\n // it at runtime in those places.\n return paramCacheKey.split('/');\n }\n return paramCacheKey;\n}\nexport function urlSearchParamsToParsedUrlQuery(searchParams) {\n // Converts a URLSearchParams object to the same type used by the server when\n // creating search params props, i.e. the type returned by Node's\n // \"querystring\" module.\n const result = {};\n for (const [key, value] of searchParams.entries()){\n if (result[key] === undefined) {\n result[key] = value;\n } else if (Array.isArray(result[key])) {\n result[key].push(value);\n } else {\n result[key] = [\n result[key],\n value\n ];\n }\n }\n return result;\n}\n\n//# sourceMappingURL=route-params.js.map","import { parsePath } from './parse-path';\n/**\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */ export function pathHasPrefix(path, prefix) {\n if (typeof path !== 'string') {\n return false;\n }\n const { pathname } = parsePath(path);\n return pathname === prefix || pathname.startsWith(prefix + '/');\n}\n\n//# sourceMappingURL=path-has-prefix.js.map","'use client'\n\nimport type { ReactNode } from 'react'\nimport {\n METADATA_BOUNDARY_NAME,\n VIEWPORT_BOUNDARY_NAME,\n OUTLET_BOUNDARY_NAME,\n ROOT_LAYOUT_BOUNDARY_NAME,\n} from './boundary-constants'\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [METADATA_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [VIEWPORT_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [OUTLET_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [ROOT_LAYOUT_BOUNDARY_NAME]: function ({\n children,\n }: {\n children: ReactNode\n }) {\n return children\n },\n}\n\nexport const MetadataBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[METADATA_BOUNDARY_NAME.slice(0) as typeof METADATA_BOUNDARY_NAME]\n\nexport const ViewportBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[VIEWPORT_BOUNDARY_NAME.slice(0) as typeof VIEWPORT_BOUNDARY_NAME]\n\nexport const OutletBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[OUTLET_BOUNDARY_NAME.slice(0) as typeof OUTLET_BOUNDARY_NAME]\n\nexport const RootLayoutBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n ROOT_LAYOUT_BOUNDARY_NAME.slice(0) as typeof ROOT_LAYOUT_BOUNDARY_NAME\n ]\n","export const METADATA_BOUNDARY_NAME = '__next_metadata_boundary__'\nexport const VIEWPORT_BOUNDARY_NAME = '__next_viewport_boundary__'\nexport const OUTLET_BOUNDARY_NAME = '__next_outlet_boundary__'\nexport const ROOT_LAYOUT_BOUNDARY_NAME = '__next_root_layout_boundary__'\n","'use client'\n\n// This is a client component that only renders during SSR,\n// but will be replaced during streaming with an icon insertion script tag.\n// We don't want it to be presented anywhere so it's only visible during streaming,\n// right after the icon meta tags so that browser can pick it up as soon as it's rendered.\n// Note: we don't just emit the script here because we only need the script if it's not in the head,\n// and we need it to be hoistable alongside the other metadata but sync scripts are not hoistable.\nexport const IconMark = () => {\n if (typeof window !== 'undefined') {\n return null\n }\n return <meta name=\"«nxt-icon»\" />\n}\n","export { RequestCookies, ResponseCookies, stringifyCookie } from 'next/dist/compiled/@edge-runtime/cookies';\n\n//# sourceMappingURL=cookies.js.map","const INSTANT_VALIDATION_ERROR_DIGEST = 'INSTANT_VALIDATION_ERROR';\n/** Check if an error is an exhaustive samples validation error (by digest). */ export function isInstantValidationError(err) {\n return !!(err && typeof err === 'object' && err instanceof Error && err.digest === INSTANT_VALIDATION_ERROR_DIGEST);\n}\nexport class InstantValidationError extends Error {\n constructor(...args){\n super(...args), this.digest = INSTANT_VALIDATION_ERROR_DIGEST;\n }\n}\n\n//# sourceMappingURL=instant-validation-error.js.map","export const ActionDidNotRevalidate = 0;\nexport const ActionDidRevalidateStaticAndDynamic = 1;\nexport const ActionDidRevalidateDynamicOnly = 2;\n\n//# sourceMappingURL=action-revalidation-kind.js.map","import { getLocationOrigin } from '../../utils';\nimport { searchParamsToUrlQuery } from './querystring';\nexport function parseRelativeUrl(url, base, parseQuery = true) {\n const globalBase = new URL(typeof window === 'undefined' ? 'http://n' : getLocationOrigin());\n const resolvedBase = base ? new URL(base, globalBase) : url.startsWith('.') ? new URL(typeof window === 'undefined' ? 'http://n' : window.location.href) : globalBase;\n const { pathname, searchParams, search, hash, href, origin } = url.startsWith('/') ? // See https://nodejs.org/api/http.html#messageurl\n // Not using `origin` to support other protocols\n new URL(`${resolvedBase.protocol}//${resolvedBase.host}${url}`) : new URL(url, resolvedBase);\n if (origin !== globalBase.origin) {\n throw new Error(`invariant: invalid relative URL, router received ${url}`);\n }\n return {\n auth: null,\n host: null,\n hostname: null,\n pathname,\n port: null,\n protocol: null,\n query: parseQuery ? searchParamsToUrlQuery(searchParams) : undefined,\n search,\n hash,\n href: href.slice(origin.length),\n // We don't know for relative URLs at this point since we set a custom, internal\n // base that isn't surfaced to users.\n slashes: null\n };\n}\n\n//# sourceMappingURL=parse-relative-url.js.map","import { RequestCookies } from '../cookies';\nimport { ResponseCookies } from '../cookies';\nimport { ReflectAdapter } from './reflect';\nimport { workAsyncStorage } from '../../../app-render/work-async-storage.external';\nimport { ActionDidRevalidateStaticAndDynamic } from '../../../../shared/lib/action-revalidation-kind';\n/**\n * @internal\n */ export class ReadonlyRequestCookiesError extends Error {\n constructor(){\n super('Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options');\n }\n static callable() {\n throw new ReadonlyRequestCookiesError();\n }\n}\nexport class RequestCookiesAdapter {\n static seal(cookies) {\n return new Proxy(cookies, {\n get (target, prop, receiver) {\n switch(prop){\n case 'clear':\n case 'delete':\n case 'set':\n return ReadonlyRequestCookiesError.callable;\n default:\n return ReflectAdapter.get(target, prop, receiver);\n }\n }\n });\n }\n /**\n * @param cookies\n * @returns A fresh object identity backed by the original value\n */ static fresh(cookies) {\n return new Proxy(cookies, {\n get (target, prop, receiver) {\n return ReflectAdapter.get(target, prop, receiver);\n }\n });\n }\n}\nconst SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies');\nexport function getModifiedCookieValues(cookies) {\n const modified = cookies[SYMBOL_MODIFY_COOKIE_VALUES];\n if (!modified || !Array.isArray(modified) || modified.length === 0) {\n return [];\n }\n return modified;\n}\nexport function appendMutableCookies(headers, mutableCookies) {\n const modifiedCookieValues = getModifiedCookieValues(mutableCookies);\n if (modifiedCookieValues.length === 0) {\n return false;\n }\n // Return a new response that extends the response with\n // the modified cookies as fallbacks. `res` cookies\n // will still take precedence.\n const resCookies = new ResponseCookies(headers);\n const returnedCookies = resCookies.getAll();\n // Set the modified cookies as fallbacks.\n for (const cookie of modifiedCookieValues){\n resCookies.set(cookie);\n }\n // Set the original cookies as the final values.\n for (const cookie of returnedCookies){\n resCookies.set(cookie);\n }\n return true;\n}\nexport class MutableRequestCookiesAdapter {\n static wrap(cookies, onUpdateCookies) {\n const responseCookies = new ResponseCookies(new Headers());\n for (const cookie of cookies.getAll()){\n responseCookies.set(cookie);\n }\n let modifiedValues = [];\n const modifiedCookies = new Set();\n const updateResponseCookies = ()=>{\n // TODO-APP: change method of getting workStore\n const workStore = workAsyncStorage.getStore();\n if (workStore) {\n workStore.pathWasRevalidated = ActionDidRevalidateStaticAndDynamic;\n }\n const allCookies = responseCookies.getAll();\n modifiedValues = allCookies.filter((c)=>modifiedCookies.has(c.name));\n if (onUpdateCookies) {\n const serializedCookies = [];\n for (const cookie of modifiedValues){\n const tempCookies = new ResponseCookies(new Headers());\n tempCookies.set(cookie);\n serializedCookies.push(tempCookies.toString());\n }\n onUpdateCookies(serializedCookies);\n }\n };\n const wrappedCookies = new Proxy(responseCookies, {\n get (target, prop, receiver) {\n switch(prop){\n // A special symbol to get the modified cookie values\n case SYMBOL_MODIFY_COOKIE_VALUES:\n return modifiedValues;\n // TODO: Throw error if trying to set a cookie after the response\n // headers have been set.\n case 'delete':\n return function(...args) {\n modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name);\n try {\n target.delete(...args);\n return wrappedCookies;\n } finally{\n updateResponseCookies();\n }\n };\n case 'set':\n return function(...args) {\n modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name);\n try {\n target.set(...args);\n return wrappedCookies;\n } finally{\n updateResponseCookies();\n }\n };\n default:\n return ReflectAdapter.get(target, prop, receiver);\n }\n }\n });\n return wrappedCookies;\n }\n}\nexport function createCookiesWithMutableAccessCheck(requestStore) {\n const wrappedCookies = new Proxy(requestStore.mutableCookies, {\n get (target, prop, receiver) {\n switch(prop){\n case 'delete':\n return function(...args) {\n ensureCookiesAreStillMutable(requestStore, 'cookies().delete');\n target.delete(...args);\n return wrappedCookies;\n };\n case 'set':\n return function(...args) {\n ensureCookiesAreStillMutable(requestStore, 'cookies().set');\n target.set(...args);\n return wrappedCookies;\n };\n default:\n return ReflectAdapter.get(target, prop, receiver);\n }\n }\n });\n return wrappedCookies;\n}\nexport function areCookiesMutableInCurrentPhase(requestStore) {\n return requestStore.phase === 'action';\n}\n/** Ensure that cookies() starts throwing on mutation\n * if we changed phases and can no longer mutate.\n *\n * This can happen when going:\n * 'render' -> 'after'\n * 'action' -> 'render'\n * */ function ensureCookiesAreStillMutable(requestStore, _callingExpression) {\n if (!areCookiesMutableInCurrentPhase(requestStore)) {\n // TODO: maybe we can give a more precise error message based on callingExpression?\n throw new ReadonlyRequestCookiesError();\n }\n}\nexport function responseCookiesToRequestCookies(responseCookies) {\n const requestCookies = new RequestCookies(new Headers());\n for (const cookie of responseCookies.getAll()){\n requestCookies.set(cookie);\n }\n return requestCookies;\n}\n\n//# sourceMappingURL=request-cookies.js.map","import { normalizeAppPath } from './app-paths';\n// order matters here, the first match will be used\nexport const INTERCEPTION_ROUTE_MARKERS = [\n '(..)(..)',\n '(.)',\n '(..)',\n '(...)'\n];\nfunction parseRoutePattern(route) {\n const segments = route.split('/').filter(Boolean);\n const tail = segments.at(-1);\n const isOptionalCatchAll = tail !== undefined && tail.startsWith('[[...') && tail.endsWith(']]');\n const isCatchAll = tail !== undefined && tail.startsWith('[...') && tail.endsWith(']');\n const unbounded = isOptionalCatchAll || isCatchAll;\n const prefixSegments = unbounded ? segments.slice(0, -1) : segments;\n return {\n prefix: prefixSegments.map((segment)=>segment.startsWith('[') && segment.endsWith(']') ? null : segment),\n minLength: prefixSegments.length + (isCatchAll && !isOptionalCatchAll ? 1 : 0),\n unbounded\n };\n}\nfunction acceptsLength(pattern, length) {\n return pattern.unbounded ? length >= pattern.minLength : length === pattern.minLength;\n}\nfunction prefixCovers(canonical, intercepted) {\n return canonical.prefix.every((canonicalSegment, index)=>{\n if (canonicalSegment === null) return true;\n const interceptedSegment = intercepted.prefix[index];\n return interceptedSegment !== undefined && interceptedSegment !== null && canonicalSegment === interceptedSegment;\n });\n}\nfunction patternCoversAtLength(canonical, intercepted, length) {\n return acceptsLength(canonical, length) && acceptsLength(intercepted, length) && prefixCovers(canonical, intercepted);\n}\n/** Returns whether ordinary route patterns cover every URL in `route`. */ function isRoutePatternCovered(route, ordinaryRoutes) {\n const intercepted = parseRoutePattern(route);\n if (!intercepted.unbounded) {\n return ordinaryRoutes.some((pattern)=>patternCoversAtLength(pattern, intercepted, intercepted.minLength));\n }\n let unboundedCoverageStart = Infinity;\n for (const pattern of ordinaryRoutes){\n if (pattern.unbounded && prefixCovers(pattern, intercepted)) {\n unboundedCoverageStart = Math.min(unboundedCoverageStart, Math.max(intercepted.minLength, pattern.minLength));\n }\n }\n if (unboundedCoverageStart === Infinity) return false;\n // An optional or required catchall can have its shorter paths covered by\n // fixed routes before another catchall takes over the remaining suffix.\n for(let length = intercepted.minLength; length < unboundedCoverageStart; length++){\n if (!ordinaryRoutes.some((pattern)=>patternCoversAtLength(pattern, intercepted, length))) {\n return false;\n }\n }\n return true;\n}\nexport function isInterceptionRouteAppPath(path) {\n // TODO-APP: add more serious validation\n return path.split('/').find((segment)=>INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m))) !== undefined;\n}\nexport function extractInterceptionRouteInformation(path) {\n let interceptingRoute;\n let marker;\n let interceptedRoute;\n for (const segment of path.split('/')){\n marker = INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m));\n if (marker) {\n ;\n [interceptingRoute, interceptedRoute] = path.split(marker, 2);\n break;\n }\n }\n if (!interceptingRoute || !marker || !interceptedRoute) {\n throw new Error(`Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);\n }\n interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed\n ;\n switch(marker){\n case '(.)':\n // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route\n if (interceptingRoute === '/') {\n interceptedRoute = `/${interceptedRoute}`;\n } else {\n interceptedRoute = interceptingRoute + '/' + interceptedRoute;\n }\n break;\n case '(..)':\n // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route\n if (interceptingRoute === '/') {\n throw new Error(`Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`);\n }\n interceptedRoute = interceptingRoute.split('/').slice(0, -1).concat(interceptedRoute).join('/');\n break;\n case '(...)':\n // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route\n interceptedRoute = '/' + interceptedRoute;\n break;\n case '(..)(..)':\n // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route\n const splitInterceptingRoute = interceptingRoute.split('/');\n if (splitInterceptingRoute.length <= 2) {\n throw new Error(`Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`);\n }\n interceptedRoute = splitInterceptingRoute.slice(0, -2).concat(interceptedRoute).join('/');\n break;\n default:\n throw new Error('Invariant: unexpected marker');\n }\n return {\n interceptingRoute,\n interceptedRoute\n };\n}\n/**\n * Finds interception matchers that cannot be loaded as an ordinary request.\n *\n * This must run after catch-all normalization and pruning so `appPaths`\n * contains the final matcher set rather than every possible matcher candidate.\n */ export function findMissingCanonicalInterceptionRoutes(appPaths) {\n const canonicalRoutes = Object.keys(appPaths).filter((route)=>!isInterceptionRouteAppPath(route));\n const canonicalRoutePatterns = canonicalRoutes.map(parseRoutePattern);\n return Object.keys(appPaths).filter(isInterceptionRouteAppPath).map((interceptionRoute)=>({\n interceptionRoute,\n canonicalRoute: extractInterceptionRouteInformation(interceptionRoute).interceptedRoute\n })).filter(({ canonicalRoute })=>!isRoutePatternCovered(canonicalRoute, canonicalRoutePatterns)).sort((a, b)=>a.interceptionRoute.localeCompare(b.interceptionRoute));\n}\n\n//# sourceMappingURL=interception-routes.js.map","import { INTERCEPTION_ROUTE_MARKERS } from './interception-routes';\n/**\n * Parse dynamic route segment to type of parameter\n */ export function getSegmentParam(segment) {\n const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((marker)=>segment.startsWith(marker));\n // if an interception marker is part of the path segment, we need to jump ahead\n // to the relevant portion for param parsing\n if (interceptionMarker) {\n segment = segment.slice(interceptionMarker.length);\n }\n if (segment.startsWith('[[...') && segment.endsWith(']]')) {\n return {\n // TODO-APP: Optional catchall does not currently work with parallel routes,\n // so for now aren't handling a potential interception marker.\n paramType: 'optional-catchall',\n paramName: segment.slice(5, -2)\n };\n }\n if (segment.startsWith('[...') && segment.endsWith(']')) {\n return {\n paramType: interceptionMarker ? `catchall-intercepted-${interceptionMarker}` : 'catchall',\n paramName: segment.slice(4, -1)\n };\n }\n if (segment.startsWith('[') && segment.endsWith(']')) {\n return {\n paramType: interceptionMarker ? `dynamic-intercepted-${interceptionMarker}` : 'dynamic',\n paramName: segment.slice(1, -1)\n };\n }\n return null;\n}\nexport function isCatchAll(type) {\n return type === 'catchall' || type === 'catchall-intercepted-(..)(..)' || type === 'catchall-intercepted-(.)' || type === 'catchall-intercepted-(..)' || type === 'catchall-intercepted-(...)' || type === 'optional-catchall';\n}\nexport function getParamProperties(paramType) {\n let repeat = false;\n let optional = false;\n switch(paramType){\n case 'catchall':\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n repeat = true;\n break;\n case 'optional-catchall':\n repeat = true;\n optional = true;\n break;\n case 'dynamic':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)':\n break;\n default:\n paramType;\n }\n return {\n repeat,\n optional\n };\n}\n\n//# sourceMappingURL=get-segment-param.js.map","import { ReflectAdapter } from './reflect';\n/**\n * @internal\n */ export class ReadonlyHeadersError extends Error {\n constructor(){\n super('Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers');\n }\n static callable() {\n throw new ReadonlyHeadersError();\n }\n}\n/**\n * Builds the read methods for a sealed view that exposes all of `target`.\n */ function createPassThroughMethods(target, sealed) {\n return {\n get: target.get.bind(target),\n has: target.has.bind(target),\n getSetCookie: target.getSetCookie.bind(target),\n keys: target.keys.bind(target),\n values: target.values.bind(target),\n entries: target.entries.bind(target),\n [Symbol.iterator]: target[Symbol.iterator].bind(target),\n // The native method passes the unsealed target as the callback's `parent`\n // argument. That is a mutable handle on the underlying headers. Pass the\n // sealed view instead.\n forEach (callbackfn, thisArg) {\n for (const [name, value] of target.entries()){\n callbackfn.call(thisArg, value, name, sealed);\n }\n }\n };\n}\n/**\n * Builds the read methods for a sealed view that omits the header names matched\n * by `isHidden`.\n */ function createHidingMethods(target, sealed, isHidden) {\n function* entries() {\n for (const entry of target.entries()){\n if (!isHidden(entry[0])) {\n yield entry;\n }\n }\n }\n return {\n entries,\n [Symbol.iterator]: entries,\n get: (name)=>isHidden(name) ? null : target.get(name),\n has: (name)=>isHidden(name) ? false : target.has(name),\n getSetCookie: ()=>isHidden('set-cookie') ? [] : target.getSetCookie(),\n *keys () {\n for (const name of target.keys()){\n if (!isHidden(name)) {\n yield name;\n }\n }\n },\n *values () {\n for (const [, value] of entries()){\n yield value;\n }\n },\n // The native method passes the unsealed target as the callback's `parent`\n // argument. That is a mutable handle on the underlying headers. Pass the\n // sealed view instead.\n forEach (callbackfn, thisArg) {\n for (const [name, value] of entries()){\n callbackfn.call(thisArg, value, name, sealed);\n }\n }\n };\n}\nexport class HeadersAdapter extends Headers {\n constructor(headers){\n // We've already overridden the methods that would be called, so we're just\n // calling the super constructor to ensure that the instanceof check works.\n super();\n this.headers = new Proxy(headers, {\n get (target, prop, receiver) {\n // Because this is just an object, we expect that all \"get\" operations\n // are for properties. If it's a \"get\" for a symbol, we'll just return\n // the symbol.\n if (typeof prop === 'symbol') {\n return ReflectAdapter.get(target, prop, receiver);\n }\n const lowercased = prop.toLowerCase();\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);\n // If the original casing doesn't exist, return undefined.\n if (typeof original === 'undefined') return;\n // If the original casing exists, return the value.\n return ReflectAdapter.get(target, original, receiver);\n },\n set (target, prop, value, receiver) {\n if (typeof prop === 'symbol') {\n return ReflectAdapter.set(target, prop, value, receiver);\n }\n const lowercased = prop.toLowerCase();\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);\n // If the original casing doesn't exist, use the prop as the key.\n return ReflectAdapter.set(target, original ?? prop, value, receiver);\n },\n has (target, prop) {\n if (typeof prop === 'symbol') return ReflectAdapter.has(target, prop);\n const lowercased = prop.toLowerCase();\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);\n // If the original casing doesn't exist, return false.\n if (typeof original === 'undefined') return false;\n // If the original casing exists, return true.\n return ReflectAdapter.has(target, original);\n },\n deleteProperty (target, prop) {\n if (typeof prop === 'symbol') return ReflectAdapter.deleteProperty(target, prop);\n const lowercased = prop.toLowerCase();\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);\n // If the original casing doesn't exist, return true.\n if (typeof original === 'undefined') return true;\n // If the original casing exists, delete the property.\n return ReflectAdapter.deleteProperty(target, original);\n }\n });\n }\n /**\n * Seals a Headers instance to prevent modification by throwing an error when\n * any mutating method is called.\n *\n * The sealed view stays live. Later writes to `headers` remain visible\n * through it.\n *\n * `hidden` omits the given header names from every read operation (`get`,\n * `has`, `getSetCookie`, `forEach`, and iteration). The names must be\n * lowercase. The underlying headers are neither copied nor mutated, so hidden\n * headers remain available to the framework.\n */ static seal(headers, hidden) {\n const isHidden = hidden && hidden.size > 0 ? (name)=>hidden.has(name.toLowerCase()) : null;\n // The methods are built once per sealed view and reused, so repeated access\n // returns the same function instead of a fresh closure. They are assigned\n // after the proxy exists because `forEach` hands the proxy to its callback.\n // Creating the proxy runs no trap, so nothing can read them before then.\n let methods;\n const sealed = new Proxy(headers, {\n get (target, prop, receiver) {\n switch(prop){\n case 'append':\n case 'delete':\n case 'set':\n return ReadonlyHeadersError.callable;\n case Symbol.iterator:\n return methods[Symbol.iterator];\n case 'get':\n case 'has':\n case 'getSetCookie':\n case 'keys':\n case 'values':\n case 'entries':\n case 'forEach':\n return methods[prop];\n default:\n return ReflectAdapter.get(target, prop, receiver);\n }\n }\n });\n methods = isHidden ? createHidingMethods(headers, sealed, isHidden) : createPassThroughMethods(headers, sealed);\n return sealed;\n }\n /**\n * @param headers\n * @returns A fresh object identity backed by the original value\n */ static fresh(headers) {\n return new Proxy(headers, {\n get (target, prop, receiver) {\n return ReflectAdapter.get(target, prop, receiver);\n }\n });\n }\n /**\n * Merges a header value into a string. This stores multiple values as an\n * array, so we need to merge them into a string.\n *\n * @param value a header value\n * @returns a merged header value (a string)\n */ merge(value) {\n if (Array.isArray(value)) return value.join(', ');\n return value;\n }\n /**\n * Creates a Headers instance from a plain object or a Headers instance.\n *\n * @param headers a plain object or a Headers instance\n * @returns a headers instance\n */ static from(headers) {\n if (headers instanceof Headers) return headers;\n return new HeadersAdapter(headers);\n }\n append(name, value) {\n const existing = this.headers[name];\n if (typeof existing === 'string') {\n this.headers[name] = [\n existing,\n value\n ];\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n this.headers[name] = value;\n }\n }\n delete(name) {\n delete this.headers[name];\n }\n get(name) {\n const value = this.headers[name];\n if (typeof value !== 'undefined') return this.merge(value);\n return null;\n }\n has(name) {\n return typeof this.headers[name] !== 'undefined';\n }\n set(name, value) {\n this.headers[name] = value;\n }\n forEach(callbackfn, thisArg) {\n for (const [name, value] of this.entries()){\n callbackfn.call(thisArg, value, name, this);\n }\n }\n *entries() {\n for (const key of Object.keys(this.headers)){\n const name = key.toLowerCase();\n // We assert here that this is a string because we got it from the\n // Object.keys() call above.\n const value = this.get(name);\n yield [\n name,\n value\n ];\n }\n }\n *keys() {\n for (const key of Object.keys(this.headers)){\n const name = key.toLowerCase();\n yield name;\n }\n }\n *values() {\n for (const key of Object.keys(this.headers)){\n // We assert here that this is a string because we got it from the\n // Object.keys() call above.\n const value = this.get(key);\n yield value;\n }\n }\n [Symbol.iterator]() {\n return this.entries();\n }\n}\n\n//# sourceMappingURL=headers.js.map","import { RequestCookies } from '../../web/spec-extension/cookies';\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies';\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers';\nimport { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param';\nimport { parseRelativeUrl } from '../../../shared/lib/router/utils/parse-relative-url';\nimport { InvariantError } from '../../../shared/lib/invariant-error';\nimport { InstantValidationError } from './instant-validation-error';\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external';\nimport { wellKnownProperties } from '../../../shared/lib/utils/reflect-utils';\nexport function createValidationSampleTracking() {\n return {\n missingSampleErrors: []\n };\n}\nfunction getExpectedSampleTracking() {\n let validationSampleTracking = null;\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'request':\n case 'validation-client':\n // TODO(instant-validation-build): do we need any special handling for caches?\n validationSampleTracking = workUnitStore.validationSampleTracking ?? null;\n break;\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'prerender-client':\n case 'prerender':\n case 'prerender-runtime':\n case 'build-time-generator':\n break;\n default:\n workUnitStore;\n }\n }\n if (!validationSampleTracking) {\n throw new InvariantError('Expected to have a workUnitStore that provides validationSampleTracking');\n }\n return validationSampleTracking;\n}\nexport function trackMissingSampleError(error) {\n const validationSampleTracking = getExpectedSampleTracking();\n validationSampleTracking.missingSampleErrors.push(error);\n}\nexport function trackMissingSampleErrorAndThrow(error) {\n // TODO(instant-validation-build): this should abort the render\n trackMissingSampleError(error);\n throw error;\n}\n/**\n * Creates ReadonlyRequestCookies from sample cookie data.\n * Accessing a cookie not declared in the sample will throw an error.\n * Cookies with `value: null` are declared (allowed to access) but return no value.\n */ export function createCookiesFromSample(sampleCookies, route) {\n const declaredNames = new Set();\n const cookies = new RequestCookies(new Headers());\n if (sampleCookies) {\n for (const cookie of sampleCookies){\n declaredNames.add(cookie.name);\n if (cookie.value !== null) {\n cookies.set(cookie.name, cookie.value);\n }\n }\n }\n const sealed = RequestCookiesAdapter.seal(cookies);\n return new Proxy(sealed, {\n get (target, prop, receiver) {\n if (prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver);\n const wrappedMethod = function(name) {\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(createMissingCookieSampleError(route, name));\n }\n return originalMethod.call(target, name);\n };\n return wrappedMethod;\n }\n if (prop === 'get') {\n const originalMethod = Reflect.get(target, prop, receiver);\n const wrappedMethod = function(nameOrCookie) {\n let name;\n if (typeof nameOrCookie === 'string') {\n name = nameOrCookie;\n } else if (nameOrCookie && typeof nameOrCookie === 'object' && typeof nameOrCookie.name === 'string') {\n name = nameOrCookie.name;\n } else {\n // This is an invalid input. Pass it through to the original method so it can error.\n return originalMethod.call(target, nameOrCookie);\n }\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(createMissingCookieSampleError(route, name));\n }\n return originalMethod.call(target, name);\n };\n return wrappedMethod;\n }\n // TODO(instant-validation-build): what should getAll do?\n // Maybe we should only allow it if there's an array (possibly empty?)\n return Reflect.get(target, prop, receiver);\n }\n });\n}\nfunction createMissingCookieSampleError(route, name) {\n return new InstantValidationError(`Route \"${route}\" accessed cookie \"${name}\" which is not defined in the \\`unstable_samples\\` ` + `of \\`instant\\`. Add it to the sample's \\`cookies\\` array, ` + `or \\`{ name: \"${name}\", value: null }\\` if it should be absent.`);\n}\n/**\n * Creates ReadonlyHeaders from sample header data.\n * Accessing a header not declared in the sample will throw an error.\n * Headers with `value: null` are declared (allowed to access) but return null.\n */ export function createHeadersFromSample(rawSampleHeaders, sampleCookies, route) {\n // If we have cookie samples, add a `cookie` header to match.\n // Accessing it will be implicitly allowed by the proxy --\n // if the user defined some cookies, accessing the \"cookie\" header is also fine.\n const sampleHeaders = rawSampleHeaders ? [\n ...rawSampleHeaders\n ] : [];\n if (sampleHeaders.find(([name])=>name.toLowerCase() === 'cookie')) {\n throw new InstantValidationError('Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.');\n }\n if (sampleCookies) {\n const cookieHeaderValue = sampleCookies.toString();\n sampleHeaders.push([\n 'cookie',\n // if the `cookies` samples were empty, or they were all `null`, then we have no cookies,\n // and the header isn't present, but should remains readable, so we set it to null.\n cookieHeaderValue !== '' ? cookieHeaderValue : null\n ]);\n }\n const declaredNames = new Set();\n const headersInit = {};\n for (const [name, value] of sampleHeaders){\n declaredNames.add(name.toLowerCase());\n if (value !== null) {\n headersInit[name.toLowerCase()] = value;\n }\n }\n const sealed = HeadersAdapter.seal(HeadersAdapter.from(headersInit));\n return new Proxy(sealed, {\n get (target, prop, receiver) {\n if (prop === 'get' || prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver);\n const patchedMethod = function(rawName) {\n const name = rawName.toLowerCase();\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(new InstantValidationError(`Route \"${route}\" accessed header \"${name}\" which is not defined in the \\`unstable_samples\\` ` + `of \\`instant\\`. Add it to the sample's \\`headers\\` array, ` + `or \\`[\"${name}\", null]\\` if it should be absent.`));\n }\n // typescript can't reconcile a union of functions with a union of return types,\n // so we have to cast the original return type away\n return originalMethod.call(target, name);\n };\n return patchedMethod;\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\n/**\n * Creates a DraftModeProvider that always returns isEnabled: false.\n */ export function createDraftModeForValidation() {\n // Create a minimal DraftModeProvider-compatible object\n // that always reports draft mode as disabled.\n //\n // private properties that can't be set from outside the class.\n return {\n get isEnabled () {\n return false;\n },\n enable () {\n throw new Error('Draft mode cannot be enabled during build-time instant validation.');\n },\n disable () {\n throw new Error('Draft mode cannot be disabled during build-time instant validation.');\n }\n };\n}\n/**\n * Creates params wrapped with an exhaustive proxy.\n * Accessing a param not declared in the sample will throw an error.\n */ export function createExhaustiveParamsProxy(underlyingParams, declaredParamNames, route) {\n return new Proxy(underlyingParams, {\n get (target, prop, receiver) {\n if (typeof prop === 'string' && !wellKnownProperties.has(prop) && // Only error when accessing a param that is part of the route but wasn't provided.\n // accessing properties that aren't expected to be a valid param value is fine.\n prop in underlyingParams && !declaredParamNames.has(prop)) {\n trackMissingSampleErrorAndThrow(new InstantValidationError(`Route \"${route}\" accessed param \"${prop}\" which is not defined in the \\`unstable_samples\\` ` + `of \\`instant\\`. Add it to the sample's \\`params\\` object.`));\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\n/**\n * Creates searchParams wrapped with an exhaustive proxy.\n * Accessing a searchParam not declared in the sample will throw an error.\n * A searchParam with `value: undefined` means \"declared but absent\" (allowed to access, returns undefined).\n */ export function createExhaustiveSearchParamsProxy(searchParams, declaredSearchParamNames, route) {\n return new Proxy(searchParams, {\n get (target, prop, receiver) {\n if (typeof prop === 'string' && !wellKnownProperties.has(prop) && !declaredSearchParamNames.has(prop)) {\n trackMissingSampleErrorAndThrow(createMissingSearchParamSampleError(route, prop));\n }\n return Reflect.get(target, prop, receiver);\n },\n has (target, prop) {\n if (typeof prop === 'string' && !wellKnownProperties.has(prop) && !declaredSearchParamNames.has(prop)) {\n trackMissingSampleErrorAndThrow(createMissingSearchParamSampleError(route, prop));\n }\n return Reflect.has(target, prop);\n }\n });\n}\n/**\n * Wraps a URLSearchParams (or subclass like ReadonlyURLSearchParams) with an\n * exhaustive proxy. Accessing a search param not declared in the sample via\n * get/getAll/has will throw an error.\n */ export function createExhaustiveURLSearchParamsProxy(searchParams, declaredSearchParamNames, route) {\n return new Proxy(searchParams, {\n get (target, prop, receiver) {\n // Intercept method calls that access specific param names\n if (prop === 'get' || prop === 'getAll' || prop === 'has') {\n const originalMathod = Reflect.get(target, prop, receiver);\n return (name)=>{\n if (typeof name === 'string' && !declaredSearchParamNames.has(name)) {\n trackMissingSampleErrorAndThrow(createMissingSearchParamSampleError(route, name));\n }\n return originalMathod.call(target, name);\n };\n }\n const value = Reflect.get(target, prop, receiver);\n // Prevent `TypeError: Value of \"this\" must be of type URLSearchParams` for methods\n if (typeof value === 'function' && !Object.hasOwn(target, prop)) {\n return value.bind(target);\n }\n return value;\n }\n });\n}\nfunction createMissingSearchParamSampleError(route, name) {\n return new InstantValidationError(`Route \"${route}\" accessed searchParam \"${name}\" which is not defined in the \\`unstable_samples\\` ` + `of \\`instant\\`. Add it to the sample's \\`searchParams\\` object, ` + `or \\`{ \"${name}\": null }\\` if it should be absent.`);\n}\nexport function createRelativeURLFromSamples(route, sampleParams, sampleSearchParams) {\n // Build searchParams query object and URL search string from sample\n const pathname = createPathnameFromRouteAndSampleParams(route, sampleParams ?? {});\n let search = '';\n if (sampleSearchParams) {\n const qs = createURLSearchParamsFromSample(sampleSearchParams).toString();\n if (qs) {\n search = '?' + qs;\n }\n }\n return parseRelativeUrl(pathname + search, undefined, true);\n}\nfunction createURLSearchParamsFromSample(sampleSearchParams) {\n const result = new URLSearchParams();\n if (sampleSearchParams) {\n for (const [key, value] of Object.entries(sampleSearchParams)){\n if (value === null || value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value){\n result.append(key, v);\n }\n } else {\n result.set(key, value);\n }\n }\n }\n return result;\n}\n/**\n * Substitute sample params into `workStore.route` to create a plausible pathname.\n * TODO(instant-validation-build): this logic is somewhat hacky and likely incomplete,\n * but it should be good enough for some initial testing.\n */ function createPathnameFromRouteAndSampleParams(route, params) {\n let interpolatedSegments = [];\n const rawSegments = route.split('/');\n for (const rawSegment of rawSegments){\n const param = getSegmentParam(rawSegment);\n if (param) {\n switch(param.paramType){\n case 'catchall':\n case 'optional-catchall':\n {\n let paramValue = params[param.paramName];\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[...NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = [\n rawSegment\n ];\n } else if (!Array.isArray(paramValue)) {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(`Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`);\n }\n interpolatedSegments.push(...paramValue.map((v)=>encodeURIComponent(v)));\n break;\n }\n case 'dynamic':\n {\n let paramValue = params[param.paramName];\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = rawSegment;\n } else if (typeof paramValue !== 'string') {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(`Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`);\n }\n interpolatedSegments.push(encodeURIComponent(paramValue));\n break;\n }\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)':\n {\n // TODO(instant-validation-build): i don't know how these are supposed to work, or if we can even get them here\n throw new InvariantError('Not implemented: Validation of interception routes');\n }\n default:\n {\n param.paramType;\n }\n }\n } else {\n interpolatedSegments.push(rawSegment);\n }\n }\n return interpolatedSegments.join('/');\n}\nexport function assertRootParamInSamples(workStore, sampleParams, paramName) {\n if (sampleParams && paramName in sampleParams) {\n // The param is defined in the samples.\n } else {\n const route = workStore.route;\n trackMissingSampleErrorAndThrow(new InstantValidationError(`Route \"${route}\" accessed root param \"${paramName}\" which is not defined in the \\`unstable_samples\\` ` + `of \\`instant\\`. Add it to the sample's \\`params\\` object.`));\n }\n}\n\n//# sourceMappingURL=instant-samples.js.map","/**\n * The functions provided by this module are used to communicate certain properties\n * about the currently running code so that Next.js can make decisions on how to handle\n * the current execution in different rendering modes such as pre-rendering, resuming, and SSR.\n *\n * Today Next.js treats all code as potentially static. Certain APIs may only make sense when dynamically rendering.\n * Traditionally this meant deopting the entire render to dynamic however with PPR we can now deopt parts\n * of a React tree as dynamic while still keeping other parts static. There are really two different kinds of\n * Dynamic indications.\n *\n * The first is simply an intention to be dynamic. unstable_noStore is an example of this where\n * the currently executing code simply declares that the current scope is dynamic but if you use it\n * inside unstable_cache it can still be cached. This type of indication can be removed if we ever\n * make the default dynamic to begin with because the only way you would ever be static is inside\n * a cache scope which this indication does not affect.\n *\n * The second is an indication that a dynamic data source was read. This is a stronger form of dynamic\n * because it means that it is inappropriate to cache this at all. using a dynamic data source inside\n * unstable_cache should error. If you want to use some dynamic data inside unstable_cache you should\n * read that data outside the cache and pass it in as an argument to the cached function.\n */ // Once postpone is in stable we should switch to importing the postpone export directly\nimport React from 'react';\nimport { DynamicServerError } from '../../client/components/hooks-server-context';\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout';\nimport { getStagedRenderingController } from './work-unit-async-storage.external';\nimport { isClientHookDynamicError } from '../dynamic-rendering-utils';\nimport { METADATA_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME, OUTLET_BOUNDARY_NAME, ROOT_LAYOUT_BOUNDARY_NAME } from '../../lib/framework/boundary-constants';\nimport { scheduleOnNextTick } from '../../lib/scheduler';\nimport { createRuntimeBodyError, createDynamicBodyError, createRuntimeBodyErrorInNavigation, createNavigationBodyErrorInNavigation, createPrefetchBodyErrorInNavigation, createDynamicBodyErrorInNavigation, createDynamicOrRuntimeBodyError, createRuntimeMetadataError, createDynamicMetadataError, createRuntimeViewportError, createNavigationViewportError, createPrefetchViewportError, createDynamicViewportError, createDynamicOrRuntimeViewportError, createDynamicOrRuntimeMetadataError, logBuildDebugHint, createLinkBodyErrorInNavigation, createLinkMetadataError, createLinkViewportError, createNavigationMetadataError, createPrefetchMetadataError, createNonPrerenderableMetadataErrorInStaticRoute, createNonPrerenderableViewportErrorInStaticRoute, createNonPrerenderableBodyErrorInStaticRoute, createRuntimeBodyErrorInStaticRoute, createDynamicBodyErrorInStaticRoute, createRuntimeMetadataErrorInStaticRoute, createDynamicMetadataErrorInStaticRoute, createRuntimeViewportErrorInStaticRoute, createDynamicViewportErrorInStaticRoute } from './blocking-route-messages';\nimport { InvariantError } from '../../shared/lib/invariant-error';\nimport { INSTANT_VALIDATION_BOUNDARY_NAME, INSTANT_SLOT_MARKER_PREFIX, INSTANT_SLOT_MARKER_SUFFIX } from './instant-validation/boundary-constants';\nimport { allRequiredBoundariesRendered } from './instant-validation/boundary-tracking';\nimport { createUnrenderedSegmentError } from '../../shared/lib/instant-messages';\nimport { getReactBrowserBailoutReason } from '../../shared/lib/lazy-dynamic/react-browser-bailout';\nexport function createDynamicTrackingState(isDebugDynamicAccesses) {\n return {\n isDebugDynamicAccesses,\n dynamicAccesses: [],\n syncDynamicErrorWithStack: null,\n syncDynamicErrorWithStackPostMicrotask: false\n };\n}\nexport function createDynamicValidationState() {\n return {\n hasSuspenseAboveBody: false,\n hasDynamicMetadata: false,\n dynamicMetadata: null,\n hasDynamicViewport: false,\n hasAllowedDynamic: false,\n dynamicErrors: []\n };\n}\nfunction getPendingClientSyncDynamicError(clientDynamic) {\n return clientDynamic.syncDynamicErrorWithStackPostMicrotask ? null : clientDynamic.syncDynamicErrorWithStack;\n}\nexport function getFirstDynamicReason(trackingState) {\n var _trackingState_dynamicAccesses_;\n return (_trackingState_dynamicAccesses_ = trackingState.dynamicAccesses[0]) == null ? void 0 : _trackingState_dynamicAccesses_.expression;\n}\n/**\n * This function communicates that the current scope should be treated as dynamic.\n *\n * In most cases this function is a no-op but if called during\n * a PPR prerender it will postpone the current sub-tree and calling\n * it during a normal prerender will cause the entire prerender to abort\n */ export function markCurrentScopeAsDynamic(store, workUnitStore, expression) {\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'cache':\n case 'unstable-cache':\n // Inside cache scopes, marking a scope as dynamic has no effect,\n // because the outer cache scope creates a cache boundary. This is\n // subtly different from reading a dynamic data source, which is\n // forbidden inside a cache scope.\n return;\n case 'private-cache':\n // A private cache scope is already dynamic by definition.\n return;\n case 'prerender-legacy':\n case 'request':\n case 'build-time-generator':\n break;\n default:\n workUnitStore;\n }\n }\n // If we're forcing dynamic rendering or we're forcing static rendering, we\n // don't need to do anything here because the entire page is already dynamic\n // or it's static and it should not throw or postpone here.\n if (store.forceDynamic || store.forceStatic) return;\n if (store.dynamicShouldError) {\n throw new StaticGenBailoutError(`Route ${store.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);\n }\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender-legacy':\n workUnitStore.revalidate = 0;\n // We aren't prerendering, but we are generating a static page. We need\n // to bail out of static generation.\n const err = new DynamicServerError(`Route ${store.route} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);\n store.dynamicUsageDescription = expression;\n store.dynamicUsageStack = err.stack;\n throw err;\n case 'request':\n markRequestStoreAsDynamic(workUnitStore);\n break;\n case 'build-time-generator':\n break;\n default:\n workUnitStore;\n }\n }\n}\n/**\n * This function is meant to be used when prerendering without cacheComponents or PPR.\n * When called during a build it will cause Next.js to consider the route as dynamic.\n *\n * @internal\n */ export function throwToInterruptStaticGeneration(expression, store, prerenderStore) {\n // We aren't prerendering but we are generating a static page. We need to bail out of static generation\n const err = new DynamicServerError(`Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);\n prerenderStore.revalidate = 0;\n store.dynamicUsageDescription = expression;\n store.dynamicUsageStack = err.stack;\n throw err;\n}\n/**\n * This function should be used to track whether something dynamic happened even when\n * we are in a dynamic render. This is useful for Dev where all renders are dynamic but\n * we still track whether dynamic APIs were accessed for helpful messaging\n *\n * @internal\n */ export function trackDynamicDataInDynamicRender(workUnitStore) {\n switch(workUnitStore.type){\n case 'cache':\n case 'unstable-cache':\n // Inside cache scopes, marking a scope as dynamic has no effect,\n // because the outer cache scope creates a cache boundary. This is\n // subtly different from reading a dynamic data source, which is\n // forbidden inside a cache scope.\n return;\n case 'private-cache':\n // A private cache scope is already dynamic by definition.\n return;\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'prerender-client':\n case 'validation-client':\n case 'build-time-generator':\n break;\n case 'request':\n markRequestStoreAsDynamic(workUnitStore);\n break;\n default:\n workUnitStore;\n }\n}\nfunction markRequestStoreAsDynamic(requestStore) {\n if (process.env.__NEXT_DEV_SERVER && requestStore.phase === 'render') {\n requestStore.usedDynamic = true;\n }\n}\nfunction abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore) {\n const reason = `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`;\n const error = createPrerenderInterruptedError(reason);\n prerenderStore.controller.abort(error);\n const dynamicTracking = prerenderStore.dynamicTracking;\n if (dynamicTracking) {\n dynamicTracking.dynamicAccesses.push({\n // When we aren't debugging, we don't need to create another error for the\n // stack trace.\n stack: dynamicTracking.isDebugDynamicAccesses ? new Error().stack : undefined,\n expression\n });\n }\n}\nexport function abortOnSynchronousPlatformIOAccess(route, expression, errorWithStack, prerenderStore) {\n const dynamicTracking = prerenderStore.dynamicTracking;\n if (dynamicTracking && dynamicTracking.syncDynamicErrorWithStack === null) {\n dynamicTracking.syncDynamicErrorWithStack = errorWithStack;\n // React completes the task that is currently rendering before scheduled\n // abort cleanup. Client tracking can attribute the sync IO only during\n // that current task; server tracking keeps the error regardless.\n queueMicrotask(()=>{\n dynamicTracking.syncDynamicErrorWithStackPostMicrotask = true;\n });\n }\n abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore);\n}\n/**\n * use this function when prerendering with cacheComponents. If we are doing a\n * prospective prerender we don't actually abort because we want to discover\n * all caches for the shell. If this is the actual prerender we do abort.\n *\n * This function accepts a prerenderStore but the caller should ensure we're\n * actually running in cacheComponents mode.\n *\n * @internal\n */ export function abortAndThrowOnSynchronousRequestDataAccess(route, expression, errorWithStack, prerenderStore) {\n const prerenderSignal = prerenderStore.controller.signal;\n if (prerenderSignal.aborted === false) {\n // TODO it would be better to move this aborted check into the callsite so we can avoid making\n // the error object when it isn't relevant to the aborting of the prerender however\n // since we need the throw semantics regardless of whether we abort it is easier to land\n // this way. See how this was handled with `abortOnSynchronousPlatformIOAccess` for a closer\n // to ideal implementation\n abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore);\n // Preserve the exact server-side dynamic access for final validation after\n // interrupting this render.\n const dynamicTracking = prerenderStore.dynamicTracking;\n if (dynamicTracking) {\n if (dynamicTracking.syncDynamicErrorWithStack === null) {\n dynamicTracking.syncDynamicErrorWithStack = errorWithStack;\n }\n }\n }\n throw createPrerenderInterruptedError(`Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`);\n}\nconst NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED';\nfunction createPrerenderInterruptedError(message) {\n const error = new Error(message);\n error.digest = NEXT_PRERENDER_INTERRUPTED;\n return error;\n}\nexport function isPrerenderInterruptedError(error) {\n return typeof error === 'object' && error !== null && error.digest === NEXT_PRERENDER_INTERRUPTED && 'name' in error && 'message' in error && error instanceof Error;\n}\nexport function accessedDynamicData(dynamicAccesses) {\n return dynamicAccesses.length > 0;\n}\nexport function consumeDynamicAccess(serverDynamic, clientDynamic) {\n // We mutate because we only call this once we are no longer writing\n // to the dynamicTrackingState and it's more efficient than creating a new\n // array.\n serverDynamic.dynamicAccesses.push(...clientDynamic.dynamicAccesses);\n return serverDynamic.dynamicAccesses;\n}\nexport function formatDynamicAPIAccesses(dynamicAccesses) {\n return dynamicAccesses.filter((access)=>typeof access.stack === 'string' && access.stack.length > 0).map(({ expression, stack })=>{\n stack = stack.split('\\n')// Remove the \"Error: \" prefix from the first line of the stack trace as\n // well as the first 4 lines of the stack trace which is the distance\n // from the user code and the `new Error().stack` call.\n .slice(4).filter((line)=>{\n // Exclude Next.js internals from the stack trace.\n if (line.includes('node_modules/next/')) {\n return false;\n }\n // Exclude anonymous functions from the stack trace.\n if (line.includes(' (<anonymous>)')) {\n return false;\n }\n // Exclude Node.js internals from the stack trace.\n if (line.includes(' (node:')) {\n return false;\n }\n return true;\n }).join('\\n');\n return `Dynamic API Usage Debug - ${expression}:\\n${stack}`;\n });\n}\nexport function createHangingInputAbortSignal(workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-runtime':\n const controller = new AbortController();\n if (workUnitStore.cacheSignal) {\n // If we have a cacheSignal it means we're in a prospective render. If\n // the input we're waiting on is coming from another cache, we do want\n // to wait for it so that we can resolve this cache entry too.\n workUnitStore.cacheSignal.inputReady().then(()=>{\n controller.abort();\n });\n } else {\n // Otherwise we're in the final render and we should already have all\n // our caches filled.\n // If the prerender uses stages, we have wait until the final stage.\n // if an input didn't resolve at that point, then we can assume it never will.\n //\n // We might still be waiting on some microtasks so we\n // wait one tick before giving up. When we give up, we still want to\n // render the content of this cache as deeply as we can so that we can\n // suspend as deeply as possible in the tree or not at all if we don't\n // end up waiting for the input.\n const stagedRendering = getStagedRenderingController(workUnitStore);\n if (stagedRendering && stagedRendering.finalStage !== null) {\n stagedRendering.waitForStage(stagedRendering.finalStage).then(()=>scheduleOnNextTick(()=>controller.abort()), noop);\n } else {\n scheduleOnNextTick(()=>controller.abort());\n }\n }\n return controller.signal;\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n return undefined;\n default:\n workUnitStore;\n }\n}\nfunction noop() {}\nexport function annotateDynamicAccess(expression, prerenderStore) {\n const dynamicTracking = prerenderStore.dynamicTracking;\n if (dynamicTracking) {\n dynamicTracking.dynamicAccesses.push({\n stack: dynamicTracking.isDebugDynamicAccesses ? new Error().stack : undefined,\n expression\n });\n }\n}\nconst hasSuspenseRegex = /\\n\\s+at Suspense \\(<anonymous>\\)/;\n// Common implicit body tags that React will treat as body when placed directly in html\nconst bodyAndImplicitTags = 'body|div|main|section|article|aside|header|footer|nav|form|p|span|h1|h2|h3|h4|h5|h6';\n// Detects when RootLayoutBoundary (our framework marker component) appears\n// after Suspense in the component stack, indicating the root layout is wrapped\n// within a Suspense boundary. Ensures no body/html/implicit-body components are in between.\n//\n// Example matches:\n// at Suspense (<anonymous>)\n// at __next_root_layout_boundary__ (<anonymous>)\n//\n// Or with other components in between (but not body/html/implicit-body):\n// at Suspense (<anonymous>)\n// at SomeComponent (<anonymous>)\n// at __next_root_layout_boundary__ (<anonymous>)\nconst hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex = new RegExp(`\\\\n\\\\s+at Suspense \\\\(<anonymous>\\\\)(?:(?!\\\\n\\\\s+at (?:${bodyAndImplicitTags}) \\\\(<anonymous>\\\\))[\\\\s\\\\S])*?\\\\n\\\\s+at ${ROOT_LAYOUT_BOUNDARY_NAME} \\\\([^\\\\n]*\\\\)`);\nconst hasMetadataRegex = new RegExp(`\\\\n\\\\s+at ${METADATA_BOUNDARY_NAME}[\\\\n\\\\s]`);\nconst hasViewportRegex = new RegExp(`\\\\n\\\\s+at ${VIEWPORT_BOUNDARY_NAME}[\\\\n\\\\s]`);\nconst hasOutletRegex = new RegExp(`\\\\n\\\\s+at ${OUTLET_BOUNDARY_NAME}[\\\\n\\\\s]`);\nconst hasInstantValidationBoundaryRegex = new RegExp(`\\\\n\\\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\\\n\\\\s]`);\nconst slotMarkerRegex = new RegExp(`\\\\n\\\\s+at ${INSTANT_SLOT_MARKER_PREFIX}(\\\\d+)${INSTANT_SLOT_MARKER_SUFFIX}[\\\\n\\\\s]`);\n/** Look up the config factory for the slot this error belongs to.\n * Checks the component stack for a slot marker (__next_instant_slot_N__)\n * and returns the config at that index. Falls back to index 0 (root\n * config) when no slot marker is found or the slot has no config. */ function resolveInstantStack(componentStack, dynamicValidation) {\n const { slotStacks } = dynamicValidation;\n if (slotStacks.length > 1) {\n const match = slotMarkerRegex.exec(componentStack);\n if (match) {\n // Slot markers are 0-indexed in the component name but\n // slotStacks is 1-indexed (index 0 is the root config).\n const slotIndex = parseInt(match[1], 10) + 1;\n const slotStack = slotStacks[slotIndex];\n if (slotStack != null) {\n return slotStack;\n }\n }\n }\n // Fall back to root config (index 0)\n return slotStacks[0] ?? null;\n}\n/**\n * Inspects the component stack of an outlet boundary to discover whether the\n * user placed a Suspense boundary above the document body, and records the\n * opt-in on `dynamicValidation.hasSuspenseAboveBody` if so.\n *\n * The outlet itself isn't a meaningful source of dynamic — it only resolves\n * when metadata/viewport are dynamic, which we track via their own boundaries.\n * However, the outlet renders alongside the page content, so its stack passes\n * through the user's layout chain (typically reaching into `<body>` via the\n * root layout). That makes the outlet stack our best opportunity to spot a\n * Suspense boundary above the body, even when no real body content is dynamic.\n * Without this, a route whose only dynamic source is `generateViewport()` would\n * miss the Suspense-above-body opt-in, because the viewport's stack lives in\n * the head and never sees the user's root layout.\n *\n * We deliberately only set `hasSuspenseAboveBody`, not `hasAllowedDynamic`. The\n * latter tracks whether the body has dynamic content that's been wrapped in\n * Suspense (i.e., the page is partially dynamic). The outlet rendering tells us\n * about the structural opt-in for an empty shell, not about the body being\n * partially dynamic. The distinction matters because dynamic metadata is only\n * acceptable when the page is partially dynamic (via real body holes), and we\n * don't want this outlet-based detection to mask that case.\n */ function trackOutletSuspenseAboveBody(componentStack, dynamicValidation) {\n if (hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(componentStack)) {\n dynamicValidation.hasSuspenseAboveBody = true;\n }\n}\nexport function trackDynamicAccessInStaticRoute(dynamicReason, workStore, componentStack, dynamicValidation, clientDynamic, isServerPartial, kind) {\n const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic);\n if (hasOutletRegex.test(componentStack)) {\n trackOutletSuspenseAboveBody(componentStack, dynamicValidation);\n return;\n }\n if (hasMetadataRegex.test(componentStack)) {\n dynamicValidation.dynamicErrors.push(addErrorContext(createMetadataErrorInStaticRoute(kind, workStore.route), componentStack, null));\n return;\n }\n if (hasViewportRegex.test(componentStack)) {\n dynamicValidation.dynamicErrors.push(addErrorContext(createViewportErrorInStaticRoute(kind, workStore.route), componentStack, null));\n return;\n }\n let hasSuspense = false;\n if (hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(componentStack)) {\n // this error had a Suspense boundary above it, and it's above the body as well.\n dynamicValidation.hasSuspenseAboveBody = true;\n hasSuspense = true;\n } else if (hasSuspenseRegex.test(componentStack)) {\n // this error had a Suspense boundary above it.\n hasSuspense = true;\n }\n if (hasSuspense) {\n if (!isServerPartial) {\n // If we don't have holes caused by server data, then any holes must be caused\n // by client-only code, which is allowed.\n dynamicValidation.hasAllowedDynamic = true;\n return;\n }\n // We have holes that may be caused by server data.\n if (syncDynamicError || isClientHookDynamicError(dynamicReason)) {\n // We know this hole wasn't caused by server data, so it's allowed\n // (because it's wrapped in a Suspense)\n dynamicValidation.hasAllowedDynamic = true;\n return;\n }\n // Any remaining hole may be caused by a server hole.\n // These are not allowed even with Suspense.\n // (NOTE: this may misreport valid client dynamic holes as server holes)\n dynamicValidation.dynamicErrors.push(addErrorContext(createBodyErrorInStaticRoute(kind, workStore.route), componentStack, null));\n return;\n }\n if (syncDynamicError) {\n dynamicValidation.dynamicErrors.push(syncDynamicError);\n return;\n }\n if (isClientHookDynamicError(dynamicReason)) {\n dynamicValidation.dynamicErrors.push(addErrorContext(dynamicReason, componentStack, null));\n return;\n }\n const error = addErrorContext(isServerPartial ? // (NOTE: this may misreport client dynamic holes as server holes)\n createBodyErrorInStaticRoute(kind, workStore.route) : // that server data is complete\n createBodyError(kind, workStore.route), componentStack, null);\n dynamicValidation.dynamicErrors.push(error);\n}\nexport function trackAllowedDynamicAccess(dynamicReason, workStore, componentStack, dynamicValidation, clientDynamic) {\n const dynamicHoleKind = 6;\n const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic);\n if (hasOutletRegex.test(componentStack)) {\n trackOutletSuspenseAboveBody(componentStack, dynamicValidation);\n return;\n } else if (hasMetadataRegex.test(componentStack)) {\n dynamicValidation.hasDynamicMetadata = true;\n return;\n } else if (hasViewportRegex.test(componentStack)) {\n dynamicValidation.hasDynamicViewport = true;\n return;\n } else if (hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(componentStack)) {\n // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n dynamicValidation.hasAllowedDynamic = true;\n dynamicValidation.hasSuspenseAboveBody = true;\n return;\n } else if (hasSuspenseRegex.test(componentStack)) {\n // this error had a Suspense boundary above it so we don't need to report it as a source\n // of disallowed\n dynamicValidation.hasAllowedDynamic = true;\n return;\n } else if (syncDynamicError) {\n dynamicValidation.dynamicErrors.push(syncDynamicError);\n return;\n }\n if (isClientHookDynamicError(dynamicReason)) {\n dynamicValidation.dynamicErrors.push(addErrorContext(dynamicReason, componentStack, null));\n return;\n }\n const error = addErrorContext(createBodyError(dynamicHoleKind, workStore.route), componentStack, null);\n dynamicValidation.dynamicErrors.push(error);\n return;\n}\nexport var DynamicHoleKind = /*#__PURE__*/ function(DynamicHoleKind) {\n /** We know that this hole is caused by runtime data. */ DynamicHoleKind[DynamicHoleKind[\"Runtime\"] = 1] = \"Runtime\";\n /** We know that this hole is caused by link data. */ DynamicHoleKind[DynamicHoleKind[\"Link\"] = 2] = \"Link\";\n /** We know that this hole is caused by navigation(). */ DynamicHoleKind[DynamicHoleKind[\"Navigation\"] = 3] = \"Navigation\";\n /** We know that this hole is caused by prefetch(). */ DynamicHoleKind[DynamicHoleKind[\"Prefetch\"] = 4] = \"Prefetch\";\n /** We know that this hole is caused by dynamic data. */ DynamicHoleKind[DynamicHoleKind[\"Dynamic\"] = 5] = \"Dynamic\";\n /** We know that this hole is caused by runtime or dynamic data, but don't know which. */ DynamicHoleKind[DynamicHoleKind[\"RuntimeOrDynamic\"] = 6] = \"RuntimeOrDynamic\";\n return DynamicHoleKind;\n}({});\nexport function createInstantValidationState(slotStacks) {\n return {\n hasDynamicMetadata: false,\n hasAllowedClientDynamicAboveBoundary: false,\n dynamicMetadata: null,\n hasDynamicViewport: false,\n hasAllowedDynamic: false,\n dynamicErrors: [],\n validationPreventingErrors: [],\n thrownErrorsOutsideBoundary: [],\n slotStacks\n };\n}\nexport function trackDynamicHoleInNavigation(dynamicReason, workStore, componentStack, dynamicValidation, clientDynamic, kind, boundaryState) {\n const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic);\n if (hasOutletRegex.test(componentStack)) {\n // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n return;\n }\n // Resolve the config stack for this specific error. If the error\n // is inside a slot marker, use that slot's config. Otherwise fall\n // back to the default.\n const effectiveCreateInstantStack = resolveInstantStack(componentStack, dynamicValidation);\n if (hasMetadataRegex.test(componentStack)) {\n const error = addErrorContext(createMetadataError(kind, workStore.route), componentStack, effectiveCreateInstantStack);\n dynamicValidation.dynamicMetadata = error;\n return;\n }\n if (hasViewportRegex.test(componentStack)) {\n const error = addErrorContext(createViewportError(kind, workStore.route), componentStack, effectiveCreateInstantStack);\n dynamicValidation.dynamicErrors.push(error);\n return;\n }\n const boundaryLocation = hasInstantValidationBoundaryRegex.exec(componentStack);\n if (!boundaryLocation) {\n // We don't see the validation boundary in the component stack,\n // so this hole must be coming from a shared parent.\n // Shared parents are fully resolved and don't have RSC holes,\n // but they can still suspend in a client component during SSR.\n // If we managed to render all the validation boundaries, that means\n // that the client holes aren't blocking validation and we can disregard them.\n // Note that we don't even care whether they have suspense or not.\n if (allRequiredBoundariesRendered(boundaryState)) {\n dynamicValidation.hasAllowedClientDynamicAboveBoundary = true;\n dynamicValidation.hasAllowedDynamic = true // Holes outside the boundary contribute to allowing dynamic metadata\n ;\n return;\n } else {\n // TODO(instant-validation) TODO(NAR-787)\n // If shared parents blocked us from validating, we should only log\n // the errors from the innermost (segments), i.e. omit layouts whose\n // slots managed to render (because clearly they didn't block validation)\n const message = `Route \"${workStore.route}\": Could not validate \\`instant\\` because a Client Component in a parent segment prevented the page from rendering.`;\n const error = addErrorContext(new Error(message), componentStack, effectiveCreateInstantStack);\n dynamicValidation.validationPreventingErrors.push(error);\n return;\n }\n } else {\n // The hole originates inside the validation boundary.\n //\n // Check if we have a Suspense above the hole, but below the validation boundary.\n // If we do, then this dynamic usage wouldn't block a navigation to this subtree.\n // Conversely, if the nearest suspense is above the validation boundary, then this subtree would block.\n //\n // Note that in the component stack, children come before parents.\n //\n // Valid:\n // ...\n // at Suspense\n // ...\n // at __next_prefetch_validation_boundary__\n //\n // Invalid:\n // ...\n // at __next_prefetch_validation_boundary__\n // ...\n // at Suspense\n //\n const suspenseLocation = hasSuspenseRegex.exec(componentStack);\n if (suspenseLocation) {\n if (suspenseLocation.index < boundaryLocation.index) {\n dynamicValidation.hasAllowedDynamic = true;\n return;\n } else {\n // invalid - fallthrough\n }\n }\n }\n if (syncDynamicError) {\n if (effectiveCreateInstantStack !== null && syncDynamicError.cause === undefined) {\n syncDynamicError.cause = effectiveCreateInstantStack();\n }\n dynamicValidation.dynamicErrors.push(syncDynamicError);\n return;\n }\n if (isClientHookDynamicError(dynamicReason)) {\n dynamicValidation.dynamicErrors.push(addErrorContext(dynamicReason, componentStack, effectiveCreateInstantStack));\n return;\n }\n const error = addErrorContext(createBodyErrorInNavigation(kind, workStore.route), componentStack, effectiveCreateInstantStack);\n dynamicValidation.dynamicErrors.push(error);\n return;\n}\nfunction createBodyError(kind, route) {\n switch(kind){\n case 1:\n return createRuntimeBodyError(route);\n case 5:\n return createDynamicBodyError(route);\n case 6:\n return createDynamicOrRuntimeBodyError(route);\n }\n}\nfunction createBodyErrorInNavigation(kind, route) {\n switch(kind){\n case 1:\n return createRuntimeBodyErrorInNavigation(route);\n case 2:\n return createLinkBodyErrorInNavigation(route);\n case 3:\n return createNavigationBodyErrorInNavigation(route);\n case 4:\n return createPrefetchBodyErrorInNavigation(route);\n case 5:\n return createDynamicBodyErrorInNavigation(route);\n }\n}\nfunction createMetadataError(kind, route) {\n switch(kind){\n case 1:\n return createRuntimeMetadataError(route);\n case 2:\n return createLinkMetadataError(route);\n case 3:\n return createNavigationMetadataError(route);\n case 4:\n return createPrefetchMetadataError(route);\n case 5:\n return createDynamicMetadataError(route);\n case 6:\n return createDynamicOrRuntimeMetadataError(route);\n }\n}\nfunction createViewportError(kind, route) {\n switch(kind){\n case 1:\n return createRuntimeViewportError(route);\n case 2:\n return createLinkViewportError(route);\n case 3:\n return createNavigationViewportError(route);\n case 4:\n return createPrefetchViewportError(route);\n case 5:\n return createDynamicViewportError(route);\n case 6:\n return createDynamicOrRuntimeViewportError(route);\n }\n}\nfunction createBodyErrorInStaticRoute(kind, route) {\n switch(kind){\n case 1:\n return createRuntimeBodyErrorInStaticRoute(route);\n case 5:\n return createDynamicBodyErrorInStaticRoute(route);\n case 6:\n return createNonPrerenderableBodyErrorInStaticRoute(route);\n }\n}\nfunction createMetadataErrorInStaticRoute(kind, route) {\n switch(kind){\n case 1:\n return createRuntimeMetadataErrorInStaticRoute(route);\n case 5:\n return createDynamicMetadataErrorInStaticRoute(route);\n case 6:\n return createNonPrerenderableMetadataErrorInStaticRoute(route);\n }\n}\nfunction createViewportErrorInStaticRoute(kind, route) {\n switch(kind){\n case 1:\n return createRuntimeViewportErrorInStaticRoute(route);\n case 5:\n return createDynamicViewportErrorInStaticRoute(route);\n case 6:\n return createNonPrerenderableViewportErrorInStaticRoute(route);\n }\n}\nexport function trackThrownErrorInNavigation(workStore, dynamicValidation, thrownValue, componentStack, reactBrowserBailout) {\n const boundaryLocation = hasInstantValidationBoundaryRegex.exec(componentStack);\n if (!boundaryLocation) {\n // There's no validation boundary on the component stack.\n // This error may have blocked a boundary from rendering.\n // Wrap the error to provide component context.\n // This helps for errors from node_modules which would otherwise\n // have no useful stack information due to ignore-listing,\n // e.g. next/dynamic with `ssr: false`.\n if (reactBrowserBailout) {\n // React preserves Next's branded bailout reason as the error cause.\n // Replace the internal wrapper before storing the user-facing diagnostic.\n const browserBailoutReason = getReactBrowserBailoutReason(thrownValue);\n if (browserBailoutReason !== undefined) {\n const browserBailoutError = thrownValue;\n browserBailoutError.cause = browserBailoutReason;\n }\n }\n const error = addErrorContext(new Error('An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.', {\n cause: thrownValue\n }), componentStack, null);\n dynamicValidation.thrownErrorsOutsideBoundary.push(error);\n } else {\n // There's validation boundary on the component stack,\n // so we know this error didn't block a validation boundary from rendering.\n // However, this error might be hiding be hiding dynamic content that would\n // cause validation to fail.\n const suspenseLocation = hasSuspenseRegex.exec(componentStack);\n if (suspenseLocation) {\n if (suspenseLocation.index < boundaryLocation.index) {\n // There's a Suspense below the validation boundary but above this error's location.\n // This subtree can't fail instant validation because any potential\n // dynamic holes would be guarded by the Suspense anyway,\n // so we can allow this.\n return;\n } else {\n // invalid - fallthrough\n }\n }\n if (reactBrowserBailout) {\n // React preserves Next's branded bailout reason as the error cause.\n // Replace the internal wrapper before storing the user-facing diagnostic.\n const browserBailoutReason = getReactBrowserBailoutReason(thrownValue);\n if (browserBailoutReason !== undefined) {\n const browserBailoutError = thrownValue;\n browserBailoutError.cause = browserBailoutReason;\n }\n }\n const message = `Route \"${workStore.route}\": Could not validate \\`instant\\` because an error prevented the target segment from rendering.`;\n const error = addErrorContext(new Error(message, {\n cause: thrownValue\n }), componentStack, null // TODO(instant-validation-build): conflicting use of cause\n );\n dynamicValidation.validationPreventingErrors.push(error);\n }\n}\nexport function trackDynamicHoleInStaticShell(dynamicReason, workStore, componentStack, dynamicValidation, clientDynamic, kind) {\n const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic);\n if (hasOutletRegex.test(componentStack)) {\n trackOutletSuspenseAboveBody(componentStack, dynamicValidation);\n return;\n } else if (hasMetadataRegex.test(componentStack)) {\n const error = addErrorContext(createMetadataError(kind, workStore.route), componentStack, null);\n dynamicValidation.dynamicMetadata = error;\n return;\n } else if (hasViewportRegex.test(componentStack)) {\n const error = addErrorContext(createViewportError(kind, workStore.route), componentStack, null);\n dynamicValidation.dynamicErrors.push(error);\n return;\n } else if (hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(componentStack)) {\n // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n dynamicValidation.hasAllowedDynamic = true;\n dynamicValidation.hasSuspenseAboveBody = true;\n return;\n } else if (hasSuspenseRegex.test(componentStack)) {\n // this error had a Suspense boundary above it so we don't need to report it as a source\n // of disallowed\n dynamicValidation.hasAllowedDynamic = true;\n return;\n } else if (syncDynamicError) {\n dynamicValidation.dynamicErrors.push(syncDynamicError);\n return;\n }\n if (isClientHookDynamicError(dynamicReason)) {\n dynamicValidation.dynamicErrors.push(addErrorContext(dynamicReason, componentStack, null));\n return;\n }\n const error = addErrorContext(kind === 1 ? createRuntimeBodyError(workStore.route) : createDynamicBodyError(workStore.route), componentStack, null);\n dynamicValidation.dynamicErrors.push(error);\n return;\n}\n/**\n * In dev mode, we prefer using the owner stack, otherwise the provided\n * component stack is used.\n */ function addErrorContext(error, componentStack, createInstantStack) {\n const ownerStack = process.env.NODE_ENV !== 'production' && React.captureOwnerStack ? React.captureOwnerStack() : null;\n if (createInstantStack !== null) {\n error.cause = createInstantStack();\n }\n // TODO go back to owner stack here if available. This is temporarily using componentStack to get the right\n //\n error.stack = error.name + ': ' + error.message + (ownerStack || componentStack);\n return error;\n}\nexport var PreludeState = /*#__PURE__*/ function(PreludeState) {\n PreludeState[PreludeState[\"Full\"] = 0] = \"Full\";\n PreludeState[PreludeState[\"Empty\"] = 1] = \"Empty\";\n PreludeState[PreludeState[\"Errored\"] = 2] = \"Errored\";\n return PreludeState;\n}({});\nexport function logDisallowedDynamicError(workStore, error) {\n console.error(error);\n logBuildDebugHint(workStore.route);\n}\nexport function throwIfSyncIOUsed(workStore, serverDynamic) {\n if (serverDynamic.syncDynamicErrorWithStack) {\n logDisallowedDynamicError(workStore, serverDynamic.syncDynamicErrorWithStack);\n throw new StaticGenBailoutError();\n }\n}\nexport function throwIfDisallowedDynamic(workStore, prelude, dynamicValidation, serverDynamic, allowEmptyStaticShell) {\n const dynamicHoleKind = 6;\n throwIfSyncIOUsed(workStore, serverDynamic);\n // The dynamic metadata error is a mistake-detection signal. It fires when the\n // rest of the shell is otherwise fully static apart from metadata, suggesting\n // the dynamic data access in `generateMetadata` was probably unintentional.\n // That condition is independent of whether the user or build phase accepted\n // an empty shell, so we surface it before any opt-in bypass.\n if (prelude === 0 && dynamicValidation.hasAllowedDynamic === false && dynamicValidation.hasDynamicMetadata) {\n console.error(createMetadataError(dynamicHoleKind, workStore.route).message);\n throw new StaticGenBailoutError();\n }\n // Either flag expresses \"this shell is allowed to be empty/blocking\":\n // - `allowEmptyStaticShell` covers `instant = false` (user opt-in)\n // and the build-phase fallback-shell case.\n // - `hasSuspenseAboveBody` is the structural opt-in inside the user's root\n // layout.\n // Treat them as synonyms for the purpose of bypassing shell-failure errors.\n if (allowEmptyStaticShell || dynamicValidation.hasSuspenseAboveBody) {\n return;\n }\n if (prelude !== 0) {\n // We didn't have any sync bailouts but there may be user code which\n // blocked the root. We would have captured these during the prerender\n // and can log them here and then terminate the build/validating render\n const dynamicErrors = dynamicValidation.dynamicErrors;\n if (dynamicErrors.length > 0) {\n for(let i = 0; i < dynamicErrors.length; i++){\n logDisallowedDynamicError(workStore, dynamicErrors[i]);\n }\n throw new StaticGenBailoutError();\n }\n // If we got this far then the only other thing that could be blocking\n // the root is dynamic Viewport. If this is dynamic then\n // you need to opt into that by adding a Suspense boundary above the body\n // to indicate your are ok with fully dynamic rendering.\n if (dynamicValidation.hasDynamicViewport) {\n console.error(createViewportError(dynamicHoleKind, workStore.route).message);\n throw new StaticGenBailoutError();\n }\n if (prelude === 1) {\n // If we ever get this far then we messed up the tracking of invalid dynamic.\n // We still adhere to the constraint that you must produce a shell but invite the\n // user to report this as a bug in Next.js.\n console.error(`Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js.`);\n throw new StaticGenBailoutError();\n }\n }\n}\nexport function throwIfDisallowedDynamicInStaticRoute(workStore, prelude, dynamicValidation, serverDynamic, isFallbackShell, allowEmptyStaticShell, isServerPartial) {\n const reasons = getDisallowedReasonsInStaticRoute(workStore, prelude, dynamicValidation, serverDynamic, isFallbackShell, allowEmptyStaticShell, isServerPartial);\n if (reasons.length > 0) {\n for (const reason of reasons){\n logDisallowedDynamicError(workStore, reason);\n }\n throw new StaticGenBailoutError();\n }\n}\nexport function getDisallowedReasonsInStaticRoute(workStore, prelude, dynamicValidation, serverDynamic, isFallbackShell, allowEmptyStaticShell, isServerPartial) {\n if (serverDynamic && serverDynamic.syncDynamicErrorWithStack) {\n return [\n serverDynamic.syncDynamicErrorWithStack\n ];\n }\n // We do a fallback shell prerender, but it's not meant to be validated --\n // we just need it to create the relevant prerender outputs.\n if (isFallbackShell) {\n return [];\n }\n // Suspense-above-body and `instant = false` bypass reporting\n // that the shell is blocked. However, if we have non-prerenderable server\n // data, we still have to error, regardless of those two.\n if (!isServerPartial && (allowEmptyStaticShell || dynamicValidation.hasSuspenseAboveBody)) {\n return [];\n }\n const { dynamicErrors } = dynamicValidation;\n if (dynamicErrors.length > 0) {\n return dynamicErrors;\n }\n // Dynamic data may have been passed into a client component without calling `use()`,\n // in which case we wouldn't see it during the prerender, but still need to error.\n // Fall back to a generic error message.\n if (isServerPartial) {\n return [\n new Error(`Route \"${workStore.route}\": Next.js encountered data that is not available during a static prerender, but is unable to provide a location.`)\n ];\n }\n if (prelude === 1 || prelude === 2) {\n // We've somehow ended up with an empty prelude but no dynamic errors.\n // We must've messed up the tracking somehow.\n return [\n new InvariantError(`Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason.`)\n ];\n }\n return [];\n}\nexport function getStaticShellDisallowedDynamicReasons(workStore, prelude, dynamicValidation, allowEmptyStaticShell) {\n // The dynamic metadata error is a mistake-detection signal. It fires when the\n // rest of the shell is otherwise fully static apart from metadata, suggesting\n // the dynamic data access in `generateMetadata` was probably unintentional.\n // That condition is independent of whether the user or build phase accepted\n // an empty shell, so we surface it before any opt-in bypass.\n if (prelude === 0 && dynamicValidation.hasAllowedDynamic === false && dynamicValidation.dynamicErrors.length === 0 && dynamicValidation.dynamicMetadata) {\n return [\n dynamicValidation.dynamicMetadata\n ];\n }\n // Either flag expresses \"this shell is allowed to be empty/blocking\":\n // - `allowEmptyStaticShell` covers `instant = false` (user opt-in)\n // and the build-phase fallback-shell case.\n // - `hasSuspenseAboveBody` is the structural opt-in inside the user's root\n // layout.\n // Treat them as synonyms for the purpose of bypassing shell-failure errors.\n if (allowEmptyStaticShell || dynamicValidation.hasSuspenseAboveBody) {\n return [];\n }\n if (prelude !== 0) {\n // We didn't have any sync bailouts but there may be user code which\n // blocked the root. We would have captured these during the prerender\n // and can log them here and then terminate the build/validating render\n const dynamicErrors = dynamicValidation.dynamicErrors;\n if (dynamicErrors.length > 0) {\n return dynamicErrors;\n }\n if (prelude === 1) {\n // If we ever get this far then we messed up the tracking of invalid dynamic.\n // We still adhere to the constraint that you must produce a shell but invite the\n // user to report this as a bug in Next.js.\n return [\n new InvariantError(`Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason.`)\n ];\n }\n }\n // We had a non-empty prelude and there are no dynamic holes\n return [];\n}\nexport function getNavigationDisallowedDynamicReasons(workStore, prelude, dynamicValidation, validationSampleTracking, boundaryState, devRenderDidError) {\n // If we have errors related to missing samples, those should take precedence over everything else.\n if (validationSampleTracking) {\n const { missingSampleErrors } = validationSampleTracking;\n if (missingSampleErrors.length > 0) {\n return missingSampleErrors;\n }\n }\n const { validationPreventingErrors } = dynamicValidation;\n if (validationPreventingErrors.length > 0) {\n if (process.env.__NEXT_DEV_SERVER && devRenderDidError) {\n // The dev render already surfaced server errors to the user.\n // The same errors likely caused validation to be inconclusive,\n // so reporting them again as validation failures would be noisy.\n return [];\n }\n return validationPreventingErrors;\n }\n // NOTE: We don't care about Suspense above body here,\n // we're only concerned with the validation boundary\n if (prelude !== 0) {\n const dynamicErrors = dynamicValidation.dynamicErrors;\n if (dynamicErrors.length > 0) {\n return dynamicErrors;\n }\n if (prelude === 1 && !dynamicValidation.hasAllowedClientDynamicAboveBoundary && allRequiredBoundariesRendered(boundaryState)) {\n // If we ever get this far then we messed up the tracking of invalid\n // dynamic. (When boundaries are missing the deferred fallback below\n // will surface a more useful error.)\n return new InvariantError(`Route \"${workStore.route}\" failed to render during instant validation and Next.js was unable to determine a reason.`);\n }\n } else {\n const dynamicErrors = dynamicValidation.dynamicErrors;\n if (dynamicErrors.length > 0) {\n return dynamicErrors;\n }\n if (dynamicValidation.hasAllowedDynamic === false && dynamicValidation.dynamicMetadata) {\n return [\n dynamicValidation.dynamicMetadata\n ];\n }\n }\n // Missing boundaries on their own aren't a strong signal — a parent\n // layout may legitimately omit a slot. Defer this so the caller can\n // try shallower validation depths first; if every depth comes up\n // empty we still want to surface this so the user is made aware that\n // validation didn't complete. When we add a markers API, the\n // marker-based variant of this check can become strict again.\n if (!allRequiredBoundariesRendered(boundaryState)) {\n const { thrownErrorsOutsideBoundary } = dynamicValidation;\n const rootInstantStack = dynamicValidation.slotStacks[0];\n if (thrownErrorsOutsideBoundary.length === 0) {\n const missingFiles = [];\n for (const [id, filePaths] of boundaryState.requiredIds){\n if (!boundaryState.renderedIds.has(id)) {\n for (const filePath of filePaths){\n let normalized = filePath.replace(/^\\[project\\][\\\\/]?/, '').replace(process.cwd() + '/', '').replace(process.cwd() + '\\\\', '');\n missingFiles.push(normalized);\n }\n }\n }\n missingFiles.sort();\n return createUnrenderedSegmentError(workStore.route, missingFiles);\n } else if (process.env.__NEXT_DEV_SERVER && devRenderDidError) {\n // Errors outside the boundary likely blocked it from rendering,\n // but they're already being reported to the user via the dev\n // render. Suppress the validation failure to avoid noise.\n return [];\n } else if (thrownErrorsOutsideBoundary.length === 1) {\n const message = `Route \"${workStore.route}\": Could not validate \\`instant\\` because the target segment was prevented from rendering, likely due to the following error.`;\n const error = rootInstantStack !== null ? rootInstantStack() : new Error();\n error.name = 'Error';\n error.message = message;\n return new AggregateError([\n error,\n thrownErrorsOutsideBoundary[0]\n ]);\n } else {\n const message = `Route \"${workStore.route}\": Could not validate \\`instant\\` because the target segment was prevented from rendering, likely due to one of the following errors.`;\n const error = rootInstantStack !== null ? rootInstantStack() : new Error();\n error.name = 'Error';\n error.message = message;\n return new AggregateError([\n error,\n ...thrownErrorsOutsideBoundary\n ]);\n }\n }\n // We had a non-empty prelude and there are no dynamic holes\n return [];\n}\n\n//# sourceMappingURL=dynamic-rendering.js.map","const DYNAMIC_ERROR_CODE = 'DYNAMIC_SERVER_USAGE';\nexport class DynamicServerError extends Error {\n constructor(description){\n super(`Dynamic server usage: ${description}`), this.description = description, this.digest = DYNAMIC_ERROR_CODE;\n }\n}\nexport function isDynamicServerError(err) {\n if (typeof err !== 'object' || err === null || !('digest' in err) || typeof err.digest !== 'string') {\n return false;\n }\n return err.digest === DYNAMIC_ERROR_CODE;\n}\n\n//# sourceMappingURL=hooks-server-context.js.map","import { InvariantError } from '../shared/lib/invariant-error';\nimport { createPromiseWithResolvers } from '../shared/lib/promise-with-resolvers';\nimport { EnsureStaticLevel } from './app-render/segment-config/ensure-static';\nimport { RenderStage } from './app-render/staged-rendering';\nimport { workAsyncStorage } from './app-render/work-async-storage.external';\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external';\nimport { getServerReact, getClientReact } from './runtime-reacts.external';\nexport function isHangingPromiseRejectionError(err) {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false;\n }\n return err.digest === HANGING_PROMISE_REJECTION;\n}\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION';\nclass HangingPromiseRejectionError extends Error {\n constructor(route, expression){\n super(`During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`), this.route = route, this.expression = expression, this.digest = HANGING_PROMISE_REJECTION;\n }\n}\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC';\nexport class ClientHookDynamicError extends Error {\n constructor(route, expression){\n super(`Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` + `This blocks prerendering because the value is only available at runtime.\\n\\n` + `Ways to fix this:\\n` + ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` + ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`), this.digest = CLIENT_HOOK_DYNAMIC;\n }\n}\nexport function isClientHookDynamicError(err) {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false;\n }\n return err.digest === CLIENT_HOOK_DYNAMIC;\n}\nconst abortListenersBySignal = new WeakMap();\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n */ export function makeDynamicHangingPromise(signal, route, expression) {\n return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression));\n}\nexport function makeUntrackedHangingPromise(signal, route, expression) {\n return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression));\n}\n/**\n * Constructs a promise that never resolves, standing in for session data\n * (which a runtime shell can access).\n * Examples: cookies, headers\n *\n * Awaiting one of these during a static prerender records on the prerender\n * store that a runtime shell would produce more content than the static\n * static shell, which the segment prefetch encoding uses\n * to tell the client whether a runtime request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n */ export function makeSessionDataHangingPromise(signal, route, expression, workUnitStore) {\n const promise = makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression));\n return trackPromiseUsed(promise, trackSessionDataAccessed.bind(null, workUnitStore, expression));\n}\n/**\n * Constructs a promise that never resolves, standing in for URL data,\n * which can be accessed in a runtime prefetch (but not a runtime shell).\n * Examples: fallback params, searchParams\n *\n * Awaiting one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response, which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself.\n * Such a caller MUST call `trackURLDataAccessed` from every path that\n * observes the promise (e.g. the proxy traps for `then`/`status`),\n * against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n */ export function makeURLDataHangingPromise(signal, route, expression, workUnitStore) {\n const promise = makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression));\n if (workUnitStore === null) {\n return promise;\n }\n return trackPromiseUsed(promise, trackURLDataAccessed.bind(null, workUnitStore, expression));\n}\n/**\n * Creates a promise that stands in for a result that will either be session data\n * or URL data, but we don't know which.\n */ export function makeUnknownRuntimeDataHangingPromise(signal, route, expression, workUnitStore) {\n // We don't know if this is session or URL data, i.e. if it should affect the shell\n // or only the prefetch. Track it conservatively as affecting both.\n return makeSessionDataHangingPromise(signal, route, expression, workUnitStore);\n}\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in the prefetch, but not in the shell, e.g. `prefetch()`.\n * This usage does *not* indicate that a runtime request is needed,\n * only that the data is not available in a shell.\n *\n * @internal\n */ export function makePrefetchHangingPromise(signal, route, expression) {\n return makeUntrackedHangingPromise(signal, route, expression);\n}\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access,\n * awaiting it records the access on the prerender store's response-level flag,\n * but its effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself by calling `trackFallbackParamsAccessed`\n * from every path that observes the promise.\n */ export function makeFallbackParamsHangingPromise(signal, route, expression, workUnitStore) {\n const promise = makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression));\n if (workUnitStore === null) {\n return promise;\n }\n return trackPromiseUsed(promise, trackFallbackParamsAccessed.bind(null, workUnitStore, expression));\n}\nexport function createPrerenderDataTracking() {\n return {\n runtimeDataAccessed: createPromiseWithResolvers(),\n shouldAttemptStaticShell: true,\n shouldAttemptStaticPrefetch: true\n };\n}\nexport function finishPrerenderDataTracking(prerenderDataTracking) {\n // If a runtime data access already resolved this promise, this is a no-op.\n prerenderDataTracking.runtimeDataAccessed.resolve(false);\n}\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved in a runtime shell (or runtime prefetch).\n * No-op for all other store types.\n *\n * Prefer `makeRuntimeHangingPromise`. Use this function only when implementing\n * similar tracking and that one is not enough.\n */ function trackSessionDataAccessed(workUnitStore, expression) {\n trackRuntimeDataAccessed(workUnitStore, 1, expression);\n}\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved in a runtime prefetch (but NOT in a runtime shell)\n * No-op for all other store types.\n *\n * Prefer `makeRuntimeHangingPromise`. Use this function only when implementing\n * similar tracking and that one is not enough.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice.\n */ export function trackURLDataAccessed(workUnitStore, expression) {\n trackRuntimeDataAccessed(workUnitStore, 2, expression);\n}\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */ export function trackFallbackParamsAccessed(workUnitStore, expression) {\n trackRuntimeDataAccessed(workUnitStore, 3, expression);\n}\nfunction trackRuntimeDataAccessed(workUnitStore, dataKind, expression) {\n switch(workUnitStore.type){\n case 'prerender':\n {\n const { prerenderDataTracking, stagedRendering } = workUnitStore;\n if (!prerenderDataTracking || !stagedRendering) {\n return;\n }\n const { currentStage } = stagedRendering;\n if (currentStage === RenderStage.Before) {\n console.error(new InvariantError('Unexpected trackRuntimeDataAccessed in the Before stage.'));\n return;\n }\n if (currentStage >= RenderStage.NavigationStatic) {\n // Ignore any accesses that happen after `navigation()` resolves.\n // The purpose of this tracking is to judge whether a runtime prefetch\n // would give us a more complete result than a static one.\n // But `navigation()` wouldn't have resolved in a runtime prefetch,\n // so e.g. `await navigation(); await cookies()` wouldn't have more content\n // in those, and we shouldn't count it.\n return;\n }\n const ensureStaticLevel = workUnitStore.ensureStaticLevel ?? EnsureStaticLevel.None;\n // NOTE: In general, we keep hints in sync with `needsRuntimeRequest`, but they\n // don't have to always match. The client re-uses hints for the entire route,\n // while `needsRuntimeRequest` can vary across individual prerendered param values\n // (e.g. if cookies are accessed depending on a param value).\n // Hints can also become outdated if a route only starts using runtime data\n // after a revalidation, so we have to expect this and be resilient to it.\n // Also see the upgradeable fallback params case below, which deliberately\n // puts them out of sync.\n switch(dataKind){\n case 1:\n {\n // Potentially deopt both the shell and the prefetch,\n // because if the shell accessed runtime data, so does the prefetch.\n // However, if we're already past the shell stage, the shell is not affected.\n // (which makes e.g. `await prefetch(); await cookies()` only affect the prefetch)\n let firstAffectedStage = null;\n if (currentStage <= RenderStage.ShellStatic && // Only track if we're not forcing the shell to be static.\n ensureStaticLevel < EnsureStaticLevel.Shell) {\n prerenderDataTracking.shouldAttemptStaticShell = false;\n firstAffectedStage ??= RenderStage.ShellStatic;\n logRuntimeDeopt == null ? void 0 : logRuntimeDeopt(expression, 'shell');\n }\n if (currentStage <= RenderStage.PrefetchStatic && // Only track if we're not forcing the prefetch to be static.\n ensureStaticLevel < EnsureStaticLevel.Prefetch) {\n prerenderDataTracking.shouldAttemptStaticPrefetch = false;\n // NOTE: if the shell is affected, don't override it.\n firstAffectedStage ??= RenderStage.PrefetchStatic;\n logRuntimeDeopt == null ? void 0 : logRuntimeDeopt(expression, 'prefetch');\n }\n if (firstAffectedStage !== null) {\n markRuntimeDataAccessWhenStageReached(prerenderDataTracking, stagedRendering, firstAffectedStage);\n }\n break;\n }\n case 3:\n {\n if (workUnitStore.isFallbackUpgradeable) {\n // An fallback-param access is transient when the route is\n // fallback-upgradeable (i.e. ISR later produces the concrete prerender a\n // static prefetch would hit) so it does not indicate the need for a runtime\n // request and thus does not affect the static hints.\n //\n // If runtime prefetches are not disallowed by `ensureStatic`, then we still\n // set `runtimeDataAccessed` (while keeping the hints static). This means that\n // if the concrete prerender isn't ready yet and we served the fallback, then\n // the client knows it can use a *runtime* prefetch for speculative links --\n // a runtime prefetch can provide the same content (or more) as the concrete\n // prerender would.\n if (ensureStaticLevel < EnsureStaticLevel.Prefetch) {\n markRuntimeDataAccessWhenStageReached(prerenderDataTracking, stagedRendering, // `params` are URL data, so they only affect the prefetch\n RenderStage.PrefetchStatic);\n logRuntimeUpgradeableFallback == null ? void 0 : logRuntimeUpgradeableFallback();\n }\n break;\n }\n // not an upgradeable fallback param access, so we treat it as URL data.\n // intentional fallthrough\n }\n case 2:\n {\n // Only deopt the prefetch, not the shell, which cannot access URL data anyway.\n if (currentStage <= RenderStage.PrefetchStatic && ensureStaticLevel < EnsureStaticLevel.Prefetch) {\n prerenderDataTracking.shouldAttemptStaticPrefetch = false;\n logRuntimeDeopt == null ? void 0 : logRuntimeDeopt(expression, 'prefetch');\n markRuntimeDataAccessWhenStageReached(prerenderDataTracking, stagedRendering, RenderStage.PrefetchStatic);\n }\n break;\n }\n }\n break;\n }\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break;\n default:\n workUnitStore;\n }\n}\n/**\n * Tracks a runtime data access on the `runtimeDataAccessed` promise,\n * but with a delay until `targetStage`.\n *\n * When we encounter a URL data access like `await params`, we need to mark the\n * *prefetch* as needing runtime data, but the *shell* should remain unaffected\n * (because it cannot access params anyway).\n *\n * However, the shell and the prefetch share one `runtimeDataAccessed` promise,\n * and it needs to be accurately rewindable by the client\n * In other words, we need to make sure that it reads as `false` when rewound\n * to a shell, but as `true` in the final response (the prefetch).\n *\n * This means that if the `await params` is encountered during the shell stage, we\n * cannot resolve `runtimeDataAccessed` immediately.\n * Instead, we delay the resolution until the PrefetchStatic stage, so the promise\n * will remain unresolved when rewound to the shell stage (which reads as `false`).\n */ function markRuntimeDataAccessWhenStageReached(prerenderDataTracking, stageController, targetStage) {\n const { runtimeDataAccessed } = prerenderDataTracking;\n // NOTE: If we're already in or past the target stage, we can avoid allocating a closure,\n // because `onStage` would've executed the callback immediately anyway.\n if (stageController.currentStage >= targetStage) {\n runtimeDataAccessed.resolve(true);\n } else {\n stageController.onStage(targetStage, runtimeDataAccessed.resolve.bind(null, true));\n }\n}\nconst logRuntimeDeopt = process.env.NEXT_PRIVATE_DEBUG_RUNTIME_DATA ? (expression, kind)=>{\n const { route } = workAsyncStorage.getStore();\n console.log(`Route '${route}': deopting to a runtime ${kind} because it used ${expression}`);\n} : undefined;\nconst logRuntimeUpgradeableFallback = process.env.NEXT_PRIVATE_DEBUG_RUNTIME_DATA ? ()=>{\n const { route } = workAsyncStorage.getStore();\n console.log(`Route '${route}': marking upgradeable fallback as runtime prefetchable`);\n} : undefined;\n/**\n * Signals that we cannot recover both a runtime shell and a static (PPR) shell\n * from the same render. Use this whenever the stage of a promise varies on\n * `RequestStore.needsRuntimeShell`.\n * */ export function trackIncompatibleShellContent(workUnitStore, reason) {\n const { stagedRendering } = workUnitStore;\n if (!stagedRendering) {\n return;\n }\n // TODO(app-shells): optimize this to only consider stages that are relevant for validation.\n // We should only track incompatible content when it can affect them.\n // For now, we simply exclude everything that happens in the dynamic stage.\n // (Note that we also need to account for cache misses that move things to a\n // different stage -- those should also preemptively set `hasIncompatibleShellContent`\n // because there's a chance that a render with warm caches would set it)\n const { currentStage } = stagedRendering;\n if (currentStage === RenderStage.Dynamic || currentStage === RenderStage.Abandoned) {\n return;\n }\n if (process.env.NEXT_PRIVATE_DEBUG_VALIDATION) {\n const workStore = workAsyncStorage.getStore();\n console.log(`Route ${workStore.route}: Incompatible shell content: ${reason}`);\n }\n workUnitStore.hasIncompatibleShellContent = true;\n}\nexport function makeClientHookHangingPromise(signal, error) {\n return makeHangingPromiseWithError(signal, error);\n}\nfunction makeHangingPromiseWithError(signal, error) {\n if (signal.aborted) {\n return Promise.reject(error);\n } else {\n const hangingPromise = new Promise((_, reject)=>{\n const boundRejection = reject.bind(null, error);\n let currentListeners = abortListenersBySignal.get(signal);\n if (currentListeners) {\n currentListeners.push(boundRejection);\n } else {\n const listeners = [\n boundRejection\n ];\n abortListenersBySignal.set(signal, listeners);\n signal.addEventListener('abort', ()=>{\n for(let i = 0; i < listeners.length; i++){\n listeners[i]();\n }\n }, {\n once: true\n });\n }\n });\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject);\n return hangingPromise;\n }\n}\nfunction ignoreReject() {}\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */ export function makePromiseFromTrigger(trigger, value) {\n const promise = trigger.then(()=>value);\n promise.catch(ignoreReject);\n return promise;\n}\nexport function makeDevtoolsIOAwarePromise(underlying, requestStore, stage) {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(stage, undefined, underlying);\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise((resolve)=>{\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(()=>{\n resolve(underlying);\n }, 0);\n });\n}\n/**\n * Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise\n * or when the promise is awaited. */ export function trackPromiseUsed(promise, onUse) {\n // We can instrument `.then()/.catch()/.finally()` in one go by using a Promise subclass\n // that implements a custom `.then()`, because `catch` and `finally` delegate to it.\n //\n // Alternative implementation ideas that were tried and rejected:\n //\n // 1. Patching the methods directly via `promise.then = (..args) => { ... }`:\n // doesn't work, because Node does not call the monkeypatched methods for native `await`:\n // > Native Promise [...]: The promise is directly used and awaited natively, without calling `then()`.\n // > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#description\n //\n // 2. Wrapping in a proxy that returns a custom `then/catch/finally`:\n // breaks async stacks in React's IO tracking (stack becomes `Promise.then`)\n return TrackedPromise.from(promise, onUse);\n}\nclass TrackedPromise extends Promise {\n #onUse;\n // We don't need derived promises to also be a TrackedPromise.\n // We only care about the first level of `.then()`.\n static get [Symbol.species]() {\n return Promise;\n }\n static from(promise, onUse) {\n // Whenever the promise we're tracking resolves/rejects, we should follow.\n const tracked = new TrackedPromise(promise.then.bind(promise));\n tracked.#onUse = onUse;\n // Hanging promises catch rejections when created. Tracked promises are generally derived\n // from promises that may hang & reject, so we need to do the same.\n // However, we have to bypass the tracking we do in `TrackedPromise.then`.\n // (we're using `then` directly, because `catch` ends up delegating `TrackedPromise.then`)\n Promise.prototype.then.call(tracked, undefined, ignoreReject);\n return tracked;\n }\n then(onFulfilled, onRejected) {\n const onUse = this.#onUse;\n if (onUse) {\n try {\n onUse();\n } catch (err) {\n // We don't want to break the method even if our tracking errored.\n console.error(err);\n }\n }\n return Promise.prototype.then.call(this, onFulfilled, onRejected);\n }\n constructor(...args){\n super(...args), this.#onUse = null;\n }\n}\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime,\n /**\n * Statically-prerenderable URL data, like static `params`.\n * It may need to be pushed to a runtime stage in a runtime prerender,\n * but it's semantically distinct from `runtimeUrlData` like `searchParams`,\n * which is always excluded from static prerenders.\n * */ staticUrlData: {\n /**\n * From that app's point of view, `prefetch()` is semantically the same as\n * `staticUrlData`, because it does not resolve in a shell but resolves in\n * a prefetch (even a static one).\n * We handle it separately to provide a specialized error in validation renders.\n */ prefetchApi: {\n static: RenderStage.PrefetchStatic_prefetchApi,\n runtime: RenderStage.PrefetchRuntime_prefetchApi\n },\n static: RenderStage.PrefetchStatic,\n runtime: RenderStage.PrefetchRuntime\n },\n /**\n * URL data that is never statically-prerenderable, like static `searchParams`.\n * */ runtimeUrlData: RenderStage.PrefetchRuntime\n};\nexport function applyOwnerStack(error) {\n if (process.env.NODE_ENV !== 'production') {\n var _getClientReact_captureOwnerStack, _getClientReact, _getServerReact_captureOwnerStack, _getServerReact;\n let ownerStack;\n const workUnitStore = workUnitAsyncStorage.getStore();\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack = ((_getClientReact = getClientReact()) == null ? void 0 : (_getClientReact_captureOwnerStack = _getClientReact.captureOwnerStack) == null ? void 0 : _getClientReact_captureOwnerStack.call(_getClientReact)) ?? ((_getServerReact = getServerReact()) == null ? void 0 : (_getServerReact_captureOwnerStack = _getServerReact.captureOwnerStack) == null ? void 0 : _getServerReact_captureOwnerStack.call(_getServerReact));\n switch(workUnitStore == null ? void 0 : workUnitStore.type){\n case 'cache':\n case 'private-cache':\n ownerStack = (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') || undefined;\n break;\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'build-time-generator':\n case undefined:\n ownerStack = innerOwnerStack;\n break;\n default:\n workUnitStore;\n }\n if (ownerStack) {\n let stack = ownerStack;\n if (error.stack) {\n const frames = [];\n for (const frame of error.stack.split('\\n').slice(1)){\n if (frame.includes('react_stack_bottom_frame')) {\n break;\n }\n frames.push(frame);\n }\n stack = '\\n' + frames.join('\\n') + stack;\n }\n error.stack = error.name + ': ' + error.message + stack;\n }\n }\n return error;\n}\n\n//# sourceMappingURL=dynamic-rendering-utils.js.map","export const INSTANT_VALIDATION_BOUNDARY_NAME = '__next_instant_validation_boundary__';\nexport const INSTANT_SLOT_MARKER_PREFIX = '__next_instant_slot_';\nexport const INSTANT_SLOT_MARKER_SUFFIX = '__';\n\n//# sourceMappingURL=boundary-constants.js.map","import { InvariantError } from '../../shared/lib/invariant-error';\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers';\nexport var RenderStage = /*#__PURE__*/ function(RenderStage) {\n RenderStage[RenderStage[\"Before\"] = 1] = \"Before\";\n //\n RenderStage[RenderStage[\"ShellStatic\"] = 10] = \"ShellStatic\";\n /** Discrimination-only stage: `prefetch()` in validation renders (static) */ RenderStage[RenderStage[\"PrefetchStatic_prefetchApi\"] = 11] = \"PrefetchStatic_prefetchApi\";\n RenderStage[RenderStage[\"PrefetchStatic\"] = 12] = \"PrefetchStatic\";\n RenderStage[RenderStage[\"NavigationStatic\"] = 13] = \"NavigationStatic\";\n RenderStage[RenderStage[\"Static\"] = 14] = \"Static\";\n //\n RenderStage[RenderStage[\"ShellRuntime\"] = 20] = \"ShellRuntime\";\n /** Discrimination-only stage: `prefetch()` in validation renders (runtime) */ RenderStage[RenderStage[\"PrefetchRuntime_prefetchApi\"] = 21] = \"PrefetchRuntime_prefetchApi\";\n RenderStage[RenderStage[\"PrefetchRuntime\"] = 22] = \"PrefetchRuntime\";\n RenderStage[RenderStage[\"NavigationRuntime\"] = 23] = \"NavigationRuntime\";\n //\n RenderStage[RenderStage[\"Dynamic\"] = 30] = \"Dynamic\";\n RenderStage[RenderStage[\"Abandoned\"] = 40] = \"Abandoned\";\n return RenderStage;\n}({});\nexport const RENDER_STAGE_ADVANCE_ORDER = [\n 10,\n 11,\n 12,\n 13,\n 14,\n 20,\n 21,\n 22,\n 23,\n 30\n];\nexport function getNextStage(stage) {\n return RENDER_STAGE_ADVANCE_ORDER[RENDER_STAGE_ADVANCE_ORDER.indexOf(stage) + 1];\n}\nexport function isAdvanceableRenderStage(stage) {\n return 1 < stage && stage <= 30;\n}\nexport var SyncIOMode = /*#__PURE__*/ function(SyncIOMode) {\n /** Sync IO does not error in any stage. */ SyncIOMode[SyncIOMode[\"Untracked\"] = 1] = \"Untracked\";\n /** Before `partialPrefetching`: Sync IO errors in static stages, and is allowed otherwise. */ SyncIOMode[SyncIOMode[\"AllowedInRuntimeOrDynamic\"] = 2] = \"AllowedInRuntimeOrDynamic\";\n /** After `partialPrefetching`: Sync IO errors in all stages other than dynamic. */ SyncIOMode[SyncIOMode[\"AllowedInDynamic\"] = 3] = \"AllowedInDynamic\";\n return SyncIOMode;\n}({});\nexport class StagedRenderingController {\n constructor({ abortSignal, abandonController, syncIO, finalStage }){\n this.currentStage = 1;\n this.syncInterruptReason = null;\n this.triggers = createAdvanceableStageTriggers();\n this.abortSignal = abortSignal;\n this.abandonController = abandonController;\n this.syncIOMode = syncIO;\n this.finalStage = finalStage;\n if (abortSignal) {\n abortSignal.addEventListener('abort', ()=>{\n // Reject all stage promises that haven't already been resolved.\n // `cancelStageTrigger` is a noop if the trigger already resolved.\n const { reason } = abortSignal;\n for (const trigger of Object.values(this.triggers)){\n cancelStageTrigger(trigger, reason);\n }\n }, {\n once: true\n });\n }\n if (abandonController) {\n abandonController.signal.addEventListener('abort', ()=>{\n this.abandonRender();\n }, {\n once: true\n });\n }\n }\n /**\n * Schedules a callback that will execute synchronously when the controller is advanced\n * to `stage` or past it, before any promises for that stage are resolved.\n * If the controller is already past `stage`, the callback is executed immediately.\n * */ onStage(stage, callback) {\n addSyncTriggerListener(this.triggers[stage], callback);\n }\n shouldTrackSyncInterrupt() {\n const { syncIOMode, currentStage } = this;\n switch(syncIOMode){\n case 1:\n {\n return false;\n }\n case 2:\n {\n // Legacy: track Sync IO only in static stages.\n // Do not track it before the render, or in runtime/dynamic stages.\n return currentStage > 1 && currentStage <= 14;\n }\n case 3:\n {\n // Track sync IO in all cacheable stages.\n // This means all stages except:\n // - before the render\n // - in the dynamic stage\n return currentStage > 1 && currentStage < 30;\n }\n }\n }\n /** Note: only call this if `shouldTrackSyncInterrupt()` returned true */ syncInterruptCurrentStageWithReason(reason) {\n const { currentStage } = this;\n if (currentStage === 1 || currentStage === 30 || currentStage === 40) {\n // Not interruptible. Defensive noop.\n return;\n }\n // If Sync IO occurs during an abandonable render, we trigger the abandon.\n // The abandon listener will call abandonRender which advances through\n // stages to let caches fill before marking as Abandoned.\n if (this.abandonController) {\n this.abandonController.abort();\n return;\n }\n if (this.abortSignal) {\n // If this is an abortable render, we capture the interruption reason and stop advancing.\n // We don't release any more promises.\n // The caller is expected to abort the signal.\n this.syncInterruptReason = reason;\n this.currentStage = 40;\n return;\n }\n // If we're in a non-abandonable & non-abortable render,\n // we need to advance to the Dynamic stage and capture the interruption reason.\n // (in dev, this will be the restarted render)\n this.syncInterruptReason = reason;\n this.advanceStage(30);\n }\n getSyncInterruptReason() {\n return this.syncInterruptReason;\n }\n getStageEndTime(stage) {\n return this.triggers[getNextStage(stage)].triggeredAt ?? Infinity;\n }\n abandonRender() {\n // In staged rendering, only the initial render is abandonable.\n // We can abandon the initial render if\n // 1. We notice a cache miss, and need to wait for caches to fill\n // 2. A sync IO error occurs, and the render should be interrupted\n // (this might be a lazy intitialization of a module,\n // so we still want to restart in this case and see if it still occurs)\n // In either case, we'll be doing another render after this one,\n // so we only want to unblock the next stage, not Dynamic, because\n // unblocking the dynamic stage would likely lead to wasted (uncached) IO.\n const { currentStage } = this;\n if (currentStage === 1) {\n throw new InvariantError(\"A render that hasn't started yet cannot be abandoned\");\n }\n if (currentStage === 30 || currentStage === 40) {\n // We shouldn't ever trigger an abandon in these. Defensive noop.\n return;\n }\n // Resolve all stages after the current one, up to runtime (excluding dynamic)\n const nextStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1;\n const dynamicStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(30);\n for(let i = nextStageIx; i < dynamicStageIx; i++){\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i]);\n }\n this.currentStage = 40;\n }\n advanceStage(targetStage) {\n if (this.finalStage !== null && targetStage > this.finalStage) {\n throw new InvariantError(`Attempted to advance to stage ${RenderStage[targetStage]} but the render is limited to ${RenderStage[this.finalStage]}`);\n }\n const { currentStage } = this;\n if (currentStage === 30 || currentStage === 40) {\n // Terminal stages, nowhere left to advance.\n return;\n }\n // If we're already at the target stage or beyond, do nothing.\n if (targetStage <= currentStage) {\n return;\n }\n this.currentStage = targetStage;\n // Resolve all stages between the current stage and the target.\n const nextStageIx = currentStage === 1 ? 0 : RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1;\n const targetStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(targetStage);\n for(let i = nextStageIx; i <= targetStageIx; i++){\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i]);\n }\n }\n resolveStage(stage) {\n fireStageTrigger(this.triggers[stage]);\n }\n getStagePromise(stage) {\n return this.triggers[stage].promise;\n }\n waitForStage(stage) {\n return this.getStagePromise(stage);\n }\n delayUntilStage(stage, displayName, resolvedValue) {\n const stagePromise = this.getStagePromise(stage);\n const promise = process.env.NODE_ENV === 'development' ? makeDevtoolsIOPromiseFromIOTrigger(stagePromise, displayName, resolvedValue) : stagePromise.then(()=>resolvedValue);\n // Analogously to `makeDynamicHangingPromise`, we might reject this promise if the signal is invoked.\n // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).\n // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.\n if (this.abortSignal) {\n promise.catch(ignoreReject);\n }\n return promise;\n }\n}\nfunction createAdvanceableStageTriggers() {\n const triggers = {};\n for (const stage of RENDER_STAGE_ADVANCE_ORDER){\n triggers[stage] = createStageTrigger();\n }\n return triggers;\n}\nfunction ignoreReject() {}\n// TODO(restart-on-cache-miss): the layering of `delayUntilStage`,\n// `makeDevtoolsIOPromiseFromIOTrigger` and and `makeDevtoolsIOAwarePromise`\n// is confusing, we should clean it up.\nfunction makeDevtoolsIOPromiseFromIOTrigger(ioTrigger, displayName, resolvedValue) {\n // If we create a `new Promise` and give it a displayName\n // (with no userspace code above us in the stack)\n // React Devtools will use it as the IO cause when determining \"suspended by\".\n // In particular, it should shadow any inner IO that resolved/rejected the promise\n // (in case of staged rendering, this will be the `setTimeout` that triggers the relevant stage)\n const promise = new Promise((resolve, reject)=>{\n ioTrigger.then(resolve.bind(null, resolvedValue), reject);\n });\n if (displayName !== undefined) {\n // @ts-expect-error\n promise.displayName = displayName;\n }\n return promise;\n}\nfunction addSyncTriggerListener(trigger, listener) {\n if (trigger.state === 'pending') {\n trigger._listeners.push(listener);\n } else {\n listener();\n }\n}\nfunction createStageTrigger() {\n const { promise, resolve, reject } = createPromiseWithResolvers();\n return {\n state: 'pending',\n triggeredAt: null,\n promise,\n _listeners: [],\n _resolvePromise: resolve,\n _rejectPromise: reject\n };\n}\nfunction fireStageTrigger(trigger) {\n if (trigger.state !== 'pending') {\n return;\n }\n trigger.state = 'triggered';\n trigger.triggeredAt = performance.now() + performance.timeOrigin;\n try {\n const { _listeners: listeners } = trigger;\n for(let i = 0; i < listeners.length; i++){\n listeners[i]();\n }\n listeners.length = 0;\n } finally{\n trigger._resolvePromise();\n }\n}\nfunction cancelStageTrigger(trigger, reason) {\n if (trigger.state !== 'pending') {\n return;\n }\n trigger.state = 'cancelled';\n // we didn't trigger, so don't save `triggeredAt`.\n // We're not gonna fire the listeners, we may as well free them.\n trigger._listeners.length = 0;\n // Suppress unhandled rejection warnings for promises that no one is awaiting.\n trigger.promise.catch(ignoreReject);\n trigger._rejectPromise(reason);\n}\n\n//# sourceMappingURL=staged-rendering.js.map","import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree';\nimport { getLayoutOrPageModule } from '../../lib/app-dir-module';\n/**\n * The outcome of resolving a route's `ensureStatic` config.\n * The ordering is intentional -- higher values indicate a\n * more constrained route that forces more request kinds to be static.\n *\n * A constraint also implies all its predecessors:\n * - `Prefetch` implies `Shell`, i.e. if prefetches are static, so are shells.\n * - `Navigation` implies `Prefetch` and `Shell`, i.e. if the whole page is static,\n * then so are its shells and prefetches.\n *\n * Note that this flattens `\"auto\"` and `false` into `None`.\n * This is because rendering code does not need to distinguish them --\n * both indicate that the route follows normal Partial Prefetching semantics\n * and does not force anything to be static.\n * However, it is only correct to collapse them into one *after* resolving the\n * config for the entire route, because they have different interactions with\n * configs from other segments on the same route.\n */ export var EnsureStaticLevel = /*#__PURE__*/ function(EnsureStaticLevel) {\n /** The route follows standard Partial Prefetching semantics. */ EnsureStaticLevel[EnsureStaticLevel[\"None\"] = 0] = \"None\";\n /** The route requires that app shells must be statically prerendered. */ EnsureStaticLevel[EnsureStaticLevel[\"Shell\"] = 1] = \"Shell\";\n /** The route requires that app shells and prefetches must be statically prerendered. */ EnsureStaticLevel[EnsureStaticLevel[\"Prefetch\"] = 2] = \"Prefetch\";\n /** The route requires that app shells, prefetches, and the whole page must be statically prerendered. */ EnsureStaticLevel[EnsureStaticLevel[\"Navigation\"] = 3] = \"Navigation\";\n return EnsureStaticLevel;\n}({});\nfunction getEnsureStaticLevel(ensureStatic) {\n switch(ensureStatic){\n case 'auto':\n case false:\n {\n return 0;\n }\n case 'shell':\n {\n return 1;\n }\n case 'prefetch':\n {\n return 2;\n }\n case 'navigation':\n {\n return 3;\n }\n }\n}\nexport async function resolveEnsureStaticLevel(tree, partialPrefetching) {\n return getEnsureStaticLevel(await resolveEnsureStaticConfig(tree, partialPrefetching));\n}\nexport async function resolveEnsureStaticConfig(tree, partialPrefetching) {\n let { config, filePath } = await resolveEnsureStaticConfigImpl(tree);\n if (!partialPrefetching) {\n // If Partial Prefetching is not enabled for this route, we only support\n // a subset of `ensureStatic` values.\n // (We error in `getAppPageStaticInfo` if `ensureStatic` is used without enabling\n // Cache Components, so we don't have to assert that here)\n switch(config){\n case 'auto':\n {\n // Default to the equivalent of Cache Components prefetching behavior.\n config = 'prefetch';\n break;\n }\n case false:\n case 'shell':\n {\n // Not meaningful in Cache Components without Partial Prefetching\n const originalConfig = config;\n config = 'prefetch';\n console.warn(`${formatEnsureStaticExport(originalConfig)} has no effect unless the route is using Partial Prefetching.` + `\\n (from: ${filePath})`);\n break;\n }\n case 'prefetch':\n break;\n case 'navigation':\n break;\n default:\n config;\n }\n }\n if (config === false) {\n // `false` and \"auto\" are equivalent once resolved.\n return 'auto';\n } else {\n return config;\n }\n}\nasync function resolveEnsureStaticConfigImpl(tree) {\n const { mod: layoutOrPageMod, filePath } = await getLayoutOrPageModule(tree);\n const config = getEnsureStaticConfigForModule(layoutOrPageMod);\n const parentResult = {\n config,\n filePath: filePath ?? null\n };\n // Walk the slots if any and validate that they don't have incompatible configs\n // with each other. If compatible, pick the most constrained value from the slots.\n let slotsResult = null;\n let slotResultKey = null;\n const { parallelRoutes } = parseLoaderTree(tree);\n for(const parallelRouteKey in parallelRoutes){\n const parallelRoute = parallelRoutes[parallelRouteKey];\n const childResult = await resolveEnsureStaticConfigImpl(parallelRoute);\n if (!slotsResult) {\n slotsResult = childResult;\n slotResultKey = parallelRouteKey;\n } else {\n // Check if the child is compatible with the current result for the slots.\n switch(compareEnsureStatic(childResult.config, slotsResult.config)){\n case 2:\n {\n // 'auto' is compatible with anything, but if the current result is 'auto' and the new one isn't,\n // we want to use the more specific result.\n if (slotsResult.config === 'auto' && childResult.config !== 'auto') {\n slotsResult = childResult;\n slotResultKey = parallelRouteKey;\n }\n break;\n }\n case 4:\n case 1:\n case 3:\n {\n throw new Error(`Parallel slots cannot have incompatible \\`ensureStatic\\`.` + `\\n ${formatParallelSlot(slotResultKey)}: ` + `\\n ${formatEnsureStaticExport(slotsResult.config)}` + `\\n (from: ${slotsResult.filePath})` + `\\n` + `\\n ${formatParallelSlot(parallelRouteKey)}: ` + `\\n ${formatEnsureStaticExport(childResult.config)}` + `\\n (from: ${childResult.filePath})` + `\\n` + `\\n Possible fixes:` + `\\n - Remove one of the \\`ensureStatic\\` exports` + `\\n - Change one of the \\`ensureStatic\\` exports to match the other`);\n }\n }\n }\n }\n // Child segments can override the config from the parent with a more constrained value,\n // but they cannot have a less constrained value.\n if (!slotsResult) {\n return parentResult;\n } else {\n const comparison = compareEnsureStatic(slotsResult.config, parentResult.config);\n switch(comparison){\n case 2:\n {\n // 'auto' is compatible with anything, but if the parent result is 'auto' and the slots one isn't,\n // we want to use the more constrained result.\n if (parentResult.config === 'auto' && slotsResult.config !== 'auto') {\n return slotsResult;\n } else {\n return parentResult;\n }\n }\n case 3:\n {\n return slotsResult;\n }\n case 1:\n case 4:\n {\n throw new Error((comparison === 1 ? `A child segment cannot override a parent segment with a less-constrained \\`ensureStatic\\`.` : `A child segment cannot override a parent segment with an incompatible \\`ensureStatic\\`.`) + `\\n Parent has: ` + `\\n ${formatEnsureStaticExport(parentResult.config)}` + `\\n (from: ${parentResult.filePath})` + `\\n Child has: ` + `\\n ${formatEnsureStaticExport(slotsResult.config)}` + `\\n (from: ${slotsResult.filePath})` + `\\n` + `\\n Possible fixes:` + `\\n - Remove one of the \\`ensureStatic\\` exports` + `\\n - Change one of the \\`ensureStatic\\` exports to match the other`);\n }\n }\n }\n}\nfunction formatParallelSlot(slot) {\n return slot === 'children' ? slot : `@${slot}`;\n}\nfunction formatEnsureStaticExport(config) {\n return `export const ensureStatic = ${JSON.stringify(config)}`;\n}\nvar Comparison = /*#__PURE__*/ function(Comparison) {\n Comparison[Comparison[\"LessConstrained\"] = 1] = \"LessConstrained\";\n Comparison[Comparison[\"Compatible\"] = 2] = \"Compatible\";\n Comparison[Comparison[\"MoreConstrained\"] = 3] = \"MoreConstrained\";\n Comparison[Comparison[\"Incompatible\"] = 4] = \"Incompatible\";\n return Comparison;\n}(Comparison || {});\nconst ENSURE_STATIC_ORDER = [\n 'shell',\n 'prefetch',\n 'navigation'\n];\nfunction compareEnsureStatic(left, right) {\n // 'auto' is compatible with everything.\n if (left === 'auto' || right === 'auto') {\n return 2;\n }\n // `false` is compatible with false.\n if (left === false && right === false) {\n return 2;\n }\n // If only one of the values is `false` (we know it's not both), it's incompatible.\n if (left === false || right === false) {\n return 4;\n }\n const leftSort = ENSURE_STATIC_ORDER.indexOf(left);\n const rightSort = ENSURE_STATIC_ORDER.indexOf(right);\n return leftSort < rightSort ? 1 : leftSort === rightSort ? 2 : 3;\n}\nfunction getEnsureStaticConfigForModule(mod) {\n return (mod ? mod.ensureStatic : undefined) ?? 'auto';\n}\n\n//# sourceMappingURL=ensure-static.js.map","// This regex will have fast negatives meaning valid identifiers may not pass\n// this test. However this is only used during static generation to provide hints\n// about why a page bailed out of some or all prerendering and we can use bracket notation\n// for example while `ಠ_ಠ` is a valid identifier it's ok to print `searchParams['ಠ_ಠ']`\n// even if this would have been fine too `searchParams.ಠ_ಠ`\nconst isDefinitelyAValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nexport function describeStringPropertyAccess(target, prop) {\n if (isDefinitelyAValidIdentifier.test(prop)) {\n return `\\`${target}.${prop}\\``;\n }\n return `\\`${target}[${JSON.stringify(prop)}]\\``;\n}\nexport function describeHasCheckingStringProperty(target, prop) {\n const stringifiedProp = JSON.stringify(prop);\n return `\\`Reflect.has(${target}, ${stringifiedProp})\\`, \\`${stringifiedProp} in ${target}\\`, or similar`;\n}\nexport const wellKnownProperties = new Set([\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toString',\n 'valueOf',\n 'toLocaleString',\n // Promise prototype\n 'then',\n 'catch',\n 'finally',\n // React Promise extension\n 'status',\n // 'value',\n // 'error',\n // React introspection\n 'displayName',\n '_debugInfo',\n // Common tested properties\n 'toJSON',\n '$$typeof',\n '__esModule',\n // Tested by flight when checking for iterables\n '@@iterator'\n]);\n\n//# sourceMappingURL=reflect-utils.js.map","export class ReflectAdapter {\n static get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (typeof value === 'function') {\n return value.bind(target);\n }\n return value;\n }\n static set(target, prop, value, receiver) {\n return Reflect.set(target, prop, value, receiver);\n }\n static has(target, prop) {\n return Reflect.has(target, prop);\n }\n static deleteProperty(target, prop) {\n return Reflect.deleteProperty(target, prop);\n }\n}\n\n//# sourceMappingURL=reflect.js.map","export class InvariantError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(\n `Invariant: ${message.endsWith('.') ? message : message + '.'} This is a bug in Next.js.`,\n options\n )\n this.name = 'InvariantError'\n }\n}\n","export function createPromiseWithResolvers<T>(): PromiseWithResolvers<T> {\n // Shim of Stage 4 Promise.withResolvers proposal\n let resolve: (value: T | PromiseLike<T>) => void\n let reject: (reason: any) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n return { resolve: resolve!, reject: reject!, promise }\n}\n","import type { ParsedUrlQuery } from 'querystring'\n\nexport function getRenderedSearch(query: ParsedUrlQuery): string {\n // Inlined implementation of querystring.encode, which is not available in\n // the Edge runtime.\n const pairs = []\n for (const key in query) {\n const value = query[key]\n if (value == null) continue\n if (Array.isArray(value)) {\n for (const v of value) {\n pairs.push(\n `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n }\n } else {\n pairs.push(\n `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`\n )\n }\n }\n\n // The result should match the format of a web URL's `search` property, since\n // this is the format that's stored in the App Router state.\n // TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query\n // header omits the leading question mark. Should refactor to always do\n // that instead.\n if (pairs.length === 0) {\n // If the search string is empty, return an empty string.\n return ''\n }\n // Prepend '?' to the search params string.\n return '?' + pairs.join('&')\n}\n\nexport function searchParamsToUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n const query: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n const existing = query[key]\n if (typeof existing === 'undefined') {\n query[key] = value\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n query[key] = [existing, value]\n }\n }\n return query\n}\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n if (typeof param === 'string') {\n return param\n }\n\n if (\n (typeof param === 'number' && !isNaN(param)) ||\n typeof param === 'boolean'\n ) {\n return String(param)\n } else {\n return ''\n }\n}\n\nexport function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, stringifyUrlQueryParam(item))\n }\n } else {\n searchParams.set(key, stringifyUrlQueryParam(value))\n }\n }\n return searchParams\n}\n\nexport function assign(\n target: URLSearchParams,\n ...searchParamsList: URLSearchParams[]\n): URLSearchParams {\n for (const searchParams of searchParamsList) {\n for (const key of searchParams.keys()) {\n target.delete(key)\n }\n\n for (const [key, value] of searchParams.entries()) {\n target.append(key, value)\n }\n }\n\n return target\n}\n","module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].AppRouterContext\n","module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].HooksClientContext\n","module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].ServerInsertedHtml\n","module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactDOM\n","module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactServerDOMTurbopackClient\n"],"names":["__defProp","Object","defineProperty","__getOwnPropDesc","getOwnPropertyDescriptor","__getOwnPropNames","getOwnPropertyNames","__hasOwnProp","prototype","hasOwnProperty","__export","target","all","name","get","enumerable","__copyProps","to","from","except","desc","key","call","__toCommonJS","mod","value","src_exports","RequestCookies","ResponseCookies","parseCookie","parseSetCookie","stringifyCookie","module","exports","c","_a","attrs","path","expires","Date","toUTCString","maxAge","domain","secure","httpOnly","sameSite","partitioned","priority","filter","Boolean","stringified","encodeURIComponent","length","join","cookie","map","Map","pair","split","splitAt","indexOf","set","slice","decodeURIComponent","setCookie","attributes","httponly","maxage","samesite","fromEntries","value2","toLowerCase","replace","Number","parseSameSite","parsePriority","compact","t","newT","SAME_SITE","string","includes","PRIORITY","splitCookiesString","cookiesString","cookiesStrings","pos","start","ch","lastComma","nextStart","cookiesSeparatorFound","skipWhitespace","test","charAt","notSpecialChar","push","substring","requestHeaders","_parsed","_headers","header","parsed","Symbol","iterator","size","args","getAll","Array","_","n","has","delete","names","result","isArray","clear","keys","for","JSON","stringify","toString","values","v","responseHeaders","_b","_c","getSetCookie","cookieStrings","cookieString","normalizeCookie","options","bag","headers","serialized","append","now","_done","_seen","VaryParamsAccumulator","id","add","_resolve","asyncIterator","done","_buffer","close","undefined","next","Promise","resolve","shift","Set","emptyVaryParamsAccumulator","createResponseVaryParamsAccumulator","head","rootParams","segments","paramName","createVaryParamsAccumulator","workUnitStore","getStore","responseAccumulator","optionalCatchAllParamName","accumulator","getMetadataVaryParamsAccumulator1","_getVaryParamsAccumulator","prop","getViewportVaryParamsAccumulator","getRootParamsVaryParamsAccumulator","underlyingParamsWithVarying","accumulateVaryParam","accumulateRootVaryParam","rootParamsAccumulator","originalSearchParamsObject","createVaryingParams","originalParamsObject","receiver","Proxy","Reflect","ownKeys","createVaryingSearchParams1","SEARCH_PARAMS_VARY_ID","finishAccumulatingVaryParams","segmentAccumulator","LayoutRouterContext","use","createClientParams","ClientSegmentRoot","Component","slots","serverProvidedParams","params","layoutRouterContext","parentParams","clientParams","unresolvedThenable","then","React","useContext","TemplateContext","RenderFromTemplateContext","children","PrefetchHint1","StaticPrefetchDisabled","StaticAttemptHints","SubtreePrefetchHints","parentHints","propagateSubtreeBits","childHints","getSegmentValue","segment","isGroupSegment","endsWith","computeSelectedLayoutSegment","isParallelRouteSegment","startsWith","parallelRouteKey","rawSegment","DEFAULT_SEGMENT_KEY","getSelectedLayoutSegmentPath","tree","first","segmentPath","node","parallelRoutes","NOT_FOUND_SEGMENT_KEY","segmentValue","PAGE_SEGMENT_KEY","METADATA_BOUNDARY_NAME","VIEWPORT_BOUNDARY_NAME","OUTLET_BOUNDARY_NAME","ROOT_LAYOUT_BOUNDARY_NAME","NameSpace","MetadataBoundary","ViewportBoundary","OutletBoundary","RootLayoutBoundary","IconMark","window","meta","EnsureStaticLevel","getEnsureStaticLevel","ensureStatic","resolveEnsureStaticConfig","resolveEnsureStaticLevel","partialPrefetching","config","filePath","resolveEnsureStaticConfigImpl","slotsResult","originalConfig","console","warn","formatEnsureStaticExport","formatParallelSlot","layoutOrPageMod","getLayoutOrPageModule","getEnsureStaticConfigForModule","parentResult","slotResultKey","parseLoaderTree","parallelRoute","childResult","compareEnsureStatic","Error","slot","comparison","Comparison","leftSort","ENSURE_STATIC_ORDER","left","right","rightSort","ReflectAdapter","bind","deleteProperty","InvariantError","constructor","message","createPromiseWithResolvers","reject","promise","res","rej","getRenderedSearch","query","pairs","String","searchParamsToUrlQuery","searchParams","entries","existing","stringifyUrlQueryParam","param","isNaN","urlQueryToSearchParams","URLSearchParams","item","assign","searchParamsList","require","vendored","AppRouterContext","HooksClientContext","ServerInsertedHtml","ReactDOM","ReactServerDOMTurbopackClient"],"mappings":"mDACA,IAAIA,EAAYC,OAAOC,cAAc,CACjCC,EAAmBF,OAAOG,wBAAwB,CAClDC,EAAoBJ,OAAOK,mBAAmB,CAC9CC,EAAeN,OAAOO,SAAS,CAACC,cAAc,CAgB9CiB,EAAc,CAAC,EAfKd,EAgBF,CACpBe,eAAgB,IAAMA,EACtBC,gBAAiB,IAAMA,EACvBC,YAAa,IAAMA,EACnBC,eAAgB,IAAMA,EACtBC,gBAAiB,IAAMA,CACzB,EArBE,IAAK,IAAIlB,KAAQD,EACfZ,EAcK0B,EAdab,EAAM,CAAEC,GAAhBH,CAAqBC,CAAG,CAACC,EAAK,CAAEE,WAAY,EAAK,GAwB/D,SAASgB,EAAgBG,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,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106]}